@mcpjam/cli 1.0.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/README.md +131 -0
- package/bin/mcpjam.js +12 -0
- package/dist/index.js +1011 -0
- package/dist/index.js.map +1 -0
- package/package.json +48 -0
package/README.md
ADDED
|
@@ -0,0 +1,131 @@
|
|
|
1
|
+
# MCPJam CLI
|
|
2
|
+
|
|
3
|
+
MCPJam CLI for programmatic MCP testing, designed for CI/CD integration and local development workflows.
|
|
4
|
+
|
|
5
|
+
## Installation
|
|
6
|
+
|
|
7
|
+
```bash
|
|
8
|
+
npm install -g @mcpjam/cli
|
|
9
|
+
```
|
|
10
|
+
|
|
11
|
+
## Usage
|
|
12
|
+
|
|
13
|
+
### Run MCP Evaluations
|
|
14
|
+
|
|
15
|
+
```bash
|
|
16
|
+
mcpjam evals run --tests weather-tests.json --environment local-dev.json
|
|
17
|
+
```
|
|
18
|
+
|
|
19
|
+
Short flags:
|
|
20
|
+
|
|
21
|
+
```bash
|
|
22
|
+
mcpjam evals run -t weather-tests.json -e local-dev.json
|
|
23
|
+
```
|
|
24
|
+
|
|
25
|
+
### CLI Options
|
|
26
|
+
|
|
27
|
+
- `--tests, -t <file>`: Path to the tests configuration file (required)
|
|
28
|
+
- `--environment, -e <file>`: Path to the environment configuration file (required)
|
|
29
|
+
- `--help, -h`: Show help information
|
|
30
|
+
- `--version, -V`: Display version number
|
|
31
|
+
|
|
32
|
+
### Example Files
|
|
33
|
+
|
|
34
|
+
The CLI includes example configuration files in the `examples/` directory:
|
|
35
|
+
|
|
36
|
+
- `test-servers.json`: Sample tests configuration
|
|
37
|
+
- `mcp-environment.json`: Sample environment configuration
|
|
38
|
+
|
|
39
|
+
## File Formats
|
|
40
|
+
|
|
41
|
+
### Tests File (mcp-tests.json)
|
|
42
|
+
|
|
43
|
+
```json
|
|
44
|
+
{
|
|
45
|
+
"tests": [
|
|
46
|
+
{
|
|
47
|
+
"title": "Test weather tool",
|
|
48
|
+
"prompt": "What's the weather in San Francisco?",
|
|
49
|
+
"expectedTools": ["get_weather"],
|
|
50
|
+
"model": { "id": "claude-3-5-sonnet-20241022", "provider": "anthropic" },
|
|
51
|
+
"selectedServers": ["weather-server"],
|
|
52
|
+
"advancedConfig": {
|
|
53
|
+
"instructions": "You are a helpful weather assistant",
|
|
54
|
+
"temperature": 0.1,
|
|
55
|
+
"maxSteps": 5,
|
|
56
|
+
"toolChoice": "auto"
|
|
57
|
+
}
|
|
58
|
+
}
|
|
59
|
+
]
|
|
60
|
+
}
|
|
61
|
+
```
|
|
62
|
+
|
|
63
|
+
### Environment File (mcp-environment.json)
|
|
64
|
+
|
|
65
|
+
```json
|
|
66
|
+
{
|
|
67
|
+
"mcpServers": {
|
|
68
|
+
"weather-server": {
|
|
69
|
+
"command": "python",
|
|
70
|
+
"args": ["weather_server.py"],
|
|
71
|
+
"env": {
|
|
72
|
+
"WEATHER_API_KEY": "${WEATHER_API_KEY}"
|
|
73
|
+
}
|
|
74
|
+
},
|
|
75
|
+
"api-server": {
|
|
76
|
+
"url": "https://api.example.com/mcp",
|
|
77
|
+
"headers": {
|
|
78
|
+
"Authorization": "Bearer ${API_TOKEN}"
|
|
79
|
+
}
|
|
80
|
+
}
|
|
81
|
+
},
|
|
82
|
+
"providerApiKeys": {
|
|
83
|
+
"anthropic": "${ANTHROPIC_API_KEY}",
|
|
84
|
+
"openai": "${OPENAI_API_KEY}",
|
|
85
|
+
"deepseek": "${DEEPSEEK_API_KEY}"
|
|
86
|
+
}
|
|
87
|
+
}
|
|
88
|
+
```
|
|
89
|
+
|
|
90
|
+
## Environment Variables
|
|
91
|
+
|
|
92
|
+
The CLI resolves template variables like `${ANTHROPIC_API_KEY}` from your environment at runtime.
|
|
93
|
+
|
|
94
|
+
Required environment variables depend on your test configuration:
|
|
95
|
+
|
|
96
|
+
- `ANTHROPIC_API_KEY` - For Claude models
|
|
97
|
+
- `OPENAI_API_KEY` - For OpenAI models
|
|
98
|
+
- `DEEPSEEK_API_KEY` - For DeepSeek models
|
|
99
|
+
- Custom variables for your MCP servers (e.g., `WEATHER_API_KEY`)
|
|
100
|
+
|
|
101
|
+
## Output Format
|
|
102
|
+
|
|
103
|
+
```
|
|
104
|
+
MCPJAM Evals v1.0.0
|
|
105
|
+
|
|
106
|
+
Running 3 tests against weather-server...
|
|
107
|
+
|
|
108
|
+
✅ Weather tool functionality
|
|
109
|
+
Called tools: get_weather
|
|
110
|
+
Duration: 1.2s
|
|
111
|
+
|
|
112
|
+
❌ Error handling test
|
|
113
|
+
Called tools: get_weather, validate_location
|
|
114
|
+
Missing: []
|
|
115
|
+
Unexpected: validate_location
|
|
116
|
+
Duration: 0.8s
|
|
117
|
+
|
|
118
|
+
Results: 2 passed, 1 failed (2.0s total)
|
|
119
|
+
```
|
|
120
|
+
|
|
121
|
+
## Supported Providers
|
|
122
|
+
|
|
123
|
+
- **anthropic**: Claude models via Anthropic API
|
|
124
|
+
- **openai**: GPT models via OpenAI API
|
|
125
|
+
- **deepseek**: DeepSeek models via DeepSeek API
|
|
126
|
+
- **ollama**: Local models via Ollama (requires Ollama to be running)
|
|
127
|
+
|
|
128
|
+
## Supported MCP Server Types
|
|
129
|
+
|
|
130
|
+
- **STDIO**: Local processes with command + args
|
|
131
|
+
- **HTTP**: Remote servers with URL + headers authentication
|
package/bin/mcpjam.js
ADDED
|
@@ -0,0 +1,12 @@
|
|
|
1
|
+
#!/usr/bin/env node
|
|
2
|
+
|
|
3
|
+
import { fileURLToPath } from "url";
|
|
4
|
+
import { dirname, resolve } from "path";
|
|
5
|
+
|
|
6
|
+
const __dirname = dirname(fileURLToPath(import.meta.url));
|
|
7
|
+
const cliPath = resolve(__dirname, "../dist/index.js");
|
|
8
|
+
|
|
9
|
+
import(cliPath).catch((err) => {
|
|
10
|
+
console.error("Failed to start MCPJam CLI:", err.message);
|
|
11
|
+
process.exit(1);
|
|
12
|
+
});
|
package/dist/index.js
ADDED
|
@@ -0,0 +1,1011 @@
|
|
|
1
|
+
// src/index.ts
|
|
2
|
+
import { Command as Command2 } from "commander";
|
|
3
|
+
|
|
4
|
+
// src/commands/evals.ts
|
|
5
|
+
import { Command } from "commander";
|
|
6
|
+
import { readFile } from "fs/promises";
|
|
7
|
+
import { resolve } from "path";
|
|
8
|
+
|
|
9
|
+
// schemas/test-schema.ts
|
|
10
|
+
import { z } from "zod";
|
|
11
|
+
var ModelSchema = z.object({
|
|
12
|
+
id: z.string(),
|
|
13
|
+
provider: z.enum(["openai", "anthropic", "deepseek", "ollama"])
|
|
14
|
+
});
|
|
15
|
+
var AdvancedConfigSchema = z.object({
|
|
16
|
+
instructions: z.string().optional(),
|
|
17
|
+
temperature: z.number().min(0).max(2).optional(),
|
|
18
|
+
maxSteps: z.number().positive().optional(),
|
|
19
|
+
toolChoice: z.enum(["auto", "required", "none"]).optional()
|
|
20
|
+
});
|
|
21
|
+
var TestSchema = z.object({
|
|
22
|
+
title: z.string(),
|
|
23
|
+
prompt: z.string(),
|
|
24
|
+
expectedTools: z.array(z.string()),
|
|
25
|
+
model: ModelSchema,
|
|
26
|
+
selectedServers: z.array(z.string()),
|
|
27
|
+
advancedConfig: AdvancedConfigSchema.optional()
|
|
28
|
+
});
|
|
29
|
+
var TestsFileSchema = z.object({
|
|
30
|
+
tests: z.array(TestSchema)
|
|
31
|
+
});
|
|
32
|
+
|
|
33
|
+
// schemas/environment-schema.ts
|
|
34
|
+
import { z as z2 } from "zod";
|
|
35
|
+
var MCPServerConfigSchema = z2.union([
|
|
36
|
+
// STDIO server
|
|
37
|
+
z2.object({
|
|
38
|
+
command: z2.string(),
|
|
39
|
+
args: z2.array(z2.string()).optional(),
|
|
40
|
+
env: z2.record(z2.string()).optional()
|
|
41
|
+
}),
|
|
42
|
+
// HTTP server
|
|
43
|
+
z2.object({
|
|
44
|
+
url: z2.string().url(),
|
|
45
|
+
headers: z2.record(z2.string()).optional()
|
|
46
|
+
})
|
|
47
|
+
]);
|
|
48
|
+
var EnvironmentFileSchema = z2.object({
|
|
49
|
+
mcpServers: z2.record(MCPServerConfigSchema),
|
|
50
|
+
providerApiKeys: z2.object({
|
|
51
|
+
anthropic: z2.string().optional(),
|
|
52
|
+
openai: z2.string().optional(),
|
|
53
|
+
deepseek: z2.string().optional()
|
|
54
|
+
}).optional()
|
|
55
|
+
});
|
|
56
|
+
|
|
57
|
+
// src/runner/test-runner.ts
|
|
58
|
+
import { createServer } from "http";
|
|
59
|
+
import { serve } from "@hono/node-server";
|
|
60
|
+
import { Hono as Hono2 } from "hono";
|
|
61
|
+
|
|
62
|
+
// src/server/tests-router.ts
|
|
63
|
+
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
|
+
import { Agent } from "@mastra/core/agent";
|
|
68
|
+
|
|
69
|
+
// ../server/services/mcpjam-client-manager.ts
|
|
70
|
+
import { MCPClient as MCPClient2 } from "@mastra/mcp";
|
|
71
|
+
|
|
72
|
+
// ../server/utils/mcp-utils.ts
|
|
73
|
+
import { MCPClient } from "@mastra/mcp";
|
|
74
|
+
function validateServerConfig(serverConfig) {
|
|
75
|
+
if (!serverConfig) {
|
|
76
|
+
return {
|
|
77
|
+
success: false,
|
|
78
|
+
error: {
|
|
79
|
+
message: "Server configuration is required",
|
|
80
|
+
status: 400
|
|
81
|
+
}
|
|
82
|
+
};
|
|
83
|
+
}
|
|
84
|
+
const config = { ...serverConfig };
|
|
85
|
+
if (config.url) {
|
|
86
|
+
try {
|
|
87
|
+
if (typeof config.url === "string") {
|
|
88
|
+
const parsed = new URL(config.url);
|
|
89
|
+
parsed.search = "";
|
|
90
|
+
parsed.hash = "";
|
|
91
|
+
config.url = parsed;
|
|
92
|
+
} else if (typeof config.url === "object" && !config.url.href) {
|
|
93
|
+
return {
|
|
94
|
+
success: false,
|
|
95
|
+
error: {
|
|
96
|
+
message: "Invalid URL configuration",
|
|
97
|
+
status: 400
|
|
98
|
+
}
|
|
99
|
+
};
|
|
100
|
+
}
|
|
101
|
+
if (config.oauth?.access_token) {
|
|
102
|
+
const authHeaders = {
|
|
103
|
+
Authorization: `Bearer ${config.oauth.access_token}`,
|
|
104
|
+
...config.requestInit?.headers || {}
|
|
105
|
+
};
|
|
106
|
+
config.requestInit = {
|
|
107
|
+
...config.requestInit,
|
|
108
|
+
headers: authHeaders
|
|
109
|
+
};
|
|
110
|
+
config.eventSourceInit = {
|
|
111
|
+
fetch(input, init) {
|
|
112
|
+
const headers = new Headers(init?.headers || {});
|
|
113
|
+
headers.set(
|
|
114
|
+
"Authorization",
|
|
115
|
+
`Bearer ${config.oauth.access_token}`
|
|
116
|
+
);
|
|
117
|
+
if (config.requestInit?.headers) {
|
|
118
|
+
const requestHeaders = new Headers(config.requestInit.headers);
|
|
119
|
+
requestHeaders.forEach((value, key) => {
|
|
120
|
+
if (key.toLowerCase() !== "authorization") {
|
|
121
|
+
headers.set(key, value);
|
|
122
|
+
}
|
|
123
|
+
});
|
|
124
|
+
}
|
|
125
|
+
return fetch(input, {
|
|
126
|
+
...init,
|
|
127
|
+
headers
|
|
128
|
+
});
|
|
129
|
+
}
|
|
130
|
+
};
|
|
131
|
+
} else if (config.requestInit?.headers) {
|
|
132
|
+
config.eventSourceInit = {
|
|
133
|
+
fetch(input, init) {
|
|
134
|
+
const headers = new Headers(init?.headers || {});
|
|
135
|
+
const requestHeaders = new Headers(config.requestInit.headers);
|
|
136
|
+
requestHeaders.forEach((value, key) => {
|
|
137
|
+
headers.set(key, value);
|
|
138
|
+
});
|
|
139
|
+
return fetch(input, {
|
|
140
|
+
...init,
|
|
141
|
+
headers
|
|
142
|
+
});
|
|
143
|
+
}
|
|
144
|
+
};
|
|
145
|
+
}
|
|
146
|
+
} catch (error) {
|
|
147
|
+
return {
|
|
148
|
+
success: false,
|
|
149
|
+
error: {
|
|
150
|
+
message: `Invalid URL format: ${error}`,
|
|
151
|
+
status: 400
|
|
152
|
+
}
|
|
153
|
+
};
|
|
154
|
+
}
|
|
155
|
+
}
|
|
156
|
+
return {
|
|
157
|
+
success: true,
|
|
158
|
+
config
|
|
159
|
+
};
|
|
160
|
+
}
|
|
161
|
+
|
|
162
|
+
// ../server/services/mcpjam-client-manager.ts
|
|
163
|
+
function generateUniqueServerId(serverId) {
|
|
164
|
+
const normalizedBase = serverId.toLowerCase().replace(/[\s\-]+/g, "_").replace(/[^a-z0-9_]/g, "");
|
|
165
|
+
const timestamp = Date.now().toString(36);
|
|
166
|
+
const random = Math.random().toString(36).substring(2, 8);
|
|
167
|
+
return `${normalizedBase}_${timestamp}_${random}`;
|
|
168
|
+
}
|
|
169
|
+
var MCPJamClientManager = class {
|
|
170
|
+
mcpClients = /* @__PURE__ */ new Map();
|
|
171
|
+
statuses = /* @__PURE__ */ new Map();
|
|
172
|
+
configs = /* @__PURE__ */ new Map();
|
|
173
|
+
// Map original server names to unique IDs
|
|
174
|
+
serverIdMapping = /* @__PURE__ */ new Map();
|
|
175
|
+
// Track in-flight connections to avoid duplicate concurrent connects
|
|
176
|
+
pendingConnections = /* @__PURE__ */ new Map();
|
|
177
|
+
toolRegistry = /* @__PURE__ */ new Map();
|
|
178
|
+
resourceRegistry = /* @__PURE__ */ new Map();
|
|
179
|
+
promptRegistry = /* @__PURE__ */ new Map();
|
|
180
|
+
// Store for pending elicitation requests with Promise resolvers
|
|
181
|
+
pendingElicitations = /* @__PURE__ */ new Map();
|
|
182
|
+
// Optional callback for handling elicitation requests
|
|
183
|
+
elicitationCallback;
|
|
184
|
+
// Helper method to get unique ID for a server name
|
|
185
|
+
getServerUniqueId(serverName) {
|
|
186
|
+
return this.serverIdMapping.get(serverName);
|
|
187
|
+
}
|
|
188
|
+
// Public method to get server ID for external use (like frontend)
|
|
189
|
+
getServerIdForName(serverName) {
|
|
190
|
+
return this.serverIdMapping.get(serverName);
|
|
191
|
+
}
|
|
192
|
+
// Public method to get original server name from a unique server ID
|
|
193
|
+
getOriginalNameForId(uniqueServerId) {
|
|
194
|
+
for (const [originalName, uid] of this.serverIdMapping.entries()) {
|
|
195
|
+
if (uid === uniqueServerId) return originalName;
|
|
196
|
+
}
|
|
197
|
+
return void 0;
|
|
198
|
+
}
|
|
199
|
+
// Convenience: map an array of unique IDs to their original names (fallback to ID if not found)
|
|
200
|
+
mapIdsToOriginalNames(uniqueIds) {
|
|
201
|
+
return uniqueIds.map((id) => this.getOriginalNameForId(id) || id);
|
|
202
|
+
}
|
|
203
|
+
async connectToServer(serverId, serverConfig) {
|
|
204
|
+
const pending = this.pendingConnections.get(serverId);
|
|
205
|
+
if (pending) {
|
|
206
|
+
await pending;
|
|
207
|
+
return;
|
|
208
|
+
}
|
|
209
|
+
const connectPromise = (async () => {
|
|
210
|
+
let id = this.serverIdMapping.get(serverId);
|
|
211
|
+
if (!id) {
|
|
212
|
+
id = generateUniqueServerId(serverId);
|
|
213
|
+
this.serverIdMapping.set(serverId, id);
|
|
214
|
+
}
|
|
215
|
+
if (this.mcpClients.has(id)) return;
|
|
216
|
+
const validation = validateServerConfig(serverConfig);
|
|
217
|
+
if (!validation.success) {
|
|
218
|
+
this.statuses.set(id, "error");
|
|
219
|
+
throw new Error(validation.error.message);
|
|
220
|
+
}
|
|
221
|
+
this.configs.set(id, validation.config);
|
|
222
|
+
this.statuses.set(id, "connecting");
|
|
223
|
+
const client = new MCPClient2({
|
|
224
|
+
id: `mcpjam-${id}`,
|
|
225
|
+
servers: { [id]: validation.config }
|
|
226
|
+
});
|
|
227
|
+
try {
|
|
228
|
+
await client.getTools();
|
|
229
|
+
this.mcpClients.set(id, client);
|
|
230
|
+
this.statuses.set(id, "connected");
|
|
231
|
+
if (client.elicitation?.onRequest) {
|
|
232
|
+
client.elicitation.onRequest(
|
|
233
|
+
id,
|
|
234
|
+
async (elicitationRequest) => {
|
|
235
|
+
return await this.handleElicitationRequest(elicitationRequest);
|
|
236
|
+
}
|
|
237
|
+
);
|
|
238
|
+
}
|
|
239
|
+
await this.discoverServerResources(id);
|
|
240
|
+
} catch (err) {
|
|
241
|
+
this.statuses.set(id, "error");
|
|
242
|
+
try {
|
|
243
|
+
await client.disconnect();
|
|
244
|
+
} catch {
|
|
245
|
+
}
|
|
246
|
+
this.mcpClients.delete(id);
|
|
247
|
+
throw err;
|
|
248
|
+
}
|
|
249
|
+
})().finally(() => {
|
|
250
|
+
this.pendingConnections.delete(serverId);
|
|
251
|
+
});
|
|
252
|
+
this.pendingConnections.set(serverId, connectPromise);
|
|
253
|
+
await connectPromise;
|
|
254
|
+
}
|
|
255
|
+
async disconnectFromServer(serverId) {
|
|
256
|
+
const id = this.getServerUniqueId(serverId);
|
|
257
|
+
if (!id) return;
|
|
258
|
+
const client = this.mcpClients.get(id);
|
|
259
|
+
if (client) {
|
|
260
|
+
try {
|
|
261
|
+
await client.disconnect();
|
|
262
|
+
} catch {
|
|
263
|
+
}
|
|
264
|
+
}
|
|
265
|
+
this.mcpClients.delete(id);
|
|
266
|
+
this.statuses.set(id, "disconnected");
|
|
267
|
+
this.serverIdMapping.delete(serverId);
|
|
268
|
+
for (const key of Array.from(this.toolRegistry.keys())) {
|
|
269
|
+
const item = this.toolRegistry.get(key);
|
|
270
|
+
if (item.serverId === id) this.toolRegistry.delete(key);
|
|
271
|
+
}
|
|
272
|
+
for (const key of Array.from(this.resourceRegistry.keys())) {
|
|
273
|
+
const item = this.resourceRegistry.get(key);
|
|
274
|
+
if (item.serverId === id) this.resourceRegistry.delete(key);
|
|
275
|
+
}
|
|
276
|
+
for (const key of Array.from(this.promptRegistry.keys())) {
|
|
277
|
+
const item = this.promptRegistry.get(key);
|
|
278
|
+
if (item.serverId === id) this.promptRegistry.delete(key);
|
|
279
|
+
}
|
|
280
|
+
}
|
|
281
|
+
getConnectionStatus(serverId) {
|
|
282
|
+
const id = this.getServerUniqueId(serverId);
|
|
283
|
+
return id ? this.statuses.get(id) || "disconnected" : "disconnected";
|
|
284
|
+
}
|
|
285
|
+
getConnectedServers() {
|
|
286
|
+
const servers = {};
|
|
287
|
+
for (const [originalName, uniqueId] of this.serverIdMapping.entries()) {
|
|
288
|
+
servers[originalName] = {
|
|
289
|
+
status: this.statuses.get(uniqueId) || "disconnected",
|
|
290
|
+
config: this.configs.get(uniqueId)
|
|
291
|
+
};
|
|
292
|
+
}
|
|
293
|
+
return servers;
|
|
294
|
+
}
|
|
295
|
+
async discoverAllResources() {
|
|
296
|
+
const serverIds = Array.from(this.mcpClients.keys());
|
|
297
|
+
await Promise.all(serverIds.map((id) => this.discoverServerResources(id)));
|
|
298
|
+
}
|
|
299
|
+
async discoverServerResources(serverId) {
|
|
300
|
+
const client = this.mcpClients.get(serverId);
|
|
301
|
+
if (!client) return;
|
|
302
|
+
const toolsets = await client.getToolsets();
|
|
303
|
+
const flattenedTools = {};
|
|
304
|
+
Object.values(toolsets).forEach((serverTools) => {
|
|
305
|
+
Object.assign(flattenedTools, serverTools);
|
|
306
|
+
});
|
|
307
|
+
for (const [name, tool] of Object.entries(flattenedTools)) {
|
|
308
|
+
this.toolRegistry.set(`${serverId}:${name}`, {
|
|
309
|
+
name,
|
|
310
|
+
description: tool.description,
|
|
311
|
+
inputSchema: tool.inputSchema,
|
|
312
|
+
outputSchema: tool.outputSchema,
|
|
313
|
+
serverId
|
|
314
|
+
});
|
|
315
|
+
}
|
|
316
|
+
try {
|
|
317
|
+
const res = await client.resources.list();
|
|
318
|
+
for (const [, list] of Object.entries(res)) {
|
|
319
|
+
for (const r of list) {
|
|
320
|
+
this.resourceRegistry.set(`${serverId}:${r.uri}`, {
|
|
321
|
+
uri: r.uri,
|
|
322
|
+
name: r.name,
|
|
323
|
+
description: r.description,
|
|
324
|
+
mimeType: r.mimeType,
|
|
325
|
+
serverId
|
|
326
|
+
});
|
|
327
|
+
}
|
|
328
|
+
}
|
|
329
|
+
} catch {
|
|
330
|
+
}
|
|
331
|
+
try {
|
|
332
|
+
const prompts = await client.prompts.list();
|
|
333
|
+
for (const [, list] of Object.entries(prompts)) {
|
|
334
|
+
for (const p of list) {
|
|
335
|
+
this.promptRegistry.set(`${serverId}:${p.name}`, {
|
|
336
|
+
name: p.name,
|
|
337
|
+
description: p.description,
|
|
338
|
+
arguments: p.arguments,
|
|
339
|
+
serverId
|
|
340
|
+
});
|
|
341
|
+
}
|
|
342
|
+
}
|
|
343
|
+
} catch {
|
|
344
|
+
}
|
|
345
|
+
}
|
|
346
|
+
getAvailableTools() {
|
|
347
|
+
return Array.from(this.toolRegistry.values());
|
|
348
|
+
}
|
|
349
|
+
async getToolsetsForServer(serverId) {
|
|
350
|
+
const id = this.getServerUniqueId(serverId);
|
|
351
|
+
if (!id) {
|
|
352
|
+
throw new Error(`No MCP client available for server: ${serverId}`);
|
|
353
|
+
}
|
|
354
|
+
const client = this.mcpClients.get(id);
|
|
355
|
+
if (!client) {
|
|
356
|
+
throw new Error(`No MCP client available for server: ${serverId}`);
|
|
357
|
+
}
|
|
358
|
+
const toolsets = await client.getToolsets();
|
|
359
|
+
const flattenedTools = {};
|
|
360
|
+
Object.values(toolsets).forEach((serverTools) => {
|
|
361
|
+
Object.assign(flattenedTools, serverTools);
|
|
362
|
+
});
|
|
363
|
+
return flattenedTools;
|
|
364
|
+
}
|
|
365
|
+
getAvailableResources() {
|
|
366
|
+
return Array.from(this.resourceRegistry.values());
|
|
367
|
+
}
|
|
368
|
+
getResourcesForServer(serverId) {
|
|
369
|
+
const id = this.getServerUniqueId(serverId);
|
|
370
|
+
if (!id) return [];
|
|
371
|
+
return Array.from(this.resourceRegistry.values()).filter(
|
|
372
|
+
(r) => r.serverId === id
|
|
373
|
+
);
|
|
374
|
+
}
|
|
375
|
+
getAvailablePrompts() {
|
|
376
|
+
return Array.from(this.promptRegistry.values());
|
|
377
|
+
}
|
|
378
|
+
getPromptsForServer(serverId) {
|
|
379
|
+
const id = this.getServerUniqueId(serverId);
|
|
380
|
+
if (!id) return [];
|
|
381
|
+
return Array.from(this.promptRegistry.values()).filter(
|
|
382
|
+
(p) => p.serverId === id
|
|
383
|
+
);
|
|
384
|
+
}
|
|
385
|
+
async executeToolDirect(toolName, parameters = {}) {
|
|
386
|
+
let serverId = "";
|
|
387
|
+
let name = toolName;
|
|
388
|
+
if (toolName.includes(":")) {
|
|
389
|
+
const [sid, n] = toolName.split(":", 2);
|
|
390
|
+
const mappedId = this.getServerUniqueId(sid);
|
|
391
|
+
serverId = mappedId || (this.mcpClients.has(sid) ? sid : "");
|
|
392
|
+
name = n;
|
|
393
|
+
} else {
|
|
394
|
+
for (const tool2 of this.toolRegistry.values()) {
|
|
395
|
+
if (tool2.name === toolName) {
|
|
396
|
+
serverId = tool2.serverId;
|
|
397
|
+
name = toolName;
|
|
398
|
+
break;
|
|
399
|
+
}
|
|
400
|
+
}
|
|
401
|
+
}
|
|
402
|
+
if (!serverId) {
|
|
403
|
+
for (const [clientServerId, client2] of this.mcpClients.entries()) {
|
|
404
|
+
try {
|
|
405
|
+
const toolsets2 = await client2.getToolsets();
|
|
406
|
+
const flattenedTools2 = {};
|
|
407
|
+
Object.values(toolsets2).forEach((serverTools) => {
|
|
408
|
+
Object.assign(flattenedTools2, serverTools);
|
|
409
|
+
});
|
|
410
|
+
if (flattenedTools2[toolName]) {
|
|
411
|
+
serverId = clientServerId;
|
|
412
|
+
name = toolName;
|
|
413
|
+
break;
|
|
414
|
+
}
|
|
415
|
+
} catch {
|
|
416
|
+
}
|
|
417
|
+
}
|
|
418
|
+
}
|
|
419
|
+
if (!serverId) {
|
|
420
|
+
throw new Error(`Tool not found in any connected server: ${toolName}`);
|
|
421
|
+
}
|
|
422
|
+
const client = this.mcpClients.get(serverId);
|
|
423
|
+
if (!client)
|
|
424
|
+
throw new Error(`No MCP client available for server: ${serverId}`);
|
|
425
|
+
const toolsets = await client.getToolsets();
|
|
426
|
+
const flattenedTools = {};
|
|
427
|
+
Object.values(toolsets).forEach((serverTools) => {
|
|
428
|
+
Object.assign(flattenedTools, serverTools);
|
|
429
|
+
});
|
|
430
|
+
const tool = flattenedTools[name];
|
|
431
|
+
if (!tool)
|
|
432
|
+
throw new Error(`Tool '${name}' not found in server '${serverId}'`);
|
|
433
|
+
const schema = tool.inputSchema;
|
|
434
|
+
const hasContextProperty = schema && typeof schema === "object" && schema.properties && Object.prototype.hasOwnProperty.call(
|
|
435
|
+
schema.properties,
|
|
436
|
+
"context"
|
|
437
|
+
);
|
|
438
|
+
const requiresContext = hasContextProperty || schema && Array.isArray(schema.required) && schema.required.includes("context");
|
|
439
|
+
const contextWrapped = { context: parameters || {} };
|
|
440
|
+
const direct = parameters || {};
|
|
441
|
+
const attempts = requiresContext ? [contextWrapped, direct] : [direct, contextWrapped];
|
|
442
|
+
let lastError = void 0;
|
|
443
|
+
for (const args of attempts) {
|
|
444
|
+
try {
|
|
445
|
+
const result = await tool.execute(args);
|
|
446
|
+
return { result };
|
|
447
|
+
} catch (err) {
|
|
448
|
+
lastError = err;
|
|
449
|
+
}
|
|
450
|
+
}
|
|
451
|
+
throw lastError;
|
|
452
|
+
}
|
|
453
|
+
async getResource(resourceUri, serverId) {
|
|
454
|
+
let uri = resourceUri;
|
|
455
|
+
const mappedId = this.getServerUniqueId(serverId);
|
|
456
|
+
const resolvedServerId = mappedId || (this.mcpClients.has(serverId) ? serverId : void 0);
|
|
457
|
+
if (!resolvedServerId) {
|
|
458
|
+
throw new Error(`No MCP client available for server: ${serverId}`);
|
|
459
|
+
}
|
|
460
|
+
const client = this.mcpClients.get(resolvedServerId);
|
|
461
|
+
if (!client) throw new Error("No MCP client available");
|
|
462
|
+
const content = await client.resources.read(resolvedServerId, uri);
|
|
463
|
+
return { contents: content?.contents || [] };
|
|
464
|
+
}
|
|
465
|
+
async getPrompt(promptName, serverId, args) {
|
|
466
|
+
const mappedId = this.getServerUniqueId(serverId);
|
|
467
|
+
const resolvedServerId = mappedId || (this.mcpClients.has(serverId) ? serverId : void 0);
|
|
468
|
+
if (!resolvedServerId) {
|
|
469
|
+
throw new Error(`No MCP client available for server: ${serverId}`);
|
|
470
|
+
}
|
|
471
|
+
const client = this.mcpClients.get(resolvedServerId);
|
|
472
|
+
if (!client) throw new Error("No MCP client available");
|
|
473
|
+
const content = await client.prompts.get({
|
|
474
|
+
serverName: resolvedServerId,
|
|
475
|
+
name: promptName,
|
|
476
|
+
args: args || {}
|
|
477
|
+
});
|
|
478
|
+
return { content };
|
|
479
|
+
}
|
|
480
|
+
/**
|
|
481
|
+
* Handles elicitation requests from MCP servers during direct tool execution
|
|
482
|
+
*/
|
|
483
|
+
async handleElicitationRequest(elicitationRequest) {
|
|
484
|
+
const requestId = `elicit_${Date.now()}_${Math.random().toString(36).substr(2, 9)}`;
|
|
485
|
+
return new Promise((resolve2, reject) => {
|
|
486
|
+
this.pendingElicitations.set(requestId, { resolve: resolve2, reject });
|
|
487
|
+
if (this.elicitationCallback) {
|
|
488
|
+
this.elicitationCallback({
|
|
489
|
+
requestId,
|
|
490
|
+
message: elicitationRequest.message,
|
|
491
|
+
schema: elicitationRequest.requestedSchema
|
|
492
|
+
}).then(resolve2).catch(reject);
|
|
493
|
+
} else {
|
|
494
|
+
const error = new Error("ELICITATION_REQUIRED");
|
|
495
|
+
error.elicitationRequest = {
|
|
496
|
+
requestId,
|
|
497
|
+
message: elicitationRequest.message,
|
|
498
|
+
schema: elicitationRequest.requestedSchema
|
|
499
|
+
};
|
|
500
|
+
reject(error);
|
|
501
|
+
}
|
|
502
|
+
});
|
|
503
|
+
}
|
|
504
|
+
/**
|
|
505
|
+
* Responds to a pending elicitation request
|
|
506
|
+
*/
|
|
507
|
+
respondToElicitation(requestId, response) {
|
|
508
|
+
const pending = this.pendingElicitations.get(requestId);
|
|
509
|
+
if (!pending) {
|
|
510
|
+
return false;
|
|
511
|
+
}
|
|
512
|
+
pending.resolve(response);
|
|
513
|
+
this.pendingElicitations.delete(requestId);
|
|
514
|
+
return true;
|
|
515
|
+
}
|
|
516
|
+
/**
|
|
517
|
+
* Gets the pending elicitations map for external access
|
|
518
|
+
*/
|
|
519
|
+
getPendingElicitations() {
|
|
520
|
+
return this.pendingElicitations;
|
|
521
|
+
}
|
|
522
|
+
/**
|
|
523
|
+
* Sets a callback to handle elicitation requests
|
|
524
|
+
*/
|
|
525
|
+
setElicitationCallback(callback) {
|
|
526
|
+
this.elicitationCallback = callback;
|
|
527
|
+
}
|
|
528
|
+
/**
|
|
529
|
+
* Clears the elicitation callback
|
|
530
|
+
*/
|
|
531
|
+
clearElicitationCallback() {
|
|
532
|
+
this.elicitationCallback = void 0;
|
|
533
|
+
}
|
|
534
|
+
};
|
|
535
|
+
|
|
536
|
+
// src/server/tests-router.ts
|
|
537
|
+
function createTestsRouter() {
|
|
538
|
+
const tests = new Hono();
|
|
539
|
+
tests.post("/run-all", async (c) => {
|
|
540
|
+
const encoder = new TextEncoder();
|
|
541
|
+
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
|
+
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);
|
|
572
|
+
}
|
|
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
|
+
);
|
|
656
|
+
}
|
|
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
|
+
}
|
|
728
|
+
}
|
|
729
|
+
console.log(`\u2705 Test ${test.title} cleanup complete`);
|
|
730
|
+
}
|
|
731
|
+
}
|
|
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
|
+
}
|
|
754
|
+
});
|
|
755
|
+
} catch (err) {
|
|
756
|
+
return c.json(
|
|
757
|
+
{ success: false, error: err?.message || "Unknown error" },
|
|
758
|
+
500
|
|
759
|
+
);
|
|
760
|
+
}
|
|
761
|
+
});
|
|
762
|
+
return tests;
|
|
763
|
+
}
|
|
764
|
+
|
|
765
|
+
// src/runner/test-runner.ts
|
|
766
|
+
async function findAvailablePort(startPort = 3500) {
|
|
767
|
+
return new Promise((resolve2, reject) => {
|
|
768
|
+
const server = createServer();
|
|
769
|
+
server.listen(0, () => {
|
|
770
|
+
const port = server.address()?.port;
|
|
771
|
+
server.close(() => {
|
|
772
|
+
resolve2(port || startPort);
|
|
773
|
+
});
|
|
774
|
+
});
|
|
775
|
+
server.on("error", () => {
|
|
776
|
+
resolve2(startPort);
|
|
777
|
+
});
|
|
778
|
+
});
|
|
779
|
+
}
|
|
780
|
+
async function runTests(tests, environment) {
|
|
781
|
+
const startTime = Date.now();
|
|
782
|
+
const app = new Hono2();
|
|
783
|
+
app.route("/mcp/tests", createTestsRouter());
|
|
784
|
+
const port = await findAvailablePort();
|
|
785
|
+
const server = serve({
|
|
786
|
+
fetch: app.fetch,
|
|
787
|
+
port
|
|
788
|
+
});
|
|
789
|
+
await new Promise((resolve2) => setTimeout(resolve2, 100));
|
|
790
|
+
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
|
+
);
|
|
819
|
+
}
|
|
820
|
+
const results = await processStreamingResults(response, tests);
|
|
821
|
+
const duration = ((Date.now() - startTime) / 1e3).toFixed(1);
|
|
822
|
+
return {
|
|
823
|
+
passed: results.filter((r) => r.passed).length,
|
|
824
|
+
failed: results.filter((r) => !r.passed).length,
|
|
825
|
+
duration,
|
|
826
|
+
results
|
|
827
|
+
};
|
|
828
|
+
} finally {
|
|
829
|
+
if (server && typeof server.close === "function") {
|
|
830
|
+
server.close();
|
|
831
|
+
}
|
|
832
|
+
}
|
|
833
|
+
}
|
|
834
|
+
function convertServerConfig(config) {
|
|
835
|
+
if ("command" in config) {
|
|
836
|
+
return {
|
|
837
|
+
command: config.command,
|
|
838
|
+
args: config.args || [],
|
|
839
|
+
env: config.env || {}
|
|
840
|
+
};
|
|
841
|
+
} else {
|
|
842
|
+
return {
|
|
843
|
+
url: config.url,
|
|
844
|
+
requestInit: {
|
|
845
|
+
headers: config.headers || {}
|
|
846
|
+
},
|
|
847
|
+
eventSourceInit: {
|
|
848
|
+
headers: config.headers || {}
|
|
849
|
+
}
|
|
850
|
+
};
|
|
851
|
+
}
|
|
852
|
+
}
|
|
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
|
+
}
|
|
918
|
+
}
|
|
919
|
+
return results;
|
|
920
|
+
}
|
|
921
|
+
|
|
922
|
+
// src/utils/env-resolver.ts
|
|
923
|
+
function resolveEnvironmentVariables(env) {
|
|
924
|
+
return {
|
|
925
|
+
...env,
|
|
926
|
+
mcpServers: Object.fromEntries(
|
|
927
|
+
Object.entries(env.mcpServers).map(([name, config]) => [
|
|
928
|
+
name,
|
|
929
|
+
resolveServerConfig(config)
|
|
930
|
+
])
|
|
931
|
+
),
|
|
932
|
+
providerApiKeys: env.providerApiKeys ? {
|
|
933
|
+
anthropic: resolveTemplate(env.providerApiKeys.anthropic),
|
|
934
|
+
openai: resolveTemplate(env.providerApiKeys.openai),
|
|
935
|
+
deepseek: resolveTemplate(env.providerApiKeys.deepseek)
|
|
936
|
+
} : void 0
|
|
937
|
+
};
|
|
938
|
+
}
|
|
939
|
+
function resolveServerConfig(config) {
|
|
940
|
+
if ("command" in config) {
|
|
941
|
+
return {
|
|
942
|
+
...config,
|
|
943
|
+
env: config.env ? Object.fromEntries(
|
|
944
|
+
Object.entries(config.env).map(([key, value]) => [
|
|
945
|
+
key,
|
|
946
|
+
resolveTemplate(value)
|
|
947
|
+
])
|
|
948
|
+
) : void 0
|
|
949
|
+
};
|
|
950
|
+
} else {
|
|
951
|
+
return {
|
|
952
|
+
...config,
|
|
953
|
+
headers: config.headers ? Object.fromEntries(
|
|
954
|
+
Object.entries(config.headers).map(([key, value]) => [
|
|
955
|
+
key,
|
|
956
|
+
resolveTemplate(value)
|
|
957
|
+
])
|
|
958
|
+
) : void 0
|
|
959
|
+
};
|
|
960
|
+
}
|
|
961
|
+
}
|
|
962
|
+
function resolveTemplate(value) {
|
|
963
|
+
if (!value) return value;
|
|
964
|
+
const collapseWhitespace = (s) => s.replace(/[\r\n]+/g, "").replace(/\s{2,}/g, "");
|
|
965
|
+
return value.replace(/\$\{([^}]+)\}/g, (match, envVar) => {
|
|
966
|
+
const raw = process.env[envVar];
|
|
967
|
+
const resolved = raw ? collapseWhitespace(raw) : raw;
|
|
968
|
+
if (resolved === void 0) {
|
|
969
|
+
console.warn(`\u26A0\uFE0F Warning: Environment variable ${envVar} is not set`);
|
|
970
|
+
return match;
|
|
971
|
+
}
|
|
972
|
+
return resolved;
|
|
973
|
+
});
|
|
974
|
+
}
|
|
975
|
+
|
|
976
|
+
// src/commands/evals.ts
|
|
977
|
+
var evalsCommand = new Command("evals");
|
|
978
|
+
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
|
+
try {
|
|
980
|
+
console.log("MCPJAM Evals v1.0.0\n");
|
|
981
|
+
const testsContent = await readFile(resolve(options.tests), "utf8");
|
|
982
|
+
const testsData = TestsFileSchema.parse(JSON.parse(testsContent));
|
|
983
|
+
const envContent = await readFile(resolve(options.environment), "utf8");
|
|
984
|
+
const envData = EnvironmentFileSchema.parse(JSON.parse(envContent));
|
|
985
|
+
const resolvedEnv = resolveEnvironmentVariables(envData);
|
|
986
|
+
console.log(`Running ${testsData.tests.length} tests...
|
|
987
|
+
`);
|
|
988
|
+
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
|
+
);
|
|
994
|
+
if (results.failed > 0) {
|
|
995
|
+
process.exit(1);
|
|
996
|
+
}
|
|
997
|
+
} catch (error) {
|
|
998
|
+
console.error(
|
|
999
|
+
"\u274C Error:",
|
|
1000
|
+
error instanceof Error ? error.message : String(error)
|
|
1001
|
+
);
|
|
1002
|
+
process.exit(1);
|
|
1003
|
+
}
|
|
1004
|
+
});
|
|
1005
|
+
|
|
1006
|
+
// src/index.ts
|
|
1007
|
+
var program = new Command2();
|
|
1008
|
+
program.name("mcpjam").description("MCPJam CLI for programmatic MCP testing").version("1.0.0");
|
|
1009
|
+
program.addCommand(evalsCommand);
|
|
1010
|
+
program.parse();
|
|
1011
|
+
//# sourceMappingURL=index.js.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"sources":["../src/index.ts","../src/commands/evals.ts","../schemas/test-schema.ts","../schemas/environment-schema.ts","../src/runner/test-runner.ts","../src/server/tests-router.ts","../../server/services/mcpjam-client-manager.ts","../../server/utils/mcp-utils.ts","../src/utils/env-resolver.ts"],"sourcesContent":["import { Command } from \"commander\";\nimport { evalsCommand } from \"./commands/evals.js\";\n\nconst program = new Command();\n\nprogram\n .name(\"mcpjam\")\n .description(\"MCPJam CLI for programmatic MCP testing\")\n .version(\"1.0.0\");\n\nprogram.addCommand(evalsCommand);\n\nprogram.parse();\n","import { Command } from \"commander\";\nimport { readFile } from \"fs/promises\";\nimport { resolve } from \"path\";\nimport { TestsFileSchema } from \"../../schemas/test-schema.js\";\nimport { EnvironmentFileSchema } from \"../../schemas/environment-schema.js\";\nimport { runTests } from \"../runner/test-runner.js\";\nimport { resolveEnvironmentVariables } from \"../utils/env-resolver.js\";\n\nexport const evalsCommand = new Command(\"evals\");\n\nevalsCommand\n .description(\"Run MCP evaluations\")\n .command(\"run\")\n .description(\"Run tests against MCP servers\")\n .requiredOption(\"-t, --tests <file>\", \"Path to tests JSON file\")\n .requiredOption(\"-e, --environment <file>\", \"Path to environment JSON file\")\n .action(async (options) => {\n try {\n console.log(\"MCPJAM Evals v1.0.0\\n\");\n\n // Read and parse test file\n const testsContent = await readFile(resolve(options.tests), \"utf8\");\n const testsData = TestsFileSchema.parse(JSON.parse(testsContent));\n\n // Read and parse environment file\n const envContent = await readFile(resolve(options.environment), \"utf8\");\n const envData = EnvironmentFileSchema.parse(JSON.parse(envContent));\n\n // Resolve environment variables\n const resolvedEnv = resolveEnvironmentVariables(envData);\n\n console.log(`Running ${testsData.tests.length} tests...\\n`);\n\n // Run tests\n const results = await runTests(testsData.tests, resolvedEnv);\n\n // Display results\n console.log(\n `\\nResults: ${results.passed} passed, ${results.failed} failed (${results.duration}s total)\\n`,\n );\n\n // Exit with error code if any tests failed\n if (results.failed > 0) {\n process.exit(1);\n }\n } catch (error) {\n console.error(\n \"❌ Error:\",\n error instanceof Error ? error.message : String(error),\n );\n process.exit(1);\n }\n });\n","import { z } from \"zod\";\n\nexport const ModelSchema = z.object({\n id: z.string(),\n provider: z.enum([\"openai\", \"anthropic\", \"deepseek\", \"ollama\"]),\n});\n\nexport const AdvancedConfigSchema = z.object({\n instructions: z.string().optional(),\n temperature: z.number().min(0).max(2).optional(),\n maxSteps: z.number().positive().optional(),\n toolChoice: z.enum([\"auto\", \"required\", \"none\"]).optional(),\n});\n\nexport const TestSchema = z.object({\n title: z.string(),\n prompt: z.string(),\n expectedTools: z.array(z.string()),\n model: ModelSchema,\n selectedServers: z.array(z.string()),\n advancedConfig: AdvancedConfigSchema.optional(),\n});\n\nexport const TestsFileSchema = z.object({\n tests: z.array(TestSchema),\n});\n\nexport type Model = z.infer<typeof ModelSchema>;\nexport type AdvancedConfig = z.infer<typeof AdvancedConfigSchema>;\nexport type Test = z.infer<typeof TestSchema>;\nexport type TestsFile = z.infer<typeof TestsFileSchema>;\n","import { z } from \"zod\";\n\nexport const MCPServerConfigSchema = z.union([\n // STDIO server\n z.object({\n command: z.string(),\n args: z.array(z.string()).optional(),\n env: z.record(z.string()).optional(),\n }),\n // HTTP server\n z.object({\n url: z.string().url(),\n headers: z.record(z.string()).optional(),\n }),\n]);\n\nexport const EnvironmentFileSchema = z.object({\n mcpServers: z.record(MCPServerConfigSchema),\n providerApiKeys: z\n .object({\n anthropic: z.string().optional(),\n openai: z.string().optional(),\n deepseek: z.string().optional(),\n })\n .optional(),\n});\n\nexport type MCPServerConfig = z.infer<typeof MCPServerConfigSchema>;\nexport type EnvironmentFile = z.infer<typeof EnvironmentFileSchema>;\n","import { createServer } from \"http\";\nimport { serve } from \"@hono/node-server\";\nimport { Hono } from \"hono\";\nimport type { Test } from \"../../schemas/test-schema.js\";\nimport type { EnvironmentFile } from \"../../schemas/environment-schema.js\";\nimport { createTestsRouter } from \"../server/tests-router.js\";\n\nasync function findAvailablePort(startPort = 3500): Promise<number> {\n return new Promise((resolve, reject) => {\n const server = createServer();\n server.listen(0, () => {\n const port = (server.address() as any)?.port;\n server.close(() => {\n resolve(port || startPort);\n });\n });\n server.on(\"error\", () => {\n resolve(startPort);\n });\n });\n}\n\nexport interface TestResult {\n testId: string;\n title: string;\n passed: boolean;\n calledTools: string[];\n missingTools: string[];\n unexpectedTools: string[];\n error?: string;\n duration: number;\n}\n\nexport interface TestRunResults {\n passed: number;\n failed: number;\n duration: string;\n results: TestResult[];\n}\n\nexport async function runTests(\n tests: Test[],\n environment: EnvironmentFile,\n): Promise<TestRunResults> {\n const startTime = Date.now();\n\n // Start temporary backend server\n const app = new Hono();\n app.route(\"/mcp/tests\", createTestsRouter());\n\n // Find an available port\n const port = await findAvailablePort();\n const server = serve({\n fetch: app.fetch,\n port,\n });\n\n // Wait a moment for server to start\n await new Promise((resolve) => setTimeout(resolve, 100));\n\n try {\n // Convert tests to backend format\n const backendTests = tests.map((test, index) => ({\n id: `test_${index}`,\n title: test.title,\n prompt: test.prompt,\n expectedTools: test.expectedTools,\n model: test.model,\n selectedServers: test.selectedServers,\n }));\n\n // Convert environment to backend format\n const backendServers = Object.fromEntries(\n Object.entries(environment.mcpServers).map(([name, config]) => [\n name,\n convertServerConfig(config),\n ]),\n );\n\n const payload = {\n tests: backendTests,\n allServers: backendServers,\n providerApiKeys: environment.providerApiKeys || {},\n };\n\n // Make request to backend\n const response = await fetch(`http://localhost:${port}/mcp/tests/run-all`, {\n method: \"POST\",\n headers: { \"Content-Type\": \"application/json\" },\n body: JSON.stringify(payload),\n });\n\n if (!response.ok) {\n throw new Error(\n `Server error: ${response.status} ${response.statusText}`,\n );\n }\n\n // Process streaming response\n const results = await processStreamingResults(response, tests);\n\n const duration = ((Date.now() - startTime) / 1000).toFixed(1);\n\n return {\n passed: results.filter((r) => r.passed).length,\n failed: results.filter((r) => !r.passed).length,\n duration,\n results,\n };\n } finally {\n if (server && typeof server.close === \"function\") {\n server.close();\n }\n }\n}\n\nfunction convertServerConfig(config: any): any {\n if (\"command\" in config) {\n // STDIO server\n return {\n command: config.command,\n args: config.args || [],\n env: config.env || {},\n };\n } else {\n // HTTP server - keep URL as string per schema\n return {\n url: config.url,\n requestInit: {\n headers: config.headers || {},\n },\n eventSourceInit: {\n headers: config.headers || {},\n },\n };\n }\n}\n\nasync function processStreamingResults(\n response: Response,\n tests: Test[],\n): Promise<TestResult[]> {\n const results: TestResult[] = [];\n const reader = response.body?.getReader();\n const decoder = new TextDecoder();\n\n if (!reader) {\n throw new Error(\"No response body\");\n }\n\n let buffer = \"\";\n\n while (true) {\n const { done, value } = await reader.read();\n if (done) break;\n\n buffer += decoder.decode(value, { stream: true });\n\n // Process complete lines\n const lines = buffer.split(\"\\n\");\n buffer = lines.pop() || \"\";\n\n for (const line of lines) {\n if (line.startsWith(\"data: \")) {\n const data = line.slice(6);\n if (data === \"[DONE]\") break;\n\n try {\n const event = JSON.parse(data);\n\n if (event.type === \"result\") {\n const testIndex = parseInt(event.testId.split(\"_\")[1]);\n const test = tests[testIndex];\n const testStart = Date.now();\n\n const result: TestResult = {\n testId: event.testId,\n title: test?.title || \"Unknown Test\",\n passed: event.passed,\n calledTools: event.calledTools || [],\n missingTools: event.missingTools || [],\n unexpectedTools: event.unexpectedTools || [],\n error: event.error,\n duration: 0, // We don't have individual timing from the stream\n };\n\n results.push(result);\n\n // Print result immediately\n if (result.passed) {\n console.log(`✅ ${result.title}`);\n console.log(\n ` Called tools: ${result.calledTools.join(\", \") || \"none\"}`,\n );\n } else {\n console.log(`❌ ${result.title}`);\n if (result.error) {\n console.log(` Error: ${result.error}`);\n } else {\n console.log(\n ` Called tools: ${result.calledTools.join(\", \") || \"none\"}`,\n );\n if (result.missingTools.length > 0) {\n console.log(` Missing: ${result.missingTools.join(\", \")}`);\n }\n if (result.unexpectedTools.length > 0) {\n console.log(\n ` Unexpected: ${result.unexpectedTools.join(\", \")}`,\n );\n }\n }\n }\n } else if (event.type === \"trace_step\") {\n // Optional: could show progress steps\n }\n } catch (e) {\n // Ignore malformed JSON\n }\n }\n }\n }\n\n return results;\n}\n","import { Hono } from \"hono\";\nimport { createAnthropic } from \"@ai-sdk/anthropic\";\nimport { createOpenAI } from \"@ai-sdk/openai\";\nimport { createOllama } from \"ollama-ai-provider\";\nimport { Agent } from \"@mastra/core/agent\";\nimport { MCPJamClientManager } from \"../../../server/services/mcpjam-client-manager.js\";\n\n// Simplified version of the server's tests router for CLI use\nexport function createTestsRouter() {\n const tests = new Hono();\n\n tests.post(\"/run-all\", async (c) => {\n const encoder = new TextEncoder();\n try {\n const body = await c.req.json();\n const testsInput = (body?.tests || []) as Array<{\n id: string;\n title: string;\n prompt: string;\n expectedTools: string[];\n model: { id: string; provider: string };\n selectedServers?: string[];\n }>;\n const allServers = body?.allServers || {};\n const providerApiKeys = body?.providerApiKeys || {};\n\n if (!Array.isArray(testsInput) || testsInput.length === 0) {\n return c.json({ success: false, error: \"No tests provided\" }, 400);\n }\n\n function createModel(model: { id: string; provider: string }) {\n switch (model.provider) {\n case \"anthropic\":\n return createAnthropic({\n apiKey:\n providerApiKeys?.anthropic ||\n process.env.ANTHROPIC_API_KEY ||\n \"\",\n })(model.id);\n case \"openai\":\n return createOpenAI({\n apiKey:\n providerApiKeys?.openai || process.env.OPENAI_API_KEY || \"\",\n })(model.id);\n case \"deepseek\":\n return createOpenAI({\n apiKey:\n providerApiKeys?.deepseek || process.env.DEEPSEEK_API_KEY || \"\",\n baseURL: \"https://api.deepseek.com/v1\",\n })(model.id);\n case \"ollama\":\n return createOllama({\n baseURL: process.env.OLLAMA_BASE_URL || \"http://localhost:11434\",\n })(model.id, { simulateStreaming: true });\n default:\n throw new Error(`Unsupported provider: ${model.provider}`);\n }\n }\n\n const readableStream = new ReadableStream({\n async start(controller) {\n let failed = false;\n\n const clientManager = new MCPJamClientManager();\n\n for (const test of testsInput) {\n console.log(`🔍 Starting test: ${test.title}`);\n const calledTools = new Set<string>();\n const expectedSet = new Set<string>(test.expectedTools || []);\n\n // Build servers for this test - keep in outer scope for cleanup\n let serverConfigs: Record<string, any> = {};\n if (test.selectedServers && test.selectedServers.length > 0) {\n for (const name of test.selectedServers) {\n if (allServers[name]) serverConfigs[name] = allServers[name];\n }\n } else {\n serverConfigs = allServers;\n }\n\n console.log(\n `📋 Test ${test.title} using servers: ${Object.keys(serverConfigs).join(\", \")}`,\n );\n\n if (Object.keys(serverConfigs).length === 0) {\n console.error(\n `❌ No valid MCP server configs for test ${test.title}`,\n );\n continue;\n }\n\n try {\n // Connect to all servers for this test using the client manager (like chat route)\n console.log(`🔌 Connecting to servers for ${test.title}...`);\n for (const [serverName, serverConfig] of Object.entries(\n serverConfigs,\n )) {\n console.log(` Connecting to ${serverName}...`);\n await clientManager.connectToServer(serverName, serverConfig);\n console.log(` ✅ Connected to ${serverName}`);\n }\n\n console.log(\n `🤖 Creating model ${test.model.provider}:${test.model.id}...`,\n );\n const model = createModel(test.model);\n\n console.log(`🛠️ Getting tools for ${test.title}...`);\n\n // Get available tools and create the tool structure like chat.ts\n const allTools = clientManager.getAvailableTools();\n const toolsByServer: Record<string, any> = {};\n\n // Group tools by server for the agent (like chat route)\n for (const tool of allTools) {\n if (!toolsByServer[tool.serverId]) {\n toolsByServer[tool.serverId] = {};\n }\n toolsByServer[tool.serverId][tool.name] = {\n description: tool.description,\n inputSchema: tool.inputSchema,\n execute: async (params: any) => {\n const result = await clientManager.executeToolDirect(\n `${tool.serverId}:${tool.name}`,\n params,\n );\n return result.result;\n },\n };\n }\n\n console.log(\n `✅ Got ${allTools.length} total tools across ${Object.keys(toolsByServer).length} servers`,\n );\n // Map unique server IDs back to original names for readability using client manager helper\n console.log(\n `🔍 Servers:`,\n clientManager.mapIdsToOriginalNames(Object.keys(toolsByServer)),\n );\n\n const agent = new Agent({\n name: `TestAgent-${test.id}`,\n instructions:\n \"You are a helpful assistant with access to MCP tools\",\n model,\n });\n\n console.log(`💬 Starting agent stream for ${test.title}...`);\n const streamOptions: any = {\n maxSteps: 10,\n toolsets: toolsByServer,\n onStepFinish: ({\n text,\n toolCalls,\n toolResults,\n }: {\n text: string;\n toolCalls?: any[];\n toolResults?: any[];\n }) => {\n if (toolCalls && toolCalls.length) {\n console.log(\n `🛠️ Tool calls:`,\n toolCalls.map((c: any) => c?.name || c?.toolName),\n );\n }\n // Accumulate tool names\n (toolCalls || []).forEach((c: any) => {\n const toolName = c?.name || c?.toolName;\n if (toolName) {\n calledTools.add(toolName);\n }\n });\n },\n };\n // Only set toolChoice if explicitly configured, don't force \"required\"\n const tAny = test as any;\n if (tAny?.advancedConfig?.toolChoice) {\n streamOptions.toolChoice = tAny.advancedConfig.toolChoice;\n }\n const stream = await agent.stream(\n [{ role: \"user\", content: test.prompt || \"\" }] as any,\n streamOptions,\n );\n\n // Drain the stream\n console.log(`📄 Draining text stream for ${test.title}...`);\n for await (const _ of stream.textStream) {\n // no-op\n }\n console.log(`✅ Stream completed for ${test.title}`);\n\n const called = Array.from(calledTools);\n const missing = Array.from(expectedSet).filter(\n (t) => !calledTools.has(t),\n );\n const unexpected = called.filter((t) => !expectedSet.has(t));\n const passed = missing.length === 0 && unexpected.length === 0;\n\n console.log(\n `📊 Test ${test.title} result: ${passed ? \"PASSED\" : \"FAILED\"}`,\n );\n if (!passed) failed = true;\n\n controller.enqueue(\n encoder.encode(\n `data: ${JSON.stringify({\n type: \"result\",\n testId: test.id,\n passed,\n calledTools: called,\n missingTools: missing,\n unexpectedTools: unexpected,\n })}\\n\\n`,\n ),\n );\n } catch (err) {\n console.error(`❌ Test ${test.title} failed:`, err);\n failed = true;\n controller.enqueue(\n encoder.encode(\n `data: ${JSON.stringify({\n type: \"result\",\n testId: test.id,\n passed: false,\n error: (err as Error)?.message,\n })}\\n\\n`,\n ),\n );\n } finally {\n console.log(`🔌 Disconnecting servers for ${test.title}...`);\n for (const serverName of Object.keys(serverConfigs)) {\n try {\n await clientManager.disconnectFromServer(serverName);\n console.log(` ✅ Disconnected from ${serverName}`);\n } catch (disconnectErr) {\n console.log(\n ` ⚠️ Disconnect error from ${serverName}:`,\n disconnectErr,\n );\n }\n }\n console.log(`✅ Test ${test.title} cleanup complete`);\n }\n }\n\n controller.enqueue(\n encoder.encode(\n `data: ${JSON.stringify({\n type: \"run_complete\",\n passed: !failed,\n })}\\n\\n`,\n ),\n );\n controller.enqueue(encoder.encode(`data: [DONE]\\n\\n`));\n controller.close();\n },\n });\n\n return new Response(readableStream, {\n headers: {\n \"Content-Type\": \"text/event-stream\",\n \"Cache-Control\": \"no-cache\",\n Connection: \"keep-alive\",\n },\n });\n } catch (err) {\n return c.json(\n { success: false, error: (err as Error)?.message || \"Unknown error\" },\n 500,\n );\n }\n });\n\n return tests;\n}\n","import { MCPClient, MastraMCPServerDefinition } from \"@mastra/mcp\";\nimport { validateServerConfig } from \"../utils/mcp-utils\";\n\nexport type ConnectionStatus =\n | \"disconnected\"\n | \"connecting\"\n | \"connected\"\n | \"error\";\n\nexport interface DiscoveredTool {\n name: string;\n description?: string;\n inputSchema: any;\n outputSchema?: any;\n serverId: string;\n}\n\nexport interface DiscoveredResource {\n uri: string;\n name: string;\n description?: string;\n mimeType?: string;\n serverId: string;\n}\n\nexport interface DiscoveredPrompt {\n name: string;\n description?: string;\n arguments?: Record<string, any>;\n serverId: string;\n}\n\nexport interface ChatMessage {\n role: \"user\" | \"assistant\" | \"system\";\n content: string;\n}\n\nexport interface ChatResponse {\n text?: string;\n toolCalls?: any[];\n toolResults?: any[];\n}\n\nexport interface ToolResult {\n result: any;\n}\n\nexport interface ElicitationRequest {\n message: string;\n requestedSchema: any;\n}\n\nexport interface ElicitationResponse {\n [key: string]: unknown;\n action: \"accept\" | \"decline\" | \"cancel\";\n content?: any;\n _meta?: any;\n}\n\nexport interface ResourceContent {\n contents: any[];\n}\n\nexport interface PromptResult {\n content: any;\n}\n\nfunction generateUniqueServerId(serverId: string) {\n // Generate unique server ID that avoids collisions\n const normalizedBase = serverId\n .toLowerCase()\n .replace(/[\\s\\-]+/g, \"_\")\n .replace(/[^a-z0-9_]/g, \"\");\n const timestamp = Date.now().toString(36);\n const random = Math.random().toString(36).substring(2, 8);\n return `${normalizedBase}_${timestamp}_${random}`;\n}\n\nclass MCPJamClientManager {\n private mcpClients: Map<string, MCPClient> = new Map();\n private statuses: Map<string, ConnectionStatus> = new Map();\n private configs: Map<string, MastraMCPServerDefinition> = new Map();\n\n // Map original server names to unique IDs\n private serverIdMapping: Map<string, string> = new Map();\n\n // Track in-flight connections to avoid duplicate concurrent connects\n private pendingConnections: Map<string, Promise<void>> = new Map();\n\n private toolRegistry: Map<string, DiscoveredTool> = new Map();\n private resourceRegistry: Map<string, DiscoveredResource> = new Map();\n private promptRegistry: Map<string, DiscoveredPrompt> = new Map();\n\n // Store for pending elicitation requests with Promise resolvers\n private pendingElicitations: Map<\n string,\n {\n resolve: (response: ElicitationResponse) => void;\n reject: (error: any) => void;\n }\n > = new Map();\n\n // Optional callback for handling elicitation requests\n private elicitationCallback?: (request: {\n requestId: string;\n message: string;\n schema: any;\n }) => Promise<ElicitationResponse>;\n\n // Helper method to get unique ID for a server name\n private getServerUniqueId(serverName: string): string | undefined {\n return this.serverIdMapping.get(serverName);\n }\n\n // Public method to get server ID for external use (like frontend)\n getServerIdForName(serverName: string): string | undefined {\n return this.serverIdMapping.get(serverName);\n }\n\n // Public method to get original server name from a unique server ID\n getOriginalNameForId(uniqueServerId: string): string | undefined {\n for (const [originalName, uid] of this.serverIdMapping.entries()) {\n if (uid === uniqueServerId) return originalName;\n }\n return undefined;\n }\n\n // Convenience: map an array of unique IDs to their original names (fallback to ID if not found)\n mapIdsToOriginalNames(uniqueIds: string[]): string[] {\n return uniqueIds.map((id) => this.getOriginalNameForId(id) || id);\n }\n\n async connectToServer(serverId: string, serverConfig: any): Promise<void> {\n // If a connection is already in-flight for this server name, wait for it\n const pending = this.pendingConnections.get(serverId);\n if (pending) {\n await pending;\n return;\n }\n\n const connectPromise = (async () => {\n // Reuse existing unique ID for this server name if present; otherwise generate and map one\n let id = this.serverIdMapping.get(serverId);\n if (!id) {\n id = generateUniqueServerId(serverId);\n this.serverIdMapping.set(serverId, id);\n }\n\n // If already connected, no-op\n if (this.mcpClients.has(id)) return;\n\n // Validate server configuration\n const validation = validateServerConfig(serverConfig);\n if (!validation.success) {\n this.statuses.set(id, \"error\");\n throw new Error(validation.error!.message);\n }\n\n this.configs.set(id, validation.config!);\n this.statuses.set(id, \"connecting\");\n\n const client = new MCPClient({\n id: `mcpjam-${id}`,\n servers: { [id]: validation.config! },\n });\n\n try {\n // touch the server to verify connection\n await client.getTools();\n this.mcpClients.set(id, client);\n this.statuses.set(id, \"connected\");\n\n // Register elicitation handler for this server\n if (client.elicitation?.onRequest) {\n client.elicitation.onRequest(\n id,\n async (elicitationRequest: ElicitationRequest) => {\n return await this.handleElicitationRequest(elicitationRequest);\n },\n );\n }\n\n await this.discoverServerResources(id);\n } catch (err) {\n this.statuses.set(id, \"error\");\n try {\n await client.disconnect();\n } catch {}\n this.mcpClients.delete(id);\n throw err;\n }\n })().finally(() => {\n this.pendingConnections.delete(serverId);\n });\n\n this.pendingConnections.set(serverId, connectPromise);\n await connectPromise;\n }\n\n async disconnectFromServer(serverId: string): Promise<void> {\n const id = this.getServerUniqueId(serverId);\n if (!id) return; // Server not found\n\n const client = this.mcpClients.get(id);\n if (client) {\n try {\n await client.disconnect();\n } catch {}\n }\n this.mcpClients.delete(id);\n this.statuses.set(id, \"disconnected\");\n this.serverIdMapping.delete(serverId); // Clean up the mapping\n\n // purge registries for this server\n for (const key of Array.from(this.toolRegistry.keys())) {\n const item = this.toolRegistry.get(key)!;\n if (item.serverId === id) this.toolRegistry.delete(key);\n }\n for (const key of Array.from(this.resourceRegistry.keys())) {\n const item = this.resourceRegistry.get(key)!;\n if (item.serverId === id) this.resourceRegistry.delete(key);\n }\n for (const key of Array.from(this.promptRegistry.keys())) {\n const item = this.promptRegistry.get(key)!;\n if (item.serverId === id) this.promptRegistry.delete(key);\n }\n }\n\n getConnectionStatus(serverId: string): ConnectionStatus {\n const id = this.getServerUniqueId(serverId);\n return id ? this.statuses.get(id) || \"disconnected\" : \"disconnected\";\n }\n\n getConnectedServers(): Record<\n string,\n { status: ConnectionStatus; config?: any }\n > {\n const servers: Record<string, { status: ConnectionStatus; config?: any }> =\n {};\n\n // Return data keyed by the original server names provided by callers\n for (const [originalName, uniqueId] of this.serverIdMapping.entries()) {\n servers[originalName] = {\n status: this.statuses.get(uniqueId) || \"disconnected\",\n config: this.configs.get(uniqueId),\n };\n }\n\n return servers;\n }\n\n async discoverAllResources(): Promise<void> {\n const serverIds = Array.from(this.mcpClients.keys());\n await Promise.all(serverIds.map((id) => this.discoverServerResources(id)));\n }\n\n private async discoverServerResources(serverId: string): Promise<void> {\n // serverId is already the unique ID when called from connectToServer\n const client = this.mcpClients.get(serverId);\n if (!client) return;\n\n // Tools - use toolsets instead of getTools for consistency\n const toolsets = await client.getToolsets();\n const flattenedTools: Record<string, any> = {};\n Object.values(toolsets).forEach((serverTools: any) => {\n Object.assign(flattenedTools, serverTools);\n });\n\n for (const [name, tool] of Object.entries<any>(flattenedTools)) {\n this.toolRegistry.set(`${serverId}:${name}`, {\n name,\n description: tool.description,\n inputSchema: tool.inputSchema,\n outputSchema: (tool as any).outputSchema,\n serverId: serverId,\n });\n }\n\n // Resources\n try {\n const res = await client.resources.list();\n for (const [, list] of Object.entries<any>(res)) {\n for (const r of list as any[]) {\n this.resourceRegistry.set(`${serverId}:${r.uri}`, {\n uri: r.uri,\n name: r.name,\n description: r.description,\n mimeType: r.mimeType,\n serverId: serverId,\n });\n }\n }\n } catch {}\n\n // Prompts\n try {\n const prompts = await client.prompts.list();\n for (const [, list] of Object.entries<any>(prompts)) {\n for (const p of list as any[]) {\n this.promptRegistry.set(`${serverId}:${p.name}`, {\n name: p.name,\n description: p.description,\n arguments: p.arguments,\n serverId: serverId,\n });\n }\n }\n } catch {}\n }\n\n getAvailableTools(): DiscoveredTool[] {\n return Array.from(this.toolRegistry.values());\n }\n\n async getToolsetsForServer(serverId: string): Promise<Record<string, any>> {\n const id = this.getServerUniqueId(serverId);\n if (!id) {\n throw new Error(`No MCP client available for server: ${serverId}`);\n }\n const client = this.mcpClients.get(id);\n if (!client) {\n throw new Error(`No MCP client available for server: ${serverId}`);\n }\n\n // Get toolsets like in the chat route - this gives us server-prefixed tools\n const toolsets = await client.getToolsets();\n\n // Flatten toolsets to get un-prefixed tool names like in chat route\n const flattenedTools: Record<string, any> = {};\n Object.values(toolsets).forEach((serverTools: any) => {\n Object.assign(flattenedTools, serverTools);\n });\n\n return flattenedTools;\n }\n getAvailableResources(): DiscoveredResource[] {\n return Array.from(this.resourceRegistry.values());\n }\n\n getResourcesForServer(serverId: string): DiscoveredResource[] {\n const id = this.getServerUniqueId(serverId);\n if (!id) return [];\n return Array.from(this.resourceRegistry.values()).filter(\n (r) => r.serverId === id,\n );\n }\n\n getAvailablePrompts(): DiscoveredPrompt[] {\n return Array.from(this.promptRegistry.values());\n }\n\n getPromptsForServer(serverId: string): DiscoveredPrompt[] {\n const id = this.getServerUniqueId(serverId);\n if (!id) return [];\n return Array.from(this.promptRegistry.values()).filter(\n (p) => p.serverId === id,\n );\n }\n\n async executeToolDirect(\n toolName: string,\n parameters: Record<string, any> = {},\n ): Promise<ToolResult> {\n // toolName may include server prefix \"serverId:tool\"\n let serverId = \"\";\n let name = toolName;\n\n if (toolName.includes(\":\")) {\n const [sid, n] = toolName.split(\":\", 2);\n // Resolve provided server identifier (original name or unique ID) to the unique ID\n const mappedId = this.getServerUniqueId(sid);\n serverId = mappedId || (this.mcpClients.has(sid) ? sid : \"\");\n name = n;\n } else {\n // Find which server has this tool by checking un-prefixed name\n for (const tool of this.toolRegistry.values()) {\n if (tool.name === toolName) {\n serverId = tool.serverId;\n name = toolName;\n break;\n }\n }\n }\n\n // If not found in registry, try to find it using toolsets from all connected servers\n if (!serverId) {\n for (const [clientServerId, client] of this.mcpClients.entries()) {\n try {\n const toolsets = await client.getToolsets();\n // Flatten toolsets to check for the tool\n const flattenedTools: Record<string, any> = {};\n Object.values(toolsets).forEach((serverTools: any) => {\n Object.assign(flattenedTools, serverTools);\n });\n\n if (flattenedTools[toolName]) {\n serverId = clientServerId;\n name = toolName;\n break;\n }\n } catch {\n // Continue to next server if this one fails\n }\n }\n }\n\n if (!serverId) {\n throw new Error(`Tool not found in any connected server: ${toolName}`);\n }\n\n const client = this.mcpClients.get(serverId);\n if (!client)\n throw new Error(`No MCP client available for server: ${serverId}`);\n\n // Use toolsets to get the actual tool (since tools might be prefixed in getTools())\n const toolsets = await client.getToolsets();\n const flattenedTools: Record<string, any> = {};\n Object.values(toolsets).forEach((serverTools: any) => {\n Object.assign(flattenedTools, serverTools);\n });\n\n const tool = flattenedTools[name];\n if (!tool)\n throw new Error(`Tool '${name}' not found in server '${serverId}'`);\n\n // Inspect input schema to choose the most likely argument shape, but be robust and\n // fall back to the alternate shape on invalid-arguments errors.\n const schema: any = (tool as any).inputSchema;\n const hasContextProperty =\n schema &&\n typeof schema === \"object\" &&\n (schema as any).properties &&\n Object.prototype.hasOwnProperty.call(\n (schema as any).properties,\n \"context\",\n );\n const requiresContext =\n hasContextProperty ||\n (schema &&\n Array.isArray((schema as any).required) &&\n (schema as any).required.includes(\"context\"));\n\n const contextWrapped = { context: parameters || {} };\n const direct = parameters || {};\n const attempts = requiresContext\n ? [contextWrapped, direct]\n : [direct, contextWrapped];\n\n let lastError: any = undefined;\n for (const args of attempts) {\n try {\n const result = await tool.execute(args);\n return { result };\n } catch (err: any) {\n lastError = err;\n }\n }\n throw lastError;\n }\n\n async getResource(\n resourceUri: string,\n serverId: string,\n ): Promise<ResourceContent> {\n // resourceUri may include server prefix\n let uri = resourceUri;\n // Resolve provided server identifier (original name or unique ID) to the unique ID\n const mappedId = this.getServerUniqueId(serverId);\n const resolvedServerId =\n mappedId || (this.mcpClients.has(serverId) ? serverId : undefined);\n\n if (!resolvedServerId) {\n throw new Error(`No MCP client available for server: ${serverId}`);\n }\n\n const client = this.mcpClients.get(resolvedServerId);\n if (!client) throw new Error(\"No MCP client available\");\n const content = await client.resources.read(resolvedServerId, uri);\n return { contents: content?.contents || [] };\n }\n\n async getPrompt(\n promptName: string,\n serverId: string,\n args?: Record<string, any>,\n ): Promise<PromptResult> {\n // Resolve provided server identifier (original name or unique ID) to the unique ID\n const mappedId = this.getServerUniqueId(serverId);\n const resolvedServerId =\n mappedId || (this.mcpClients.has(serverId) ? serverId : undefined);\n\n if (!resolvedServerId) {\n throw new Error(`No MCP client available for server: ${serverId}`);\n }\n\n const client = this.mcpClients.get(resolvedServerId);\n if (!client) throw new Error(\"No MCP client available\");\n const content = await client.prompts.get({\n serverName: resolvedServerId,\n name: promptName,\n args: args || {},\n });\n return { content };\n }\n\n /**\n * Handles elicitation requests from MCP servers during direct tool execution\n */\n private async handleElicitationRequest(\n elicitationRequest: ElicitationRequest,\n ): Promise<ElicitationResponse> {\n const requestId = `elicit_${Date.now()}_${Math.random().toString(36).substr(2, 9)}`;\n\n // Create a promise that will be resolved when the user responds\n return new Promise<ElicitationResponse>((resolve, reject) => {\n this.pendingElicitations.set(requestId, { resolve, reject });\n\n // If there's an active elicitation callback, use it\n if (this.elicitationCallback) {\n this.elicitationCallback({\n requestId,\n message: elicitationRequest.message,\n schema: elicitationRequest.requestedSchema,\n })\n .then(resolve)\n .catch(reject);\n } else {\n // If no callback is set, reject with details for the tools route to handle\n const error = new Error(\"ELICITATION_REQUIRED\");\n (error as any).elicitationRequest = {\n requestId,\n message: elicitationRequest.message,\n schema: elicitationRequest.requestedSchema,\n };\n reject(error);\n }\n });\n }\n\n /**\n * Responds to a pending elicitation request\n */\n respondToElicitation(\n requestId: string,\n response: ElicitationResponse,\n ): boolean {\n const pending = this.pendingElicitations.get(requestId);\n if (!pending) {\n return false;\n }\n\n pending.resolve(response);\n this.pendingElicitations.delete(requestId);\n return true;\n }\n\n /**\n * Gets the pending elicitations map for external access\n */\n getPendingElicitations(): Map<\n string,\n {\n resolve: (response: ElicitationResponse) => void;\n reject: (error: any) => void;\n }\n > {\n return this.pendingElicitations;\n }\n\n /**\n * Sets a callback to handle elicitation requests\n */\n setElicitationCallback(\n callback: (request: {\n requestId: string;\n message: string;\n schema: any;\n }) => Promise<ElicitationResponse>,\n ): void {\n this.elicitationCallback = callback;\n }\n\n /**\n * Clears the elicitation callback\n */\n clearElicitationCallback(): void {\n this.elicitationCallback = undefined;\n }\n}\n\n// Export the class directly instead of singleton\nexport { MCPJamClientManager };\nexport default MCPJamClientManager;\n","import { MastraMCPServerDefinition, MCPClient } from \"@mastra/mcp\";\n\n// Hono-compatible error response type\nexport interface HonoErrorResponse {\n message: string;\n status: number;\n}\n\nexport interface ValidationResult {\n success: boolean;\n config?: MastraMCPServerDefinition;\n error?: HonoErrorResponse;\n}\n\nexport interface MultipleValidationResult {\n success: boolean;\n validConfigs?: Record<string, MastraMCPServerDefinition>;\n errors?: Record<string, string>;\n error?: HonoErrorResponse;\n}\n\nexport function validateServerConfig(serverConfig: any): ValidationResult {\n if (!serverConfig) {\n return {\n success: false,\n error: {\n message: \"Server configuration is required\",\n status: 400,\n },\n };\n }\n\n // Validate and prepare config\n const config = { ...serverConfig };\n\n // Validate and convert URL if provided\n if (config.url) {\n try {\n // Convert string URL to URL object if needed and strip query/hash\n if (typeof config.url === \"string\") {\n const parsed = new URL(config.url);\n parsed.search = \"\";\n parsed.hash = \"\";\n config.url = parsed;\n } else if (typeof config.url === \"object\" && !config.url.href) {\n return {\n success: false,\n error: {\n message: \"Invalid URL configuration\",\n status: 400,\n },\n };\n }\n\n // Handle OAuth authentication for HTTP servers\n if (config.oauth?.access_token) {\n const authHeaders = {\n Authorization: `Bearer ${config.oauth.access_token}`,\n ...(config.requestInit?.headers || {}),\n };\n\n config.requestInit = {\n ...config.requestInit,\n headers: authHeaders,\n };\n\n // For SSE connections, add eventSourceInit with OAuth headers\n config.eventSourceInit = {\n fetch(input: Request | URL | string, init?: RequestInit) {\n const headers = new Headers(init?.headers || {});\n\n // Add OAuth authorization header\n headers.set(\n \"Authorization\",\n `Bearer ${config.oauth!.access_token}`,\n );\n\n // Copy other headers from requestInit\n if (config.requestInit?.headers) {\n const requestHeaders = new Headers(config.requestInit.headers);\n requestHeaders.forEach((value, key) => {\n if (key.toLowerCase() !== \"authorization\") {\n headers.set(key, value);\n }\n });\n }\n\n return fetch(input, {\n ...init,\n headers,\n });\n },\n };\n } else if (config.requestInit?.headers) {\n // For SSE connections without OAuth, add eventSourceInit if requestInit has custom headers\n config.eventSourceInit = {\n fetch(input: Request | URL | string, init?: RequestInit) {\n const headers = new Headers(init?.headers || {});\n\n // Copy headers from requestInit\n const requestHeaders = new Headers(config.requestInit.headers);\n requestHeaders.forEach((value, key) => {\n headers.set(key, value);\n });\n\n return fetch(input, {\n ...init,\n headers,\n });\n },\n };\n }\n } catch (error) {\n return {\n success: false,\n error: {\n message: `Invalid URL format: ${error}`,\n status: 400,\n },\n };\n }\n }\n\n return {\n success: true,\n config,\n };\n}\n\nexport function createMCPClient(\n config: MastraMCPServerDefinition,\n id: string,\n): MCPClient {\n return new MCPClient({\n id,\n servers: {\n server: config,\n },\n });\n}\n\nexport interface MultipleValidationResult {\n success: boolean;\n validConfigs?: Record<string, MastraMCPServerDefinition>;\n serverNameMapping?: Record<string, string>; // serverID -> originalName\n errors?: Record<string, string>;\n error?: HonoErrorResponse;\n}\n\n// Generate unique server ID that avoids collisions\nfunction generateUniqueServerID(serverName: string): string {\n // Use normalized name as base + timestamp + random suffix to ensure uniqueness\n const normalizedBase = normalizeServerConfigName(serverName);\n const timestamp = Date.now().toString(36);\n const random = Math.random().toString(36).substring(2, 8);\n return `${normalizedBase}_${timestamp}_${random}`;\n}\n\nexport const validateMultipleServerConfigs = (\n serverConfigs: Record<string, MastraMCPServerDefinition>,\n): MultipleValidationResult => {\n if (!serverConfigs || Object.keys(serverConfigs).length === 0) {\n return {\n success: false,\n error: {\n message: \"At least one server configuration is required\",\n status: 400,\n },\n };\n }\n\n const validConfigs: Record<string, MastraMCPServerDefinition> = {};\n const serverNameMapping: Record<string, string> = {};\n const errors: Record<string, string> = {};\n let hasErrors = false;\n\n // Validate each server configuration\n for (const [serverName, serverConfig] of Object.entries(serverConfigs)) {\n const validationResult = validateServerConfig(serverConfig);\n\n if (validationResult.success && validationResult.config) {\n // Generate unique server ID to avoid collisions from normalized names\n const serverID = generateUniqueServerID(serverName);\n validConfigs[serverID] = validationResult.config;\n serverNameMapping[serverID] = serverName; // Map serverID back to original name\n } else {\n hasErrors = true;\n let errorMessage = \"Configuration validation failed\";\n if (validationResult.error) {\n errorMessage = validationResult.error.message;\n }\n // Use original server name for error keys since this is for user display\n errors[serverName] = errorMessage;\n }\n }\n\n // If all configs are valid, return success\n if (!hasErrors) {\n return {\n success: true,\n validConfigs,\n serverNameMapping,\n };\n }\n\n // If some configs are valid but others failed, return partial success\n if (Object.keys(validConfigs).length > 0) {\n return {\n success: false,\n validConfigs,\n serverNameMapping,\n errors,\n };\n }\n\n // If all configs failed, return error\n return {\n success: false,\n errors,\n error: {\n message: \"All server configurations failed validation\",\n status: 400,\n },\n };\n};\n\nexport function createMCPClientWithMultipleConnections(\n serverConfigs: Record<string, MastraMCPServerDefinition>,\n): MCPClient {\n // Custom MCPClient wrapper to fix double prefixing issue\n const originalMCPClient = new MCPClient({\n id: `chat-${Date.now()}`,\n servers: serverConfigs,\n });\n\n // Override getTools method to fix double prefixing\n const originalGetTools = originalMCPClient.getTools.bind(originalMCPClient);\n originalMCPClient.getTools = async () => {\n const tools = await originalGetTools();\n const fixedTools: Record<string, any> = {};\n\n for (const [toolName, toolConfig] of Object.entries(tools)) {\n // Check if tool name has double prefix pattern (serverName_serverName_actualTool)\n const parts = toolName.split(\"_\");\n if (parts.length >= 3 && parts[0] === parts[1]) {\n // Remove the duplicate prefix: \"asana_asana_list_workspaces\" -> \"asana_list_workspaces\"\n const fixedName = parts.slice(1).join(\"_\");\n fixedTools[fixedName] = toolConfig;\n } else {\n fixedTools[toolName] = toolConfig;\n }\n }\n\n return fixedTools;\n };\n\n return originalMCPClient;\n}\n\nexport function normalizeServerConfigName(serverName: string): string {\n // Convert to lowercase and replace spaces/hyphens with underscores\n return serverName\n .toLowerCase()\n .replace(/[\\s\\-]+/g, \"_\")\n .replace(/[^a-z0-9_]/g, \"\");\n}\n\nexport function createErrorResponse(\n message: string,\n details?: string,\n status: number = 500,\n): HonoErrorResponse {\n return {\n message: details ? `${message}: ${details}` : message,\n status,\n };\n}\n","import type { EnvironmentFile } from \"../../schemas/environment-schema.js\";\n\nexport function resolveEnvironmentVariables(\n env: EnvironmentFile,\n): EnvironmentFile {\n return {\n ...env,\n mcpServers: Object.fromEntries(\n Object.entries(env.mcpServers).map(([name, config]) => [\n name,\n resolveServerConfig(config),\n ]),\n ),\n providerApiKeys: env.providerApiKeys\n ? {\n anthropic: resolveTemplate(env.providerApiKeys.anthropic),\n openai: resolveTemplate(env.providerApiKeys.openai),\n deepseek: resolveTemplate(env.providerApiKeys.deepseek),\n }\n : undefined,\n };\n}\n\nfunction resolveServerConfig(config: any): any {\n if (\"command\" in config) {\n // STDIO server\n return {\n ...config,\n env: config.env\n ? Object.fromEntries(\n Object.entries(config.env).map(([key, value]) => [\n key,\n resolveTemplate(value as string),\n ]),\n )\n : undefined,\n };\n } else {\n // HTTP server - handle simple headers format like the UI\n return {\n ...config,\n headers: config.headers\n ? Object.fromEntries(\n Object.entries(config.headers).map(([key, value]) => [\n key,\n resolveTemplate(value as string),\n ]),\n )\n : undefined,\n };\n }\n}\n\nfunction resolveTemplate(value: string | undefined): string | undefined {\n if (!value) return value;\n // Collapse whitespace in env var values to avoid broken multi-line exports\n const collapseWhitespace = (s: string) =>\n s.replace(/[\\r\\n]+/g, \"\").replace(/\\s{2,}/g, \"\");\n\n return value.replace(/\\$\\{([^}]+)\\}/g, (match, envVar) => {\n const raw = process.env[envVar];\n const resolved = raw ? collapseWhitespace(raw) : raw;\n if (resolved === undefined) {\n console.warn(`⚠️ Warning: Environment variable ${envVar} is not set`);\n return match;\n }\n return resolved;\n });\n}\n"],"mappings":";AAAA,SAAS,WAAAA,gBAAe;;;ACAxB,SAAS,eAAe;AACxB,SAAS,gBAAgB;AACzB,SAAS,eAAe;;;ACFxB,SAAS,SAAS;AAEX,IAAM,cAAc,EAAE,OAAO;AAAA,EAClC,IAAI,EAAE,OAAO;AAAA,EACb,UAAU,EAAE,KAAK,CAAC,UAAU,aAAa,YAAY,QAAQ,CAAC;AAChE,CAAC;AAEM,IAAM,uBAAuB,EAAE,OAAO;AAAA,EAC3C,cAAc,EAAE,OAAO,EAAE,SAAS;AAAA,EAClC,aAAa,EAAE,OAAO,EAAE,IAAI,CAAC,EAAE,IAAI,CAAC,EAAE,SAAS;AAAA,EAC/C,UAAU,EAAE,OAAO,EAAE,SAAS,EAAE,SAAS;AAAA,EACzC,YAAY,EAAE,KAAK,CAAC,QAAQ,YAAY,MAAM,CAAC,EAAE,SAAS;AAC5D,CAAC;AAEM,IAAM,aAAa,EAAE,OAAO;AAAA,EACjC,OAAO,EAAE,OAAO;AAAA,EAChB,QAAQ,EAAE,OAAO;AAAA,EACjB,eAAe,EAAE,MAAM,EAAE,OAAO,CAAC;AAAA,EACjC,OAAO;AAAA,EACP,iBAAiB,EAAE,MAAM,EAAE,OAAO,CAAC;AAAA,EACnC,gBAAgB,qBAAqB,SAAS;AAChD,CAAC;AAEM,IAAM,kBAAkB,EAAE,OAAO;AAAA,EACtC,OAAO,EAAE,MAAM,UAAU;AAC3B,CAAC;;;ACzBD,SAAS,KAAAC,UAAS;AAEX,IAAM,wBAAwBA,GAAE,MAAM;AAAA;AAAA,EAE3CA,GAAE,OAAO;AAAA,IACP,SAASA,GAAE,OAAO;AAAA,IAClB,MAAMA,GAAE,MAAMA,GAAE,OAAO,CAAC,EAAE,SAAS;AAAA,IACnC,KAAKA,GAAE,OAAOA,GAAE,OAAO,CAAC,EAAE,SAAS;AAAA,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AAK,MAAM,UAAU,CAAC;AAGlE,UAAM,cAAc,4BAA4B,OAAO;AAEvD,YAAQ,IAAI,WAAW,UAAU,MAAM,MAAM;AAAA,CAAa;AAG1D,UAAM,UAAU,MAAM,SAAS,UAAU,OAAO,WAAW;AAG3D,YAAQ;AAAA,MACN;AAAA,WAAc,QAAQ,MAAM,YAAY,QAAQ,MAAM,YAAY,QAAQ,QAAQ;AAAA;AAAA,IACpF;AAGA,QAAI,QAAQ,SAAS,GAAG;AACtB,cAAQ,KAAK,CAAC;AAAA,IAChB;AAAA,EACF,SAAS,OAAO;AACd,YAAQ;AAAA,MACN;AAAA,MACA,iBAAiB,QAAQ,MAAM,UAAU,OAAO,KAAK;AAAA,IACvD;AACA,YAAQ,KAAK,CAAC;AAAA,EAChB;AACF,CAAC;;;ADjDH,IAAM,UAAU,IAAIE,SAAQ;AAE5B,QACG,KAAK,QAAQ,EACb,YAAY,yCAAyC,EACrD,QAAQ,OAAO;AAElB,QAAQ,WAAW,YAAY;AAE/B,QAAQ,MAAM;","names":["Command","z","Hono","MCPClient","MCPClient","tool","client","toolsets","flattenedTools","resolve","createModel","c","resolve","Hono","Command"]}
|
package/package.json
ADDED
|
@@ -0,0 +1,48 @@
|
|
|
1
|
+
{
|
|
2
|
+
"name": "@mcpjam/cli",
|
|
3
|
+
"version": "1.0.0",
|
|
4
|
+
"type": "module",
|
|
5
|
+
"description": "MCPJam CLI for programmatic MCP testing",
|
|
6
|
+
"license": "Apache-2.0",
|
|
7
|
+
"author": "MCPJam (https://mcpjam.com)",
|
|
8
|
+
"homepage": "https://mcpjam.com",
|
|
9
|
+
"repository": {
|
|
10
|
+
"type": "git",
|
|
11
|
+
"url": "https://github.com/MCPJam/inspector.git",
|
|
12
|
+
"directory": "cli"
|
|
13
|
+
},
|
|
14
|
+
"main": "dist/index.js",
|
|
15
|
+
"bin": {
|
|
16
|
+
"mcpjam": "bin/mcpjam.js"
|
|
17
|
+
},
|
|
18
|
+
"files": [
|
|
19
|
+
"bin",
|
|
20
|
+
"dist",
|
|
21
|
+
"package.json",
|
|
22
|
+
"README.md"
|
|
23
|
+
],
|
|
24
|
+
"scripts": {
|
|
25
|
+
"build": "tsup",
|
|
26
|
+
"dev": "tsup --watch",
|
|
27
|
+
"start": "node bin/mcpjam.js"
|
|
28
|
+
},
|
|
29
|
+
"dependencies": {
|
|
30
|
+
"@ai-sdk/anthropic": "^1.2.12",
|
|
31
|
+
"@ai-sdk/deepseek": "^1.0.5",
|
|
32
|
+
"@ai-sdk/openai": "^1.3.23",
|
|
33
|
+
"@hono/node-server": "^1.13.7",
|
|
34
|
+
"@mastra/core": "^0.13.2",
|
|
35
|
+
"@mastra/mcp": "^0.10.11",
|
|
36
|
+
"@modelcontextprotocol/sdk": "^1.17.3",
|
|
37
|
+
"ai": "^5.0.11",
|
|
38
|
+
"commander": "^12.0.0",
|
|
39
|
+
"hono": "^4.6.11",
|
|
40
|
+
"ollama-ai-provider": "^1.2.0",
|
|
41
|
+
"zod": "^3.25.76"
|
|
42
|
+
},
|
|
43
|
+
"devDependencies": {
|
|
44
|
+
"@types/node": "^20",
|
|
45
|
+
"tsup": "^8.3.5",
|
|
46
|
+
"typescript": "^5"
|
|
47
|
+
}
|
|
48
|
+
}
|