@mcpjam/cli 1.0.0 → 1.0.2

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/dist/index.js CHANGED
@@ -55,17 +55,134 @@ var EnvironmentFileSchema = z2.object({
55
55
  });
56
56
 
57
57
  // src/runner/test-runner.ts
58
- import { createServer } from "http";
59
58
  import { serve } from "@hono/node-server";
60
59
  import { Hono as Hono2 } from "hono";
61
60
 
62
61
  // src/server/tests-router.ts
63
62
  import { Hono } from "hono";
64
- import { createAnthropic } from "@ai-sdk/anthropic";
65
- import { createOpenAI } from "@ai-sdk/openai";
66
- import { createOllama } from "ollama-ai-provider";
67
63
  import { Agent } from "@mastra/core/agent";
68
64
 
65
+ // src/utils/logger.ts
66
+ import chalk from "chalk";
67
+ import Table from "cli-table3";
68
+ var Logger = class {
69
+ static progressCounter = 0;
70
+ static totalTests = 0;
71
+ static header(version) {
72
+ console.log(chalk.bold.blue(`MCPJAM CLI ${version}`));
73
+ console.log();
74
+ }
75
+ static startTests(count) {
76
+ this.progressCounter = 0;
77
+ this.totalTests = count;
78
+ console.log(chalk.gray(`Running ${count} tests...`));
79
+ console.log();
80
+ }
81
+ static toolCall(toolName) {
82
+ console.log(chalk.gray(`Tool called: ${toolName}`));
83
+ }
84
+ static testResult(result) {
85
+ this.progressCounter++;
86
+ const status = result.passed ? chalk.green("PASS") : chalk.red("FAIL");
87
+ const symbol = "\u25CF";
88
+ const testName = result.title.padEnd(40);
89
+ if (result.passed) {
90
+ const tools = result.calledTools.length > 0 ? chalk.gray(`(tools: ${result.calledTools.join(", ")})`) : chalk.gray("(no tools)");
91
+ console.log(` ${symbol} ${testName} ${status} ${tools}`);
92
+ } else {
93
+ console.log(` ${symbol} ${testName} ${status}`);
94
+ if (result.error) {
95
+ console.log(chalk.red(` Error: ${result.error}`));
96
+ } else {
97
+ if (result.calledTools.length > 0) {
98
+ console.log(
99
+ chalk.gray(` Called: ${result.calledTools.join(", ")}`)
100
+ );
101
+ }
102
+ if (result.missingTools.length > 0) {
103
+ console.log(
104
+ chalk.red(` Missing: ${result.missingTools.join(", ")}`)
105
+ );
106
+ }
107
+ if (result.unexpectedTools.length > 0) {
108
+ console.log(
109
+ chalk.yellow(
110
+ ` Unexpected: ${result.unexpectedTools.join(", ")}`
111
+ )
112
+ );
113
+ }
114
+ }
115
+ }
116
+ }
117
+ static summary(results) {
118
+ console.log();
119
+ const table = new Table({
120
+ chars: {
121
+ top: "\u2500",
122
+ "top-mid": "\u252C",
123
+ "top-left": "\u250C",
124
+ "top-right": "\u2510",
125
+ bottom: "\u2500",
126
+ "bottom-mid": "\u2534",
127
+ "bottom-left": "\u2514",
128
+ "bottom-right": "\u2518",
129
+ left: "\u2502",
130
+ "left-mid": "\u251C",
131
+ mid: "\u2500",
132
+ "mid-mid": "\u253C",
133
+ right: "\u2502",
134
+ "right-mid": "\u2524",
135
+ middle: "\u2502"
136
+ },
137
+ style: {
138
+ "padding-left": 1,
139
+ "padding-right": 1,
140
+ border: ["gray"]
141
+ },
142
+ colWidths: [65]
143
+ });
144
+ const passedText = results.passed > 0 ? chalk.green(`${results.passed} passed`) : "0 passed";
145
+ const failedText = results.failed > 0 ? chalk.red(`${results.failed} failed`) : "0 failed";
146
+ const summaryText = `Results: ${passedText}, ${failedText} (${results.duration}s total)`;
147
+ table.push([summaryText]);
148
+ console.log(table.toString());
149
+ }
150
+ static error(message) {
151
+ console.log();
152
+ console.log(chalk.red(`\u2715 Error: ${message}`));
153
+ }
154
+ static progress(current, total, testName) {
155
+ const progress = `[${current}/${total}]`;
156
+ console.log(chalk.gray(`${progress} ${testName}...`));
157
+ }
158
+ static testStarting(testName) {
159
+ console.log(chalk.gray(` Running ${testName}...`));
160
+ }
161
+ static serverConnection(serverCount, toolCount) {
162
+ console.log(
163
+ chalk.gray(
164
+ ` Connected to ${serverCount} servers (${toolCount} tools available)`
165
+ )
166
+ );
167
+ }
168
+ static testError(testName, error) {
169
+ console.log(chalk.red(` \u2715 ${testName} failed: ${error}`));
170
+ }
171
+ static connectionError(serverName, error) {
172
+ console.log(chalk.red(` \u2715 Failed to connect to ${serverName}: ${error}`));
173
+ }
174
+ static apiKeyError(provider, error) {
175
+ console.log(chalk.red(` \u2715 API key error for ${provider}: ${error}`));
176
+ }
177
+ static modelCreationError(provider, modelId, error) {
178
+ console.log(
179
+ chalk.red(
180
+ ` \u2715 Failed to create ${provider} model "${modelId}": ${error}`
181
+ )
182
+ );
183
+ }
184
+ };
185
+
69
186
  // ../server/services/mcpjam-client-manager.ts
70
187
  import { MCPClient as MCPClient2 } from "@mastra/mcp";
71
188
 
@@ -443,6 +560,10 @@ var MCPJamClientManager = class {
443
560
  for (const args of attempts) {
444
561
  try {
445
562
  const result = await tool.execute(args);
563
+ if (result && result.isError) {
564
+ const errorText = result.content && result.content[0] && result.content[0].text ? result.content[0].text : "Unknown error";
565
+ throw new Error(errorText);
566
+ }
446
567
  return { result };
447
568
  } catch (err) {
448
569
  lastError = err;
@@ -533,237 +654,348 @@ var MCPJamClientManager = class {
533
654
  }
534
655
  };
535
656
 
657
+ // src/utils/test-errors.ts
658
+ var TestError = class extends Error {
659
+ constructor(message, code, details) {
660
+ super(message);
661
+ this.code = code;
662
+ this.details = details;
663
+ this.name = "TestError";
664
+ }
665
+ };
666
+ var ModelError = class extends TestError {
667
+ constructor(provider, modelId, originalError) {
668
+ const message = formatModelError(provider, originalError);
669
+ super(message, "MODEL_ERROR", { provider, modelId, originalError });
670
+ }
671
+ };
672
+ var ServerConnectionError = class extends TestError {
673
+ constructor(serverName, originalError) {
674
+ super(
675
+ `Failed to connect to server '${serverName}': ${originalError}`,
676
+ "SERVER_CONNECTION_ERROR",
677
+ {
678
+ serverName,
679
+ originalError
680
+ }
681
+ );
682
+ }
683
+ };
684
+ var ValidationError = class extends TestError {
685
+ constructor(field, value, expected) {
686
+ super(
687
+ `Invalid ${field}: expected ${expected}, got ${value}`,
688
+ "VALIDATION_ERROR",
689
+ {
690
+ field,
691
+ value,
692
+ expected
693
+ }
694
+ );
695
+ }
696
+ };
697
+ function formatModelError(provider, originalError) {
698
+ const lowerError = originalError.toLowerCase();
699
+ if (lowerError.includes("api key") || lowerError.includes("401") || lowerError.includes("unauthorized") || lowerError.includes("authentication")) {
700
+ return `Invalid or missing API key for ${provider}. Check your API key configuration.`;
701
+ }
702
+ if (lowerError.includes("model") && lowerError.includes("not found")) {
703
+ return `Model not found for ${provider}. Check if the model ID is correct.`;
704
+ }
705
+ if (lowerError.includes("quota") || lowerError.includes("rate limit")) {
706
+ return `Rate limit or quota exceeded for ${provider}. Try again later.`;
707
+ }
708
+ return `Failed to create ${provider} model: ${originalError}`;
709
+ }
710
+ function createTestResult(testId, title, passed, error, calledTools = [], missingTools = [], unexpectedTools = []) {
711
+ return {
712
+ testId,
713
+ title,
714
+ passed,
715
+ calledTools,
716
+ missingTools,
717
+ unexpectedTools,
718
+ error,
719
+ duration: 0
720
+ };
721
+ }
722
+
723
+ // src/utils/connection-manager.ts
724
+ var TestConnectionManager = class {
725
+ clientManager;
726
+ connectedServers = /* @__PURE__ */ new Set();
727
+ constructor() {
728
+ this.clientManager = new MCPJamClientManager();
729
+ }
730
+ async connectToServers(serverConfigs) {
731
+ const connectionPromises = Object.entries(serverConfigs).map(
732
+ async ([name, config]) => {
733
+ if (!this.connectedServers.has(name)) {
734
+ try {
735
+ await this.clientManager.connectToServer(name, config);
736
+ this.connectedServers.add(name);
737
+ } catch (error) {
738
+ throw new ServerConnectionError(
739
+ name,
740
+ error?.message || "Unknown connection error"
741
+ );
742
+ }
743
+ }
744
+ }
745
+ );
746
+ await Promise.all(connectionPromises);
747
+ Logger.serverConnection(
748
+ Object.keys(serverConfigs).length,
749
+ this.clientManager.getAvailableTools().length
750
+ );
751
+ }
752
+ getAvailableTools() {
753
+ return this.clientManager.getAvailableTools();
754
+ }
755
+ getFlattenedTools() {
756
+ const allTools = this.getAvailableTools();
757
+ const flattenedTools = {};
758
+ for (const tool of allTools) {
759
+ flattenedTools[tool.name] = tool;
760
+ }
761
+ return flattenedTools;
762
+ }
763
+ async cleanup() {
764
+ try {
765
+ for (const serverName of this.connectedServers) {
766
+ await this.clientManager.disconnectFromServer(serverName);
767
+ }
768
+ this.connectedServers.clear();
769
+ } catch (error) {
770
+ throw new Error(
771
+ `Cleanup failed: ${error?.message || "Unknown error"}`
772
+ );
773
+ }
774
+ }
775
+ isConnected(serverName) {
776
+ return this.connectedServers.has(serverName);
777
+ }
778
+ getConnectedServers() {
779
+ return Array.from(this.connectedServers);
780
+ }
781
+ };
782
+
783
+ // src/utils/model-factory.ts
784
+ import { createAnthropic } from "@ai-sdk/anthropic";
785
+ import { createOpenAI } from "@ai-sdk/openai";
786
+ import { createOllama } from "ollama-ai-provider";
787
+ var MODEL_CREATORS = {
788
+ anthropic: (apiKey, modelId) => createAnthropic({ apiKey })(modelId),
789
+ openai: (apiKey, modelId) => createOpenAI({ apiKey })(modelId),
790
+ deepseek: (apiKey, modelId) => createOpenAI({
791
+ apiKey,
792
+ baseURL: "https://api.deepseek.com/v1"
793
+ })(modelId),
794
+ ollama: (_, modelId) => createOllama({
795
+ baseURL: process.env.OLLAMA_BASE_URL || "http://localhost:11434/api"
796
+ })(modelId, { simulateStreaming: true })
797
+ };
798
+ var ENV_KEYS = {
799
+ anthropic: "ANTHROPIC_API_KEY",
800
+ openai: "OPENAI_API_KEY",
801
+ deepseek: "DEEPSEEK_API_KEY"
802
+ };
803
+ function createModel(modelConfig, providerApiKeys = {}) {
804
+ const { provider, id: modelId } = modelConfig;
805
+ if (!(provider in MODEL_CREATORS)) {
806
+ throw new ModelError(
807
+ provider,
808
+ modelId,
809
+ `Unsupported provider: ${provider}`
810
+ );
811
+ }
812
+ try {
813
+ let apiKey;
814
+ if (provider !== "ollama") {
815
+ apiKey = providerApiKeys[provider] || process.env[ENV_KEYS[provider]];
816
+ if (!apiKey) {
817
+ throw new Error(
818
+ `Missing ${provider.toUpperCase()} API key. Set ${ENV_KEYS[provider]} environment variable or provide in environment file.`
819
+ );
820
+ }
821
+ }
822
+ const creator = MODEL_CREATORS[provider];
823
+ return creator(apiKey || "", modelId);
824
+ } catch (error) {
825
+ throw new ModelError(
826
+ provider,
827
+ modelId,
828
+ error?.message || "Unknown error"
829
+ );
830
+ }
831
+ }
832
+
833
+ // src/utils/test-validation.ts
834
+ function validateTest(test) {
835
+ if (!test) {
836
+ throw new ValidationError("test", test, "non-null object");
837
+ }
838
+ if (!test.id || typeof test.id !== "string") {
839
+ throw new ValidationError("test.id", test.id, "non-empty string");
840
+ }
841
+ if (!test.title || typeof test.title !== "string") {
842
+ throw new ValidationError("test.title", test.title, "non-empty string");
843
+ }
844
+ if (!test.model || typeof test.model !== "object") {
845
+ throw new ValidationError("test.model", test.model, "object");
846
+ }
847
+ if (!test.model.id || typeof test.model.id !== "string") {
848
+ throw new ValidationError(
849
+ "test.model.id",
850
+ test.model.id,
851
+ "non-empty string"
852
+ );
853
+ }
854
+ if (!test.model.provider || typeof test.model.provider !== "string") {
855
+ throw new ValidationError(
856
+ "test.model.provider",
857
+ test.model.provider,
858
+ "non-empty string"
859
+ );
860
+ }
861
+ }
862
+ function validateServerConfigs(serverConfigs, selectedServers) {
863
+ let validConfigs = {};
864
+ if (selectedServers && selectedServers.length > 0) {
865
+ for (const name of selectedServers) {
866
+ if (serverConfigs[name]) {
867
+ validConfigs[name] = serverConfigs[name];
868
+ }
869
+ }
870
+ } else {
871
+ validConfigs = serverConfigs;
872
+ }
873
+ if (Object.keys(validConfigs).length === 0) {
874
+ throw new ValidationError(
875
+ "serverConfigs",
876
+ validConfigs,
877
+ "at least one valid server configuration"
878
+ );
879
+ }
880
+ return validConfigs;
881
+ }
882
+ function analyzeToolResults(calledTools, expectedTools = []) {
883
+ const called = Array.from(calledTools);
884
+ const expectedSet = new Set(expectedTools);
885
+ const missing = expectedTools.filter((t) => !calledTools.has(t));
886
+ const unexpected = called.filter((t) => !expectedSet.has(t));
887
+ const passed = missing.length === 0 && unexpected.length === 0;
888
+ return {
889
+ called,
890
+ missing,
891
+ unexpected,
892
+ passed
893
+ };
894
+ }
895
+
536
896
  // src/server/tests-router.ts
537
897
  function createTestsRouter() {
538
898
  const tests = new Hono();
539
- tests.post("/run-all", async (c) => {
540
- const encoder = new TextEncoder();
899
+ let connectionManager = null;
900
+ tests.post("/run", async (c) => {
541
901
  try {
542
- let createModel2 = function(model) {
543
- switch (model.provider) {
544
- case "anthropic":
545
- return createAnthropic({
546
- apiKey: providerApiKeys?.anthropic || process.env.ANTHROPIC_API_KEY || ""
547
- })(model.id);
548
- case "openai":
549
- return createOpenAI({
550
- apiKey: providerApiKeys?.openai || process.env.OPENAI_API_KEY || ""
551
- })(model.id);
552
- case "deepseek":
553
- return createOpenAI({
554
- apiKey: providerApiKeys?.deepseek || process.env.DEEPSEEK_API_KEY || "",
555
- baseURL: "https://api.deepseek.com/v1"
556
- })(model.id);
557
- case "ollama":
558
- return createOllama({
559
- baseURL: process.env.OLLAMA_BASE_URL || "http://localhost:11434"
560
- })(model.id, { simulateStreaming: true });
561
- default:
562
- throw new Error(`Unsupported provider: ${model.provider}`);
563
- }
564
- };
565
- var createModel = createModel2;
566
902
  const body = await c.req.json();
567
- const testsInput = body?.tests || [];
568
- const allServers = body?.allServers || {};
569
- const providerApiKeys = body?.providerApiKeys || {};
570
- if (!Array.isArray(testsInput) || testsInput.length === 0) {
571
- return c.json({ success: false, error: "No tests provided" }, 400);
903
+ const { test, allServers = {}, providerApiKeys = {} } = body;
904
+ validateTest(test);
905
+ if (!connectionManager) {
906
+ connectionManager = new TestConnectionManager();
572
907
  }
573
- const readableStream = new ReadableStream({
574
- async start(controller) {
575
- let failed = false;
576
- const clientManager = new MCPJamClientManager();
577
- for (const test of testsInput) {
578
- console.log(`\u{1F50D} Starting test: ${test.title}`);
579
- const calledTools = /* @__PURE__ */ new Set();
580
- const expectedSet = new Set(test.expectedTools || []);
581
- let serverConfigs = {};
582
- if (test.selectedServers && test.selectedServers.length > 0) {
583
- for (const name of test.selectedServers) {
584
- if (allServers[name]) serverConfigs[name] = allServers[name];
585
- }
586
- } else {
587
- serverConfigs = allServers;
588
- }
589
- console.log(
590
- `\u{1F4CB} Test ${test.title} using servers: ${Object.keys(serverConfigs).join(", ")}`
591
- );
592
- if (Object.keys(serverConfigs).length === 0) {
593
- console.error(
594
- `\u274C No valid MCP server configs for test ${test.title}`
595
- );
596
- continue;
597
- }
598
- try {
599
- console.log(`\u{1F50C} Connecting to servers for ${test.title}...`);
600
- for (const [serverName, serverConfig] of Object.entries(
601
- serverConfigs
602
- )) {
603
- console.log(` Connecting to ${serverName}...`);
604
- await clientManager.connectToServer(serverName, serverConfig);
605
- console.log(` \u2705 Connected to ${serverName}`);
606
- }
607
- console.log(
608
- `\u{1F916} Creating model ${test.model.provider}:${test.model.id}...`
609
- );
610
- const model = createModel2(test.model);
611
- console.log(`\u{1F6E0}\uFE0F Getting tools for ${test.title}...`);
612
- const allTools = clientManager.getAvailableTools();
613
- const toolsByServer = {};
614
- for (const tool of allTools) {
615
- if (!toolsByServer[tool.serverId]) {
616
- toolsByServer[tool.serverId] = {};
617
- }
618
- toolsByServer[tool.serverId][tool.name] = {
619
- description: tool.description,
620
- inputSchema: tool.inputSchema,
621
- execute: async (params) => {
622
- const result = await clientManager.executeToolDirect(
623
- `${tool.serverId}:${tool.name}`,
624
- params
625
- );
626
- return result.result;
627
- }
628
- };
629
- }
630
- console.log(
631
- `\u2705 Got ${allTools.length} total tools across ${Object.keys(toolsByServer).length} servers`
632
- );
633
- console.log(
634
- `\u{1F50D} Servers:`,
635
- clientManager.mapIdsToOriginalNames(Object.keys(toolsByServer))
636
- );
637
- const agent = new Agent({
638
- name: `TestAgent-${test.id}`,
639
- instructions: "You are a helpful assistant with access to MCP tools",
640
- model
641
- });
642
- console.log(`\u{1F4AC} Starting agent stream for ${test.title}...`);
643
- const streamOptions = {
644
- maxSteps: 10,
645
- toolsets: toolsByServer,
646
- onStepFinish: ({
647
- text,
648
- toolCalls,
649
- toolResults
650
- }) => {
651
- if (toolCalls && toolCalls.length) {
652
- console.log(
653
- `\u{1F6E0}\uFE0F Tool calls:`,
654
- toolCalls.map((c2) => c2?.name || c2?.toolName)
655
- );
908
+ Logger.testStarting(test.title);
909
+ const calledTools = /* @__PURE__ */ new Set();
910
+ const serverConfigs = validateServerConfigs(
911
+ allServers,
912
+ test.selectedServers
913
+ );
914
+ try {
915
+ await connectionManager.connectToServers(serverConfigs);
916
+ const model = createModel(test.model, providerApiKeys);
917
+ const flattenedTools = connectionManager.getFlattenedTools();
918
+ const agent = new Agent({
919
+ name: `TestAgent-${test.id}`,
920
+ instructions: "You are a helpful assistant with access to MCP tools",
921
+ model,
922
+ tools: flattenedTools
923
+ });
924
+ const executeOptions = {
925
+ maxSteps: 15,
926
+ timeout: 6e4
927
+ // 60 second timeout
928
+ };
929
+ const result = await agent.generate(
930
+ [{ role: "user", content: test.prompt || "" }],
931
+ executeOptions
932
+ );
933
+ if (result.steps) {
934
+ for (let i = 0; i < result.steps.length; i++) {
935
+ const step = result.steps[i];
936
+ if (step) {
937
+ if (step.toolCalls) {
938
+ for (const toolCall of step.toolCalls) {
939
+ const toolName = toolCall?.toolName;
940
+ if (toolName) {
941
+ Logger.toolCall(toolName);
942
+ calledTools.add(toolName);
656
943
  }
657
- (toolCalls || []).forEach((c2) => {
658
- const toolName = c2?.name || c2?.toolName;
659
- if (toolName) {
660
- calledTools.add(toolName);
661
- }
662
- });
663
- }
664
- };
665
- const tAny = test;
666
- if (tAny?.advancedConfig?.toolChoice) {
667
- streamOptions.toolChoice = tAny.advancedConfig.toolChoice;
668
- }
669
- const stream = await agent.stream(
670
- [{ role: "user", content: test.prompt || "" }],
671
- streamOptions
672
- );
673
- console.log(`\u{1F4C4} Draining text stream for ${test.title}...`);
674
- for await (const _ of stream.textStream) {
675
- }
676
- console.log(`\u2705 Stream completed for ${test.title}`);
677
- const called = Array.from(calledTools);
678
- const missing = Array.from(expectedSet).filter(
679
- (t) => !calledTools.has(t)
680
- );
681
- const unexpected = called.filter((t) => !expectedSet.has(t));
682
- const passed = missing.length === 0 && unexpected.length === 0;
683
- console.log(
684
- `\u{1F4CA} Test ${test.title} result: ${passed ? "PASSED" : "FAILED"}`
685
- );
686
- if (!passed) failed = true;
687
- controller.enqueue(
688
- encoder.encode(
689
- `data: ${JSON.stringify({
690
- type: "result",
691
- testId: test.id,
692
- passed,
693
- calledTools: called,
694
- missingTools: missing,
695
- unexpectedTools: unexpected
696
- })}
697
-
698
- `
699
- )
700
- );
701
- } catch (err) {
702
- console.error(`\u274C Test ${test.title} failed:`, err);
703
- failed = true;
704
- controller.enqueue(
705
- encoder.encode(
706
- `data: ${JSON.stringify({
707
- type: "result",
708
- testId: test.id,
709
- passed: false,
710
- error: err?.message
711
- })}
712
-
713
- `
714
- )
715
- );
716
- } finally {
717
- console.log(`\u{1F50C} Disconnecting servers for ${test.title}...`);
718
- for (const serverName of Object.keys(serverConfigs)) {
719
- try {
720
- await clientManager.disconnectFromServer(serverName);
721
- console.log(` \u2705 Disconnected from ${serverName}`);
722
- } catch (disconnectErr) {
723
- console.log(
724
- ` \u26A0\uFE0F Disconnect error from ${serverName}:`,
725
- disconnectErr
726
- );
727
944
  }
728
945
  }
729
- console.log(`\u2705 Test ${test.title} cleanup complete`);
730
946
  }
731
947
  }
732
- controller.enqueue(
733
- encoder.encode(
734
- `data: ${JSON.stringify({
735
- type: "run_complete",
736
- passed: !failed
737
- })}
738
-
739
- `
740
- )
741
- );
742
- controller.enqueue(encoder.encode(`data: [DONE]
743
-
744
- `));
745
- controller.close();
746
- }
747
- });
748
- return new Response(readableStream, {
749
- headers: {
750
- "Content-Type": "text/event-stream",
751
- "Cache-Control": "no-cache",
752
- Connection: "keep-alive"
753
948
  }
754
- });
949
+ const { called, missing, unexpected, passed } = analyzeToolResults(
950
+ calledTools,
951
+ test.expectedTools
952
+ );
953
+ return c.json({
954
+ success: true,
955
+ testId: test.id,
956
+ passed,
957
+ calledTools: called,
958
+ missingTools: missing,
959
+ unexpectedTools: unexpected
960
+ });
961
+ } catch (err) {
962
+ const errorMessage = err?.message || "Unknown error";
963
+ Logger.testError(test.title, errorMessage);
964
+ const failedResult = createTestResult(
965
+ test.id,
966
+ test.title,
967
+ false,
968
+ errorMessage,
969
+ [],
970
+ test.expectedTools || [],
971
+ []
972
+ );
973
+ return c.json({ success: false, ...failedResult });
974
+ }
755
975
  } catch (err) {
756
- return c.json(
757
- { success: false, error: err?.message || "Unknown error" },
758
- 500
759
- );
976
+ const errorMessage = err?.message || "Unknown error";
977
+ return c.json({ success: false, error: errorMessage }, 500);
978
+ }
979
+ });
980
+ tests.post("/cleanup", async (c) => {
981
+ if (connectionManager) {
982
+ try {
983
+ await connectionManager.cleanup();
984
+ connectionManager = null;
985
+ return c.json({ success: true });
986
+ } catch (err) {
987
+ const errorMessage = err?.message || "Unknown error";
988
+ return c.json({ success: false, error: errorMessage }, 500);
989
+ }
760
990
  }
991
+ return c.json({ success: true });
761
992
  });
762
993
  return tests;
763
994
  }
764
995
 
765
- // src/runner/test-runner.ts
766
- async function findAvailablePort(startPort = 3500) {
996
+ // src/utils/utils.ts
997
+ import { createServer } from "http";
998
+ function findAvailablePort(startPort = 3500) {
767
999
  return new Promise((resolve2, reject) => {
768
1000
  const server = createServer();
769
1001
  server.listen(0, () => {
@@ -777,6 +1009,8 @@ async function findAvailablePort(startPort = 3500) {
777
1009
  });
778
1010
  });
779
1011
  }
1012
+
1013
+ // src/runner/test-runner.ts
780
1014
  async function runTests(tests, environment) {
781
1015
  const startTime = Date.now();
782
1016
  const app = new Hono2();
@@ -788,36 +1022,49 @@ async function runTests(tests, environment) {
788
1022
  });
789
1023
  await new Promise((resolve2) => setTimeout(resolve2, 100));
790
1024
  try {
791
- const backendTests = tests.map((test, index) => ({
792
- id: `test_${index}`,
793
- title: test.title,
794
- prompt: test.prompt,
795
- expectedTools: test.expectedTools,
796
- model: test.model,
797
- selectedServers: test.selectedServers
798
- }));
799
- const backendServers = Object.fromEntries(
800
- Object.entries(environment.mcpServers).map(([name, config]) => [
801
- name,
802
- convertServerConfig(config)
803
- ])
804
- );
805
- const payload = {
806
- tests: backendTests,
807
- allServers: backendServers,
808
- providerApiKeys: environment.providerApiKeys || {}
809
- };
810
- const response = await fetch(`http://localhost:${port}/mcp/tests/run-all`, {
811
- method: "POST",
812
- headers: { "Content-Type": "application/json" },
813
- body: JSON.stringify(payload)
814
- });
815
- if (!response.ok) {
816
- throw new Error(
817
- `Server error: ${response.status} ${response.statusText}`
818
- );
1025
+ const backendServers = convertServersConfig(environment.mcpServers);
1026
+ const results = [];
1027
+ for (let i = 0; i < tests.length; i++) {
1028
+ const test = tests[i];
1029
+ if (!test) {
1030
+ throw new Error(`Test ${i} is undefined`);
1031
+ }
1032
+ const payload = {
1033
+ test: { ...test, id: `test_${i}` },
1034
+ allServers: backendServers,
1035
+ providerApiKeys: environment.providerApiKeys || {}
1036
+ };
1037
+ try {
1038
+ const response = await fetch(`http://localhost:${port}/mcp/tests/run`, {
1039
+ method: "POST",
1040
+ headers: { "Content-Type": "application/json" },
1041
+ body: JSON.stringify(payload)
1042
+ });
1043
+ if (!response.ok) {
1044
+ throw new Error(
1045
+ `Server error: ${response.status} ${response.statusText}`
1046
+ );
1047
+ }
1048
+ const result = await response.json();
1049
+ const testResult = { ...result, title: test.title, duration: 0 };
1050
+ results.push(testResult);
1051
+ Logger.testResult(testResult);
1052
+ } catch (testError) {
1053
+ const errorMessage = testError?.message || "Unknown error";
1054
+ const testResult = createTestResult(
1055
+ `test_${i}`,
1056
+ test.title,
1057
+ false,
1058
+ errorMessage,
1059
+ [],
1060
+ test.expectedTools || [],
1061
+ []
1062
+ );
1063
+ results.push(testResult);
1064
+ Logger.testResult(testResult);
1065
+ }
819
1066
  }
820
- const results = await processStreamingResults(response, tests);
1067
+ await cleanupServerConnections(port);
821
1068
  const duration = ((Date.now() - startTime) / 1e3).toFixed(1);
822
1069
  return {
823
1070
  passed: results.filter((r) => r.passed).length,
@@ -838,85 +1085,30 @@ function convertServerConfig(config) {
838
1085
  args: config.args || [],
839
1086
  env: config.env || {}
840
1087
  };
841
- } else {
842
- return {
843
- url: config.url,
844
- requestInit: {
845
- headers: config.headers || {}
846
- },
847
- eventSourceInit: {
848
- headers: config.headers || {}
849
- }
850
- };
851
1088
  }
1089
+ return {
1090
+ url: config.url,
1091
+ requestInit: { headers: config.headers || {} },
1092
+ eventSourceInit: { headers: config.headers || {} }
1093
+ };
852
1094
  }
853
- async function processStreamingResults(response, tests) {
854
- const results = [];
855
- const reader = response.body?.getReader();
856
- const decoder = new TextDecoder();
857
- if (!reader) {
858
- throw new Error("No response body");
859
- }
860
- let buffer = "";
861
- while (true) {
862
- const { done, value } = await reader.read();
863
- if (done) break;
864
- buffer += decoder.decode(value, { stream: true });
865
- const lines = buffer.split("\n");
866
- buffer = lines.pop() || "";
867
- for (const line of lines) {
868
- if (line.startsWith("data: ")) {
869
- const data = line.slice(6);
870
- if (data === "[DONE]") break;
871
- try {
872
- const event = JSON.parse(data);
873
- if (event.type === "result") {
874
- const testIndex = parseInt(event.testId.split("_")[1]);
875
- const test = tests[testIndex];
876
- const testStart = Date.now();
877
- const result = {
878
- testId: event.testId,
879
- title: test?.title || "Unknown Test",
880
- passed: event.passed,
881
- calledTools: event.calledTools || [],
882
- missingTools: event.missingTools || [],
883
- unexpectedTools: event.unexpectedTools || [],
884
- error: event.error,
885
- duration: 0
886
- // We don't have individual timing from the stream
887
- };
888
- results.push(result);
889
- if (result.passed) {
890
- console.log(`\u2705 ${result.title}`);
891
- console.log(
892
- ` Called tools: ${result.calledTools.join(", ") || "none"}`
893
- );
894
- } else {
895
- console.log(`\u274C ${result.title}`);
896
- if (result.error) {
897
- console.log(` Error: ${result.error}`);
898
- } else {
899
- console.log(
900
- ` Called tools: ${result.calledTools.join(", ") || "none"}`
901
- );
902
- if (result.missingTools.length > 0) {
903
- console.log(` Missing: ${result.missingTools.join(", ")}`);
904
- }
905
- if (result.unexpectedTools.length > 0) {
906
- console.log(
907
- ` Unexpected: ${result.unexpectedTools.join(", ")}`
908
- );
909
- }
910
- }
911
- }
912
- } else if (event.type === "trace_step") {
913
- }
914
- } catch (e) {
915
- }
916
- }
917
- }
1095
+ function convertServersConfig(mcpServers) {
1096
+ return Object.fromEntries(
1097
+ Object.entries(mcpServers).map(([name, config]) => [
1098
+ name,
1099
+ convertServerConfig(config)
1100
+ ])
1101
+ );
1102
+ }
1103
+ async function cleanupServerConnections(port) {
1104
+ try {
1105
+ await fetch(`http://localhost:${port}/mcp/tests/cleanup`, {
1106
+ method: "POST",
1107
+ headers: { "Content-Type": "application/json" }
1108
+ });
1109
+ } catch (cleanupError) {
1110
+ console.warn("Warning: Failed to cleanup server connections");
918
1111
  }
919
- return results;
920
1112
  }
921
1113
 
922
1114
  // src/utils/env-resolver.ts
@@ -977,28 +1169,20 @@ function resolveTemplate(value) {
977
1169
  var evalsCommand = new Command("evals");
978
1170
  evalsCommand.description("Run MCP evaluations").command("run").description("Run tests against MCP servers").requiredOption("-t, --tests <file>", "Path to tests JSON file").requiredOption("-e, --environment <file>", "Path to environment JSON file").action(async (options) => {
979
1171
  try {
980
- console.log("MCPJAM Evals v1.0.0\n");
1172
+ Logger.header("v1.0.0");
981
1173
  const testsContent = await readFile(resolve(options.tests), "utf8");
982
1174
  const testsData = TestsFileSchema.parse(JSON.parse(testsContent));
983
1175
  const envContent = await readFile(resolve(options.environment), "utf8");
984
1176
  const envData = EnvironmentFileSchema.parse(JSON.parse(envContent));
985
1177
  const resolvedEnv = resolveEnvironmentVariables(envData);
986
- console.log(`Running ${testsData.tests.length} tests...
987
- `);
1178
+ Logger.startTests(testsData.tests.length);
988
1179
  const results = await runTests(testsData.tests, resolvedEnv);
989
- console.log(
990
- `
991
- Results: ${results.passed} passed, ${results.failed} failed (${results.duration}s total)
992
- `
993
- );
1180
+ Logger.summary(results);
994
1181
  if (results.failed > 0) {
995
1182
  process.exit(1);
996
1183
  }
997
1184
  } catch (error) {
998
- console.error(
999
- "\u274C Error:",
1000
- error instanceof Error ? error.message : String(error)
1001
- );
1185
+ Logger.error(error instanceof Error ? error.message : String(error));
1002
1186
  process.exit(1);
1003
1187
  }
1004
1188
  });