├── .actor ├── Dockerfile ├── actor.json ├── input_schema.json └── pay_per_event.json ├── .dockerignore ├── .editorconfig ├── .env.example ├── .github └── workflows │ └── check.yaml ├── .gitignore ├── LICENSE.md ├── README.md ├── docs └── chat-ui.png ├── eslint.config.mjs ├── package-lock.json ├── package.json ├── src ├── clientFactory.ts ├── const.ts ├── conversationManager.ts ├── counter.ts ├── input.ts ├── logger.ts ├── main.ts ├── public │ ├── client.js │ ├── favicon.ico │ ├── index.html │ ├── logo512.png │ └── styles.css ├── types.ts └── utils.ts ├── tests └── utils.test.ts ├── tsconfig.eslint.json ├── tsconfig.json └── vitest.config.ts /.actor/Dockerfile: -------------------------------------------------------------------------------- 1 | # Specify the base Docker image. You can read more about 2 | # the available images at https://docs.apify.com/sdk/js/docs/guides/docker-images 3 | # You can also use any other image from Docker Hub. 4 | FROM apify/actor-node:20 AS builder 5 | 6 | # Check preinstalled packages 7 | RUN npm ls crawlee apify puppeteer playwright 8 | 9 | # Copy just package.json and package-lock.json 10 | # to speed up the build using Docker layer cache. 11 | COPY package*.json ./ 12 | 13 | # Install all dependencies. Don't audit to speed up the installation. 14 | RUN npm install --include=dev --audit=false 15 | 16 | # Next, copy the source files using the user set 17 | # in the base image. 18 | COPY . ./ 19 | 20 | # Install all dependencies and build the project. 21 | # Don't audit to speed up the installation. 22 | RUN npm run build 23 | 24 | # Create final image 25 | FROM apify/actor-node:20 26 | 27 | # Check preinstalled packages 28 | RUN npm ls crawlee apify puppeteer playwright 29 | 30 | # Copy just package.json and package-lock.json 31 | # to speed up the build using Docker layer cache. 32 | COPY package*.json ./ 33 | 34 | # Install NPM packages, skip optional and development dependencies to 35 | # keep the image small. Avoid logging too much and print the dependency 36 | # tree for debugging 37 | RUN npm --quiet set progress=false \ 38 | && npm install --omit=dev --omit=optional \ 39 | && echo "Installed NPM packages:" \ 40 | && (npm list --omit=dev --all || true) \ 41 | && echo "Node.js version:" \ 42 | && node --version \ 43 | && echo "NPM version:" \ 44 | && npm --version \ 45 | && rm -r ~/.npm 46 | 47 | # Copy built JS files from builder image 48 | COPY --from=builder /usr/src/app/dist ./dist 49 | COPY --from=builder /usr/src/app/src/public ./dist/src/public 50 | 51 | # Next, copy the remaining files and directories with the source code. 52 | # Since we do this after NPM install, quick build will be really fast 53 | # for most source file changes. 54 | COPY . ./ 55 | 56 | # Run the image. 57 | CMD ["npm", "run", "start:prod", "--silent"] 58 | -------------------------------------------------------------------------------- /.actor/actor.json: -------------------------------------------------------------------------------- 1 | { 2 | "actorSpecification": 1, 3 | "name": "apify-mcp-client", 4 | "title": "Model Context Protocol Client for Apify Actors", 5 | "description": "Client for the Model Context Protocol (MCP) for Apify Actors", 6 | "version": "0.1", 7 | "input": "./input_schema.json", 8 | "dockerfile": "./Dockerfile" 9 | } 10 | -------------------------------------------------------------------------------- /.actor/input_schema.json: -------------------------------------------------------------------------------- 1 | { 2 | "title": "Apify MCP Client", 3 | "type": "object", 4 | "schemaVersion": 1, 5 | "properties": { 6 | "mcpSseUrl": { 7 | "title": "MCP Server Sent Events (SSE) URL", 8 | "type": "string", 9 | "description": "MCP Server Sent Events (SSE) URL for receiving updates from the server.\n\nMake sure that URL path ends with `/sse`", 10 | "editor": "hidden" 11 | }, 12 | "mcpUrl": { 13 | "title": "MCP Server URL", 14 | "type": "string", 15 | "description": "URL of the MCP Server for updates. Use `SSEClientTransport` if the URL ends with `/sse`; otherwise, use `HttpStreamableClientTransport`.", 16 | "editor": "textfield", 17 | "default": "https://mcp.apify.com/sse?enableAddingActors=true", 18 | "prefill": "https://mcp.apify.com/sse?enableAddingActors=true" 19 | }, 20 | "mcpTransportType": { 21 | "title": "MCP transport type specification", 22 | "type": "string", 23 | "description": "This setting helps you to override the MCP transport layer if required. Use `SSEClientTransport` for Server Sent Events (2024-11-05) or `HttpStreamableClientTransport` for JSON Response Streamable HTTP (2025-03-26).", 24 | "enum": ["sse", "http-streamable-json-response"], 25 | "enumTitles": ["SSE (Server Sent Events, 2024-11-05)", "JSON Response Streamable HTTP (2025-03-26)"], 26 | "default": "sse" 27 | }, 28 | "headers": { 29 | "title": "HTTP headers", 30 | "type": "object", 31 | "description": "HTTP headers to be sent with the request to the MCP server. If you are using Apify's MCP server, headers are NOT required", 32 | "editor": "json" 33 | }, 34 | "systemPrompt": { 35 | "title": "System prompt", 36 | "type": "string", 37 | "description": "System prompt for the Claude model", 38 | "editor": "textarea", 39 | "default": "You are a helpful Apify assistant with tools called Actors.\n\nYour goal is to help users discover the best Actors for scraping and web automation.\nYou have access to a list of tools that can help you discover Actors, find details, and include them among tools for later execution.\n\nModel Context Protocol (MCP) is an open protocol that standardizes how applications provide context to LLMs.\n\nChoose the appropriate Actor based on the conversation context. If no Actor is needed, reply directly.\n\nPrefer Actors with more users, stars, and runs.\nWhen you need to use an Actor, explain how it is used and with which parameters.\nNever call an Actor unless it is required by the user!\nAfter receiving an Actor's response:\n1. Transform the raw data into a natural, conversational response.\n2. Keep responses concise but informative.\n3. Focus on the most relevant information.\n4. Use appropriate context from the user's question.\n5. Avoid simply repeating the raw data.\nAlways use 'Actor', not 'actor'. Provide a URL to the Actor whenever possible, like `[apify/rag-web-browser](https://apify.com/apify/rag-web-browser)`.\nActor execution may take some time, and results can be large. Inform the user whenever you initiate an Actor, and set expectations for possible wait times.\nIf possible, limit the number of results to 3, 5, or 10. Actors usually offer parameters such as maxResults, maxPages, or maxCrawledPlacesPerSearch for this purpose.\nThe server limits the number of results returned, but you can always request more results from paginated datasets or fetch additional data from the key-value store if needed.\n", 40 | "prefill": "You are a helpful Apify assistant with tools called Actors.\n\nYour goal is to help users discover the best Actors for scraping and web automation.\nYou have access to a list of tools that can help you discover Actors, find details, and include them among tools for later execution.\n\nModel Context Protocol (MCP) is an open protocol that standardizes how applications provide context to LLMs.\n\nChoose the appropriate Actor based on the conversation context. If no Actor is needed, reply directly.\n\nPrefer Actors with more users, stars, and runs.\nWhen you need to use an Actor, explain how it is used and with which parameters.\nNever call an Actor unless it is required by the user!\nAfter receiving an Actor's response:\n1. Transform the raw data into a natural, conversational response.\n2. Keep responses concise but informative.\n3. Focus on the most relevant information.\n4. Use appropriate context from the user's question.\n5. Avoid simply repeating the raw data.\nAlways use 'Actor', not 'actor'. Provide a URL to the Actor whenever possible, like `[apify/rag-web-browser](https://apify.com/apify/rag-web-browser)`.\nActor execution may take some time, and results can be large. Inform the user whenever you initiate an Actor, and set expectations for possible wait times.\nIf possible, limit the number of results to 3, 5, or 10. Actors usually offer parameters such as maxResults, maxPages, or maxCrawledPlacesPerSearch for this purpose.\nThe server limits the number of results returned, but you can always request more results from paginated datasets or fetch additional data from the key-value store if needed.\n" 41 | }, 42 | "modelName": { 43 | "title": "Anthropic Claude model (Anthropic is only supported provider now)", 44 | "type": "string", 45 | "description": "Select a model to be used for selecting tools and generating text.\n\n- Claude Sonnet 4 - the most intelligent model\n- Claude 3.7 Sonnet - highly intelligent model\n- Claude 3.5 Haiku - a fastest model", 46 | "editor": "select", 47 | "enum": [ 48 | "claude-sonnet-4-0", 49 | "claude-3-7-sonnet-latest", 50 | "claude-3-5-haiku-latest" 51 | ], 52 | "enumTitles": [ 53 | "Claude Sonnet 4", 54 | "Claude Sonnet 3.7", 55 | "Claude Haiku 3.5" 56 | ], 57 | "default": "claude-3-5-haiku-latest" 58 | }, 59 | "llmProviderApiKey": { 60 | "title": "LLM Provider API key (Anthropic is only supported provider now)", 61 | "type": "string", 62 | "description": "API key for accessing a Large Language Model. If you provide your own API key, Actor will not charge for query answered event.", 63 | "editor": "textfield", 64 | "isSecret": true 65 | }, 66 | "modelMaxOutputTokens": { 67 | "title": "Maximum tokens for Claude response", 68 | "type": "integer", 69 | "description": "Maximum number of tokens in the Claude response. The higher the number, the longer the response time", 70 | "editor": "number", 71 | "prefill": 2048, 72 | "default": 2048, 73 | "maximum": 10000 74 | }, 75 | "maxNumberOfToolCallsPerQuery": { 76 | "title": "Maximum number of tool calls per query", 77 | "type": "integer", 78 | "description": "Maximum number of times a tool can be called with one query. Keep this number low for simple flows", 79 | "editor": "number", 80 | "prefill": 20, 81 | "default": 20 82 | }, 83 | "toolCallTimeoutSec": { 84 | "title": "Tool call timeout", 85 | "type": "integer", 86 | "description": "Timeout for a single tool call in seconds", 87 | "editor": "number", 88 | "prefill": 300, 89 | "default": 300 90 | } 91 | }, 92 | "required": [ 93 | "mcpUrl", 94 | "modelName" 95 | ] 96 | } 97 | -------------------------------------------------------------------------------- /.actor/pay_per_event.json: -------------------------------------------------------------------------------- 1 | { 2 | "actor-start": { 3 | "eventTitle": "Actor start", 4 | "eventDescription": "Flat fee for starting an Actor run.", 5 | "eventPriceUsd": 0.005 6 | }, 7 | "actor-running-time": { 8 | "eventTitle": "Actor running time (5 minutes)", 9 | "eventDescription": "Cost per running time for each 5 minutes.", 10 | "eventPriceUsd":0.005 11 | }, 12 | "input-tokens-sonnet-4": { 13 | "eventTitle": "100 input tokens (Sonnet-4)", 14 | "eventDescription": "Cost per 100 input tokens for Claude 4 Sonnet (1M tokens = 3$).", 15 | "eventPriceUsd": 0.0003 16 | }, 17 | "output-tokens-sonnet-4": { 18 | "eventTitle": "100 output tokens (Sonnet-4)", 19 | "eventDescription": "Cost per 100 output tokens for Claude 4 Sonnet (1M tokens = 15$).", 20 | "eventPriceUsd": 0.0015 21 | }, 22 | "input-tokens-sonnet-3-7": { 23 | "eventTitle": "100 input tokens (Sonnet-3.7)", 24 | "eventDescription": "Cost per 100 input tokens for Claude 3.7 Sonnet (1M tokens = 3$).", 25 | "eventPriceUsd": 0.0003 26 | }, 27 | "output-tokens-sonnet-3-7": { 28 | "eventTitle": "100 output tokens (Sonnet-3.7)", 29 | "eventDescription": "Cost per 100 output tokens for Claude 3.7 Sonnet (1M tokens = 15$).", 30 | "eventPriceUsd": 0.0015 31 | }, 32 | "input-tokens-haiku-3-5": { 33 | "eventTitle": "100 input tokens (Haiku-3.5)", 34 | "eventDescription": "Cost per 100 input tokens for Claude 3.5 Haiku (1M tokens = 0.8$).", 35 | "eventPriceUsd": 0.00008 36 | }, 37 | "output-tokens-haiku-3-5": { 38 | "eventTitle": "100 output tokens (Haiku-3.5)", 39 | "eventDescription": "Cost per 100 output tokens for Claude 3.5 Haiku (1M tokens = 4$).", 40 | "eventPriceUsd": 0.0004 41 | }, 42 | "query-answered": { 43 | "eventTitle": "Query answered", 44 | "eventDescription": "Cost per query answered.", 45 | "eventPriceUsd": 0.005 46 | } 47 | } 48 | -------------------------------------------------------------------------------- /.dockerignore: -------------------------------------------------------------------------------- 1 | # configurations 2 | .idea 3 | 4 | # crawlee and apify storage folders 5 | apify_storage 6 | crawlee_storage 7 | storage 8 | src/storage 9 | 10 | # installed files 11 | node_modules 12 | 13 | # git folder 14 | .git 15 | 16 | # data 17 | data 18 | dist 19 | .env 20 | -------------------------------------------------------------------------------- /.editorconfig: -------------------------------------------------------------------------------- 1 | root = true 2 | 3 | [*] 4 | indent_style = space 5 | indent_size = 4 6 | charset = utf-8 7 | trim_trailing_whitespace = true 8 | insert_final_newline = true 9 | end_of_line = lf 10 | -------------------------------------------------------------------------------- /.env.example: -------------------------------------------------------------------------------- 1 | APIFY_TOKEN= 2 | LLM_PROVIDER_API_KEY= 3 | -------------------------------------------------------------------------------- /.github/workflows/check.yaml: -------------------------------------------------------------------------------- 1 | # This workflow runs for every pull request to lint and test the proposed changes. 2 | 3 | name: Check 4 | 5 | on: 6 | pull_request: 7 | 8 | # Push to master will trigger code checks 9 | push: 10 | branches: 11 | - master 12 | tags-ignore: 13 | - "**" # Ignore all tags to prevent duplicate builds when tags are pushed. 14 | 15 | jobs: 16 | lint_and_test: 17 | name: Build & Test 18 | runs-on: ubuntu-latest 19 | 20 | steps: 21 | - uses: actions/checkout@v4 22 | - name: Use Node.js 22 23 | uses: actions/setup-node@v4 24 | with: 25 | node-version: 22 26 | cache: 'npm' 27 | cache-dependency-path: 'package-lock.json' 28 | - name: Install Dependencies 29 | run: npm ci 30 | 31 | - name: Lint 32 | run: npm run lint 33 | 34 | - name: Build 35 | run: npm run build 36 | 37 | - name: Test 38 | run: npm run test 39 | -------------------------------------------------------------------------------- /.gitignore: -------------------------------------------------------------------------------- 1 | # This file tells Git which files shouldn't be added to source control 2 | 3 | .idea 4 | .vscode 5 | storage 6 | apify_storage 7 | crawlee_storage 8 | node_modules 9 | dist 10 | tsconfig.tsbuildinfo 11 | storage/* 12 | !storage/key_value_stores 13 | storage/key_value_stores/* 14 | !storage/key_value_stores/default 15 | storage/key_value_stores/default/* 16 | !storage/key_value_stores/default/INPUT.json 17 | 18 | # Added by Apify CLI 19 | .venv 20 | .env 21 | -------------------------------------------------------------------------------- /LICENSE.md: -------------------------------------------------------------------------------- 1 | Apache License 2 | Version 2.0, January 2004 3 | http://www.apache.org/licenses/ 4 | 5 | TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION 6 | 7 | 1. Definitions. 8 | 9 | "License" shall mean the terms and conditions for use, reproduction, 10 | and distribution as defined by Sections 1 through 9 of this document. 11 | 12 | "Licensor" shall mean the copyright owner or entity authorized by 13 | the copyright owner that is granting the License. 14 | 15 | "Legal Entity" shall mean the union of the acting entity and all 16 | other entities that control, are controlled by, or are under common 17 | control with that entity. For the purposes of this definition, 18 | "control" means (i) the power, direct or indirect, to cause the 19 | direction or management of such entity, whether by contract or 20 | otherwise, or (ii) ownership of fifty percent (50%) or more of the 21 | outstanding shares, or (iii) beneficial ownership of such entity. 22 | 23 | "You" (or "Your") shall mean an individual or Legal Entity 24 | exercising permissions granted by this License. 25 | 26 | "Source" form shall mean the preferred form for making modifications, 27 | including but not limited to software source code, documentation 28 | source, and configuration files. 29 | 30 | "Object" form shall mean any form resulting from mechanical 31 | transformation or translation of a Source form, including but 32 | not limited to compiled object code, generated documentation, 33 | and conversions to other media types. 34 | 35 | "Work" shall mean the work of authorship, whether in Source or 36 | Object form, made available under the License, as indicated by a 37 | copyright notice that is included in or attached to the work 38 | (an example is provided in the Appendix below). 39 | 40 | "Derivative Works" shall mean any work, whether in Source or Object 41 | form, that is based on (or derived from) the Work and for which the 42 | editorial revisions, annotations, elaborations, or other modifications 43 | represent, as a whole, an original work of authorship. For the purposes 44 | of this License, Derivative Works shall not include works that remain 45 | separable from, or merely link (or bind by name) to the interfaces of, 46 | the Work and Derivative Works thereof. 47 | 48 | "Contribution" shall mean any work of authorship, including 49 | the original version of the Work and any modifications or additions 50 | to that Work or Derivative Works thereof, that is intentionally 51 | submitted to Licensor for inclusion in the Work by the copyright owner 52 | or by an individual or Legal Entity authorized to submit on behalf of 53 | the copyright owner. For the purposes of this definition, "submitted" 54 | means any form of electronic, verbal, or written communication sent 55 | to the Licensor or its representatives, including but not limited to 56 | communication on electronic mailing lists, source code control systems, 57 | and issue tracking systems that are managed by, or on behalf of, the 58 | Licensor for the purpose of discussing and improving the Work, but 59 | excluding communication that is conspicuously marked or otherwise 60 | designated in writing by the copyright owner as "Not a Contribution." 61 | 62 | "Contributor" shall mean Licensor and any individual or Legal Entity 63 | on behalf of whom a Contribution has been received by Licensor and 64 | subsequently incorporated within the Work. 65 | 66 | 2. Grant of Copyright License. Subject to the terms and conditions of 67 | this License, each Contributor hereby grants to You a perpetual, 68 | worldwide, non-exclusive, no-charge, royalty-free, irrevocable 69 | copyright license to reproduce, prepare Derivative Works of, 70 | publicly display, publicly perform, sublicense, and distribute the 71 | Work and such Derivative Works in Source or Object form. 72 | 73 | 3. Grant of Patent License. Subject to the terms and conditions of 74 | this License, each Contributor hereby grants to You a perpetual, 75 | worldwide, non-exclusive, no-charge, royalty-free, irrevocable 76 | (except as stated in this section) patent license to make, have made, 77 | use, offer to sell, sell, import, and otherwise transfer the Work, 78 | where such license applies only to those patent claims licensable 79 | by such Contributor that are necessarily infringed by their 80 | Contribution(s) alone or by combination of their Contribution(s) 81 | with the Work to which such Contribution(s) was submitted. If You 82 | institute patent litigation against any entity (including a 83 | cross-claim or counterclaim in a lawsuit) alleging that the Work 84 | or a Contribution incorporated within the Work constitutes direct 85 | or contributory patent infringement, then any patent licenses 86 | granted to You under this License for that Work shall terminate 87 | as of the date such litigation is filed. 88 | 89 | 4. Redistribution. You may reproduce and distribute copies of the 90 | Work or Derivative Works thereof in any medium, with or without 91 | modifications, and in Source or Object form, provided that You 92 | meet the following conditions: 93 | 94 | (a) You must give any other recipients of the Work or 95 | Derivative Works a copy of this License; and 96 | 97 | (b) You must cause any modified files to carry prominent notices 98 | stating that You changed the files; and 99 | 100 | (c) You must retain, in the Source form of any Derivative Works 101 | that You distribute, all copyright, patent, trademark, and 102 | attribution notices from the Source form of the Work, 103 | excluding those notices that do not pertain to any part of 104 | the Derivative Works; and 105 | 106 | (d) If the Work includes a "NOTICE" text file as part of its 107 | distribution, then any Derivative Works that You distribute must 108 | include a readable copy of the attribution notices contained 109 | within such NOTICE file, excluding those notices that do not 110 | pertain to any part of the Derivative Works, in at least one 111 | of the following places: within a NOTICE text file distributed 112 | as part of the Derivative Works; within the Source form or 113 | documentation, if provided along with the Derivative Works; or, 114 | within a display generated by the Derivative Works, if and 115 | wherever such third-party notices normally appear. The contents 116 | of the NOTICE file are for informational purposes only and 117 | do not modify the License. You may add Your own attribution 118 | notices within Derivative Works that You distribute, alongside 119 | or as an addendum to the NOTICE text from the Work, provided 120 | that such additional attribution notices cannot be construed 121 | as modifying the License. 122 | 123 | You may add Your own copyright statement to Your modifications and 124 | may provide additional or different license terms and conditions 125 | for use, reproduction, or distribution of Your modifications, or 126 | for any such Derivative Works as a whole, provided Your use, 127 | reproduction, and distribution of the Work otherwise complies with 128 | the conditions stated in this License. 129 | 130 | 5. Submission of Contributions. Unless You explicitly state otherwise, 131 | any Contribution intentionally submitted for inclusion in the Work 132 | by You to the Licensor shall be under the terms and conditions of 133 | this License, without any additional terms or conditions. 134 | Notwithstanding the above, nothing herein shall supersede or modify 135 | the terms of any separate license agreement you may have executed 136 | with Licensor regarding such Contributions. 137 | 138 | 6. Trademarks. This License does not grant permission to use the trade 139 | names, trademarks, service marks, or product names of the Licensor, 140 | except as required for reasonable and customary use in describing the 141 | origin of the Work and reproducing the content of the NOTICE file. 142 | 143 | 7. Disclaimer of Warranty. Unless required by applicable law or 144 | agreed to in writing, Licensor provides the Work (and each 145 | Contributor provides its Contributions) on an "AS IS" BASIS, 146 | WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or 147 | implied, including, without limitation, any warranties or conditions 148 | of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A 149 | PARTICULAR PURPOSE. You are solely responsible for determining the 150 | appropriateness of using or redistributing the Work and assume any 151 | risks associated with Your exercise of permissions under this License. 152 | 153 | 8. Limitation of Liability. In no event and under no legal theory, 154 | whether in tort (including negligence), contract, or otherwise, 155 | unless required by applicable law (such as deliberate and grossly 156 | negligent acts) or agreed to in writing, shall any Contributor be 157 | liable to You for damages, including any direct, indirect, special, 158 | incidental, or consequential damages of any character arising as a 159 | result of this License or out of the use or inability to use the 160 | Work (including but not limited to damages for loss of goodwill, 161 | work stoppage, computer failure or malfunction, or any and all 162 | other commercial damages or losses), even if such Contributor 163 | has been advised of the possibility of such damages. 164 | 165 | 9. Accepting Warranty or Additional Liability. While redistributing 166 | the Work or Derivative Works thereof, You may choose to offer, 167 | and charge a fee for, acceptance of support, warranty, indemnity, 168 | or other liability obligations and/or rights consistent with this 169 | License. However, in accepting such obligations, You may act only 170 | on Your own behalf and on Your sole responsibility, not on behalf 171 | of any other Contributor, and only if You agree to indemnify, 172 | defend, and hold each Contributor harmless for any liability 173 | incurred by, or claims asserted against, such Contributor by reason 174 | of your accepting any such warranty or additional liability. 175 | 176 | END OF TERMS AND CONDITIONS 177 | 178 | APPENDIX: How to apply the Apache License to your work. 179 | 180 | To apply the Apache License to your work, attach the following 181 | boilerplate notice, with the fields enclosed by brackets "{}" 182 | replaced with your own identifying information. (Don't include 183 | the brackets!) The text should be enclosed in the appropriate 184 | comment syntax for the file format. We also recommend that a 185 | file or class name and description of purpose be included on the 186 | same "printed page" as the copyright notice for easier 187 | identification within third-party archives. 188 | 189 | Copyright 2024 Apify Technologies s.r.o. 190 | 191 | Licensed under the Apache License, Version 2.0 (the "License"); 192 | you may not use this file except in compliance with the License. 193 | You may obtain a copy of the License at 194 | 195 | http://www.apache.org/licenses/LICENSE-2.0 196 | 197 | Unless required by applicable law or agreed to in writing, software 198 | distributed under the License is distributed on an "AS IS" BASIS, 199 | WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 200 | See the License for the specific language governing permissions and 201 | limitations under the License. 202 | -------------------------------------------------------------------------------- /README.md: -------------------------------------------------------------------------------- 1 | # Tester Client for Model Context Protocol (MCP) 2 | 3 | [![Actors MCP Client](https://apify.com/actor-badge?actor=jiri.spilka/tester-mcp-client)](https://apify.com/jiri.spilka/tester-mcp-client) 4 | 5 | Implementation of a model context protocol (MCP) client that connects to an MCP server using Server-Sent Events (SSE) and displays the conversation in a chat-like UI. 6 | It is a standalone Actor server designed for testing MCP servers over SSE. 7 | It uses [Pay-per-event](https://docs.apify.com/sdk/js/docs/guides/pay-per-event) pricing model. 8 | 9 | For more information, see the [Model Context Protocol](https://modelcontextprotocol.org/) website or blogpost [What is MCP and why does it matter?](https://blog.apify.com/what-is-model-context-protocol/). 10 | 11 | Once you run the Actor, check the output or logs for a link to the chat UI interface to interact with the MCP server. 12 | The URL will look like this and will vary each run: 13 | ```shell 14 | Navigate to https://...apify.net to interact with chat-ui interface. 15 | ``` 16 | 17 | ## 🚀 Main features 18 | 19 | - 🔌 Connects to an MCP server using Server-Sent Events (SSE) or Streamable HTTP 20 | - 💬 Provides a chat-like UI for displaying tool calls and results 21 | - 🇦 Connects to an [Apify MCP Server](https://mcp.apify.com) for interacting with one or more Apify Actors 22 | - 💥 Dynamically uses tools based on context and user queries (if supported by a server) 23 | - 🔓 Use Authorization headers and API keys for secure connections 24 | - 🪟 Open source, so you can review it, suggest improvements, or modify it 25 | 26 | ## 🎯 What does Tester MCP Client do? 27 | 28 | When connected to [Apify MCP Server](https://mcp.apify.com/) the Tester MCP Client provides an interactive chat interface where you can: 29 | 30 | - "What are the most popular Actors for social media scraping?" 31 | - "Show me the best way to use the Instagram Scraper" 32 | - "Which Actor should I use to extract data from LinkedIn?" 33 | - "Can you help me understand how to scrape Google search results?" 34 | 35 | ![Tester-MCP-client-screenshot](https://raw.githubusercontent.com/apify/tester-mcp-client/refs/heads/main/docs/chat-ui.png) 36 | 37 | ## 📖 How does it work? 38 | 39 | The Apify MCP Client connects to a running MCP server over Server-Sent Events (SSE) and it does the following: 40 | 41 | - Initiates an SSE connection to the MCP server `/sse`. 42 | - Sends user queries to the MCP server via `POST /message`. 43 | - Receives real-time streamed responses (via `GET /sse`) that may include LLM output, and **tool usage** blocks 44 | - Based on the LLM response, orchestrates tool calls and displays the conversation 45 | - Displays the conversation 46 | 47 | ## ⚙️ Usage 48 | 49 | - Test any MCP server over SSE 50 | - Test [Apify MCP Server](https://mcp.apify.com/) and the ability to dynamically select amongst thousands of tools 51 | 52 | ### Normal Mode (on Apify) 53 | 54 | You can run the Tester MCP Client on Apify and connect it to any MCP server that supports SSE. 55 | Configuration can be done via the Apify UI or API by specifying parameters such as the MCP server URL, system prompt, and API key. 56 | 57 | Once you run Actor, check the logs for a link to the Tester MCP Client UI, where you can interact with the MCP server: 58 | The URL will look like this and will be different from run to run: 59 | ```shell 60 | INFO Navigate to https://......runs.apify.net in your browser to interact with an MCP server. 61 | ``` 62 | 63 | ## 💰 Pricing 64 | 65 | The Apify MCP Client is free to use. You only pay for LLM provider usage and resources consumed on the Apify platform. 66 | 67 | This Actor uses a modern and flexible approach for AI Agents monetization and pricing called [Pay-per-event](https://docs.apify.com/sdk/js/docs/guides/pay-per-event). 68 | 69 | Events charged: 70 | - Actor start (based on memory used, charged per 128 MB unit) 71 | - Running time (charged every 5 minutes, per 128 MB unit) 72 | - Query answered (depends on the model used, not charged if you provide your own API key for LLM provider) 73 | 74 | When you use your own LLM provider API key, running the MCP Client for 1 hour with 128 MB memory costs approximately $0.06. 75 | With the Apify Free tier (no credit card required 💳), you can run the MCP Client for 80 hours per month. 76 | Definitely enough to test your MCP server! 77 | 78 | ## 📖 How it works 79 | 80 | ```plaintext 81 | Browser ← (SSE) → Tester MCP Client ← (SSE) → MCP Server 82 | ``` 83 | We create this chain to keep any custom bridging logic inside the Tester MCP Client, while leaving the main MCP Server unchanged. 84 | The browser uses SSE to communicate with the Tester MCP Client, and the Tester MCP Client relies on SSE to talk to the MCP Server. 85 | This separates extra client-side logic from the core server, making it easier to maintain and debug. 86 | 87 | 1. Navigate to `https://tester-mcp-client.apify.actor?token=YOUR-API-TOKEN` (or http://localhost:3000 if you are running it locally). 88 | 2. Files `index.html` and `client.js` are served from the `public/` directory. 89 | 3. Browser opens SSE stream via `GET /sse`. 90 | 4. The user's query is sent with `POST /message`. 91 | 5. Query processing: 92 | - Calls Large Language Model. 93 | - Optionally calls tools if required using 94 | 6. For each result chunk, `sseEmit(role, content)` 95 | 96 | 97 | ### Local development 98 | 99 | The Tester MCP Client Actor is open source and available on [GitHub](https://github.com/apify/rag-web-browser), allowing you to modify and develop it as needed. 100 | 101 | Download the source code: 102 | 103 | ```bash 104 | git clone https://github.com/apify/tester-mcp-client.git 105 | cd tester-mcp-client 106 | ``` 107 | Install the dependencies: 108 | ```shell 109 | npm install 110 | ``` 111 | 112 | Create a `.env` file with the following content (refer to the `.env.example` file for guidance): 113 | 114 | ```plaintext 115 | APIFY_TOKEN=YOUR_APIFY_TOKEN 116 | LLM_PROVIDER_API_KEY=YOUR_API_KEY 117 | ``` 118 | 119 | Default values for settings such as `mcpUrl`, `systemPrompt`, and others are defined in the `const.ts` file. You can adjust these as needed for your development. 120 | 121 | Run the client locally 122 | 123 | ```bash 124 | npm start 125 | ``` 126 | 127 | Navigate to [http://localhost:3000](http://localhost:3000) in your browser to interact with the MCP server. 128 | 129 | **Happy chatting with Apify Actors!** 130 | 131 | ## ⓘ Limitations and feedback 132 | 133 | The client does not support all MCP features, such as Prompts and Resource. 134 | 135 | ## References 136 | 137 | - [Model Context Protocol](https://modelcontextprotocol.org/) 138 | - [Apify Actors MCP Server](https://apify.com/apify/actors-mcp-server) 139 | - [Apify MCP Server](https://docs.apify.com/platform/integrations/mcp) 140 | - [Pay-per-event pricing model](https://docs.apify.com/sdk/js/docs/guides/pay-per-event) 141 | - [What are AI Agents?](https://blog.apify.com/what-are-ai-agents/) 142 | - [What is MCP and why does it matter?](https://blog.apify.com/what-is-model-context-protocol/) 143 | - [How to use MCP with Apify Actors](https://blog.apify.com/how-to-use-mcp/) 144 | -------------------------------------------------------------------------------- /docs/chat-ui.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/apify/tester-mcp-client/f4f3fa67b21f3b13b8ebf2f0a08deca40e66ac66/docs/chat-ui.png -------------------------------------------------------------------------------- /eslint.config.mjs: -------------------------------------------------------------------------------- 1 | import apify from '@apify/eslint-config'; 2 | 3 | // eslint-disable-next-line import/no-default-export 4 | export default [ 5 | { ignores: ['**/dist'] }, // Ignores need to happen first 6 | ...apify, 7 | { 8 | languageOptions: { 9 | sourceType: 'module', 10 | 11 | parserOptions: { 12 | project: 'tsconfig.eslint.json', 13 | }, 14 | }, 15 | }, 16 | ]; 17 | -------------------------------------------------------------------------------- /package.json: -------------------------------------------------------------------------------- 1 | { 2 | "name": "@apify/actors-mcp-client", 3 | "version": "0.1.0", 4 | "type": "module", 5 | "description": "Model Context Protocol Client", 6 | "engines": { 7 | "node": ">=18.0.0" 8 | }, 9 | "main": "dist/src/main.js", 10 | "bin": { 11 | "actors-mcp-client": "./dist/src/main.js" 12 | }, 13 | "files": [ 14 | "dist", 15 | "LICENSE" 16 | ], 17 | "repository": { 18 | "type": "git", 19 | "url": "https://github.com/apify/actors-mcp-client.git" 20 | }, 21 | "bugs": { 22 | "url": "https://github.com/apify/actors-mcp-client/issues" 23 | }, 24 | "homepage": "https://apify.com/apify/actors-mcp-client", 25 | "keywords": [ 26 | "apify", 27 | "mcp", 28 | "client", 29 | "actors", 30 | "model context protocol" 31 | ], 32 | "dependencies": { 33 | "@anthropic-ai/sdk": "^0.36.2", 34 | "@anthropic-ai/tokenizer": "^0.0.4", 35 | "@modelcontextprotocol/sdk": "^1.12.0", 36 | "apify": "^3.3.2", 37 | "cors": "^2.8.5", 38 | "dotenv": "^16.4.7", 39 | "eventsource": "^3.0.2", 40 | "express": "^4.21.2", 41 | "vitest": "^3.1.2" 42 | }, 43 | "devDependencies": { 44 | "@apify/eslint-config": "^0.5.0-beta.2", 45 | "@apify/tsconfig": "^0.1.0", 46 | "@types/cors": "^2.8.17", 47 | "@types/express": "^4.0.0", 48 | "@types/minimist": "^1.2.5", 49 | "eslint": "^9.17.0", 50 | "tsx": "^4.6.2", 51 | "typescript": "^5.3.3", 52 | "typescript-eslint": "^8.18.2" 53 | }, 54 | "scripts": { 55 | "start": "npm run start:dev", 56 | "start:prod": "node dist/src/main.js", 57 | "start:dev": "tsx src/main.ts", 58 | "lint": "eslint .", 59 | "lint:fix": "eslint . --fix", 60 | "build": "tsc", 61 | "test": "vitest run", 62 | "watch": "tsc --watch", 63 | "inspector": "npx @modelcontextprotocol/inspector dist/src/main.js" 64 | }, 65 | "author": "Apify", 66 | "license": "MIT" 67 | } 68 | -------------------------------------------------------------------------------- /src/clientFactory.ts: -------------------------------------------------------------------------------- 1 | // clientFactory.ts 2 | import { Client } from '@modelcontextprotocol/sdk/client/index.js'; 3 | import { SSEClientTransport } from '@modelcontextprotocol/sdk/client/sse.js'; 4 | import { StreamableHTTPClientTransport } from '@modelcontextprotocol/sdk/client/streamableHttp.js'; 5 | import { ToolListChangedNotificationSchema, LoggingMessageNotificationSchema } from '@modelcontextprotocol/sdk/types.js'; 6 | import type { LoggingMessageNotification, ListToolsResult } from '@modelcontextprotocol/sdk/types.js'; 7 | import { log } from 'apify'; 8 | 9 | /** 10 | * Create a client for the MCP server 11 | * @param serverUrl - The URL of the MCP server 12 | * @param mcpTransport - The transport method to use for the MCP server. Either 'sse' or 'http-streamable-json-response' 13 | * @param customHeaders - Custom headers to send to the MCP server 14 | * @param onToolsUpdate - A function to call when the tools list changes. Used to update the tools in the conversation manager 15 | * @param onNotification - A function to call when a notification is received. Used to log notifications 16 | * @returns A client for the MCP server 17 | */ 18 | export async function createClient( 19 | serverUrl: string, 20 | mcpTransport: 'sse' | 'http-streamable-json-response', 21 | customHeaders: Record | null, 22 | onToolsUpdate: (listTools: ListToolsResult) => Promise, 23 | onNotification: (notification: LoggingMessageNotification) => void, 24 | ): Promise { 25 | const client = new Client( 26 | { name: 'example-client', version: '1.0.0' }, 27 | { capabilities: {} }, 28 | ); 29 | 30 | let transport; 31 | if (mcpTransport === 'sse') { 32 | transport = new SSEClientTransport( 33 | new URL(serverUrl), 34 | { 35 | requestInit: { headers: customHeaders || undefined }, 36 | eventSourceInit: { 37 | // The EventSource package augments EventSourceInit with a "fetch" parameter. 38 | // You can use this to set additional headers on the outgoing request. 39 | // Based on this example: https://github.com/modelcontextprotocol/typescript-sdk/issues/118 40 | async fetch(input: Request | URL | string, init?: RequestInit) { 41 | const headers = new Headers({ ...(init?.headers || {}), ...customHeaders }); 42 | return fetch(input, { ...init, headers }); 43 | }, 44 | // We have to cast to "any" to use it, since it's non-standard 45 | } as any, // eslint-disable-line @typescript-eslint/no-explicit-any 46 | }, 47 | ); 48 | } else { 49 | transport = new StreamableHTTPClientTransport( 50 | new URL(serverUrl), 51 | { requestInit: { headers: customHeaders || undefined } }, 52 | ); 53 | } 54 | 55 | try { 56 | await client.connect(transport); 57 | await onToolsUpdate(await client.listTools()); 58 | log.debug(`Connection ${mcpTransport} to MCP server: ${serverUrl} established`); 59 | } catch (error) { 60 | log.error(`Failed to connect to MCP server: ${serverUrl}`, { error }); 61 | throw new Error(`Failed to connect to MCP server: ${serverUrl}, error: ${error}`); 62 | } 63 | 64 | client.setNotificationHandler(LoggingMessageNotificationSchema, (notification) => { 65 | log.debug(`Notification received: ${notification.params.level} - ${notification.params.data}`); 66 | onNotification(notification); 67 | }); 68 | 69 | client.setNotificationHandler(ToolListChangedNotificationSchema, async () => { 70 | log.debug('Received notification that tools list changed, refreshing...'); 71 | await onToolsUpdate(await client.listTools()); 72 | }); 73 | return client; 74 | } 75 | -------------------------------------------------------------------------------- /src/const.ts: -------------------------------------------------------------------------------- 1 | import inputSchema from '../.actor/input_schema.json' with { type: 'json' }; 2 | 3 | export const defaults = { 4 | mcpUrl: inputSchema.properties.mcpUrl.default, 5 | systemPrompt: inputSchema.properties.systemPrompt.default, 6 | modelName: inputSchema.properties.modelName.default, 7 | modelMaxOutputTokens: inputSchema.properties.modelMaxOutputTokens.default, 8 | maxNumberOfToolCallsPerQuery: inputSchema.properties.maxNumberOfToolCallsPerQuery.default, 9 | toolCallTimeoutSec: inputSchema.properties.toolCallTimeoutSec.default, 10 | }; 11 | 12 | export const MISSING_PARAMETER_ERROR = `Either provide parameter as Actor input or as query parameter: `; 13 | 14 | export const BASIC_INFORMATION = 'Once you have the Tester MCP Client running, you can ask:\n' 15 | + '- "What Apify Actors I can use"\n' 16 | + '- "Which Actor is the best for scraping Instagram comments"\n' 17 | + "- \"Can you scrape the first 10 pages of Google search results for 'best restaurants in Prague'?\"\n" 18 | + '\n'; 19 | 20 | export const Event = { 21 | ACTOR_STARTED: 'actor-start', 22 | ACTOR_RUNNING_TIME: 'actor-running-time', 23 | INPUT_TOKENS_SONNET_3_7: 'input-tokens-sonnet-3-7', 24 | OUTPUT_TOKENS_SONNET_3_7: 'output-tokens-sonnet-3-7', 25 | INPUT_TOKENS_HAIKU_3_5: 'input-tokens-haiku-3-5', 26 | OUTPUT_TOKENS_HAIKU_3_5: 'output-tokens-haiku-3-5', 27 | INPUT_TOKENS_SONNET_4: 'input-tokens-sonnet-4', 28 | OUTPUT_TOKENS_SONNET_4: 'output-tokens-sonnet-4', 29 | QUERY_ANSWERED: 'query-answered', 30 | }; 31 | 32 | export const CONVERSATION_RECORD_NAME = 'CONVERSATION'; 33 | 34 | export const IMAGE_BASE64_PLACEHOLDER = '[Base64 encoded content - image was pruned to save context tokens]'; 35 | -------------------------------------------------------------------------------- /src/conversationManager.ts: -------------------------------------------------------------------------------- 1 | /** 2 | * Create an MCP client that connects to the server using SSE transport 3 | * 4 | */ 5 | 6 | import { Anthropic } from '@anthropic-ai/sdk'; 7 | import type { ContentBlockParam, Message, MessageParam, TextBlockParam, ImageBlockParam } from '@anthropic-ai/sdk/resources/messages'; 8 | import type { Client } from '@modelcontextprotocol/sdk/client/index.js'; 9 | import type { ListToolsResult, Notification, CallToolResult } from '@modelcontextprotocol/sdk/types.js'; 10 | import { CallToolResultSchema } from '@modelcontextprotocol/sdk/types.js'; 11 | import { log } from 'apify'; 12 | import { EventSource } from 'eventsource'; 13 | 14 | import type { MessageParamWithBlocks, TokenCharger, Tool } from './types.js'; 15 | import { pruneAndFixConversation } from './utils.js'; 16 | 17 | if (typeof globalThis.EventSource === 'undefined') { 18 | globalThis.EventSource = EventSource as unknown as typeof globalThis.EventSource; 19 | } 20 | 21 | // Define a default, can be overridden in constructor 22 | const DEFAULT_MAX_CONTEXT_TOKENS = 200_000; 23 | // Define a safety margin to avoid edge cases 24 | const CONTEXT_TOKEN_SAFETY_MARGIN = 0.99; 25 | // Minimum number of messages to keep in the conversation 26 | // This keeps one round of user and assistant messages 27 | const MIN_CONVERSATION_LENGTH = 2; 28 | 29 | export class ConversationManager { 30 | private conversation: MessageParam[] = []; 31 | private anthropic: Anthropic; 32 | private systemPrompt: string; 33 | private modelName: string; 34 | private modelMaxOutputTokens: number; 35 | private maxNumberOfToolCallsPerQueryRound: number; 36 | private toolCallTimeoutSec: number; 37 | private readonly tokenCharger: TokenCharger | null; 38 | private tools: Tool[] = []; 39 | private readonly maxContextTokens: number; 40 | 41 | constructor( 42 | systemPrompt: string, 43 | modelName: string, 44 | apiKey: string, 45 | modelMaxOutputTokens: number, 46 | maxNumberOfToolCallsPerQuery: number, 47 | toolCallTimeoutSec: number, 48 | tokenCharger: TokenCharger | null = null, 49 | persistedConversation: MessageParam[] = [], 50 | maxContextTokens: number = DEFAULT_MAX_CONTEXT_TOKENS, 51 | ) { 52 | this.systemPrompt = systemPrompt; 53 | this.modelName = modelName; 54 | this.modelMaxOutputTokens = modelMaxOutputTokens; 55 | this.maxNumberOfToolCallsPerQueryRound = maxNumberOfToolCallsPerQuery; 56 | this.toolCallTimeoutSec = toolCallTimeoutSec; 57 | this.tokenCharger = tokenCharger; 58 | this.anthropic = new Anthropic({ apiKey }); 59 | this.conversation = [...persistedConversation]; 60 | this.maxContextTokens = Math.floor(maxContextTokens * CONTEXT_TOKEN_SAFETY_MARGIN); 61 | } 62 | 63 | /** 64 | * Returns a flattened version of the conversation history, splitting messages with multiple content blocks 65 | * into separate messages for each block. Text blocks are returned as individual messages with string content, 66 | * while tool_use and tool_result blocks are returned as messages with a single-element content array. 67 | * 68 | * This is needed because of how the frontend client expects the conversation history to be structured. 69 | * 70 | * @returns {MessageParam[]} The flattened conversation history, with each message containing either a string (for text) 71 | * or an array with a single tool_use/tool_result block. 72 | */ 73 | getConversation(): MessageParam[] { 74 | // split messages blocks into separate messages with text or single block 75 | const result: MessageParam[] = []; 76 | for (const message of this.conversation) { 77 | if (typeof message.content === 'string') { 78 | result.push(message); 79 | continue; 80 | } 81 | 82 | // Handle messages with content blocks 83 | for (const block of message.content) { 84 | if (block.type === 'text') { 85 | result.push({ 86 | role: message.role, 87 | content: block.text || '', 88 | }); 89 | } else if (block.type === 'tool_use' || block.type === 'tool_result') { 90 | result.push({ 91 | role: message.role, 92 | content: [block], 93 | }); 94 | } 95 | } 96 | } 97 | 98 | return result; 99 | } 100 | 101 | resetConversation() { 102 | this.conversation = []; 103 | } 104 | 105 | async handleToolUpdate(listTools: ListToolsResult) { 106 | this.tools = listTools.tools.map((x) => ({ 107 | name: x.name, 108 | description: x.description, 109 | input_schema: x.inputSchema, 110 | })); 111 | log.debug(`Connected to server with tools: ${this.tools.map((x) => x.name)}`); 112 | } 113 | 114 | async updateAndGetTools(mcpClient: Client) { 115 | const tools = await mcpClient.listTools(); 116 | await this.handleToolUpdate(tools); 117 | return this.tools; 118 | } 119 | 120 | /** 121 | * Update client settings with new values 122 | */ 123 | async updateClientSettings(settings: { 124 | systemPrompt?: string; 125 | modelName?: string; 126 | modelMaxOutputTokens?: number; 127 | maxNumberOfToolCallsPerQuery?: number; 128 | toolCallTimeoutSec?: number; 129 | }): Promise { 130 | if (settings.systemPrompt !== undefined) this.systemPrompt = settings.systemPrompt; 131 | if (settings.modelName !== undefined && settings.modelName !== this.modelName) this.modelName = settings.modelName; 132 | if (settings.modelMaxOutputTokens !== undefined) this.modelMaxOutputTokens = settings.modelMaxOutputTokens; 133 | if (settings.maxNumberOfToolCallsPerQuery !== undefined) this.maxNumberOfToolCallsPerQueryRound = settings.maxNumberOfToolCallsPerQuery; 134 | if (settings.toolCallTimeoutSec !== undefined) this.toolCallTimeoutSec = settings.toolCallTimeoutSec; 135 | 136 | return true; 137 | } 138 | 139 | // /** 140 | // * Adds fake tool_result messages for tool_use messages that don't have a corresponding tool_result message. 141 | // * @returns 142 | // */ 143 | // private fixToolResult() { 144 | // // Storing both in case the messages are in the wrong order 145 | // const toolUseIDs = new Set(); 146 | // const toolResultIDs = new Set(); 147 | // 148 | // for (let m = 0; m < this.conversation.length; m++) { 149 | // const message = this.conversation[m]; 150 | // 151 | // if (typeof message.content === 'string') continue; 152 | // 153 | // // Handle messages with content blocks 154 | // const contentBlocks = message.content as ContentBlockParam[]; 155 | // for (let i = 0; i < contentBlocks.length; i++) { 156 | // const block = contentBlocks[i]; 157 | // if (block.type === 'tool_use') { 158 | // toolUseIDs.add(block.id); 159 | // } else if (block.type === 'tool_result') { 160 | // toolResultIDs.add(block.tool_use_id); 161 | // } 162 | // } 163 | // } 164 | // const toolUseIDsWithoutResult = Array.from(toolUseIDs).filter((id) => !toolResultIDs.has(id)); 165 | // 166 | // if (toolUseIDsWithoutResult.length < 1) { 167 | // return; 168 | // } 169 | // 170 | // const fixedConversation: MessageParam[] = []; 171 | // for (let m = 0; m < this.conversation.length; m++) { 172 | // const message = this.conversation[m]; 173 | // 174 | // fixedConversation.push(message); 175 | // // Handle messages with content blocks 176 | // if (typeof message.content === 'string') continue; 177 | // 178 | // const contentBlocks = message.content as ContentBlockParam[]; 179 | // for (let i = 0; i < contentBlocks.length; i++) { 180 | // const block = contentBlocks[i]; 181 | // if (block.type === 'tool_use' && toolUseIDsWithoutResult.includes(block.id)) { 182 | // log.debug(`Adding fake tool_result message for tool_use with ID: ${block.id}`); 183 | // fixedConversation.push({ 184 | // role: 'user', 185 | // content: [ 186 | // { 187 | // type: 'tool_result', 188 | // tool_use_id: block.id, 189 | // content: '[Tool use without result - most likely tool failed or response was too large to be sent to LLM]', 190 | // }, 191 | // ], 192 | // }); 193 | // } 194 | // } 195 | // } 196 | // this.conversation = fixedConversation; 197 | // } 198 | 199 | /** 200 | * Count the number of tokens in the conversation history using Anthropic's API. 201 | * @returns The number of tokens in the conversation. 202 | */ 203 | private async countTokens(messages: MessageParam[]): Promise { 204 | if (messages.length === 0) { 205 | return 0; 206 | } 207 | try { 208 | const response = await this.anthropic.messages.countTokens({ 209 | model: this.modelName, 210 | messages, 211 | system: this.systemPrompt, 212 | tools: this.tools as any[], // eslint-disable-line @typescript-eslint/no-explicit-any 213 | }); 214 | return response.input_tokens ?? 0; 215 | } catch (error) { 216 | log.warning(`Error counting tokens: ${error instanceof Error ? error.message : String(error)}`); 217 | return Infinity; 218 | } 219 | } 220 | 221 | /** 222 | * Ensures the conversation history does not exceed the maximum token limit. 223 | * Removes oldest messages if necessary. 224 | */ 225 | private async ensureContextWindowLimit(): Promise { 226 | if (this.conversation.length <= MIN_CONVERSATION_LENGTH) { 227 | return; 228 | } 229 | 230 | let currentTokens = await this.countTokens(this.conversation); 231 | log.debug(`[Context truncation] Current token count: ${currentTokens}, max allowed: ${this.maxContextTokens}`); 232 | if (currentTokens <= this.maxContextTokens) { 233 | log.info(`[Context truncation] Current token count (${currentTokens}) is within limit (${this.maxContextTokens}). No truncation needed.`); 234 | return; 235 | } 236 | 237 | log.info(`[Context truncation] Current token count (${currentTokens}) exceeds limit (${this.maxContextTokens}). Truncating conversation...`); 238 | const initialMessagesCount = this.conversation.length; 239 | 240 | while (currentTokens > this.maxContextTokens && this.conversation.length > MIN_CONVERSATION_LENGTH) { 241 | try { 242 | log.debug(`[Context truncation] Current token count: ${currentTokens}, removing oldest message... total messages length: ${this.conversation.length}`); 243 | // Truncate oldest user and assistant messages round 244 | // This has to be done because otherwise if we just remove the oldest message 245 | // we end up with more context token than we started with (it does not make sense but it happens) 246 | this.conversation.shift(); 247 | this.conversation.shift(); 248 | this.printConversation(); 249 | this.conversation = pruneAndFixConversation(this.conversation); 250 | currentTokens = await this.countTokens(this.conversation); 251 | log.debug(`[Context truncation] New token count after removal: ${currentTokens}`); 252 | // Wait for a short period to avoid hitting the API too quickly 253 | await new Promise((resolve) => { 254 | setTimeout(() => resolve(), 5); 255 | }); 256 | } catch (error) { 257 | log.error(`Error during context window limit check: ${error instanceof Error ? error.message : String(error)}`); 258 | break; 259 | } 260 | } 261 | log.info(`[Context truncation] Finished. Removed ${initialMessagesCount - this.conversation.length} messages. ` 262 | + `Current token count: ${currentTokens}. Messages remaining: ${this.conversation.length}.`); 263 | // This is here mostly like a safety net, but it should not be needed 264 | this.conversation = pruneAndFixConversation(this.conversation); 265 | } 266 | 267 | /** 268 | * @internal 269 | * Debugging helper function that prints the current conversation state to the log. 270 | * Iterates through all messages in the conversation, logging their roles and a truncated preview of their content. 271 | * For messages with content blocks, logs details for each block, including text, tool usage, and tool results. 272 | * Useful for inspecting the structure and flow of the conversation during development or troubleshooting. 273 | */ 274 | private printConversation() { 275 | log.debug(`[internal] createMessageWithRetry conversation length: ${this.conversation.length}`); 276 | for (const message of this.conversation) { 277 | log.debug(`[internal] ----- createMessageWithRetry message role: ${message.role} -----`); 278 | if (typeof message.content === 'string') { 279 | log.debug(`[internal] createMessageWithRetry message content: ${message.role}: ${message.content.substring(0, 50)}...`); 280 | continue; 281 | } 282 | for (const block of message.content) { 283 | if (block.type === 'text') { 284 | log.debug(`[internal] createMessageWithRetry block text: ${message.role}: ${block.text?.substring(0, 50)}...`); 285 | } else if (block.type === 'tool_use') { 286 | log.debug(`[internal] createMessageWithRetry block tool_use: ${block.name}, input: ${JSON.stringify(block.input).substring(0, 50)}...`); 287 | } else if (block.type === 'tool_result') { 288 | const content = typeof block.content === 'string' ? block.content.substring(0, 50) : JSON.stringify(block.content).substring(0, 50); 289 | log.debug(`[internal] createMessageWithRetry block tool_result: ${block.tool_use_id}, content: ${content}...`); 290 | } 291 | } 292 | } 293 | } 294 | 295 | private async createMessageWithRetry( 296 | maxRetries = 3, 297 | retryDelayMs = 2000, // 2 seconds 298 | ): Promise { 299 | // Check context window before API call 300 | // TODO pruneAndFix could be a class function, I had it there but I had to revert because of images size 301 | this.conversation = pruneAndFixConversation(this.conversation); 302 | await this.ensureContextWindowLimit(); 303 | 304 | let lastError: Error | null = null; 305 | for (let attempt = 1; attempt <= maxRetries; attempt++) { 306 | try { 307 | log.debug(`Making API call with ${this.conversation.length} messages`); 308 | const response = await this.anthropic.messages.create({ 309 | model: this.modelName, 310 | max_tokens: this.modelMaxOutputTokens, 311 | messages: this.conversation, 312 | system: this.systemPrompt, 313 | tools: this.tools as any[], // eslint-disable-line @typescript-eslint/no-explicit-any 314 | }); 315 | if (this.tokenCharger && response.usage) { 316 | const inputTokens = response.usage.input_tokens ?? 0; 317 | const outputTokens = response.usage.output_tokens ?? 0; 318 | await this.tokenCharger.chargeTokens(inputTokens, outputTokens, this.modelName); 319 | } 320 | return response; 321 | } catch (error) { 322 | lastError = error as Error; 323 | if (error instanceof Error) { 324 | // Log conversation state for debugging 325 | if (error.message.includes('tool_use_id') || error.message.includes('tool_result') || error.message.includes('at least one message')) { 326 | const conversationDebug = this.conversation.map((msg, index) => ({ 327 | index, 328 | role: msg.role, 329 | contentTypes: Array.isArray(msg.content) 330 | ? msg.content.map((block) => block.type) 331 | : 'string', 332 | contentLength: typeof msg.content === 'string' ? msg.content.length : msg.content.length, 333 | })); 334 | 335 | log.error('Conversation structure error. Current conversation:', { 336 | conversationLength: this.conversation.length, 337 | conversation: conversationDebug, 338 | }); 339 | } 340 | if (error.message.includes('429') || error.message.includes('529')) { 341 | if (attempt < maxRetries) { 342 | const delay = attempt * retryDelayMs; 343 | const errorType = error.message.includes('429') ? 'Rate limit' : 'Server overload'; 344 | log.debug(`${errorType} hit, attempt ${attempt}/${maxRetries}. Retrying in ${delay / 1000} seconds...`); 345 | await new Promise((resolve) => { 346 | setTimeout(() => resolve(), delay); 347 | }); 348 | continue; 349 | } else { 350 | const errorType = error.message.includes('429') ? 'Rate limit' : 'Server overload'; 351 | const errorMsg = errorType === 'Rate limit' 352 | ? `Rate limit exceeded after ${maxRetries} attempts. Please try again in a few minutes or consider switching to a different model` 353 | : 'Server is currently experiencing high load. Please try again in a few moments or consider switching to a different model.'; 354 | throw new Error(errorMsg); 355 | } 356 | } 357 | } 358 | // For other errors, throw immediately 359 | throw error; 360 | } 361 | } 362 | throw lastError ?? new Error('Unknown error after retries in createMessageWithRetry'); 363 | } 364 | 365 | /** 366 | * Handles the response from the LLM (Large Language Model), processes text and tool_use blocks, 367 | * emits SSE events, manages tool execution, and recursively continues the conversation as needed. 368 | * 369 | * ## Flow: 370 | * 1. Processes all text blocks in the LLM response and emits them as assistant messages. 371 | * 2. Gathers all tool_use blocks: 372 | * - If tool_use blocks are present and the tool call limit is reached, emits a warning and stops further tool calls. 373 | * - Otherwise, emits tool_use blocks as assistant messages. 374 | * - The assistant message (containing only text) is added to the conversation history. 375 | * 3. If there are no tool_use blocks, the function returns (end of this response cycle). 376 | * 4. For each tool_use block: 377 | * - Calls the corresponding tool using the provided client. 378 | * - Emits the tool result (or error) as a user message via SSE. 379 | * - Appends the tool result to the conversation. 380 | * 5. After processing all tool_use blocks, requests the next response from the LLM (using updated conversation). 381 | * 6. Recursively calls itself to process the next LLM response, incrementing the tool call round counter. 382 | * 383 | * @param client - The MCP client used to call tools. 384 | * @param response - The LLM response message to process. 385 | * @param sseEmit - Function to emit SSE events to the client (role, content). 386 | * @param toolCallCountRound - The current round of tool calls for this query (used to enforce limits). 387 | * @returns A promise that resolves when the response and all recursive tool calls are fully processed. 388 | */ 389 | async handleLLMResponse(client: Client, response: Message, sseEmit: (role: string, content: string | ContentBlockParam[]) => void, toolCallCountRound = 0) { 390 | log.debug(`[internal] handleLLMResponse: ${JSON.stringify(response)}`); 391 | 392 | // Refactored: preserve block order as received 393 | const assistantMessage: MessageParamWithBlocks = { 394 | role: 'assistant', 395 | content: [], 396 | }; 397 | const toolUseBlocks: ContentBlockParam[] = []; 398 | for (const block of response.content) { 399 | if (block.type === 'text') { 400 | assistantMessage.content.push(block); 401 | log.debug(`[internal] emitting SSE text message: ${block.text}`); 402 | sseEmit('assistant', block.text || ''); 403 | } else if (block.type === 'tool_use') { 404 | if (toolCallCountRound >= this.maxNumberOfToolCallsPerQueryRound) { 405 | // Tool call limit hit before any tool_use is processed 406 | const msg = `Too many tool calls in a single turn! This has been implemented to prevent infinite loops.\nLimit is ${this.maxNumberOfToolCallsPerQueryRound}.\nYou can increase the limit by setting the "maxNumberOfToolCallsPerQuery" parameter.`; 407 | assistantMessage.content.push({ 408 | type: 'text', 409 | text: msg, 410 | }); 411 | log.debug(`[internal] emitting SSE tool limit message: ${msg}`); 412 | sseEmit('assistant', msg); 413 | this.conversation.push(assistantMessage); 414 | break; 415 | } 416 | assistantMessage.content.push(block); 417 | log.debug(`[internal] emitting SSE tool_use message: ${JSON.stringify(block)}`); 418 | sseEmit('assistant', [block]); 419 | toolUseBlocks.push(block); 420 | } 421 | } 422 | // Add the assistant message to the conversation 423 | // Assistant's turn is finished here, now we proceed with user if there are tool_use blocks 424 | // if not we just return 425 | this.conversation.push(assistantMessage); 426 | // If no tool_use blocks, we can return early 427 | if (toolUseBlocks.length === 0) { 428 | log.debug('[internal] No tool_use blocks found, returning from handleLLMResponse'); 429 | return; 430 | } 431 | 432 | // Handle tool_use blocks 433 | // call tools and append and emit tool result messages 434 | const userToolResultsMessage: MessageParamWithBlocks = { 435 | role: 'user', 436 | content: [], 437 | }; 438 | for (const block of toolUseBlocks) { 439 | if (block.type !== 'tool_use') continue; // Type guard 440 | // eslint-disable-next-line @typescript-eslint/no-explicit-any 441 | const params = { name: block.name, arguments: block.input as any }; 442 | log.debug(`[internal] Calling tool (count: ${toolCallCountRound}): ${JSON.stringify(params)}`); 443 | const toolResultBlock: ContentBlockParam = { 444 | type: 'tool_result', 445 | tool_use_id: block.id, 446 | content: [], 447 | is_error: false, 448 | }; 449 | try { 450 | const results = await client.callTool(params, CallToolResultSchema, { timeout: this.toolCallTimeoutSec * 1000 }); 451 | if (results && typeof results === 'object' && 'content' in results) { 452 | toolResultBlock.content = this.processToolResults(results as CallToolResult, params.name); 453 | } else { 454 | log.warning(`Tool ${params.name} returned unexpected result format:`, results); 455 | toolResultBlock.content = [{ 456 | type: 'text', 457 | text: `Tool "${params.name}" returned unexpected result format: ${JSON.stringify(results, null, 2)}`, 458 | }]; 459 | } 460 | } catch (error) { 461 | log.error(`Error when calling tool ${params.name}: ${error}`); 462 | toolResultBlock.content = [{ 463 | type: 'text', 464 | text: `Error when calling tool ${params.name}, error: ${error}`, 465 | }]; 466 | toolResultBlock.is_error = true; 467 | } 468 | 469 | userToolResultsMessage.content.push(toolResultBlock); 470 | log.debug(`[internal] emitting SSE tool_result message: ${JSON.stringify(toolResultBlock)}`); 471 | sseEmit('user', [toolResultBlock]); 472 | } 473 | 474 | // Add the user tool results message to the conversation 475 | this.conversation.push(userToolResultsMessage); 476 | // If we have tool results, we need to get the next response from the model 477 | log.debug('[internal] Get model response from tool result'); 478 | const nextResponse: Message = await this.createMessageWithRetry(); 479 | log.debug('[internal] Received response from model'); 480 | // Process the next response recursively 481 | await this.handleLLMResponse(client, nextResponse, sseEmit, toolCallCountRound + 1); 482 | log.debug('[internal] Finished processing tool result'); 483 | } 484 | 485 | /** 486 | * Process a user query: 487 | * 1) Use Anthropic to generate a response (which may contain "tool_use"). 488 | * 2) If "tool_use" is present, call the main actor's tool via `this.mcpClient.callTool()`. 489 | * 3) Return or yield partial results so we can SSE them to the browser. 490 | */ 491 | async processUserQuery(client: Client, query: string, sseEmit: (role: string, content: string | ContentBlockParam[]) => void) { 492 | log.debug(`[internal] Call LLM with user query: ${JSON.stringify(query)}`); 493 | this.conversation.push({ role: 'user', content: query }); 494 | 495 | try { 496 | const response = await this.createMessageWithRetry(); 497 | log.debug(`[internal] Received response: ${JSON.stringify(response.content)}`); 498 | log.debug(`[internal] Token count: ${JSON.stringify(response.usage)}`); 499 | await this.handleLLMResponse(client, response, sseEmit); 500 | } catch (error) { 501 | const errorMsg = error instanceof Error ? error.message : String(error); 502 | this.conversation.push({ role: 'assistant', content: errorMsg }); 503 | sseEmit('assistant', errorMsg); 504 | throw new Error(errorMsg); 505 | } 506 | } 507 | 508 | handleNotification(notification: Notification) { 509 | // Implement logic to handle the notification 510 | log.info(`Handling notification: ${JSON.stringify(notification)}`); 511 | // You can update the conversation or perform other actions based on the notification 512 | } 513 | 514 | /** 515 | * Process tool call results and convert them into appropriate content blocks 516 | */ 517 | private processToolResults(results: CallToolResult, toolName: string): (TextBlockParam | ImageBlockParam)[] { 518 | if (!results.content || !Array.isArray(results.content) || results.content.length === 0) { 519 | return [{ 520 | type: 'text', 521 | text: `No results retrieved from ${toolName}`, 522 | }]; 523 | } 524 | const processedContent: (TextBlockParam | ImageBlockParam)[] = []; 525 | processedContent.push({ 526 | type: 'text', 527 | text: `Tool "${toolName}" executed successfully. Results:`, 528 | }); 529 | for (const item of results.content) { 530 | if (item.type === 'image' && item.data) { 531 | const mediaType = this.detectImageFormat(item.data); 532 | log.debug(`Detected image format: ${mediaType}`); 533 | processedContent.push({ 534 | type: 'image', 535 | source: { 536 | type: 'base64', 537 | media_type: mediaType, 538 | data: item.data, 539 | }, 540 | }); 541 | continue; 542 | } 543 | if (item.type === 'text' && item.text) { 544 | processedContent.push({ 545 | type: 'text', 546 | text: item.text, 547 | }); 548 | continue; 549 | } 550 | // Other data types 551 | if (item.data) { 552 | processedContent.push({ 553 | type: 'text', 554 | text: typeof item.data === 'string' ? item.data : JSON.stringify(item.data, null, 2), 555 | }); 556 | } 557 | } 558 | return processedContent; 559 | } 560 | 561 | /** 562 | * Detect image format from base64 data 563 | */ 564 | private detectImageFormat(imageData: string): 'image/png' | 'image/jpeg' | 'image/webp' | 'image/gif' { 565 | try { 566 | const header = imageData.substring(0, 20); 567 | if (header.startsWith('/9j/')) { 568 | return 'image/jpeg'; 569 | } 570 | if (header.startsWith('iVBORw0KGgo')) { 571 | return 'image/png'; 572 | } 573 | // Binary signature detection 574 | const binaryString = atob(imageData.substring(0, 20)); 575 | const bytes = new Uint8Array(binaryString.length); 576 | for (let i = 0; i < binaryString.length; i++) { 577 | bytes[i] = binaryString.charCodeAt(i); 578 | } 579 | // PNG signature: 89 50 4E 47 0D 0A 1A 0A 580 | if (bytes[0] === 0x89 && bytes[1] === 0x50 && bytes[2] === 0x4E && bytes[3] === 0x47) { 581 | return 'image/png'; 582 | } 583 | if (bytes[0] === 0xFF && bytes[1] === 0xD8 && bytes[2] === 0xFF) { 584 | return 'image/jpeg'; 585 | } 586 | if (bytes[0] === 0x52 && bytes[1] === 0x49 && bytes[2] === 0x46 && bytes[3] === 0x46) { 587 | return 'image/webp'; 588 | } 589 | return 'image/png'; // Default fallback 590 | } catch (error) { 591 | log.warning(`Could not detect image format, using default PNG: ${error}`); 592 | return 'image/png'; 593 | } 594 | } 595 | } 596 | -------------------------------------------------------------------------------- /src/counter.ts: -------------------------------------------------------------------------------- 1 | export class Counter { 2 | private count: number; 3 | 4 | constructor(value = 0) { 5 | this.count = value; 6 | } 7 | 8 | /** 9 | * Increments the counter by 1 10 | * @returns incremented value of counter 11 | */ 12 | increment(): number { 13 | return ++this.count; 14 | } 15 | } 16 | -------------------------------------------------------------------------------- /src/input.ts: -------------------------------------------------------------------------------- 1 | import { defaults, MISSING_PARAMETER_ERROR } from './const.js'; 2 | import { log } from './logger.js'; 3 | import type { Input, StandbyInput } from './types.js'; 4 | 5 | let isChargingForTokens = true; 6 | 7 | export function getChargeForTokens() { 8 | return isChargingForTokens; 9 | } 10 | 11 | /** 12 | * Process input parameters, split actors string into an array 13 | * @param originalInput 14 | * @returns input 15 | */ 16 | export function processInput(originalInput: Partial | Partial): Input { 17 | const input = { ...defaults, ...originalInput } as StandbyInput; 18 | 19 | // MCP SSE URL is deprecated, use MCP URL instead 20 | if (input.mcpSseUrl && !input.mcpUrl) { 21 | input.mcpUrl = input.mcpSseUrl; 22 | } 23 | if (!input.mcpUrl) { 24 | throw new Error(`MCP Server URL is not provided. ${MISSING_PARAMETER_ERROR}: 'mcpUrl'`); 25 | } 26 | 27 | if (input.mcpTransportType === 'http-streamable-json-response' && input.mcpUrl.includes('/sse')) { 28 | throw new Error(`MCP URL includes /sse path, but the transport is set to 'http-streamable'. This is very likely a mistake.`); 29 | } 30 | 31 | if (input.mcpUrl.includes('/sse')) { 32 | input.mcpTransportType = 'sse'; 33 | } else { 34 | input.mcpTransportType = 'http-streamable-json-response'; 35 | } 36 | 37 | if (!input.headers) { 38 | input.headers = {}; 39 | } 40 | if (input.headers && typeof input.headers === 'string') { 41 | try { 42 | input.headers = JSON.parse(input.headers); 43 | } catch (error) { 44 | throw new Error(`Invalid JSON string in headers: ${(error as Error).message}`); 45 | } 46 | } 47 | // Automatically add APIFY_TOKEN to Authorization header (if not present) 48 | if (typeof input.headers === 'object' && !('Authorization' in input.headers) && process.env.APIFY_TOKEN) { 49 | input.headers = { ...input.headers, Authorization: `Bearer ${process.env.APIFY_TOKEN}` }; 50 | } 51 | 52 | if (!input.modelName) { 53 | throw new Error(`LLM model name is not provided. ${MISSING_PARAMETER_ERROR}: 'modelName'`); 54 | } 55 | 56 | if (input.llmProviderApiKey && input.llmProviderApiKey !== '') { 57 | log.info('Using user provided API key for an LLM provider'); 58 | isChargingForTokens = false; 59 | } else { 60 | log.info('No API key provided for an LLM provider, Actor will charge for tokens usage'); 61 | input.llmProviderApiKey = process.env.LLM_PROVIDER_API_KEY ?? ''; 62 | } 63 | return input as Input; 64 | } 65 | -------------------------------------------------------------------------------- /src/logger.ts: -------------------------------------------------------------------------------- 1 | import { log } from 'apify'; 2 | 3 | log.setLevel(log.LEVELS.DEBUG); 4 | 5 | export { log }; 6 | -------------------------------------------------------------------------------- /src/main.ts: -------------------------------------------------------------------------------- 1 | /** 2 | * # Chatbot Server with Real-Time Tool Execution 3 | * 4 | * Server for a chatbot integrated with Apify Actors and an MCP client. 5 | * Processes user queries, invokes tools dynamically, and streams real-time updates using Server-Sent Events (SSE) 6 | * 7 | * Environment variables: 8 | * - `APIFY_TOKEN` - API token for Apify (when using actors-mcp-server) 9 | */ 10 | 11 | import path from 'path'; 12 | import { fileURLToPath } from 'url'; 13 | 14 | import type { MessageParam } from '@anthropic-ai/sdk/resources/index.js'; 15 | import type { Client } from '@modelcontextprotocol/sdk/client/index.js'; 16 | import { Actor } from 'apify'; 17 | import cors from 'cors'; 18 | import dotenv from 'dotenv'; 19 | import express from 'express'; 20 | 21 | import { createClient } from './clientFactory.js'; 22 | import { BASIC_INFORMATION, CONVERSATION_RECORD_NAME, Event } from './const.js'; 23 | import { ConversationManager } from './conversationManager.js'; 24 | import { Counter } from './counter.js'; 25 | import { processInput, getChargeForTokens } from './input.js'; 26 | import { log } from './logger.js'; 27 | import type { TokenCharger, Input } from './types.js'; 28 | import inputSchema from '../.actor/input_schema.json' with { type: 'json' }; 29 | 30 | await Actor.init(); 31 | 32 | /** 33 | * Charge for token usage 34 | * We don't want to implement this in the MCPClient as we want to have MCP Client independent of Apify Actor 35 | */ 36 | export class ActorTokenCharger implements TokenCharger { 37 | async chargeTokens(inputTokens: number, outputTokens: number, modelName: string): Promise { 38 | let eventNameInput: string; 39 | let eventNameOutput: string; 40 | switch (modelName) { 41 | case 'claude-3-5-haiku-latest': 42 | eventNameInput = Event.INPUT_TOKENS_HAIKU_3_5; 43 | eventNameOutput = Event.OUTPUT_TOKENS_HAIKU_3_5; 44 | break; 45 | case 'claude-3-7-sonnet-latest': 46 | eventNameInput = Event.INPUT_TOKENS_SONNET_3_7; 47 | eventNameOutput = Event.OUTPUT_TOKENS_SONNET_3_7; 48 | break; 49 | case 'claude-sonnet-4-0': 50 | eventNameInput = Event.INPUT_TOKENS_SONNET_4; 51 | eventNameOutput = Event.OUTPUT_TOKENS_SONNET_4; 52 | break; 53 | default: 54 | eventNameInput = Event.INPUT_TOKENS_SONNET_4; 55 | eventNameOutput = Event.OUTPUT_TOKENS_SONNET_4; 56 | break; 57 | } 58 | try { 59 | await Actor.charge({ eventName: eventNameInput, count: Math.ceil(inputTokens / 100) }); 60 | await Actor.charge({ eventName: eventNameOutput, count: Math.ceil(outputTokens / 100) }); 61 | log.info(`Charged ${inputTokens} input tokens (query+tools) and ${outputTokens} output tokens`); 62 | } catch (error) { 63 | log.error('Failed to charge for token usage', { error }); 64 | throw error; 65 | } 66 | } 67 | } 68 | 69 | // Add after Actor.init() 70 | const RUNNING_TIME_INTERVAL = 5 * 60 * 1000; // 5 minutes in milliseconds 71 | setInterval(async () => { 72 | try { 73 | log.info('Charging for running time (every 5 minutes)'); 74 | await Actor.charge({ eventName: Event.ACTOR_RUNNING_TIME }); 75 | } catch (error) { 76 | log.error('Failed to charge for running time', { error }); 77 | } 78 | }, RUNNING_TIME_INTERVAL); 79 | 80 | try { 81 | log.info('Charging Actor start event.'); 82 | await Actor.charge({ eventName: Event.ACTOR_STARTED }); 83 | } catch (error) { 84 | log.error('Failed to charge for actor start event', { error }); 85 | await Actor.exit('Failed to charge for actor start event'); 86 | } 87 | 88 | const STANDBY_MODE = Actor.getEnv().metaOrigin === 'STANDBY'; 89 | const ACTOR_IS_AT_HOME = Actor.isAtHome(); 90 | let HOST: string | undefined; 91 | let PORT: string | undefined; 92 | 93 | if (ACTOR_IS_AT_HOME) { 94 | HOST = STANDBY_MODE ? process.env.ACTOR_STANDBY_URL : process.env.ACTOR_WEB_SERVER_URL; 95 | PORT = ACTOR_IS_AT_HOME ? process.env.ACTOR_STANDBY_PORT : process.env.ACTOR_WEB_SERVER_PORT; 96 | } else { 97 | const filename = fileURLToPath(import.meta.url); 98 | const dirname = path.dirname(filename); 99 | dotenv.config({ path: path.resolve(dirname, '../.env') }); 100 | HOST = 'http://localhost'; 101 | PORT = '5001'; 102 | } 103 | 104 | // Add near the top after Actor.init() 105 | let ACTOR_TIMEOUT_AT: number | undefined; 106 | try { 107 | ACTOR_TIMEOUT_AT = process.env.ACTOR_TIMEOUT_AT ? new Date(process.env.ACTOR_TIMEOUT_AT).getTime() : undefined; 108 | } catch { 109 | ACTOR_TIMEOUT_AT = undefined; 110 | } 111 | 112 | const actorInput = (await Actor.getInput>()) ?? ({} as Input); 113 | const input = processInput(actorInput ?? ({} as Input)); 114 | 115 | log.debug(`systemPrompt: ${input.systemPrompt}`); 116 | log.debug(`mcpUrl: ${input.mcpUrl}`); 117 | log.debug(`mcpTransport: ${input.mcpTransportType}`); 118 | log.debug(`modelName: ${input.modelName}`); 119 | 120 | if (!input.llmProviderApiKey) { 121 | log.error('No API key provided for LLM provider. Report this issue to Actor developer.'); 122 | await Actor.exit('No API key provided for LLM provider. Report this issue to Actor developer.'); 123 | } 124 | 125 | let runtimeSettings = { 126 | mcpUrl: input.mcpUrl, 127 | mcpTransportType: input.mcpTransportType, 128 | systemPrompt: input.systemPrompt, 129 | modelName: input.modelName, 130 | modelMaxOutputTokens: input.modelMaxOutputTokens, 131 | maxNumberOfToolCallsPerQuery: input.maxNumberOfToolCallsPerQuery, 132 | toolCallTimeoutSec: input.toolCallTimeoutSec, 133 | }; 134 | 135 | const app = express(); 136 | app.use(express.json()); 137 | app.use(cors()); 138 | 139 | // Serve your public folder (where index.html is located) 140 | const filename = fileURLToPath(import.meta.url); 141 | const publicPath = path.join(path.dirname(filename), 'public'); 142 | const publicUrl = ACTOR_IS_AT_HOME ? HOST : `${HOST}:${PORT}`; 143 | app.use(express.static(publicPath)); 144 | 145 | const persistedConversation = (await Actor.getValue(CONVERSATION_RECORD_NAME)) ?? []; 146 | const conversationCounter = new Counter(persistedConversation.length); 147 | 148 | const conversationManager = new ConversationManager( 149 | input.systemPrompt, 150 | input.modelName, 151 | input.llmProviderApiKey, 152 | input.modelMaxOutputTokens, 153 | input.maxNumberOfToolCallsPerQuery, 154 | input.toolCallTimeoutSec, 155 | getChargeForTokens() ? new ActorTokenCharger() : null, 156 | persistedConversation, 157 | ); 158 | 159 | // This should not be needed, but just in case 160 | Actor.on('migrating', async () => { 161 | log.debug(`Migrating ... persisting conversation.`); 162 | await Actor.setValue(CONVERSATION_RECORD_NAME, conversationManager.getConversation()); 163 | }); 164 | 165 | // Only one browser client can be connected at a time 166 | type BrowserSSEClient = { id: number; res: express.Response }; 167 | let browserClients: BrowserSSEClient[] = []; 168 | let nextClientId = 1; 169 | 170 | // Create a single instance of your MCP client (client is connected to the MCP-server) 171 | let client: Client | null = null; 172 | 173 | // 5) SSE endpoint for the client.js (browser) 174 | app.get('/sse', async (req, res) => { 175 | // Required headers for SSE 176 | res.set({ 177 | 'Content-Type': 'text/event-stream', 178 | 'Cache-Control': 'no-cache', 179 | Connection: 'keep-alive', 180 | 'X-Accel-Buffering': 'no', // Disable proxy buffering 181 | }); 182 | res.flushHeaders(); 183 | 184 | const clientId = nextClientId++; 185 | const keepAliveInterval = setInterval(() => { 186 | res.write(':\n\n'); // Send a comment as a keepalive 187 | }, 5000); // Send keepalive every 5 seconds 188 | 189 | browserClients.push({ id: clientId, res }); 190 | log.debug(`Browser client ${clientId} connected`); 191 | 192 | // If a client closes connection, clear an interval and remove from an array 193 | req.on('close', () => { 194 | log.debug(`Browser client ${clientId} disconnected`); 195 | clearInterval(keepAliveInterval); 196 | browserClients = browserClients.filter((browserClient) => browserClient.id !== clientId); 197 | }); 198 | 199 | // Handle client timeout 200 | req.on('timeout', () => { 201 | log.debug(`Browser client ${clientId} timeout`); 202 | clearInterval(keepAliveInterval); 203 | browserClients = browserClients.filter((browserClient) => browserClient.id !== clientId); 204 | res.end(); 205 | }); 206 | }); 207 | 208 | /** 209 | * Helper function to create or get existing MCP client 210 | * @returns Client instance or throws error 211 | */ 212 | async function getOrCreateClient(): Promise { 213 | log.debug('Getting or creating MCP client'); 214 | if (!client) { 215 | log.debug('Creating new MCP client'); 216 | try { 217 | client = await createClient( 218 | runtimeSettings.mcpUrl, 219 | runtimeSettings.mcpTransportType, 220 | input.headers, 221 | async (tools) => await conversationManager.handleToolUpdate(tools), 222 | (notification) => conversationManager.handleNotification(notification), 223 | ); 224 | } catch (err) { 225 | const error = err as Error; 226 | log.error('Failed to connect to MCP server', { error: error.message, stack: error.stack }); 227 | throw new Error(`${error.message}`); 228 | } 229 | } 230 | return client; 231 | } 232 | 233 | /** 234 | * Helper function to handle client cleanup based on transport type 235 | */ 236 | async function cleanupClient(): Promise { 237 | if (input.mcpTransportType === 'http-streamable-json-response' && client) { 238 | try { 239 | await client.close(); 240 | client = null; 241 | } catch (err) { 242 | const error = err as Error; 243 | log.error('Failed to close client connection', { error: error.message, stack: error.stack }); 244 | } 245 | } 246 | } 247 | 248 | // /message endpoint for the client.js (browser) 249 | app.post('/message', async (req, res) => { 250 | const { query } = req.body; 251 | if (!query) return res.status(400).json({ error: 'Missing "query" field' }); 252 | 253 | try { 254 | // Process the query 255 | await Actor.pushData({ role: 'user', content: query }); 256 | const mcpClient = await getOrCreateClient(); 257 | await conversationManager.processUserQuery(mcpClient, query, async (role, content) => { 258 | // Key used for sorting messages in the client UI 259 | const key = conversationCounter.increment(); 260 | await broadcastSSE({ 261 | role, 262 | content, 263 | key, 264 | }); 265 | }); 266 | // Charge for task completion 267 | await Actor.charge({ eventName: Event.QUERY_ANSWERED, count: 1 }); 268 | log.info(`Charged query answered event`); 269 | 270 | // Send a finished flag 271 | await broadcastSSE({ role: 'system', content: '', finished: true }); 272 | return res.json({ ok: true }); 273 | } catch (err) { 274 | const error = err as Error; 275 | log.exception(error, `Error in processing user query: ${query}`); 276 | // Send finished flag with error 277 | await broadcastSSE({ role: 'system', content: error.message, finished: true, error: true }); 278 | return res.json({ ok: false, error: error.message }); 279 | } 280 | }); 281 | 282 | /** 283 | * Periodically check if the main server is still reachable. 284 | */ 285 | app.get('/reconnect-mcp-server', async (_req, res) => { 286 | try { 287 | const mcpClient = await getOrCreateClient(); 288 | await mcpClient.ping(); 289 | return res.json({ status: 'OK' }); 290 | } catch (err) { 291 | const error = err as Error; 292 | return res.json({ ok: false, error: error.message }); 293 | } 294 | }); 295 | 296 | /** 297 | * GET /client-info endpoint to provide the client with necessary information 298 | */ 299 | app.get('/client-info', (_req, res) => { 300 | res.json({ 301 | mcpUrl: runtimeSettings.mcpUrl, 302 | mcpTransportType: runtimeSettings.mcpTransportType, 303 | systemPrompt: runtimeSettings.systemPrompt, 304 | modelName: runtimeSettings.modelName, 305 | publicUrl, 306 | information: BASIC_INFORMATION, 307 | }); 308 | }); 309 | 310 | /** 311 | * GET /check-timeout endpoint to check if the Actor is about to timeout 312 | */ 313 | app.get('/check-actor-timeout', (_req, res) => { 314 | if (!ACTOR_TIMEOUT_AT) { 315 | return res.json({ timeoutImminent: false }); 316 | } 317 | 318 | const now = Date.now(); 319 | const timeUntilTimeout = ACTOR_TIMEOUT_AT - now; 320 | const timeoutImminent = timeUntilTimeout < 60000; // Less than 1 minute remaining 321 | 322 | return res.json({ 323 | timeoutImminent, 324 | timeUntilTimeout, 325 | timeoutAt: ACTOR_TIMEOUT_AT, 326 | }); 327 | }); 328 | 329 | /** 330 | * POST /conversation/reset to reset the conversation 331 | */ 332 | app.post('/conversation/reset', async (_req, res) => { 333 | log.debug('Resetting conversation'); 334 | conversationManager.resetConversation(); 335 | await Actor.setValue(CONVERSATION_RECORD_NAME, conversationManager.getConversation()); 336 | res.json({ ok: true }); 337 | }); 338 | 339 | /** 340 | * GET /available-tools endpoint to fetch available tools 341 | */ 342 | app.get('/available-tools', async (_req, res) => { 343 | try { 344 | const mcpClient = await getOrCreateClient(); 345 | const tools = await conversationManager.updateAndGetTools(mcpClient); 346 | return res.json({ tools }); 347 | } catch (err) { 348 | const error = err as Error; 349 | log.error(`Error fetching tools: ${error.message}`); 350 | return res.status(500).json({ error: 'Failed to fetch tools' }); 351 | } 352 | }); 353 | 354 | /** 355 | * GET /settings endpoint to retrieve current settings 356 | */ 357 | app.get('/settings', (_req, res) => { 358 | res.json(runtimeSettings); 359 | }); 360 | 361 | /** 362 | * GET /schema/models endpoint to retrieve available model options from input schema 363 | */ 364 | app.get('/schema/models', (_req, res) => { 365 | const { enum: models, enumTitles } = inputSchema.properties.modelName; 366 | const modelOptions = models.map((model: string, index: number) => ({ 367 | value: model, 368 | label: enumTitles[index], 369 | })); 370 | res.json(modelOptions); 371 | }); 372 | 373 | /** 374 | * POST /settings endpoint to update settings 375 | */ 376 | app.post('/settings', async (req, res) => { 377 | try { 378 | const newSettings = req.body; 379 | if (newSettings.mcpUrl !== undefined && !newSettings.mcpUrl) { 380 | res.status(400).json({ success: false, error: 'MCP URL is required' }); 381 | return; 382 | } 383 | if (newSettings.modelName !== undefined && !newSettings.modelName) { 384 | res.status(400).json({ success: false, error: 'Model name is required' }); 385 | return; 386 | } 387 | runtimeSettings = { 388 | ...runtimeSettings, 389 | ...newSettings, 390 | }; 391 | await conversationManager.updateClientSettings({ 392 | systemPrompt: runtimeSettings.systemPrompt, 393 | modelName: runtimeSettings.modelName, 394 | modelMaxOutputTokens: runtimeSettings.modelMaxOutputTokens, 395 | maxNumberOfToolCallsPerQuery: runtimeSettings.maxNumberOfToolCallsPerQuery, 396 | toolCallTimeoutSec: runtimeSettings.toolCallTimeoutSec, 397 | }); 398 | 399 | if (newSettings.mcpUrl !== undefined || newSettings.mcpTransportType !== undefined) { 400 | if (client) { 401 | try { 402 | await client.close(); 403 | } catch (err) { 404 | log.warning('Error closing client connection:', { error: err }); 405 | } 406 | client = null; 407 | } 408 | // The next API request will create a new client with updated settings 409 | } 410 | log.info(`Settings updated: ${JSON.stringify(runtimeSettings)}`); 411 | res.json({ success: true }); 412 | } catch (error) { 413 | log.error('Error updating settings:', { error: (error instanceof Error) ? error.message : String(error) }); 414 | res.status(500).json({ success: false, error: 'Failed to update settings' }); 415 | } 416 | }); 417 | 418 | /** 419 | * POST /settings/reset endpoint to reset settings to defaults 420 | */ 421 | app.post('/settings/reset', async (_req, res) => { 422 | try { 423 | runtimeSettings = { 424 | mcpUrl: input.mcpUrl, 425 | mcpTransportType: input.mcpTransportType, 426 | systemPrompt: input.systemPrompt, 427 | modelName: input.modelName, 428 | modelMaxOutputTokens: input.modelMaxOutputTokens, 429 | maxNumberOfToolCallsPerQuery: input.maxNumberOfToolCallsPerQuery, 430 | toolCallTimeoutSec: input.toolCallTimeoutSec, 431 | }; 432 | await conversationManager.updateClientSettings({ 433 | systemPrompt: runtimeSettings.systemPrompt, 434 | modelName: runtimeSettings.modelName, 435 | modelMaxOutputTokens: runtimeSettings.modelMaxOutputTokens, 436 | maxNumberOfToolCallsPerQuery: runtimeSettings.maxNumberOfToolCallsPerQuery, 437 | toolCallTimeoutSec: runtimeSettings.toolCallTimeoutSec, 438 | }); 439 | 440 | // Close the existing client to force recreation with default settings 441 | if (client) { 442 | try { 443 | await client.close(); 444 | } catch (err) { 445 | log.warning('Error closing client connection:', { error: err }); 446 | } 447 | client = null; 448 | } 449 | res.json({ success: true }); 450 | } catch (error) { 451 | log.error('Error resetting settings:', { error: (error instanceof Error) ? error.message : String(error) }); 452 | res.status(500).json({ success: false, error: 'Failed to reset settings' }); 453 | } 454 | }); 455 | 456 | app.get('/conversation', (_req, res) => { 457 | res.json(conversationManager.getConversation()); 458 | }); 459 | 460 | app.get('*', (_req, res) => { 461 | res.sendFile(path.join(publicPath, 'index.html')); 462 | }); 463 | 464 | /** 465 | * Broadcasts an event to all connected SSE clients 466 | */ 467 | async function broadcastSSE(data: object) { 468 | log.debug('Push data into Apify dataset and persist conversation'); 469 | await Actor.pushData(data); 470 | await Actor.setValue(CONVERSATION_RECORD_NAME, conversationManager.getConversation()); 471 | 472 | log.debug(`Broadcasting message to ${browserClients.length} clients`); 473 | const message = `data: ${JSON.stringify(data)}\n\n`; 474 | browserClients.forEach((browserClient) => { 475 | browserClient.res.write(message); 476 | }); 477 | } 478 | 479 | app.listen(PORT, async () => { 480 | log.info(`Serving from ${path.join(publicPath, 'index.html')}`); 481 | const msg = `Navigate to ${publicUrl} to interact with the chat UI.`; 482 | await Actor.setStatusMessage(msg); 483 | }); 484 | 485 | // Fix Ctrl+C for npm run start 486 | process.on('SIGINT', async () => { 487 | log.info('Received SIGINT. Cleaning up and exiting...'); 488 | await cleanupClient(); 489 | await Actor.exit('SIGINT received'); 490 | }); 491 | -------------------------------------------------------------------------------- /src/public/client.js: -------------------------------------------------------------------------------- 1 | /* eslint-disable no-console */ 2 | // client.js 3 | 4 | // ================== DOM ELEMENTS & GLOBAL STATE ================== 5 | const chatLog = document.getElementById('chatLog'); 6 | const clearBtn = document.getElementById('clearBtn'); 7 | const clientInfo = document.getElementById('clientInfo'); 8 | const information = document.getElementById('information'); 9 | const mcpUrl = document.getElementById('mcpUrl'); 10 | const queryInput = document.getElementById('queryInput'); 11 | const sendBtn = document.getElementById('sendBtn'); 12 | const reconnectMcpServerBtn = document.getElementById('reconnectMcpServerButton'); 13 | const toolsContainer = document.getElementById('availableTools'); 14 | const toolsLoading = document.getElementById('toolsLoading'); 15 | 16 | // State for tracking message processing 17 | let isProcessingMessage = false; 18 | 19 | /** 20 | * Checks if the user is scrolling. 21 | * Determines if the user is not at the bottom of the chat log. 22 | @param {number} tolerance - The tolerance in pixels to consider the user as scrolling (default is 50). 23 | @returns {boolean} - True if the user is scrolling, false otherwise. 24 | */ 25 | function isUserScrolling(tolerance = 50) { 26 | // Check if the user is not at the bottom of the page 27 | return window.scrollY + window.innerHeight < document.body.scrollHeight - tolerance; 28 | } 29 | 30 | // Simple scroll to bottom function 31 | function scrollToBottom() { 32 | // Scroll to bottom of the page 33 | window.scrollTo(0, document.body.scrollHeight); 34 | } 35 | 36 | const messages = []; // Local message array for display only 37 | const actorTimeoutCheckDelay = 60_000; // 60 seconds between checks 38 | let timeoutCheckInterval = null; // Will store the interval ID 39 | let eventSource = null; 40 | let reconnectAttempts = 0; 41 | const maxReconnectAttempts = 3; // Reduced to 3 attempts 42 | const sseReconnectDelay = 3000; // 3 seconds between attempts 43 | 44 | // ================== SSE CONNECTION SETUP ================== 45 | 46 | // Function to handle incoming SSE messages 47 | function handleSSEMessage(event) { 48 | let data; 49 | try { 50 | data = JSON.parse(event.data); 51 | } catch { 52 | console.warn('Could not parse SSE event as JSON:', event.data); 53 | return; 54 | } 55 | console.log('Received SSE message:', data); 56 | // Handle finished flag 57 | if (data.finished) { 58 | isProcessingMessage = false; 59 | sendBtn.innerHTML = ''; 60 | queryInput.focus(); 61 | if (data.error) { 62 | appendMessage('internal', `Error: ${data.content}`); 63 | } 64 | return; 65 | } 66 | appendMessage(data.role, data.content, data.key); 67 | } 68 | 69 | // Function to handle SSE errors 70 | function handleSSEError(err) { 71 | console.error('SSE error:', err); 72 | const errorMessage = err instanceof Error ? err.message : 'Connection lost from Browser to MCP-tester-client server.'; 73 | console.log(errorMessage); 74 | 75 | // Close the current connection if it exists 76 | if (eventSource) { 77 | eventSource.close(); 78 | eventSource = null; 79 | } 80 | reconnectMcpServerBtn.classList.remove('connected'); 81 | reconnectMcpServerBtn.classList.add('disconnected'); 82 | // Only show the reconnection message if we haven't exceeded max attempts 83 | if (reconnectAttempts < maxReconnectAttempts) { 84 | reconnectAttempts++; 85 | const attemptNum = reconnectAttempts; 86 | appendMessage('internal', `${errorMessage} Attempting to reconnect (${attemptNum}/${maxReconnectAttempts})`); 87 | // Attempt to reconnect after a delay 88 | setTimeout(() => createSSEConnection(false), sseReconnectDelay); 89 | } else { 90 | appendMessage('internal', 'Maximum reconnection attempts reached. Try clicking the "Reconnect MCP Server" button in the toolbar or refresh the page.'); 91 | } 92 | } 93 | 94 | /** 95 | * Unified function to create an SSE connection 96 | * @param {boolean} isInitial - Whether this is an initial connection (resets reconnect attempts) 97 | * @param {boolean} force - Whether to force a connection attempt regardless of max attempts 98 | * @returns {boolean} - Whether a new connection was successfully initiated 99 | */ 100 | function createSSEConnection(isInitial = true, force = false) { 101 | // Check for max reconnect attempts unless forced 102 | if (!isInitial && !force && reconnectAttempts >= maxReconnectAttempts) { 103 | appendMessage('internal', 'Connection failed. Please try clicking the "Reconnect" button in the toolbar or refresh the page.'); 104 | if (eventSource) { 105 | eventSource.close(); 106 | eventSource = null; 107 | } 108 | reconnectMcpServerBtn.classList.remove('connected'); 109 | reconnectMcpServerBtn.classList.add('disconnected'); 110 | // Re-enable the send button on connection failure 111 | isProcessingMessage = false; 112 | sendBtn.disabled = false; 113 | sendBtn.style.cursor = 'pointer'; 114 | queryInput.focus(); 115 | return false; 116 | } 117 | // Reset reconnect attempts for initial connections 118 | if (isInitial) { 119 | reconnectAttempts = 0; 120 | } 121 | // Close any existing connection before creating a new one 122 | if (eventSource) { 123 | eventSource.close(); 124 | eventSource = null; 125 | } 126 | try { 127 | // Create new connection 128 | eventSource = new EventSource('/sse'); 129 | eventSource.onmessage = handleSSEMessage; 130 | eventSource.onerror = handleSSEError; 131 | eventSource.onopen = () => { 132 | console.log('SSE connection opened successfully'); 133 | appendMessage('internal', 'Connected to MCP server!'); 134 | reconnectAttempts = 0; // Reset reconnect attempts on successful connection 135 | reconnectMcpServerBtn.classList.remove('disconnected'); 136 | reconnectMcpServerBtn.classList.add('connected'); 137 | // Re-enable the send button on successful connection 138 | isProcessingMessage = false; 139 | sendBtn.disabled = false; 140 | sendBtn.style.cursor = 'pointer'; 141 | queryInput.focus(); 142 | }; 143 | return true; 144 | } catch (err) { 145 | console.error('Error creating SSE connection:', err); 146 | appendMessage('internal', `Failed to establish connection: ${err.message}`); 147 | reconnectMcpServerBtn.classList.remove('connected'); 148 | reconnectMcpServerBtn.classList.add('disconnected'); 149 | // Re-enable the send button on connection error 150 | return false; 151 | } 152 | } 153 | // Call setup on a page load 154 | createSSEConnection(true); 155 | 156 | // ================== ON PAGE LOAD (DOMContentLoaded) ================== 157 | // - Fetch client info 158 | // - Set up everything else 159 | 160 | // Initial connection on a page load 161 | document.addEventListener('DOMContentLoaded', async () => { 162 | try { 163 | const resp = await fetch('/client-info'); 164 | const data = await resp.json(); 165 | if (mcpUrl) mcpUrl.textContent = data.mcpUrl; 166 | if (clientInfo) clientInfo.textContent = `Model name: ${data.modelName}\nSystem prompt: ${data.systemPrompt}`; 167 | if (information) information.innerHTML = `${data.information}`; 168 | } catch (err) { 169 | console.error('Error fetching client info:', err); 170 | } 171 | 172 | // Add this near the DOMContentLoaded event listener 173 | window.addEventListener('beforeunload', async () => { 174 | // Note: Most modern browsers require the event to be handled synchronously 175 | // and don't allow async operations during beforeunload 176 | try { 177 | // Synchronous fetch using XMLHttpRequest 178 | const xhr = new XMLHttpRequest(); 179 | xhr.open('POST', '/conversation/reset', false); // false makes it synchronous 180 | xhr.send(); 181 | 182 | messages.length = 0; 183 | chatLog.innerHTML = ''; 184 | } catch (err) { 185 | console.error('Error resetting conversation on page reload:', err); 186 | } 187 | }); 188 | 189 | try { 190 | const response = await fetch('/conversation'); 191 | if (response.ok) { 192 | const conversation = await response.json(); 193 | conversation.forEach(({ role, content }) => { 194 | appendMessage(role, content); 195 | }); 196 | scrollToBottom(); 197 | } 198 | } catch (err) { 199 | console.warn('Could not load prior conversation:', err); 200 | } 201 | 202 | setupModals(); 203 | // Initial fetch of tools 204 | await fetchAvailableTools(); 205 | }); 206 | 207 | // Settings form handling 208 | document.addEventListener('DOMContentLoaded', async () => { 209 | const settingsForm = document.getElementById('settingsForm'); 210 | const mcpSseUrlInput = document.getElementById('mcpSseUrlInput'); 211 | const modelNameSelect = document.getElementById('modelNameSelect'); 212 | const modelMaxTokensInput = document.getElementById('modelMaxTokensInput'); 213 | const maxToolCallsInput = document.getElementById('maxToolCallsInput'); 214 | const toolCallTimeoutInput = document.getElementById('toolCallTimeoutInput'); 215 | const systemPromptInput = document.getElementById('systemPromptInput'); 216 | const resetSettingsBtn = document.getElementById('resetSettingsBtn'); 217 | // Function to load model options dynamically 218 | async function loadModelOptions() { 219 | try { 220 | const resp = await fetch('/schema/models'); 221 | const modelOptions = await resp.json(); 222 | modelNameSelect.innerHTML = ''; 223 | modelOptions.forEach((option) => { 224 | const optionElement = document.createElement('option'); 225 | optionElement.value = option.value; 226 | optionElement.textContent = option.label; 227 | modelNameSelect.appendChild(optionElement); 228 | }); 229 | } catch (err) { 230 | console.error('Error loading model options:', err); 231 | showNotification('Failed to load model options. Using defaults.', 'warning'); 232 | } 233 | } 234 | await loadModelOptions(); 235 | // Load current settings 236 | try { 237 | const resp = await fetch('/settings'); 238 | const settings = await resp.json(); 239 | mcpSseUrlInput.value = settings.mcpUrl; 240 | modelNameSelect.value = settings.modelName; 241 | modelMaxTokensInput.value = settings.modelMaxOutputTokens; 242 | maxToolCallsInput.value = settings.maxNumberOfToolCallsPerQuery; 243 | toolCallTimeoutInput.value = settings.toolCallTimeoutSec; 244 | systemPromptInput.value = settings.systemPrompt; 245 | } catch (err) { 246 | console.error('Error loading settings:', err); 247 | showNotification('Failed to load settings. Please check console for details.', 'error'); 248 | } 249 | // Handle form submission 250 | settingsForm.addEventListener('submit', async (e) => { 251 | e.preventDefault(); 252 | const newSettings = { 253 | mcpUrl: mcpSseUrlInput.value, 254 | modelName: modelNameSelect.value, 255 | modelMaxOutputTokens: parseInt(modelMaxTokensInput.value, 10), 256 | maxNumberOfToolCallsPerQuery: parseInt(maxToolCallsInput.value, 10), 257 | toolCallTimeoutSec: parseInt(toolCallTimeoutInput.value, 10), 258 | systemPrompt: systemPromptInput.value, 259 | }; 260 | try { 261 | const resp = await fetch('/settings', { 262 | method: 'POST', 263 | headers: { 'Content-Type': 'application/json' }, 264 | body: JSON.stringify(newSettings), 265 | }); 266 | const result = await resp.json(); 267 | if (result.success) { 268 | showNotification('Settings updated successfully for the current session only. Settings will reset when the Actor is restarted.', 'success'); 269 | hideModal('settingsModal'); 270 | const clientInfoResp = await fetch('/client-info'); 271 | const clientInfoData = await clientInfoResp.json(); 272 | if (mcpUrl) mcpUrl.textContent = clientInfoData.mcpUrl; 273 | } else { 274 | showNotification(`Failed to update settings: ${result.error}`, 'error'); 275 | } 276 | } catch (err) { 277 | console.error('Error saving settings:', err); 278 | showNotification('Failed to save settings. Please check console for details.', 'error'); 279 | } 280 | }); 281 | // Reset settings to defaults 282 | resetSettingsBtn.addEventListener('click', async () => { 283 | try { 284 | const resp = await fetch('/settings/reset', { method: 'POST' }); 285 | const result = await resp.json(); 286 | if (result.success) { 287 | await loadModelOptions(); 288 | // Reload the form with defaults from the server 289 | const settingsResp = await fetch('/settings'); 290 | const settings = await settingsResp.json(); 291 | mcpSseUrlInput.value = settings.mcpUrl; 292 | modelNameSelect.value = settings.modelName; 293 | modelMaxTokensInput.value = settings.modelMaxOutputTokens; 294 | maxToolCallsInput.value = settings.maxNumberOfToolCallsPerQuery; 295 | toolCallTimeoutInput.value = settings.toolCallTimeoutSec; 296 | systemPromptInput.value = settings.systemPrompt; 297 | showNotification('Settings reset to defaults successfully!', 'success'); 298 | } else { 299 | showNotification(`Failed to reset settings: ${result.error}`, 'error'); 300 | } 301 | } catch (err) { 302 | console.error('Error resetting settings:', err); 303 | showNotification('Failed to reset settings. Please check console for details.', 'error'); 304 | } 305 | }); 306 | }); 307 | 308 | // Utility to show notifications 309 | function showNotification(message, type = 'info') { 310 | const existingNotification = document.querySelector('.notification'); 311 | if (existingNotification) { 312 | existingNotification.remove(); 313 | } 314 | const notification = document.createElement('div'); 315 | notification.className = `notification ${type}`; 316 | notification.style.marginBottom = '5px'; // Add 5px margin to bottom 317 | notification.textContent = message; 318 | chatLog.parentNode.insertBefore(notification, chatLog); 319 | 320 | // Auto-dismiss 321 | setTimeout(() => { 322 | if (notification.parentNode) { 323 | notification.remove(); 324 | } 325 | }, 7000); 326 | } 327 | 328 | // ================== MAIN CHAT LOGIC: APPEND MESSAGES & TOOL BLOCKS ================== 329 | 330 | /** 331 | * Fix message order by key 332 | @returns {void} 333 | */ 334 | function fixMessageOrder() { 335 | // Fix order of messages array 336 | messages.sort((a, b) => a.key - b.key); 337 | 338 | // Fix message DOM elements 339 | const messageElements = chatLog.getElementsByClassName('message-row'); 340 | for (let i = 1; i < messageElements.length; i++) { 341 | const message = messageElements[i]; 342 | const previousMessage = messageElements[i - 1]; 343 | 344 | // Skip if either message does not have a key 345 | if (!message.dataset.key || !previousMessage.dataset.key) { 346 | continue; 347 | } 348 | 349 | try { 350 | const messageKey = parseInt(message.dataset.key, 10); 351 | const previousMessageKey = parseInt(previousMessage.dataset.key, 10); 352 | 353 | if (messageKey < previousMessageKey) { 354 | console.log('Reordering message', message, 'placing it before', previousMessage); 355 | chatLog.insertBefore(message, previousMessage); 356 | } 357 | } catch (error) { 358 | console.error('Error reordering message:', error); 359 | } 360 | } 361 | } 362 | 363 | /** 364 | * appendMessage(role, content, key): 365 | * If content is an array (potential tool blocks), 366 | * handle each item separately; otherwise just show a normal bubble. 367 | @param {string} role - The role of the message (user, assistant, internal) 368 | @param {string|array} content - The content of the message (string or array of items) 369 | @param {number|undefined} [key] - Optional key of the message (used for ordering) 370 | */ 371 | function appendMessage(role, content, key = undefined) { 372 | // Always scroll to bottom when user sends the message 373 | // otherwise only when user is not scrolling chat history 374 | const shouldScrollToBottom = role === 'user' ? true : !isUserScrolling(); 375 | messages.push({ role, content, key }); 376 | 377 | if (Array.isArray(content)) { 378 | content.forEach((item) => { 379 | if (item.type === 'tool_use' || item.type === 'tool_result') { 380 | appendToolBlock(item, key); 381 | } else { 382 | appendSingleBubble(role, item, key); 383 | } 384 | }); 385 | } else { 386 | // normal single content 387 | appendSingleBubble(role, content, key); 388 | } 389 | 390 | // Fix message order after appending 391 | fixMessageOrder(); 392 | 393 | if (shouldScrollToBottom) scrollToBottom(); 394 | } 395 | 396 | /** 397 | * appendSingleBubble(role, content, key): Renders a normal user/assistant/internal bubble 398 | @param {string} role - The role of the message (user, assistant, internal) 399 | @param {string} content - The content of the message 400 | @param {number|undefined} [key] - Optional key of the message (used for ordering) 401 | */ 402 | function appendSingleBubble(role, content, key) { 403 | const row = document.createElement('div'); 404 | row.className = 'message-row'; 405 | if (key !== undefined) row.setAttribute('data-key', key); 406 | 407 | if (role === 'user') { 408 | row.classList.add('user-message'); 409 | } else if (role === 'assistant') { 410 | row.classList.add('assistant-message'); 411 | } else { 412 | row.classList.add('internal-message'); 413 | } 414 | 415 | const bubble = document.createElement('div'); 416 | bubble.className = `bubble ${role}`; 417 | bubble.innerHTML = formatAnyContent(content); 418 | 419 | row.appendChild(bubble); 420 | chatLog.appendChild(row); 421 | } 422 | 423 | /** 424 | * isBase64(str): Returns true if the str is base64 425 | */ 426 | function isBase64(str) { 427 | if (typeof str !== 'string') return false; 428 | const s = str.trim(); 429 | // base64 must be multiple of 4 chars 430 | if (!s || s.length % 4 !== 0) return false; 431 | // only valid base64 chars + optional padding 432 | return /^([A-Za-z0-9+/]{4})*([A-Za-z0-9+/]{2}==|[A-Za-z0-9+/]{3}=)?$/.test(s); 433 | } 434 | 435 | /** 436 | * appendToolBlock(item, key): Renders a separate row for tool_use/tool_result 437 | @param {object} item - The tool use or result item 438 | @param {number|undefined} [key] - Optional key of the message (used for ordering) 439 | */ 440 | function appendToolBlock(item, key) { 441 | const row = document.createElement('div'); 442 | row.className = 'message-row tool-row'; 443 | if (key !== undefined) row.setAttribute('data-key', key); 444 | 445 | const container = document.createElement('div'); 446 | container.className = 'tool-block'; 447 | 448 | if (item.type === 'tool_use') { 449 | const inputContent = item.input ? formatAnyContent(item.input) : 'No input provided'; 450 | container.innerHTML = ` 451 |
452 | 453 |
454 |
455 | 456 |
457 |
458 |
Tool call: ${item.name || 'N/A'}
459 |
460 |
461 | 462 |
463 |
464 |
465 |
466 |
467 |
Input:
468 | ${inputContent} 469 |
470 |
471 |
`; 472 | } else if (item.type === 'tool_result') { 473 | let resultContent = 'No content'; 474 | let statusText; 475 | let iconHtml; 476 | 477 | if (item.is_error) { 478 | statusText = 'Error'; 479 | iconHtml = `
480 | 481 |
`; 482 | } else { 483 | statusText = 'Success'; 484 | iconHtml = `
485 | 486 |
`; 487 | } 488 | 489 | if (Array.isArray(item.content)) { 490 | resultContent = item.content.map((contentItem) => { 491 | if (typeof contentItem === 'object' && contentItem.type === 'image') { 492 | // Handle both formats: direct data and Anthropic source format 493 | let imageData = contentItem.data; 494 | let mediaType = 'image/png'; // default fallback 495 | 496 | if (!imageData && contentItem.source && contentItem.source.data) { 497 | imageData = contentItem.source.data; 498 | mediaType = contentItem.source.media_type || 'image/png'; 499 | } 500 | 501 | if (imageData) { 502 | return `
503 | ${contentItem.text ? `

${contentItem.text}

` : ''} 504 | Tool result image 505 |
`; 506 | } 507 | return formatAnyContent(contentItem); 508 | } 509 | if (typeof contentItem === 'object' && contentItem.type === 'text') { 510 | return `
${formatMarkdown(contentItem.text || '')}
`; 511 | } 512 | return formatAnyContent(contentItem); 513 | }).join(''); 514 | } else { 515 | resultContent = formatAnyContent(item.content); 516 | } 517 | 518 | const contentLength = typeof item.content === 'string' 519 | ? item.content.length 520 | : JSON.stringify(item.content || '').length; 521 | 522 | container.innerHTML = ` 523 |
524 | 525 |
526 | ${iconHtml} 527 |
528 |
Tool result: ${statusText}
529 |
${contentLength} chars
530 |
531 |
532 | 533 |
534 |
535 |
536 |
537 |
538 |
Output:
539 |
540 | ${resultContent} 541 |
542 |
543 |
544 |
`; 545 | } 546 | 547 | row.appendChild(container); 548 | chatLog.appendChild(row); 549 | 550 | // Add click handler for the chevron icon 551 | const chevron = container.querySelector('.fa-chevron-down'); 552 | if (chevron) { 553 | const details = container.querySelector('details'); 554 | details.addEventListener('toggle', () => { 555 | chevron.style.transform = details.open ? 'rotate(180deg)' : 'rotate(0deg)'; 556 | }); 557 | } 558 | } 559 | 560 | // ================== UTILITY FOR FORMATTING CONTENT (JSON, MD, ETC.) ================== 561 | 562 | /** HTML escaper for
 blocks, etc. */
563 | function escapeHTML(str) {
564 |     if (typeof str !== 'string') return String(str);
565 |     return str
566 |         .replace(/&/g, '&')
567 |         .replace(//g, '>');
569 | }
570 | 
571 | function formatAnyContent(content) {
572 |     if (typeof content === 'string') {
573 |         // Check if it's base64 image data
574 |         if (isBase64ImageData(content)) {
575 |             return `Generated image`;
576 |         }
577 |         // Try JSON parse for other content
578 |         try {
579 |             const parsed = JSON.parse(content);
580 |             return `
${escapeHTML(JSON.stringify(parsed, null, 2))}
`; 581 | } catch { 582 | // Looks like truncated JSON 583 | const trimmed = content.trim(); 584 | if ((trimmed.startsWith('{') || trimmed.startsWith('[')) 585 | && (trimmed.includes('"') || trimmed.includes(':'))) { 586 | return `
${escapeHTML(formatLikeJSON(trimmed))}
`; 587 | } 588 | // fallback to markdown 589 | return formatMarkdown(content); 590 | } 591 | } 592 | 593 | if (content && typeof content === 'object') { 594 | // Check if object contains image data 595 | if (content.type === 'image' && content.data) { 596 | const mediaType = content.source?.media_type || 'image/png'; 597 | return `Generated image`; 598 | } 599 | // Handle array of content blocks 600 | if (Array.isArray(content)) { 601 | return content.map((item) => { 602 | if (item.type === 'image' && item.data) { 603 | const mediaType = item.source?.media_type || 'image/png'; 604 | return `Generated image`; 605 | } if (item.type === 'text') { 606 | return formatMarkdown(item.text || ''); 607 | } 608 | return formatAnyContent(item); 609 | }).join('
'); 610 | } 611 | // Plain object → JSON 612 | return `
${escapeHTML(JSON.stringify(content, null, 2))}
`; 613 | } 614 | 615 | // fallback 616 | return String(content); 617 | } 618 | 619 | // Add helper function to detect base64 image data 620 | function isBase64ImageData(str) { 621 | if (typeof str !== 'string') return false; 622 | // Check if it's a reasonable length for image data and is valid base64 623 | return str.length > 100 && isBase64(str) && !str.includes('"') && !str.includes('{'); 624 | } 625 | 626 | /** A naive Markdown transform */ 627 | function formatMarkdown(text) { 628 | let safe = escapeHTML(text); 629 | // code fences 630 | safe = safe.replace(/```([\s\S]*?)```/g, '
$1
'); 631 | // inline code 632 | safe = safe.replace(/`([^`]+)`/g, '$1'); 633 | // bold, italics, links, newlines 634 | safe = safe.replace(/\*\*([^*]+)\*\*/g, '$1'); 635 | safe = safe.replace(/\*([^*]+)\*/g, '$1'); 636 | safe = safe.replace(/\[([^\]]+)\]\(([^)]+)\)/g, '$1'); 637 | safe = safe.replace(/\n/g, '
'); 638 | return safe; 639 | } 640 | 641 | // Helper function to add basic indentation to JSON-like strings 642 | function formatLikeJSON(str) { 643 | let indentLevel = 0; 644 | let result = ''; 645 | let inString = false; 646 | let escaped = false; 647 | 648 | for (let i = 0; i < str.length; i++) { 649 | const char = str[i]; 650 | const nextChar = str[i + 1] || ''; 651 | const nextNextChar = str[i + 2] || ''; 652 | 653 | if (!inString) { 654 | if (char === '"' && !escaped) { 655 | inString = true; 656 | } else if (char === '{' || char === '[') { 657 | result += char; 658 | indentLevel++; 659 | if (nextChar && nextChar !== '}' && nextChar !== ']') { 660 | result += `\n${' '.repeat(indentLevel)}`; 661 | } 662 | continue; 663 | } else if (char === '}' || char === ']') { 664 | if (result[result.length - 1] !== '\n') { 665 | result += `\n${' '.repeat(Math.max(0, indentLevel - 1))}`; 666 | } else { 667 | result = `${result.trimEnd()}\n${' '.repeat(Math.max(0, indentLevel - 1))}`; 668 | } 669 | indentLevel = Math.max(0, indentLevel - 1); 670 | result += char; 671 | if (nextChar === ',' && nextNextChar) { 672 | result += `,\n${' '.repeat(indentLevel)}`; 673 | i++; // skip the comma 674 | } 675 | continue; 676 | } else if (char === ',' && !inString) { 677 | result += `${char}\n${' '.repeat(indentLevel)}`; 678 | continue; 679 | } else if (char === ':' && !inString) { 680 | result += `${char} `; 681 | continue; 682 | } 683 | } else if (char === '"' && !escaped) { 684 | inString = false; 685 | } 686 | 687 | escaped = (char === '\\' && !escaped); 688 | result += char; 689 | } 690 | 691 | return result; 692 | } 693 | 694 | // ================== SENDING A USER QUERY (POST /message) ================== 695 | async function sendQuery(query) { 696 | if (isProcessingMessage) return; 697 | // Set processing state 698 | isProcessingMessage = true; 699 | // Show spinner in send button but keep it enabled 700 | sendBtn.innerHTML = ''; 701 | // First append the user message 702 | appendMessage('user', query); 703 | 704 | try { 705 | const resp = await fetch('/message', { 706 | method: 'POST', 707 | headers: { 'Content-Type': 'application/json' }, 708 | body: JSON.stringify({ query }), 709 | }); 710 | const data = await resp.json(); 711 | if (data.error) { 712 | console.log('Server error:', data.error); 713 | appendMessage('internal', `Server error: ${data.error}`); 714 | } 715 | } catch (err) { 716 | console.log('Network error:', err); 717 | appendMessage('internal', 'Network error. Try to reconnect or reload page'); 718 | } 719 | } 720 | 721 | // ================== CLEAR CONVERSATION LOG (POST /conversation/reset) ================== 722 | clearBtn.addEventListener('click', async () => { 723 | try { 724 | // Add visual feedback 725 | clearBtn.innerHTML = ''; 726 | clearBtn.disabled = true; 727 | 728 | messages.length = 0; 729 | chatLog.innerHTML = ''; 730 | 731 | const resp = await fetch('/conversation/reset', { method: 'POST' }); 732 | const data = await resp.json(); 733 | 734 | if (data.error) { 735 | console.error('Server error when resetting conversation:', data.error); 736 | appendMessage('internal', 'Failed to clear conversation. Please try again.'); 737 | } else { 738 | console.log('Server conversation reset'); 739 | } 740 | } catch (err) { 741 | console.error('Error resetting conversation:', err); 742 | appendMessage('internal', 'Error clearing conversation. Please try again.'); 743 | } finally { 744 | // Reset button state 745 | clearBtn.innerHTML = ''; 746 | clearBtn.disabled = false; 747 | } 748 | }); 749 | 750 | // Add this new function near other utility functions 751 | async function checkActorTimeout() { 752 | try { 753 | const response = await fetch('/check-actor-timeout'); 754 | const data = await response.json(); 755 | 756 | if (data.timeoutImminent) { 757 | const secondsLeft = Math.ceil(data.timeUntilTimeout / 1000); 758 | if (secondsLeft <= 0) { 759 | appendMessage('internal', '⚠️ Actor has timed out and stopped running. Please restart the Actor to continue.'); 760 | // Clear the interval when timeout is detected 761 | if (timeoutCheckInterval) { 762 | clearInterval(timeoutCheckInterval); 763 | timeoutCheckInterval = null; 764 | } 765 | } else { 766 | appendMessage('internal', `⚠️ Actor will timeout in ${secondsLeft} seconds.\n`); 767 | } 768 | } 769 | } catch (err) { 770 | console.error('Error checking timeout status:', err); 771 | } 772 | } 773 | 774 | // Store the interval ID when creating it 775 | timeoutCheckInterval = setInterval(async () => { 776 | await checkActorTimeout(); 777 | }, actorTimeoutCheckDelay); 778 | 779 | // ================== SEND BUTTON, ENTER KEY HANDLER ================== 780 | sendBtn.addEventListener('click', () => { 781 | const query = queryInput.value.trim(); 782 | if (query && !isProcessingMessage) { 783 | sendQuery(query); 784 | queryInput.value = ''; 785 | queryInput.style.height = 'auto'; 786 | } 787 | }); 788 | 789 | queryInput.addEventListener('keydown', (e) => { 790 | if (e.key === 'Enter' && !e.shiftKey) { 791 | e.preventDefault(); 792 | if (!isProcessingMessage) { 793 | sendBtn.click(); 794 | } 795 | } 796 | }); 797 | 798 | // Add ping function to check MCP server connection status 799 | async function reconnectAndPing() { 800 | try { 801 | // Force a new connection attempt 802 | createSSEConnection(false, true); 803 | const resp = await fetch('/reconnect-mcp-server'); 804 | const data = await resp.json(); 805 | console.log('Ping response:', data); 806 | if (data.status !== true && data.status !== 'OK') { 807 | appendMessage('internal', 'Not connected'); 808 | } 809 | } catch (err) { 810 | appendMessage('internal', `Error reconnecting to MCP server: ${err.message}`); 811 | } 812 | } 813 | 814 | // Add click handler for reconnect button 815 | reconnectMcpServerBtn.addEventListener('click', async () => { 816 | try { 817 | // Add visual feedback 818 | reconnectMcpServerBtn.innerHTML = ''; 819 | reconnectMcpServerBtn.disabled = true; 820 | await reconnectAndPing(); 821 | } finally { 822 | // Reset button state 823 | reconnectMcpServerBtn.innerHTML = ''; 824 | reconnectMcpServerBtn.disabled = false; 825 | } 826 | }); 827 | 828 | // ================== AVAILABLE TOOLS ================== 829 | // Fetch available tools 830 | async function fetchAvailableTools() { 831 | try { 832 | const response = await fetch('/available-tools'); 833 | const data = await response.json(); 834 | 835 | if (data.tools && data.tools.length > 0) { 836 | toolsLoading.style.display = 'none'; 837 | renderTools(data.tools); 838 | } else { 839 | toolsLoading.textContent = 'No tools available.'; 840 | } 841 | } catch (err) { 842 | toolsLoading.textContent = 'Failed to load tools. Try reconnecting.'; 843 | console.error('Error fetching tools:', err); 844 | } 845 | } 846 | 847 | // Render the tools list 848 | function renderTools(tools) { 849 | toolsContainer.innerHTML = ''; 850 | 851 | // Change the tools count 852 | const toolsCountElement = document.getElementById('toolsCount'); 853 | toolsCountElement.textContent = `(${tools.length})`; 854 | 855 | // Expandable list of tools 856 | const toolsList = document.createElement('ul'); 857 | toolsList.style.paddingLeft = '1.5rem'; 858 | toolsList.style.marginTop = '0.5rem'; 859 | 860 | tools.forEach((tool) => { 861 | const li = document.createElement('li'); 862 | li.style.marginBottom = '0.75rem'; 863 | 864 | const toolName = document.createElement('strong'); 865 | toolName.textContent = tool.name; 866 | li.appendChild(toolName); 867 | 868 | if (tool.description) { 869 | const description = document.createElement('div'); 870 | description.style.fontSize = '0.85rem'; 871 | description.style.marginTop = '0.25rem'; 872 | description.textContent = tool.description; 873 | li.appendChild(description); 874 | } 875 | 876 | toolsList.appendChild(li); 877 | }); 878 | 879 | toolsContainer.appendChild(toolsList); 880 | } 881 | 882 | // ================== MODAL HANDLING ================== 883 | 884 | // Function to show a modal 885 | function showModal(modalId) { 886 | const modalElement = document.getElementById(modalId); 887 | if (modalElement) { 888 | modalElement.style.display = 'block'; 889 | document.body.style.overflow = 'hidden'; // Prevent scrolling 890 | // Refresh tools when tools modal is opened 891 | if (modalId === 'toolsModal') { 892 | fetchAvailableTools(); 893 | } 894 | } 895 | } 896 | 897 | // Function to hide a modal 898 | function hideModal(modalId) { 899 | const modalElement = document.getElementById(modalId); 900 | if (modalElement) { 901 | modalElement.style.display = 'none'; 902 | document.body.style.overflow = ''; // Restore scrolling 903 | } 904 | } 905 | 906 | function setupModals() { 907 | // Get button elements 908 | const quickStartBtn = document.getElementById('quickStartBtn'); 909 | const settingsBtn = document.getElementById('settingsBtn'); 910 | const toolsBtn = document.getElementById('toolsBtn'); 911 | 912 | // Set up example question clicks - only for the first list 913 | const exampleQuestions = document.querySelectorAll('#quickStartModal .modal-body h4:first-of-type + ul li'); 914 | exampleQuestions.forEach((question) => { 915 | question.addEventListener('click', () => { 916 | const text = question.textContent.trim(); 917 | hideModal('quickStartModal'); 918 | queryInput.value = text; 919 | queryInput.focus(); 920 | queryInput.style.height = 'auto'; 921 | queryInput.style.height = `${Math.min(queryInput.scrollHeight, 150)}px`; 922 | }); 923 | }); 924 | 925 | // Add click handlers for modal buttons 926 | quickStartBtn.addEventListener('click', () => showModal('quickStartModal')); 927 | settingsBtn.addEventListener('click', () => showModal('settingsModal')); 928 | toolsBtn.addEventListener('click', () => showModal('toolsModal')); 929 | 930 | // Add click handlers for close buttons 931 | document.querySelectorAll('.close-modal').forEach((button) => { 932 | button.addEventListener('click', () => { 933 | const modal = button.closest('.modal'); 934 | if (modal) { 935 | hideModal(modal.id); 936 | } 937 | }); 938 | }); 939 | 940 | let mouseDownOnModal = false; 941 | window.addEventListener('mousedown', (event) => { 942 | mouseDownOnModal = event.target.classList.contains('modal'); 943 | }); 944 | window.addEventListener('mouseup', (event) => { 945 | if (mouseDownOnModal && event.target.classList.contains('modal')) { 946 | hideModal(event.target.id); 947 | } 948 | mouseDownOnModal = false; 949 | }); 950 | 951 | // Close modal with Escape key 952 | document.addEventListener('keydown', (event) => { 953 | if (event.key === 'Escape') { 954 | document.querySelectorAll('.modal').forEach((modal) => { 955 | if (modal.style.display === 'block') { 956 | hideModal(modal.id); 957 | } 958 | }); 959 | } 960 | }); 961 | } 962 | -------------------------------------------------------------------------------- /src/public/favicon.ico: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/apify/tester-mcp-client/f4f3fa67b21f3b13b8ebf2f0a08deca40e66ac66/src/public/favicon.ico -------------------------------------------------------------------------------- /src/public/index.html: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | 5 | Apify MCP client 6 | 7 | 8 | 9 | 10 | 11 | 12 | 13 | 14 |
15 |
16 |
17 |

Apify Apify MCP client

18 |
19 | 30 |
31 | 34 | 37 |
38 |
39 |
40 |
41 | 42 | 43 | 73 | 74 | 75 | 129 | 130 | 131 | 143 | 144 |
145 | 146 |
147 | 148 |
149 |
150 | 155 | 158 |
159 |
160 |
161 | 162 | 170 | 171 | 172 | -------------------------------------------------------------------------------- /src/public/logo512.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/apify/tester-mcp-client/f4f3fa67b21f3b13b8ebf2f0a08deca40e66ac66/src/public/logo512.png -------------------------------------------------------------------------------- /src/public/styles.css: -------------------------------------------------------------------------------- 1 | :root { 2 | --primary-color: #4f46e5; 3 | --primary-hover: #4338ca; 4 | --bg-color: #f9fafb; 5 | --chat-bg: #ffffff; 6 | --border-color: #e5e7eb; 7 | --text-primary: #111827; 8 | --text-secondary: #4b5563; 9 | --user-message-bg: #eef2ff; 10 | --assistant-message-bg: #ffffff; 11 | --internal-message-bg: #f3f4f6; 12 | --tool-block-bg: #fef3c7; 13 | --shadow-sm: 0 1px 2px 0 rgb(0 0 0 / 0.05); 14 | --shadow-md: 0 4px 6px -1px rgb(0 0 0 / 0.1); 15 | --radius-sm: 0.5rem; 16 | --radius-md: 0.75rem; 17 | --radius-lg: 1rem; 18 | } 19 | 20 | * { 21 | margin: 0; 22 | padding: 0; 23 | box-sizing: border-box; 24 | } 25 | 26 | body { 27 | font-family: 'Inter', -apple-system, BlinkMacSystemFont, 'Segoe UI', Roboto, 'Helvetica Neue', sans-serif; 28 | background: var(--bg-color); 29 | color: var(--text-primary); 30 | line-height: 1.5; 31 | min-height: 100vh; 32 | margin: 0; 33 | padding: 0; 34 | display: flex; 35 | flex-direction: column; 36 | overflow-y: auto; /* Changed from hidden to allow scrolling */ 37 | } 38 | 39 | #chatContainer { 40 | max-width: 1000px; 41 | margin: 0 auto; 42 | padding: 0 1rem; 43 | display: flex; 44 | flex-direction: column; 45 | width: 100%; 46 | position: relative; 47 | min-height: 100vh; 48 | padding-top: calc(4rem + 20px); 49 | padding-bottom: calc(4rem + 30px); 50 | } 51 | 52 | .header { 53 | margin-bottom: 0; 54 | background: var(--chat-bg); 55 | border-radius: var(--radius-md); 56 | padding: 1rem; 57 | box-shadow: var(--shadow-sm); 58 | position: fixed; 59 | top: 0; 60 | left: 0; 61 | right: 0; 62 | z-index: 100; 63 | max-width: 1000px; 64 | width: calc(100% - 2rem); 65 | margin-top: 1rem; 66 | margin-left: auto; 67 | margin-right: auto; 68 | } 69 | 70 | /* This is for the backgroung for the top of the header */ 71 | .header::before { 72 | content: ''; 73 | position: absolute; 74 | top: -1rem; 75 | left: 0; 76 | right: 0; 77 | height: 1rem; 78 | background: var(--bg-color); 79 | z-index: -1; 80 | } 81 | 82 | .header-content { 83 | display: flex; 84 | justify-content: space-between; 85 | align-items: center; 86 | } 87 | 88 | .header h2 { 89 | font-size: 1.5rem; 90 | font-weight: 600; 91 | color: var(--text-primary); 92 | display: flex; 93 | align-items: center; 94 | gap: 0.5rem; 95 | } 96 | 97 | .header-icon { 98 | width: 1.5rem; 99 | height: 1.5rem; 100 | vertical-align: middle; 101 | } 102 | 103 | .header-actions { 104 | display: flex; 105 | gap: 0.5rem; 106 | } 107 | 108 | .modal-buttons, 109 | .action-buttons { 110 | display: flex; 111 | gap: 0.5rem; 112 | } 113 | 114 | /* Add a visual separator between button groups */ 115 | .action-buttons { 116 | position: relative; 117 | padding-left: 1rem; 118 | } 119 | 120 | .action-buttons::before { 121 | content: ''; 122 | position: absolute; 123 | left: 0; 124 | top: 50%; 125 | transform: translateY(-50%); 126 | height: 70%; 127 | width: 1px; 128 | background-color: var(--border-color); 129 | } 130 | 131 | .icon-btn { 132 | width: 2.5rem; 133 | height: 2.5rem; 134 | border-radius: var(--radius-sm); 135 | display: flex; 136 | align-items: center; 137 | justify-content: center; 138 | background: var(--bg-color); 139 | color: var(--text-secondary); 140 | border: 1px solid var(--border-color); 141 | transition: all 0.2s ease; 142 | } 143 | 144 | .icon-btn:hover { 145 | background: var(--chat-bg); 146 | color: var(--primary-color); 147 | border-color: var(--primary-color); 148 | } 149 | 150 | /* Different hover states for different button types */ 151 | .modal-buttons .icon-btn:hover { 152 | background: var(--chat-bg); 153 | color: var(--primary-color); 154 | border-color: var(--primary-color); 155 | } 156 | 157 | .action-buttons .icon-btn:hover { 158 | background: var(--chat-bg); 159 | color: #ef4444; /* Red for destructive actions */ 160 | border-color: #ef4444; 161 | } 162 | 163 | /* Special hover for clear button */ 164 | #clearBtn:hover { 165 | color: #ef4444; 166 | border-color: #ef4444; 167 | } 168 | 169 | /* Reconnect button states */ 170 | #reconnectMcpServerButton.connected { 171 | color: #10b981; 172 | border-color: #10b981; 173 | } 174 | 175 | #reconnectMcpServerButton.disconnected { 176 | color: #ef4444; 177 | border-color: #ef4444; 178 | } 179 | 180 | .info-panels { 181 | display: flex; 182 | flex-direction: column; 183 | gap: 0.75rem; 184 | margin-bottom: 1rem; 185 | } 186 | 187 | .info-panel { 188 | background: var(--chat-bg); 189 | border: 1px solid var(--border-color); 190 | border-radius: var(--radius-md); 191 | overflow: hidden; 192 | } 193 | 194 | .info-panel summary { 195 | padding: 1rem; 196 | cursor: pointer; 197 | font-weight: 500; 198 | color: var(--text-primary); 199 | display: flex; 200 | align-items: center; 201 | gap: 0.5rem; 202 | transition: background-color 0.2s ease; 203 | } 204 | 205 | .info-panel summary:hover { 206 | background: var(--bg-color); 207 | } 208 | 209 | .panel-content { 210 | padding: 1rem; 211 | border-top: 1px solid var(--border-color); 212 | } 213 | 214 | .panel-content ul { 215 | list-style: none; 216 | margin-top: 0.5rem; 217 | } 218 | 219 | .panel-content li { 220 | padding: 0.5rem 0; 221 | display: flex; 222 | align-items: center; 223 | gap: 0.5rem; 224 | color: var(--text-secondary); 225 | } 226 | 227 | #chatLog { 228 | flex: 1; 229 | background: var(--chat-bg); 230 | border: 1px solid var(--border-color); 231 | border-radius: var(--radius-md); 232 | padding: 1rem; 233 | margin-top: 1rem; 234 | box-shadow: var(--shadow-sm); 235 | width: 100%; 236 | position: relative; 237 | overflow-y: visible; 238 | } 239 | 240 | .message-row { 241 | margin: 0.75rem 0; 242 | display: flex; 243 | gap: 0.75rem; 244 | } 245 | 246 | .message-row.user-message { 247 | justify-content: flex-end; 248 | } 249 | 250 | .bubble { 251 | max-width: 85%; 252 | padding: 0.75rem 1rem; 253 | font-size: 0.9375rem; 254 | border-radius: var(--radius-lg); 255 | line-height: 1.5; 256 | animation: fadeIn 0.3s ease; 257 | } 258 | 259 | .bubble.user { 260 | background: var(--user-message-bg); 261 | border: 1px solid #e0e7ff; 262 | border-bottom-right-radius: var(--radius-sm); 263 | } 264 | 265 | .bubble.assistant { 266 | background: var(--assistant-message-bg); 267 | border: 1px solid var(--border-color); 268 | border-bottom-left-radius: var(--radius-sm); 269 | } 270 | 271 | .bubble.internal { 272 | background: var(--internal-message-bg); 273 | font-size: 0.875rem; 274 | color: var(--text-secondary); 275 | max-width: 100%; 276 | text-align: center; 277 | padding: 0.5rem 1rem; 278 | } 279 | 280 | .tool-block { 281 | background: var(--chat-bg); 282 | border: 1px solid var(--border-color); 283 | border-radius: var(--radius-md); 284 | padding: 0; 285 | margin: 0.75rem 0; 286 | font-size: 0.875rem; 287 | max-width: 100%; 288 | width: 100%; 289 | animation: slideIn 0.3s ease; 290 | overflow: hidden; 291 | } 292 | 293 | .tool-details { 294 | width: 100%; 295 | } 296 | 297 | .tool-details summary { 298 | list-style: none; 299 | cursor: pointer; 300 | padding: 0; 301 | } 302 | 303 | .tool-details summary::-webkit-details-marker { 304 | display: none; 305 | } 306 | 307 | .tool-header { 308 | display: flex; 309 | align-items: center; 310 | gap: 0.75rem; 311 | padding: 0.75rem 1rem; 312 | background: var(--bg-color); 313 | border-bottom: 1px solid var(--border-color); 314 | } 315 | 316 | .tool-icon { 317 | width: 2rem; 318 | height: 2rem; 319 | display: flex; 320 | align-items: center; 321 | justify-content: center; 322 | background: var(--primary-color); 323 | color: white; 324 | border-radius: var(--radius-sm); 325 | font-size: 0.875rem; 326 | } 327 | 328 | .tool-icon i { 329 | font-size: 1rem; 330 | } 331 | 332 | .tool-icon i.error { 333 | color: #ef4444; 334 | } 335 | 336 | .tool-icon i.success { 337 | color: #10b981; 338 | } 339 | 340 | .tool-info { 341 | flex: 1; 342 | } 343 | 344 | .tool-name { 345 | font-weight: 600; 346 | color: var(--text-primary); 347 | margin-bottom: 0.25rem; 348 | } 349 | 350 | .tool-id { 351 | font-size: 0.75rem; 352 | color: var(--text-secondary); 353 | } 354 | 355 | .tool-status { 356 | display: flex; 357 | align-items: center; 358 | gap: 0.5rem; 359 | font-size: 0.75rem; 360 | padding: 0.25rem 0.5rem; 361 | border-radius: var(--radius-sm); 362 | background: var(--bg-color); 363 | } 364 | 365 | .tool-status.error { 366 | color: #ef4444; 367 | background: #fee2e2; 368 | } 369 | 370 | .tool-status.success { 371 | color: #10b981; 372 | background: #d1fae5; 373 | } 374 | 375 | .tool-status i { 376 | transition: transform 0.2s ease; 377 | } 378 | 379 | .tool-content { 380 | padding: 1rem; 381 | background: var(--chat-bg); 382 | } 383 | 384 | .tool-label { 385 | font-weight: 500; 386 | color: var(--text-secondary); 387 | margin-bottom: 0.5rem; 388 | font-size: 0.75rem; 389 | text-transform: uppercase; 390 | letter-spacing: 0.05em; 391 | } 392 | 393 | .tool-input, 394 | .tool-result { 395 | background: var(--bg-color); 396 | border-radius: var(--radius-sm); 397 | padding: 0.75rem; 398 | } 399 | 400 | .tool-result pre { 401 | margin: 0; 402 | background: transparent; 403 | } 404 | 405 | .tool-result-content .image-result { 406 | margin: 10px 0; 407 | padding: 10px; 408 | border: 1px solid #e0e0e0; 409 | border-radius: 8px; 410 | background: #f9f9f9; 411 | } 412 | 413 | .tool-result-content .text-result { 414 | margin: 5px 0; 415 | } 416 | 417 | .tool-icon.success { 418 | color: #28a745; 419 | } 420 | 421 | .tool-icon.error { 422 | color: #dc3545; 423 | } 424 | 425 | .tool-result-content img { 426 | box-shadow: 0 2px 8px rgba(0,0,0,0.1); 427 | } 428 | 429 | .tool-result-content img:hover { 430 | cursor: pointer; 431 | } 432 | 433 | #inputRow { 434 | position: fixed; 435 | bottom: 0; 436 | left: 0; 437 | right: 0; 438 | background: var(--bg-color); 439 | padding: 0 1rem 1rem 1rem; 440 | z-index: 10; 441 | width: 100%; 442 | display: flex; 443 | justify-content: center; 444 | margin: 0 auto; 445 | } 446 | 447 | .input-wrapper { 448 | display: flex; 449 | gap: 0.5rem; 450 | align-items: flex-end; 451 | background: var(--chat-bg); 452 | border: 1px solid var(--border-color); 453 | border-radius: var(--radius-lg); 454 | padding: 0.5rem; 455 | box-shadow: var(--shadow-sm); 456 | max-width: 1000px; 457 | width: 100%; 458 | margin: 0 auto; 459 | } 460 | 461 | #queryInput { 462 | flex: 1; 463 | padding: 0.75rem; 464 | font-size: 0.9375rem; 465 | min-height: 45px; 466 | height: auto; 467 | max-height: 150px; 468 | border: none; 469 | resize: none; 470 | overflow-y: auto; 471 | line-height: 1.5; 472 | border-radius: var(--radius-md); 473 | box-shadow: none; 474 | } 475 | 476 | #queryInput:focus { 477 | outline: none; 478 | } 479 | 480 | .send-btn { 481 | width: 45px; 482 | height: 45px; 483 | border-radius: var(--radius-md); 484 | display: flex; 485 | align-items: center; 486 | justify-content: center; 487 | background: var(--primary-color); 488 | color: white; 489 | border: none; 490 | cursor: pointer; 491 | transition: background-color 0.2s ease, opacity 0.2s ease; 492 | } 493 | 494 | .send-btn:hover { 495 | background: var(--primary-hover); 496 | } 497 | 498 | .send-btn:disabled { 499 | background: var(--border-color); 500 | cursor: not-allowed; 501 | opacity: 0.7; 502 | } 503 | 504 | .send-btn:disabled:hover { 505 | background: var(--border-color); 506 | } 507 | 508 | .send-btn i { 509 | font-size: 1.2rem; 510 | } 511 | 512 | @keyframes fadeIn { 513 | from { opacity: 0; transform: translateY(10px); } 514 | to { opacity: 1; transform: translateY(0); } 515 | } 516 | 517 | @keyframes slideIn { 518 | from { opacity: 0; transform: translateX(-10px); } 519 | to { opacity: 1; transform: translateX(0); } 520 | } 521 | 522 | pre { 523 | background: var(--bg-color); 524 | padding: 0.75rem; 525 | border-radius: var(--radius-sm); 526 | overflow-x: auto; 527 | font-family: 'JetBrains Mono', monospace; 528 | font-size: 0.875rem; 529 | line-height: 1.5; 530 | } 531 | 532 | code { 533 | font-family: 'JetBrains Mono', monospace; 534 | font-size: 0.875rem; 535 | } 536 | 537 | @media (max-width: 640px) { 538 | #chatContainer { 539 | margin: 0; 540 | padding: 0.5rem; 541 | padding-top: calc(4rem + 10px); 542 | padding-bottom: calc(3.5rem + 10px); 543 | } 544 | 545 | .bubble { 546 | max-width: 90%; 547 | } 548 | 549 | .bubble.user { 550 | max-width: 85%; 551 | } 552 | 553 | #inputRow { 554 | padding: 0 0.5rem 0.5rem 0.5rem; 555 | } 556 | 557 | .send-btn { 558 | width: 40px; 559 | height: 40px; 560 | } 561 | 562 | .tool-block { 563 | padding: 0.75rem; 564 | } 565 | 566 | .header { 567 | width: calc(100% - 1rem); 568 | } 569 | 570 | #chatLog { 571 | margin-left: 0.5rem; 572 | margin-right: 0.5rem; 573 | } 574 | } 575 | 576 | /* Modal Styles */ 577 | .modal { 578 | display: none; 579 | position: fixed; 580 | top: 0; 581 | left: 0; 582 | width: 100%; 583 | height: 100%; 584 | background-color: rgba(0, 0, 0, 0.5); 585 | z-index: 1000; 586 | } 587 | 588 | .modal-content { 589 | position: relative; 590 | background-color: var(--chat-bg); 591 | margin: 6% auto; 592 | padding: 1.25rem; 593 | width: clamp(300px, 80%, 1000px); 594 | border-radius: var(--radius-md); 595 | box-shadow: var(--shadow-md); 596 | max-height: 80vh; 597 | overflow-y: auto; 598 | } 599 | 600 | .modal-header { 601 | display: flex; 602 | justify-content: space-between; 603 | align-items: center; 604 | margin-bottom: 1rem; 605 | padding-bottom: 0.5rem; 606 | border-bottom: 1px solid var(--border-color); 607 | } 608 | 609 | .modal-header h3 { 610 | margin: 0; 611 | font-size: 1.2rem; 612 | color: var(--text-primary); 613 | } 614 | 615 | .close-modal { 616 | background: none; 617 | border: none; 618 | font-size: 1.5rem; 619 | cursor: pointer; 620 | color: var(--text-secondary); 621 | padding: 0; 622 | line-height: 1; 623 | } 624 | 625 | .close-modal:hover { 626 | color: var(--text-primary); 627 | } 628 | 629 | .modal-body { 630 | padding: 1rem 0; 631 | } 632 | 633 | .modal-body ul li { 634 | list-style-type: none; 635 | } 636 | 637 | /* Header Actions */ 638 | .header-actions { 639 | display: flex; 640 | gap: 0.5rem; 641 | } 642 | 643 | .icon-btn { 644 | background: none; 645 | border: none; 646 | padding: 0.5rem; 647 | cursor: pointer; 648 | color: #666; 649 | border-radius: 4px; 650 | transition: background-color 0.2s; 651 | width: 2.5rem; 652 | height: 2.5rem; 653 | display: flex; 654 | align-items: center; 655 | justify-content: center; 656 | } 657 | 658 | .icon-btn i { 659 | font-size: 1.1rem; 660 | } 661 | 662 | .icon-btn:hover { 663 | background-color: rgba(0, 0, 0, 0.05); 664 | color: #333; 665 | } 666 | 667 | /* Settings Form Styles */ 668 | .settings-form { 669 | width: 100%; 670 | } 671 | 672 | .form-group { 673 | margin-bottom: 1rem; 674 | } 675 | 676 | .form-group label { 677 | display: block; 678 | margin-bottom: 0.25rem; 679 | font-weight: 500; 680 | color: var(--text-secondary); 681 | font-size: 0.875rem; 682 | } 683 | 684 | .form-control { 685 | width: 100%; 686 | padding: 0.6rem 0.8rem; 687 | font-size: 0.9rem; 688 | border: 1px solid var(--border-color); 689 | border-radius: var(--radius-sm); 690 | background-color: var(--chat-bg); 691 | color: var(--text-primary); 692 | transition: border-color 0.2s ease, box-shadow 0.2s ease; 693 | } 694 | 695 | .form-control:focus { 696 | outline: none; 697 | border-color: var(--primary-color); 698 | box-shadow: 0 0 0 3px rgba(79, 70, 229, 0.1); 699 | } 700 | 701 | select.form-control { 702 | height: auto; 703 | appearance: none; 704 | background-image: url("data:image/svg+xml,%3csvg xmlns='http://www.w3.org/2000/svg' fill='none' viewBox='0 0 20 20'%3e%3cpath stroke='%236b7280' stroke-linecap='round' stroke-linejoin='round' stroke-width='1.5' d='M6 8l4 4 4-4'/%3e%3c/svg%3e"); 705 | background-position: right 0.5rem center; 706 | background-repeat: no-repeat; 707 | background-size: 1.5em 1.5em; 708 | padding-right: 2.5rem; 709 | } 710 | 711 | textarea.form-control { 712 | resize: vertical; 713 | min-height: 100px; 714 | line-height: 1.5; 715 | } 716 | 717 | .form-text { 718 | display: block; 719 | margin-top: 0.35rem; 720 | font-size: 0.8rem; 721 | color: var(--text-secondary); 722 | } 723 | 724 | .form-actions { 725 | display: flex; 726 | gap: 0.75rem; 727 | margin-top: 1.5rem; 728 | padding-top: 1rem; 729 | border-top: 1px solid var(--border-color); 730 | } 731 | 732 | .btn { 733 | padding: 0.6rem 1.2rem; 734 | border-radius: var(--radius-sm); 735 | font-weight: 500; 736 | cursor: pointer; 737 | border: 1px solid transparent; 738 | font-size: 0.9rem; 739 | transition: background-color 0.2s ease, border-color 0.2s ease, color 0.2s ease; 740 | } 741 | 742 | .btn-primary { 743 | background-color: var(--primary-color); 744 | color: white; 745 | border-color: var(--primary-color); 746 | } 747 | 748 | .btn-primary:hover { 749 | background-color: var(--primary-hover); 750 | border-color: var(--primary-hover); 751 | } 752 | 753 | .btn-secondary { 754 | background-color: var(--chat-bg); 755 | border: 1px solid var(--border-color); 756 | color: var(--text-primary); 757 | } 758 | 759 | .btn-secondary:hover { 760 | background-color: var(--bg-color); 761 | border-color: #d1d5db; 762 | } 763 | 764 | .notification { 765 | padding: 0.75rem 1rem; 766 | margin: 1rem 0 0; 767 | border-radius: var(--radius-sm); 768 | border-left-width: 4px; 769 | border-left-style: solid; 770 | font-size: 0.9rem; 771 | } 772 | 773 | .notification.success { 774 | background-color: #dcfce7; 775 | border-left-color: #22c55e; 776 | color: #166534; 777 | } 778 | 779 | .notification.error { 780 | background-color: #fee2e2; 781 | border-left-color: #ef4444; 782 | color: #991b1b; 783 | } 784 | 785 | /* Modal Styling - General */ 786 | .modal-body h4 { 787 | margin-bottom: 1rem; 788 | color: var(--primary-color); 789 | font-size: 1rem; 790 | } 791 | 792 | .modal-header h3 i { 793 | color: var(--primary-color); 794 | margin-right: 0.5rem; 795 | } 796 | 797 | /* Quick Start Modal Styling */ 798 | #quickStartModal .modal-body ul { 799 | padding-left: 0.5rem; 800 | } 801 | 802 | #quickStartModal .modal-body ul li { 803 | padding: 0.75rem 1rem; 804 | margin-bottom: 0.75rem; 805 | background: var(--bg-color); 806 | border-radius: var(--radius-md); 807 | display: flex; 808 | align-items: center; 809 | border: 1px solid var(--border-color); 810 | } 811 | 812 | /* Make only the first list (example questions) clickable */ 813 | #quickStartModal .modal-body h4:first-of-type + ul li { 814 | cursor: pointer; 815 | transition: all 0.2s ease; 816 | } 817 | 818 | #quickStartModal .modal-body h4:first-of-type + ul li:hover { 819 | background: #f8f9ff; 820 | border-color: var(--primary-color); 821 | transform: translateY(-2px); 822 | box-shadow: var(--shadow-sm); 823 | } 824 | 825 | #quickStartModal .modal-body ul li i { 826 | color: var(--primary-color); 827 | margin-right: 0.75rem; 828 | font-size: 0.875rem; 829 | } 830 | 831 | #quickStartModal .modal-header h3 i { 832 | color: var(--primary-color); 833 | margin-right: 0.5rem; 834 | } 835 | -------------------------------------------------------------------------------- /src/types.ts: -------------------------------------------------------------------------------- 1 | import type { ContentBlockParam, MessageParam } from '@anthropic-ai/sdk/resources/index.js'; 2 | 3 | export type Input = { 4 | llmProviderApiKey: string, 5 | modelName: string, 6 | headers: Record, 7 | maxNumberOfToolCallsPerQuery: number, 8 | modelMaxOutputTokens: number, 9 | /** 10 | * @deprecated MCP Use mcpUrl instead 11 | */ 12 | mcpSseUrl: string, 13 | mcpUrl: string, 14 | mcpTransportType: 'sse' | 'http-streamable-json-response', 15 | systemPrompt: string, 16 | toolCallTimeoutSec: number, 17 | }; 18 | 19 | export type StandbyInput = Input & { 20 | /** 21 | * @deprecated MCP Use mcpUrl instead 22 | */ 23 | mcpSseUrl: string, 24 | mcpUrl: string, 25 | headers: string | Record, 26 | } 27 | 28 | export type Tool = { 29 | name: string; 30 | description: string | undefined; 31 | input_schema: unknown; 32 | } 33 | 34 | /** 35 | * A function that charges tokens for a given model. 36 | * @param inputTokens - The number of input tokens. 37 | * @param outputTokens - The number of output tokens. 38 | * @param modelName - The name of the model. 39 | */ 40 | export interface TokenCharger { 41 | chargeTokens(inputTokens: number, outputTokens: number, modelName: string): Promise; 42 | } 43 | 44 | export interface MessageParamWithBlocks extends MessageParam { 45 | content: ContentBlockParam[]; 46 | } 47 | -------------------------------------------------------------------------------- /src/utils.ts: -------------------------------------------------------------------------------- 1 | import type { ContentBlockParam, MessageParam } from '@anthropic-ai/sdk/resources'; 2 | 3 | import { IMAGE_BASE64_PLACEHOLDER } from './const.js'; 4 | 5 | export function isBase64(str: string): boolean { 6 | if (!str) { 7 | return false; 8 | } 9 | try { 10 | return btoa(atob(str)) === str; 11 | } catch { 12 | return false; 13 | } 14 | } 15 | 16 | /** 17 | * Prunes base64 encoded messages from the conversation and replaces them with a placeholder to save context tokens. 18 | * Also adds fake tool_result messages for tool_use messages that don't have a corresponding tool_result message. 19 | * Also adds fake tool_use messages for tool_result messages that don't have a corresponding tool_use message. 20 | * Ensures tool_result blocks reference valid tool_use IDs. 21 | * @param conversation 22 | * @returns 23 | */ 24 | export function pruneAndFixConversation(conversation: MessageParam[]): MessageParam[] { 25 | // Create a shallow copy of the conversation array 26 | const prunedAndFixedConversation: MessageParam[] = []; 27 | 28 | // First pass: prune base64 content and collect tool IDs 29 | for (let m = 0; m < conversation.length; m++) { 30 | const message = conversation[m]; 31 | 32 | // Handle simple string messages 33 | if (typeof message.content === 'string') { 34 | prunedAndFixedConversation.push({ 35 | ...message, 36 | content: isBase64(message.content) ? IMAGE_BASE64_PLACEHOLDER : message.content, 37 | }); 38 | continue; 39 | } 40 | 41 | // Handle messages with content blocks 42 | const contentBlocks = message.content as ContentBlockParam[]; 43 | const processedBlocks = contentBlocks.map((block) => { 44 | // Handle different block types 45 | if (block.type === 'text' && isBase64(block.text)) { 46 | return { 47 | type: 'text', 48 | text: IMAGE_BASE64_PLACEHOLDER, 49 | cache_control: block.cache_control, 50 | citations: block.citations, 51 | }; 52 | } 53 | 54 | if (block.type === 'tool_use') { 55 | return block; 56 | } 57 | 58 | if (block.type === 'tool_result') { 59 | // Handle base64 encoded tool_result content (string) 60 | if (typeof block.content === 'string' && isBase64(block.content)) { 61 | return { 62 | type: 'tool_result', 63 | content: IMAGE_BASE64_PLACEHOLDER, 64 | tool_use_id: block.tool_use_id, 65 | is_error: block.is_error, 66 | cache_control: block.cache_control, 67 | }; 68 | } 69 | } 70 | 71 | return block; 72 | }) as ContentBlockParam[]; 73 | 74 | prunedAndFixedConversation.push({ 75 | role: message.role, 76 | content: processedBlocks, 77 | }); 78 | } 79 | 80 | // If first message is an user with tool_result we need to add a dummy assistant message 81 | // with a tool_use blocks to ensure the conversation is valid 82 | const firstMessage = prunedAndFixedConversation[0]; 83 | // Get all tool_result blocks from the first message 84 | const firstMessageToolResultBlocks = typeof firstMessage.content === 'string' ? [] : firstMessage.content.filter( 85 | (block) => block.type === 'tool_result', 86 | ); 87 | if (firstMessageToolResultBlocks.length > 0) { 88 | if (firstMessage.role !== 'user') { 89 | // just a sanity check 90 | throw new Error('Message with tool_result must be from user'); 91 | } 92 | 93 | // Add a dummy assistant message with a tool_use block for each tool_result block 94 | prunedAndFixedConversation.unshift({ 95 | role: 'assistant', 96 | content: firstMessageToolResultBlocks.map((block) => ({ 97 | type: 'tool_use', 98 | id: block.tool_use_id, 99 | name: '[unknown tool - this was added by the conversation manager to keep the conversation valid]', 100 | input: {}, 101 | })), 102 | }); 103 | } 104 | 105 | return prunedAndFixedConversation; 106 | } 107 | -------------------------------------------------------------------------------- /tests/utils.test.ts: -------------------------------------------------------------------------------- 1 | import type { MessageParam } from '@anthropic-ai/sdk/resources/index.js'; 2 | import { describe, it, expect } from 'vitest'; 3 | 4 | import { IMAGE_BASE64_PLACEHOLDER } from '../src/const.js'; 5 | import { pruneAndFixConversation } from '../src/utils.js'; 6 | 7 | describe('pruneAndFixConversation', () => { 8 | // Base 64 pruning 9 | it('should prune base64 encoded image content and replace with placeholder', () => { 10 | // A simple base64 string (not a real image, but enough for test) 11 | const base64String = 'aGVsbG8gd29ybGQ='; // "hello world" in base64 12 | const conversation = [ 13 | { role: 'user', content: 'Show me an image' }, 14 | { 15 | role: 'assistant', 16 | content: [ 17 | { type: 'text', text: 'I will use image tool' }, 18 | { type: 'tool_use', id: 'tool_img', name: 'img_tool', input: {} }, 19 | ], 20 | }, 21 | { 22 | role: 'user', 23 | content: [ 24 | { type: 'tool_result', tool_use_id: 'tool_img', content: base64String }, 25 | ], 26 | }, 27 | ]; 28 | 29 | const result = pruneAndFixConversation(conversation as MessageParam[]); 30 | 31 | // Check that conversation is preserved 32 | expect(result.length).toBe(conversation.length); 33 | expect(result[0].role).toBe('user'); 34 | expect(result[0].content).toBe('Show me an image'); 35 | expect(result[1].role).toBe('assistant'); 36 | expect(result[1].content[0].type).toBe('text'); 37 | expect(result[1].content[0].text).toBe('I will use image tool'); 38 | expect(result[1].content[1].type).toBe('tool_use'); 39 | expect(result[1].content[1].id).toBe('tool_img'); 40 | expect(result[1].content[1].name).toBe('img_tool'); 41 | 42 | // Check string message is replaced 43 | expect(result[2].content[0].content).toBe(IMAGE_BASE64_PLACEHOLDER); 44 | }); 45 | 46 | // Orphaned tool calling 47 | it('should NOT add dummy tool_result for tool_use in the last message', () => { 48 | const conversation: MessageParam[] = [ 49 | { role: 'user', content: 'scrape example com' }, 50 | // This is the last message with a tool_use, so it should NOT get a dummy tool_result 51 | { 52 | role: 'assistant', 53 | content: [ 54 | { type: 'text', text: 'I will use scraper tool' }, 55 | { id: 'last_tool', type: 'tool_use', name: 'scraper', input: { url: 'example.com' } }, 56 | ], 57 | }, 58 | ]; 59 | 60 | const result = pruneAndFixConversation(conversation as MessageParam[]); 61 | 62 | // Check that the result length is the same as the original conversation 63 | expect(result.length).toBe(conversation.length); 64 | expect(result[0].role).toBe('user'); 65 | expect(result[1].role).toBe('assistant'); 66 | expect(result[1].content.length).toBe(2); 67 | }); 68 | 69 | it('should add dummy tool use for orphaned tool result', () => { 70 | // it should add a message with a dummy tool use before the orphaned tool result 71 | // message 72 | const conversation: MessageParam[] = [ 73 | { 74 | role: 'user', 75 | content: [ 76 | { type: 'tool_result', tool_use_id: 'orphaned_tool_id', content: 'some result' }, 77 | ], 78 | }, 79 | { 80 | role: 'assistant', 81 | content: 'that is some nice result you got there', 82 | }, 83 | ]; 84 | 85 | const result = pruneAndFixConversation(conversation as MessageParam[]); 86 | 87 | expect(result.length).toBe(3); 88 | // Check that the first message is a dummy tool use 89 | expect(result[0].role).toBe('assistant'); 90 | expect(result[0].content[0].type).toBe('tool_use'); 91 | expect(result[0].content[0].id).toBe('orphaned_tool_id'); 92 | // Check that the second message is the original tool result 93 | expect(result[1].role).toBe('user'); 94 | expect(result[1].content[0].type).toBe('tool_result'); 95 | expect(result[1].content[0].tool_use_id).toBe('orphaned_tool_id'); 96 | // Check that the third message is the original assistant message 97 | expect(result[2].role).toBe('assistant'); 98 | expect(result[2].content).toBe('that is some nice result you got there'); 99 | }); 100 | 101 | it('should add dummy tool use for each orphaned tool result', () => { 102 | // it should add a message with a dummy tool use before each orphaned tool result 103 | const conversation: MessageParam[] = [ 104 | { 105 | role: 'user', 106 | content: [ 107 | { type: 'tool_result', tool_use_id: 'orphaned_tool_id_1', content: 'result 1' }, 108 | { type: 'tool_result', tool_use_id: 'orphaned_tool_id_2', content: 'result 2' }, 109 | ], 110 | }, 111 | { 112 | role: 'assistant', 113 | content: 'that is some nice result you got there', 114 | }, 115 | ]; 116 | const result = pruneAndFixConversation(conversation as MessageParam[]); 117 | expect(result.length).toBe(3); 118 | // Check that the first message is a dummy tool use for all orphaned tool results 119 | expect(result[0].role).toBe('assistant'); 120 | expect(result[0].content[0].type).toBe('tool_use'); 121 | expect(result[0].content[0].id).toBe('orphaned_tool_id_1'); 122 | expect(result[0].content[1].type).toBe('tool_use'); 123 | expect(result[0].content[1].id).toBe('orphaned_tool_id_2'); 124 | // Check that the second message is the first original tool result 125 | expect(result[1].role).toBe('user'); 126 | expect(result[1].content[0].type).toBe('tool_result'); 127 | expect(result[1].content[0].tool_use_id).toBe('orphaned_tool_id_1'); 128 | // Check that the third message is the second original tool result 129 | expect(result[1].content[1].type).toBe('tool_result'); 130 | expect(result[1].content[1].tool_use_id).toBe('orphaned_tool_id_2'); 131 | // Check that the fourth message is the original assistant message 132 | expect(result[2].role).toBe('assistant'); 133 | expect(result[2].content).toBe('that is some nice result you got there'); 134 | }); 135 | }); 136 | -------------------------------------------------------------------------------- /tsconfig.eslint.json: -------------------------------------------------------------------------------- 1 | { 2 | "extends": "./tsconfig.json", 3 | "include": [ 4 | "src", 5 | "test", 6 | "tests", 7 | "vitest.config.ts" 8 | ] 9 | } 10 | -------------------------------------------------------------------------------- /tsconfig.json: -------------------------------------------------------------------------------- 1 | { 2 | "extends": "@apify/tsconfig", 3 | "compilerOptions": { 4 | "module": "ESNext", 5 | "target": "ESNext", 6 | "outDir": "dist", 7 | "moduleResolution": "node", 8 | "noUnusedLocals": false, 9 | "lib": ["ES2022"], 10 | "skipLibCheck": true, 11 | "typeRoots": ["./types", "./node_modules/@types"], 12 | "strict": true 13 | }, 14 | "include": ["./src/**/*"], 15 | "exclude": ["node_modules"] 16 | } 17 | -------------------------------------------------------------------------------- /vitest.config.ts: -------------------------------------------------------------------------------- 1 | // eslint-disable-next-line import/extensions 2 | import { defineConfig } from 'vitest/config'; 3 | 4 | // eslint-disable-next-line import/no-default-export 5 | export default defineConfig({ 6 | test: { 7 | globals: true, 8 | environment: 'node', 9 | include: ['tests/**/*.ts'], 10 | }, 11 | }); 12 | --------------------------------------------------------------------------------