
MCP Stress Tester
Pricing
Pay per usage
Go to Apify Store

MCP Stress Tester
A simple MCP Stress Tester client Actor for stress-testing your Model Context Protocol server. 💻⚡
0.0 (0)
Pricing
Pay per usage
0
3
1
Last modified
3 months ago
Pricing
Pay per usage
A simple MCP Stress Tester client Actor for stress-testing your Model Context Protocol server. 💻⚡
0.0 (0)
Pricing
Pay per usage
0
3
1
Last modified
3 months ago
# configurations.idea.vscode
# crawlee and apify storage foldersapify_storagecrawlee_storagestorage
# installed filesnode_modules
# git folder.git
# dist folderdist
INPUT.json
# This file tells Git which files shouldn't be added to source control
.idea.vscode.zedstorageapify_storagecrawlee_storagenode_modulesdisttsconfig.tsbuildinfostorage/*!storage/key_value_storesstorage/key_value_stores/*!storage/key_value_stores/defaultstorage/key_value_stores/default/*!storage/key_value_stores/default/INPUT.json
# Added by Apify CLI.venv
INPUT.json
Apache License Version 2.0, January 2004 http://www.apache.org/licenses/
TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
1. Definitions.
"License" shall mean the terms and conditions for use, reproduction, and distribution as defined by Sections 1 through 9 of this document.
"Licensor" shall mean the copyright owner or entity authorized by the copyright owner that is granting the License.
"Legal Entity" shall mean the union of the acting entity and all other entities that control, are controlled by, or are under common control with that entity. For the purposes of this definition, "control" means (i) the power, direct or indirect, to cause the direction or management of such entity, whether by contract or otherwise, or (ii) ownership of fifty percent (50%) or more of the outstanding shares, or (iii) beneficial ownership of such entity.
"You" (or "Your") shall mean an individual or Legal Entity exercising permissions granted by this License.
"Source" form shall mean the preferred form for making modifications, including but not limited to software source code, documentation source, and configuration files.
"Object" form shall mean any form resulting from mechanical transformation or translation of a Source form, including but not limited to compiled object code, generated documentation, and conversions to other media types.
"Work" shall mean the work of authorship, whether in Source or Object form, made available under the License, as indicated by a copyright notice that is included in or attached to the work (an example is provided in the Appendix below).
"Derivative Works" shall mean any work, whether in Source or Object form, that is based on (or derived from) the Work and for which the editorial revisions, annotations, elaborations, or other modifications represent, as a whole, an original work of authorship. For the purposes of this License, Derivative Works shall not include works that remain separable from, or merely link (or bind by name) to the interfaces of, the Work and Derivative Works thereof.
"Contribution" shall mean any work of authorship, including the original version of the Work and any modifications or additions to that Work or Derivative Works thereof, that is intentionally submitted to Licensor for inclusion in the Work by the copyright owner or by an individual or Legal Entity authorized to submit on behalf of the copyright owner. For the purposes of this definition, "submitted" means any form of electronic, verbal, or written communication sent to the Licensor or its representatives, including but not limited to communication on electronic mailing lists, source code control systems, and issue tracking systems that are managed by, or on behalf of, the Licensor for the purpose of discussing and improving the Work, but excluding communication that is conspicuously marked or otherwise designated in writing by the copyright owner as "Not a Contribution."
"Contributor" shall mean Licensor and any individual or Legal Entity on behalf of whom a Contribution has been received by Licensor and subsequently incorporated within the Work.
2. Grant of Copyright License. Subject to the terms and conditions of this License, each Contributor hereby grants to You a perpetual, worldwide, non-exclusive, no-charge, royalty-free, irrevocable copyright license to reproduce, prepare Derivative Works of, publicly display, publicly perform, sublicense, and distribute the Work and such Derivative Works in Source or Object form.
3. Grant of Patent License. Subject to the terms and conditions of this License, each Contributor hereby grants to You a perpetual, worldwide, non-exclusive, no-charge, royalty-free, irrevocable (except as stated in this section) patent license to make, have made, use, offer to sell, sell, import, and otherwise transfer the Work, where such license applies only to those patent claims licensable by such Contributor that are necessarily infringed by their Contribution(s) alone or by combination of their Contribution(s) with the Work to which such Contribution(s) was submitted. If You institute patent litigation against any entity (including a cross-claim or counterclaim in a lawsuit) alleging that the Work or a Contribution incorporated within the Work constitutes direct or contributory patent infringement, then any patent licenses granted to You under this License for that Work shall terminate as of the date such litigation is filed.
4. Redistribution. You may reproduce and distribute copies of the Work or Derivative Works thereof in any medium, with or without modifications, and in Source or Object form, provided that You meet the following conditions:
(a) You must give any other recipients of the Work or Derivative Works a copy of this License; and
(b) You must cause any modified files to carry prominent notices stating that You changed the files; and
(c) You must retain, in the Source form of any Derivative Works that You distribute, all copyright, patent, trademark, and attribution notices from the Source form of the Work, excluding those notices that do not pertain to any part of the Derivative Works; and
(d) If the Work includes a "NOTICE" text file as part of its distribution, then any Derivative Works that You distribute must include a readable copy of the attribution notices contained within such NOTICE file, excluding those notices that do not pertain to any part of the Derivative Works, in at least one of the following places: within a NOTICE text file distributed as part of the Derivative Works; within the Source form or documentation, if provided along with the Derivative Works; or, within a display generated by the Derivative Works, if and wherever such third-party notices normally appear. The contents of the NOTICE file are for informational purposes only and do not modify the License. You may add Your own attribution notices within Derivative Works that You distribute, alongside or as an addendum to the NOTICE text from the Work, provided that such additional attribution notices cannot be construed as modifying the License.
You may add Your own copyright statement to Your modifications and may provide additional or different license terms and conditions for use, reproduction, or distribution of Your modifications, or for any such Derivative Works as a whole, provided Your use, reproduction, and distribution of the Work otherwise complies with the conditions stated in this License.
5. Submission of Contributions. Unless You explicitly state otherwise, any Contribution intentionally submitted for inclusion in the Work by You to the Licensor shall be under the terms and conditions of this License, without any additional terms or conditions. Notwithstanding the above, nothing herein shall supersede or modify the terms of any separate license agreement you may have executed with Licensor regarding such Contributions.
6. Trademarks. This License does not grant permission to use the trade names, trademarks, service marks, or product names of the Licensor, except as required for reasonable and customary use in describing the origin of the Work and reproducing the content of the NOTICE file.
7. Disclaimer of Warranty. Unless required by applicable law or agreed to in writing, Licensor provides the Work (and each Contributor provides its Contributions) on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied, including, without limitation, any warranties or conditions of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A PARTICULAR PURPOSE. You are solely responsible for determining the appropriateness of using or redistributing the Work and assume any risks associated with Your exercise of permissions under this License.
8. Limitation of Liability. In no event and under no legal theory, whether in tort (including negligence), contract, or otherwise, unless required by applicable law (such as deliberate and grossly negligent acts) or agreed to in writing, shall any Contributor be liable to You for damages, including any direct, indirect, special, incidental, or consequential damages of any character arising as a result of this License or out of the use or inability to use the Work (including but not limited to damages for loss of goodwill, work stoppage, computer failure or malfunction, or any and all other commercial damages or losses), even if such Contributor has been advised of the possibility of such damages.
9. Accepting Warranty or Additional Liability. While redistributing the Work or Derivative Works thereof, You may choose to offer, and charge a fee for, acceptance of support, warranty, indemnity, or other liability obligations and/or rights consistent with this License. However, in accepting such obligations, You may act only on Your own behalf and on Your sole responsibility, not on behalf of any other Contributor, and only if You agree to indemnify, defend, and hold each Contributor harmless for any liability incurred by, or claims asserted against, such Contributor by reason of your accepting any such warranty or additional liability.
END OF TERMS AND CONDITIONS
APPENDIX: How to apply the Apache License to your work.
To apply the Apache License to your work, attach the following boilerplate notice, with the fields enclosed by brackets "[]" replaced with your own identifying information. (Don't include the brackets!) The text should be enclosed in the appropriate comment syntax for the file format. We also recommend that a file or class name and description of purpose be included on the same "printed page" as the copyright notice for easier identification within third-party archives.
Copyright 2025 Apify Technologies s.r.o.
Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License.
{ "$schema": "https://biomejs.dev/schemas/1.9.4/schema.json", "vcs": { "enabled": false, "clientKind": "git", "useIgnoreFile": false }, "files": { "ignoreUnknown": false, "ignore": [] }, "formatter": { "enabled": true, "indentStyle": "space", "indentWidth": 4 }, "organizeImports": { "enabled": true }, "linter": { "enabled": true, "rules": { "recommended": true } }, "javascript": { "formatter": { "quoteStyle": "double" } }}
{ "name": "mcp-stress-tester", "version": "0.0.1", "type": "module", "description": "This is an example of an Apify actor.", "engines": { "node": ">=18.0.0" }, "bin": { "mcp-stress-tester": "./dist/index.js" }, "files": ["dist", "LICENSE", "README.md"], "dependencies": { "@modelcontextprotocol/sdk": "^1.12.3", "@types/yargs": "^17.0.33", "apify": "^3.4.2", "yargs": "^18.0.0", "yargs-parser": "^22.0.0" }, "devDependencies": { "@apify/tsconfig": "^0.1.1", "@biomejs/biome": "1.9.4", "tsx": "^4.19.4", "typescript": "^5.8.3" }, "scripts": { "build": "tsc", "format": "npx biome format", "format:fix": "npx biome format --write", "lint": "npx biome lint", "lint:fix": "npx biome lint --write", "test": "echo \"Error: oops, the actor has no tests yet, sad!\" && exit 1" }, "author": "It's not you it's me", "license": "ISC"}
{ "extends": "@apify/tsconfig", "compilerOptions": { "module": "NodeNext", "moduleResolution": "NodeNext", "target": "ES2022", "outDir": "dist", "noUnusedLocals": false, "skipLibCheck": true, "lib": ["DOM"] }, "include": ["./src/**/*"]}
FROM node:22-alpine AS builder
# Copy just package.json and package-lock.json# to speed up the build using Docker layer cache.COPY package*.json ./
# Install all dependencies. Don't audit to speed up the installation.RUN npm install --include=dev --audit=false
# Next, copy the source files using the user set# in the base image.COPY . ./
# Install all dependencies and build the project.# Don't audit to speed up the installation.RUN npm run build
# Create final imageFROM node:22-alpine
# Create and run as a non-root user.RUN adduser -h /home/apify -D apify# Create app directoryRUN mkdir -p /home/apify/appWORKDIR /home/apify/app
# Copy built JS files from builder imageCOPY /dist ./dist
# Copy just package.json and package-lock.json# to speed up the build using Docker layer cache.COPY package*.json ./RUN chown -R apify:apify /home/apify/appUSER apify
# Install NPM packages, skip optional and development dependencies to# keep the image small. Avoid logging too much and print the dependency# tree for debuggingRUN npm --quiet set progress=false \ && npm install --omit=dev --omit=optional \ && echo "Installed NPM packages:" \ && (npm list --omit=dev --all || true) \ && echo "Node.js version:" \ && node --version \ && echo "NPM version:" \ && npm --version \ && rm -r ~/.npm
# Tell Node.js this is a production environemntENV NODE_ENV=production
# Enable Node.js process to use a lot of memory (Actor has limit of 32GB)# Increases default size of headers. The original limit was 80kb, but from node 10+ they decided to lower it to 8kb.# However they did not think about all the sites there with large headers,# so we put back the old limit of 80kb, which seems to work just fine.ENV NODE_OPTIONS="--max_old_space_size=30000 --max-http-header-size=80000"
# Run the image.CMD ["node", "dist/main.js", "--silent"]
{ "actorSpecification": 1, "name": "mcp-stress-tester", "title": "MCP Stress Tester", "description": "A simple MCP Stress Tester client Actor for stress-testing your MCP server.", "version": "0.1", "meta": { "templateId": "ts-start" }, "input": "./input_schema.json", "dockerfile": "./Dockerfile"}
{ "title": "MCP Stress Tester", "type": "object", "schemaVersion": 1, "properties": { "target": { "title": "Target URL", "type": "string", "description": "Specify the target URL", "editor": "textfield" }, "sse": { "title": "Enable SSE", "type": "boolean", "description": "Enable SSE switch", "default": false, "editor": "checkbox" }, "token": { "title": "Bearer token", "type": "string", "description": "Optional Bearer token for authentication", "editor": "textfield", "isSecret": true }, "mode": { "title": "Test Mode", "type": "string", "description": "Test mode: 'normal' (persistent clients that continuously send operations) or 'swarm' (constantly creating/closing clients to simulate dynamic load patterns)", "default": "normal", "enum": ["normal", "swarm"], "enumTitles": ["Normal", "Swarm"], "editor": "select" }, "clients": { "title": "Number of clients", "type": "integer", "description": "In normal mode: total number of concurrent client connections to maintain. In swarm mode: number of clients to create in each batch.", "default": 10, "minimum": 1, "editor": "number" }, "clientsCreationBatchSize": { "title": "Clients creation batch size", "type": "integer", "description": "In normal mode: number of clients to create in each initialization batch (to avoid overwhelming the server). In swarm mode: this parameter is ignored.", "default": 5, "minimum": 1, "editor": "number" }, "opsRate": { "title": "Operations rate", "type": "integer", "description": "In normal mode: operations (list tools) per minute per client. In swarm mode: this parameter is ignored as each client performs exactly one operation before being closed.", "default": 30, "minimum": 1, "editor": "number" }, "swarmInterval": { "title": "Swarm interval (ms)", "type": "integer", "description": "Interval in ms between swarm batches (only used in swarm mode). Controls how frequently new client batches are created and destroyed.", "default": 5000, "minimum": 100, "editor": "number" }, "maxRetries": { "title": "Maximum retries", "type": "integer", "description": "Maximum number of retries for client creation", "default": 5, "minimum": 0, "editor": "number" }, "initialBackoffMs": { "title": "Initial backoff (ms)", "type": "integer", "description": "Initial backoff time in milliseconds", "default": 100, "minimum": 1, "editor": "number" }, "maxBackoffMs": { "title": "Maximum backoff (ms)", "type": "integer", "description": "Maximum backoff time in milliseconds", "default": 10000, "minimum": 1, "editor": "number" }, "backoffFactor": { "title": "Backoff factor", "type": "integer", "description": "Factor by which to increase backoff time after each retry", "default": 2, "minimum": 1, "editor": "number" } }, "required": ["target"]}
1#!/usr/bin/env node2import { log } from "apify";3import yargs from "yargs";4import { hideBin } from "yargs/helpers";5import { runNormalMode, runSwarmMode } from "./shared.js";6
7// Interface for input arguments8interface InputArgs {9 target: string;10 sse: boolean;11 clients: number;12 clientsCreationBatchSize: number;13 opsRate: number;14 maxRetries: number;15 initialBackoffMs: number;16 maxBackoffMs: number;17 backoffFactor: number;18 mode: "normal" | "swarm";19 swarmInterval: number;20}21
22// Parse command line arguments using yargs23const argv = yargs(hideBin(process.argv))24 .option("target", {25 alias: "t",26 type: "string",27 description: "Target MCP server URL",28 demandOption: true,29 })30 .option("sse", {31 type: "boolean",32 description: "Enable SSE transport",33 default: false,34 })35 .option("clients", {36 alias: "c",37 type: "number",38 description:39 "In normal mode: total number of concurrent client connections to maintain. In swarm mode: number of clients to create in each batch.",40 default: 10,41 })42 .option("clientsCreationBatchSize", {43 type: "number",44 description:45 "In normal mode: number of clients to create in each initialization batch (to avoid overwhelming the server). In swarm mode: this parameter is ignored.",46 default: 5,47 })48 .option("opsRate", {49 alias: "r",50 type: "number",51 description:52 "In normal mode: operations (list tools) per minute per client. In swarm mode: this parameter is ignored as each client performs exactly one operation before being closed.",53 default: 60,54 })55 .option("maxRetries", {56 type: "number",57 description: "Maximum number of retries",58 default: 3,59 })60 .option("initialBackoffMs", {61 type: "number",62 description: "Initial backoff in milliseconds",63 default: 100,64 })65 .option("maxBackoffMs", {66 type: "number",67 description: "Maximum backoff in milliseconds",68 default: 10000,69 })70 .option("backoffFactor", {71 type: "number",72 description: "Backoff factor",73 default: 2,74 })75 .option("mode", {76 type: "string",77 description:78 "Test mode: 'normal' (persistent clients that continuously send operations) or 'swarm' (constantly creating/closing clients to simulate dynamic load patterns)",79 choices: ["normal", "swarm"],80 default: "normal",81 })82 .option("swarmInterval", {83 type: "number",84 description:85 "Interval in ms between swarm batches (only used in swarm mode). Controls how frequently new client batches are created and destroyed.",86 default: 5000,87 })88 .help()89 .alias("help", "h")90 .version()91 .alias("version", "v")92 .parse();93
94const {95 target: targetUrl,96 sse: sseEnabled,97 clients: numClients,98 clientsCreationBatchSize,99 opsRate,100 maxRetries,101 initialBackoffMs,102 maxBackoffMs,103 backoffFactor,104 mode,105 swarmInterval,106}: InputArgs = argv as InputArgs;107
108async function main() {109 log.info(`Starting benchmark with the following configuration:110- Target URL: ${targetUrl}111- SSE Enabled: ${sseEnabled}112- Mode: ${mode}113- Number of Clients: ${numClients}114- Clients Creation Batch Size: ${clientsCreationBatchSize}115- Operations Per Minute: ${opsRate}116- Max Retries: ${maxRetries}117- Initial Backoff: ${initialBackoffMs}ms118- Max Backoff: ${maxBackoffMs}ms119- Backoff Factor: ${backoffFactor}120${mode === "swarm" ? `- Swarm Interval: ${swarmInterval}ms` : ""}121`);122
123 if (mode === "normal") {124 await runNormalMode(125 targetUrl,126 process.env.APIFY_TOKEN as string,127 sseEnabled,128 numClients,129 clientsCreationBatchSize,130 opsRate,131 maxRetries,132 initialBackoffMs,133 maxBackoffMs,134 backoffFactor,135 );136 } else if (mode === "swarm") {137 await runSwarmMode(138 targetUrl,139 process.env.APIFY_TOKEN as string,140 sseEnabled,141 numClients,142 swarmInterval,143 maxRetries,144 initialBackoffMs,145 maxBackoffMs,146 backoffFactor,147 );148 } else {149 log.error(`Unknown mode: ${mode}`);150 process.exit(1);151 }152}153
154main().catch((error) => {155 log.error("Error in main execution:", error);156 process.exit(1);157});
1import { Actor, log } from "apify";2import { runNormalMode, runSwarmMode } from "./shared.js";3
4await Actor.init();5
6interface Input {7 target: string;8 sse: boolean;9 token: string;10 clients: number;11 clientsCreationBatchSize: number;12 opsRate: number;13 maxRetries: number;14 initialBackoffMs: number;15 maxBackoffMs: number;16 backoffFactor: number;17 mode: "normal" | "swarm";18 swarmInterval: number;19}20// Structure of input is defined in input_schema.json21const input = await Actor.getInput<Input>();22if (!input) throw new Error("Input is missing!");23const {24 target: targetUrl,25 sse: sseEnabled,26 token,27 clients: numClients,28 clientsCreationBatchSize,29 opsRate,30 maxRetries,31 initialBackoffMs,32 maxBackoffMs,33 backoffFactor,34 mode = "normal",35 swarmInterval = 5000,36} = input;37
38log.info(`Starting benchmark with the following configuration:39- Target URL: ${targetUrl}40- SSE Enabled: ${sseEnabled}41- Mode: ${mode}42${mode === "normal" ? `- Number of Clients: ${numClients} (total concurrent connections)` : `- Clients Per Batch: ${numClients}`}43${mode === "normal" ? `- Clients Creation Batch Size: ${clientsCreationBatchSize} (for initialization)` : ""}44${mode === "normal" ? `- Operations Per Minute Per Client: ${opsRate}` : ""}45- Max Retries: ${maxRetries}46- Initial Backoff: ${initialBackoffMs}ms47- Max Backoff: ${maxBackoffMs}ms48- Backoff Factor: ${backoffFactor}49${mode === "swarm" ? `- Swarm Interval: ${swarmInterval}ms (between batches)` : ""}50`);51
52if (mode === "normal") {53 await runNormalMode(54 targetUrl,55 token,56 sseEnabled,57 numClients,58 clientsCreationBatchSize,59 opsRate,60 maxRetries,61 initialBackoffMs,62 maxBackoffMs,63 backoffFactor,64 );65} else if (mode === "swarm") {66 await runSwarmMode(67 targetUrl,68 token,69 sseEnabled,70 numClients,71 swarmInterval,72 maxRetries,73 initialBackoffMs,74 maxBackoffMs,75 backoffFactor,76 );77} else {78 log.error(`Unknown mode: ${mode}`);79 process.exit(1);80}81
82// Gracefully exit the Actor process. It's recommended to quit all Actors with an exit().83await Actor.exit();
1import type { Client } from "@modelcontextprotocol/sdk/client/index.js";2import { createClient } from "./utils.js";3import { log } from "apify";4import { StreamableHTTPClientTransport } from "@modelcontextprotocol/sdk/client/streamableHttp.js";5
6export async function runNormalMode(7 targetUrl: string,8 token: string,9 sseEnabled: boolean,10 numClients: number,11 clientsCreationBatchSize: number,12 opsRate: number,13 maxRetries: number,14 initialBackoffMs: number,15 maxBackoffMs: number,16 backoffFactor: number,17) {18 const numBatches = Math.floor(numClients / clientsCreationBatchSize);19
20 const clients: Client[] = [];21 for (let i = 0; i < numBatches; i++) {22 const batch = await Promise.all(23 Array.from({ length: clientsCreationBatchSize }, () =>24 createClient({25 targetUrl,26 sseEnabled,27 token,28 maxRetries,29 initialBackoffMs,30 maxBackoffMs,31 backoffFactor,32 }),33 ),34 );35 log.info(36 `Created client batch ${i + 1} of ${Math.ceil(numClients / clientsCreationBatchSize)}`,37 );38 clients.push(...batch);39 }40 if (numClients % clientsCreationBatchSize !== 0) {41 const remainingClients = numClients % clientsCreationBatchSize;42 const batch = await Promise.all(43 Array.from({ length: remainingClients }, () =>44 createClient({45 targetUrl,46 sseEnabled,47 token,48 maxRetries,49 initialBackoffMs,50 maxBackoffMs,51 backoffFactor,52 }),53 ),54 );55 log.info(`Created final client batch of ${remainingClients}`);56 clients.push(...batch);57 }58
59 log.info(60 `Successfully created ${clients.length} clients. Starting benchmark operations...`,61 );62
63 const startTime = Date.now();64 let operationsCompleted = 0;65 let operationsFailed = 0;66
67 const intervalIDs = clients.map((_, index) => {68 return setInterval(async () => {69 try {70 await clients[index].listTools(undefined, {71 timeout: 60000,72 });73 operationsCompleted++;74 if (operationsCompleted % 100 === 0) {75 const elapsedSeconds = (Date.now() - startTime) / 1000;76 const opsPerSec = operationsCompleted / elapsedSeconds;77 log.info(78 `Completed ${operationsCompleted} operations (${(opsPerSec).toFixed(2)} ops/sec), failed: ${operationsFailed}`,79 );80 }81 } catch (error) {82 operationsFailed++;83 log.error(`Error listing tools for client ${index}: ${error}`);84 }85 }, 60000 / opsRate);86 });87
88 process.on("SIGINT", async () => {89 log.info("Received abort. Closing clients...");90 for (const id of intervalIDs) {91 clearInterval(id);92 }93
94 const elapsedSeconds = (Date.now() - startTime) / 1000;95 log.info(`96Benchmark Summary:97- Total operations completed: ${operationsCompleted}98- Total operations failed: ${operationsFailed}99- Average throughput: ${(operationsCompleted / elapsedSeconds).toFixed(2)} ops/sec100- Total runtime: ${elapsedSeconds.toFixed(2)} seconds101`);102
103 await Promise.all(clients.map((client) => client.close()))104 .then(() => {105 log.info("All clients closed.");106 process.exit(0);107 })108 .catch((error) => {109 log.error("Error closing clients:", error);110 process.exit(1);111 });112 });113
114 while (true) {115 await new Promise((resolve) => setTimeout(resolve, 1000));116 }117}118
119export async function runSwarmMode(120 targetUrl: string,121 token: string,122 sseEnabled: boolean,123 numClients: number,124 swarmInterval: number,125 maxRetries: number,126 initialBackoffMs: number,127 maxBackoffMs: number,128 backoffFactor: number,129) {130 const startTime = Date.now();131 let batchesCompleted = 0;132 let clientsCreated = 0;133 let operationsCompleted = 0;134 let operationsFailed = 0;135 let running = true;136
137 // In swarm mode, we use the numClients parameter for each batch138 const batchSize = numClients;139
140 process.on("SIGINT", async () => {141 log.info("Received abort. Stopping swarm mode...");142 running = false;143
144 const elapsedSeconds = (Date.now() - startTime) / 1000;145 log.info(`146Swarm Benchmark Summary:147- Total batches completed: ${batchesCompleted}148- Total clients created: ${clientsCreated}149- Total operations completed: ${operationsCompleted}150- Total operations failed: ${operationsFailed}151- Average client creation rate: ${(clientsCreated / elapsedSeconds).toFixed(2)} clients/sec152- Average operation rate: ${(operationsCompleted / elapsedSeconds).toFixed(2)} ops/sec153- Total runtime: ${elapsedSeconds.toFixed(2)} seconds154`);155 process.exit(0);156 });157
158 while (running) {159 try {160 // Create a batch of clients161 log.info(162 `Creating batch #${batchesCompleted + 1} with ${batchSize} clients...`,163 );164 const clients = await Promise.all(165 Array.from({ length: batchSize }, () =>166 createClient({167 targetUrl,168 sseEnabled,169 token,170 maxRetries,171 initialBackoffMs,172 maxBackoffMs,173 backoffFactor,174 }),175 ),176 );177 clientsCreated += clients.length;178
179 // Have each client list tools180 log.info(181 `Batch #${batchesCompleted + 1}: Listing tools with ${clients.length} clients...`,182 );183 const results = await Promise.allSettled(184 clients.map((client) =>185 client.listTools(undefined, { timeout: 60000 }),186 ),187 );188
189 // Count successes and failures190 const successes = results.filter(191 (r) => r.status === "fulfilled",192 ).length;193 const failures = results.filter(194 (r) => r.status === "rejected",195 ).length;196 operationsCompleted += successes;197 operationsFailed += failures;198
199 // Close all clients200 log.info(201 `Batch #${batchesCompleted + 1}: Closing ${clients.length} clients...`,202 );203 await Promise.all(204 clients.map((client) => {205 if (206 client.transport instanceof207 StreamableHTTPClientTransport208 ) {209 return client.transport.terminateSession();210 }211 return null;212 }),213 );214 await Promise.all(clients.map((client) => client.close()));215
216 batchesCompleted++;217
218 // Log progress periodically219 if (batchesCompleted % 5 === 0) {220 const elapsedSeconds = (Date.now() - startTime) / 1000;221 log.info(`222Swarm Progress:223- Batches completed: ${batchesCompleted}224- Clients created: ${clientsCreated}225- Operations completed: ${operationsCompleted} (${(operationsCompleted / elapsedSeconds).toFixed(2)} ops/sec)226- Operations failed: ${operationsFailed}227- Runtime: ${elapsedSeconds.toFixed(2)} seconds228`);229 }230
231 // Wait before creating the next batch232 await new Promise((resolve) => setTimeout(resolve, swarmInterval));233 } catch (error) {234 log.error(`Error in swarm batch: ${error}`);235 }236 }237}
1import { Client } from "@modelcontextprotocol/sdk/client/index.js";2import { SSEClientTransport } from "@modelcontextprotocol/sdk/client/sse.js";3import { StreamableHTTPClientTransport } from "@modelcontextprotocol/sdk/client/streamableHttp.js";4
5export type CreateClientOptions = {6 targetUrl: string;7 sseEnabled: boolean;8 token?: string;9 maxRetries?: number;10 initialBackoffMs?: number;11 maxBackoffMs?: number;12 backoffFactor?: number;13};14
15/**16 * Sleep for the specified number of milliseconds17 */18const sleep = (ms: number) => new Promise((resolve) => setTimeout(resolve, ms));19
20/**21 * Create a client with exponential backoff retry logic22 */23export async function createClient(24 options: CreateClientOptions,25): Promise<Client> {26 const {27 targetUrl,28 sseEnabled,29 token = "", // Default to empty string if not provided30 maxRetries = 5,31 initialBackoffMs = 100,32 maxBackoffMs = 10000,33 backoffFactor = 2,34 } = options;35
36 let retries = 0;37 let backoffMs = initialBackoffMs;38
39 while (true) {40 try {41 let transport: StreamableHTTPClientTransport | SSEClientTransport;42 if (sseEnabled) {43 transport = new SSEClientTransport(new URL(targetUrl), {44 requestInit: {45 headers: {46 ...(token47 ? { Authorization: `Bearer ${token}` }48 : {}),49 },50 },51 eventSourceInit: {52 // The EventSource package augments EventSourceInit with a "fetch" parameter.53 // You can use this to set additional headers on the outgoing request.54 // Based on this example: https://github.com/modelcontextprotocol/typescript-sdk/issues/11855 async fetch(56 input: Request | URL | string,57 init?: RequestInit,58 ) {59 const headers = new Headers(init?.headers || {});60 if (token)61 headers.set("authorization", `Bearer ${token}`);62 return fetch(input, { ...init, headers });63 },64 // We have to cast to "any" to use it, since it's non-standard65 },66 });67 } else {68 transport = new StreamableHTTPClientTransport(69 new URL(targetUrl),70 {71 requestInit: {72 headers: {73 ...(token74 ? { Authorization: `Bearer ${token}` }75 : {}),76 },77 },78 },79 );80 }81
82 const client = new Client({83 name: "benchmark-client",84 version: "1.0.0",85 });86
87 await client.connect(transport);88 return client;89 } catch (error) {90 retries++;91 if (retries > maxRetries) {92 console.error(93 `Failed to create client after ${maxRetries} retries:`,94 error,95 );96 throw error;97 }98
99 // Add jitter to avoid thundering herd problem100 const jitter = Math.random() * 0.3 + 0.85; // Random value between 0.85 and 1.15101 const actualBackoff = Math.min(backoffMs * jitter, maxBackoffMs);102
103 console.warn(104 `Client creation failed, retrying in ${Math.round(actualBackoff)}ms (attempt ${retries}/${maxRetries})`,105 );106 await sleep(actualBackoff);107
108 // Increase backoff for next attempt109 backoffMs = Math.min(backoffMs * backoffFactor, maxBackoffMs);110 }111 }112}
name: Create release
on: workflow_dispatch: # Manual trigger inputs: version: description: 'Release version (e.g., v0.0.1)' required: true prerelease: description: 'Is this a prerelease?' required: true default: false type: boolean
jobs: build-and-release: runs-on: ubuntu-latest
steps: # Checkout the repository - name: Checkout code uses: actions/checkout@v4
# Set up Node.js - name: Set up Node.js uses: actions/setup-node@v4 with: node-version: '22' cache: 'npm'
# Install dependencies - name: Install dependencies run: npm ci
# Run linting - name: Lint run: npm run lint
# Build the project - name: Build run: npm run build
# Create binary executable - name: Make binary executable run: chmod +x ./dist/index.js
# Create directory structure for packaging - name: Create package directory run: | mkdir -p package cp -r dist package/ cp package.json package/ cp README.md package/
# Package with package/ prefix as tarball - name: Package as tarball run: tar -czf mcp-stress-tester-${{ github.event.inputs.version }}.tar.gz package
# Package with package/ prefix as zip - name: Package as zip run: zip -r mcp-stress-tester-${{ github.event.inputs.version }}.zip package
# Create GitHub release - name: Create Release uses: softprops/action-gh-release@v2 with: tag_name: ${{ github.event.inputs.version }} name: MCP Stress Tester ${{ github.event.inputs.version }} body: | ## MCP Stress Tester ${{ github.event.inputs.version }}
### Installation
```bash # Install directly from GitHub release npm install -g https://github.com/apify/mcp-stress-tester/releases/download/${{ github.event.inputs.version }}/mcp-stress-tester-${{ github.event.inputs.version }}.tar.gz ``` ``` draft: false prerelease: ${{ github.event.inputs.prerelease }} files: | mcp-stress-tester-${{ github.event.inputs.version }}.tar.gz mcp-stress-tester-${{ github.event.inputs.version }}.zip