@mcpc-tech/cli 0.1.16 → 0.1.19

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/bin/mcpc.mjs CHANGED
@@ -56,686 +56,1114 @@ var ServerSentEventStream = class extends TransformStream {
56
56
  // __mcpc__cli_latest/node_modules/@mcpc/cli/src/controllers/sse.controller.js
57
57
  import { createRoute as createRoute2, z as z2 } from "@hono/zod-openapi";
58
58
 
59
- // __mcpc__cli_latest/node_modules/@jsr/mcpc__core/src/compose.js
60
- import { CallToolRequestSchema, ListToolsRequestSchema, SetLevelRequestSchema } from "@modelcontextprotocol/sdk/types.js";
59
+ // __mcpc__cli_latest/node_modules/@mcpc/cli/src/controllers/streamable-http.controller.js
60
+ import { StreamableHTTPServerTransport } from "@modelcontextprotocol/sdk/server/streamableHttp.js";
61
61
 
62
- // __mcpc__cli_latest/node_modules/@jsr/mcpc__core/src/utils/schema.js
63
- var schemaSymbol = Symbol.for("mcpc.schema");
64
- var vercelSchemaSymbol = Symbol.for("vercel.ai.schema");
65
- var validatorSymbol = Symbol.for("mcpc.validator");
66
- function jsonSchema(schema, options = {}) {
67
- if (isWrappedSchema(schema)) {
68
- return schema;
62
+ // __mcpc__cli_latest/node_modules/@mcpc/cli/src/config/loader.js
63
+ import { mkdir, readFile, writeFile } from "node:fs/promises";
64
+ import { homedir } from "node:os";
65
+ import { dirname, join, resolve } from "node:path";
66
+ import process2 from "node:process";
67
+ function extractServerName(command, commandArgs) {
68
+ for (const arg of commandArgs) {
69
+ if (!arg.startsWith("-")) {
70
+ const name2 = arg.replace(/[@.,/\\:;!?#$%^&*()[\]{}]/g, "_").substring(0, 64);
71
+ if (name2) return name2;
72
+ }
69
73
  }
70
- return {
71
- [schemaSymbol]: true,
72
- [validatorSymbol]: true,
73
- _type: void 0,
74
- jsonSchema: schema,
75
- validate: options.validate
76
- };
77
- }
78
- function isWrappedSchema(value) {
79
- return typeof value === "object" && value !== null && (schemaSymbol in value && value[schemaSymbol] === true || vercelSchemaSymbol in value && value[vercelSchemaSymbol] === true);
74
+ const name = command.replace(/[@.,/\\:;!?#$%^&*()[\]{}]/g, "_").substring(0, 64);
75
+ return name || "agentic-tool";
80
76
  }
81
- function extractJsonSchema(schema) {
82
- if (isWrappedSchema(schema)) {
83
- return schema.jsonSchema;
84
- }
85
- return schema;
77
+ function getUserConfigDir() {
78
+ return join(homedir(), ".mcpc");
86
79
  }
87
-
88
- // __mcpc__cli_latest/node_modules/@jsr/mcpc__core/src/compose.js
89
- import { Server } from "@modelcontextprotocol/sdk/server/index.js";
90
-
91
- // __mcpc__cli_latest/node_modules/@jsr/mcpc__utils/src/json.js
92
- import { jsonrepair } from "jsonrepair";
93
- function stripMarkdownAndText(text) {
94
- text = text.trim();
95
- text = text.replace(/^```(?:json)?\s*\n?/i, "");
96
- text = text.replace(/\n?```\s*$/, "");
97
- text = text.replace(/^(?:here is|here's|response|result|output|json):\s*/i, "");
98
- const firstJsonIndex = text.search(/[\{\[]/);
99
- if (firstJsonIndex >= 0) {
100
- text = text.slice(firstJsonIndex);
101
- let depth = 0;
102
- let inString = false;
103
- let escapeNext = false;
104
- const startChar = text[0];
105
- const endChar = startChar === "{" ? "}" : "]";
106
- for (let i = 0; i < text.length; i++) {
107
- const char = text[i];
108
- if (escapeNext) {
109
- escapeNext = false;
110
- continue;
111
- }
112
- if (char === "\\") {
113
- escapeNext = true;
114
- continue;
115
- }
116
- if (char === '"' && !inString) {
117
- inString = true;
118
- continue;
119
- }
120
- if (char === '"' && inString) {
121
- inString = false;
122
- continue;
123
- }
124
- if (inString) continue;
125
- if (char === startChar) {
126
- depth++;
127
- } else if (char === endChar) {
128
- depth--;
129
- if (depth === 0) {
130
- return text.slice(0, i + 1);
131
- }
132
- }
133
- }
134
- }
135
- return text.trim();
80
+ function getUserConfigPath() {
81
+ return join(getUserConfigDir(), "config.json");
136
82
  }
137
- function parseJSON(text, throwError) {
83
+ async function saveUserConfig(config2, newAgentName) {
84
+ const configPath = getUserConfigPath();
85
+ const configDir = dirname(configPath);
138
86
  try {
139
- return JSON.parse(text);
140
- } catch (_error) {
87
+ let existingConfig = null;
141
88
  try {
142
- const cleanedText = stripMarkdownAndText(text);
143
- try {
144
- return JSON.parse(cleanedText);
145
- } catch {
146
- const repairedText = jsonrepair(cleanedText);
147
- console.warn(`Failed to parse JSON, cleaned and repaired. Original: ${text.slice(0, 100)}...`);
148
- return JSON.parse(repairedText);
149
- }
150
- } catch (_repairError) {
151
- if (throwError) {
152
- throw new Error(`Failed to parse JSON after cleanup and repair. Original error: ${_error instanceof Error ? _error.message : String(_error)}`);
89
+ const content = await readFile(configPath, "utf-8");
90
+ existingConfig = JSON.parse(content);
91
+ } catch {
92
+ }
93
+ if (existingConfig) {
94
+ const hasConflict = existingConfig.agents.some((agent) => agent.name === newAgentName);
95
+ if (hasConflict) {
96
+ console.error(`
97
+ \u26A0 Agent "${newAgentName}" already exists in ${configPath}
98
+ Use --name to choose a different name, or delete the existing agent first.
99
+ `);
100
+ return;
153
101
  }
154
- return null;
102
+ existingConfig.agents.push(...config2.agents);
103
+ await writeFile(configPath, JSON.stringify(existingConfig, null, 2), "utf-8");
104
+ console.error(`
105
+ \u2713 Added agent "${newAgentName}" (total: ${existingConfig.agents.length})
106
+ Config: ${configPath}
107
+ Run: mcpc
108
+ `);
109
+ return;
155
110
  }
111
+ await mkdir(configDir, {
112
+ recursive: true
113
+ });
114
+ await writeFile(configPath, JSON.stringify(config2, null, 2), "utf-8");
115
+ console.error(`
116
+ \u2713 Configuration saved to: ${configPath}
117
+ Run: mcpc
118
+ `);
119
+ } catch (error) {
120
+ console.error(`Failed to save config to ${configPath}:`, error);
156
121
  }
157
122
  }
158
-
159
- // __mcpc__cli_latest/node_modules/@jsr/mcpc__utils/src/ai.js
160
- var p = (template, options = {}) => {
161
- const { missingVariableHandling = "warn" } = options;
162
- const names = /* @__PURE__ */ new Set();
163
- const regex = /\{((\w|\.)+)\}/g;
164
- let match;
165
- while ((match = regex.exec(template)) !== null) {
166
- names.add(match[1]);
123
+ async function createWrapConfig(args) {
124
+ if (!args.mcpServers || args.mcpServers.length === 0) {
125
+ console.error("Error: --wrap/--add requires at least one MCP server\nExample: mcpc --wrap --mcp-stdio 'npx -y @wonderwhy-er/desktop-commander'\nMultiple: mcpc --add --mcp-stdio 'npx -y server1' --mcp-http 'https://api.example.com'");
126
+ process2.exit(1);
127
+ }
128
+ const mcpServers = {};
129
+ const serverNames = [];
130
+ const refs = [];
131
+ for (const spec of args.mcpServers) {
132
+ const serverName = extractServerName(spec.command, spec.args);
133
+ mcpServers[serverName] = {
134
+ command: spec.command,
135
+ args: spec.args,
136
+ transportType: spec.transportType
137
+ };
138
+ serverNames.push(serverName);
139
+ refs.push(`<tool name="${serverName}.__ALL__"/>`);
140
+ console.error(`Added MCP server: ${serverName}
141
+ Transport: ${spec.transportType}
142
+ Command: ${spec.command} ${spec.args.join(" ")}`);
167
143
  }
168
- const required = Array.from(names);
169
- return (input) => {
170
- let result = template;
171
- for (const name of required) {
172
- const key = name;
173
- const value = input[key];
174
- const re = new RegExp(`\\{${String(name)}\\}`, "g");
175
- if (value !== void 0 && value !== null) {
176
- result = result.replace(re, String(value));
177
- } else {
178
- switch (missingVariableHandling) {
179
- case "error":
180
- throw new Error(`Missing variable "${String(name)}" in input for template.`);
181
- case "empty":
182
- result = result.replace(re, "");
183
- break;
184
- case "warn":
185
- case "ignore":
186
- default:
187
- break;
144
+ const agentName = args.name || `${serverNames.join("__")}--orchestrator`;
145
+ const config2 = {
146
+ name: "mcpc-wrap-config",
147
+ version: "0.1.0",
148
+ capabilities: {
149
+ tools: {},
150
+ sampling: {}
151
+ },
152
+ agents: [
153
+ {
154
+ name: agentName,
155
+ description: `Orchestrate ${serverNames.length === 1 ? serverNames[0] : serverNames.join(", ")} MCP server tools`,
156
+ deps: {
157
+ mcpServers
158
+ },
159
+ options: {
160
+ mode: args.mode || "agentic",
161
+ refs
188
162
  }
189
163
  }
190
- }
191
- return result;
164
+ ]
192
165
  };
193
- };
194
-
195
- // __mcpc__cli_latest/node_modules/@jsr/mcpc__utils/src/tool-tags.js
196
- import { load } from "cheerio";
197
- function parseTags(htmlString, tags) {
198
- const $ = load(htmlString, {
199
- xml: {
200
- decodeEntities: false
201
- }
202
- });
203
- const tagToResults = {};
204
- for (const tag of tags) {
205
- const elements = $(tag);
206
- tagToResults[tag] = elements.toArray();
166
+ const modeInfo = args.mode ? `
167
+ Mode: ${args.mode}` : "";
168
+ console.error(`
169
+ Created configuration for ${serverNames.length} MCP server(s)${modeInfo}`);
170
+ if (args.saveConfig) {
171
+ await saveUserConfig(config2, agentName);
207
172
  }
208
- return {
209
- tagToResults,
210
- $
211
- };
173
+ return config2;
212
174
  }
175
+ function printHelp() {
176
+ console.log(`
177
+ MCPC CLI - Model Context Protocol Composer
213
178
 
214
- // __mcpc__cli_latest/node_modules/@jsr/mcpc__core/src/utils/common/mcp.js
215
- import { Client } from "@modelcontextprotocol/sdk/client/index.js";
216
- import { StdioClientTransport } from "@modelcontextprotocol/sdk/client/stdio.js";
217
- import { SSEClientTransport } from "@modelcontextprotocol/sdk/client/sse.js";
218
- import { StreamableHTTPClientTransport } from "@modelcontextprotocol/sdk/client/streamableHttp.js";
219
- import { InMemoryTransport } from "@modelcontextprotocol/sdk/inMemory.js";
179
+ USAGE:
180
+ mcpc [OPTIONS]
220
181
 
221
- // __mcpc__cli_latest/node_modules/@jsr/mcpc__core/src/utils/common/registory.js
222
- function connectToSmitheryServer(smitheryConfig) {
223
- const serverUrl = new URL(smitheryConfig.deploymentUrl);
224
- serverUrl.searchParams.set("config", btoa(JSON.stringify(smitheryConfig.config)));
225
- serverUrl.searchParams.set("api_key", smitheryConfig?.smitheryApiKey ?? smitheryConfig?.config?.smitheryApiKey);
226
- return {
227
- url: serverUrl.toString()
228
- };
229
- }
230
- function smitheryToolNameCompatibale(name, scope) {
231
- if (!name.startsWith("toolbox_")) {
232
- return {
233
- toolNameWithScope: `${scope}.${name}`,
234
- toolName: name
235
- };
236
- }
237
- const [, ...toolNames] = name.split("_");
238
- const toolName = toolNames.join("_");
239
- const toolNameWithScope = `${scope}.${toolName}`;
240
- return {
241
- toolNameWithScope,
242
- toolName
243
- };
244
- }
182
+ OPTIONS:
183
+ --help, -h Show this help message
184
+ --config <json> Inline JSON configuration string
185
+ --config-url <url> Fetch configuration from URL
186
+ --config-file <path> Load configuration from file path
187
+ --request-headers <header>, -H <header>
188
+ Add custom HTTP header for URL fetching
189
+ Format: "Key: Value" or "Key=Value"
190
+ Can be used multiple times
191
+ --mode <mode> Set execution mode for all agents
192
+ Supported modes:
193
+ - agentic: Fully autonomous agent mode (default)
194
+ - agentic_workflow: Agent workflow mode with dynamic or predefined steps
195
+ - agentic_sampling: Autonomous sampling mode for agentic execution
196
+ - agentic_workflow_sampling: Autonomous sampling mode for workflow execution
197
+ - code_execution: Code execution mode for most efficient token usage
198
+ --add Add MCP servers to ~/.mcpc/config.json and exit
199
+ Then run 'mcpc' to start the server with saved config
200
+ Use --mcp-stdio, --mcp-http, or --mcp-sse to specify servers
201
+ --wrap Wrap and run MCP servers immediately without saving config
202
+ Use --mcp-stdio, --mcp-http, or --mcp-sse to specify servers
203
+ --mcp-stdio <cmd> Add an MCP server with stdio transport
204
+ Example: --mcp-stdio "npx -y @wonderwhy-er/desktop-commander"
205
+ --mcp-http <url> Add an MCP server with streamable-http transport
206
+ Example: --mcp-http "https://api.github.com/mcp"
207
+ --mcp-sse <url> Add an MCP server with SSE transport
208
+ Example: --mcp-sse "https://api.example.com/sse"
209
+ --name <name> Custom agent name for wrap mode (overrides auto-detection)
245
210
 
246
- // __mcpc__cli_latest/node_modules/@jsr/mcpc__core/src/utils/common/config.js
247
- import process2 from "node:process";
248
- var GEMINI_PREFERRED_FORMAT = process2.env.GEMINI_PREFERRED_FORMAT === "0" ? false : true;
211
+ ENVIRONMENT VARIABLES:
212
+ MCPC_CONFIG Inline JSON configuration (same as --config)
213
+ MCPC_CONFIG_URL URL to fetch config from (same as --config-url)
214
+ MCPC_CONFIG_FILE Path to config file (same as --config-file)
249
215
 
250
- // __mcpc__cli_latest/node_modules/@jsr/mcpc__core/src/utils/common/json.js
251
- import { jsonrepair as jsonrepair2 } from "jsonrepair";
216
+ EXAMPLES:
217
+ # Show help
218
+ mcpc --help
252
219
 
253
- // __mcpc__cli_latest/node_modules/@jsr/mcpc__core/src/utils/common/provider.js
254
- function sanitizePropertyKey(name) {
255
- return name.replace(/[@.,/\\:;!?#$%^&*()[\]{}]/g, "_").substring(0, 64);
256
- }
257
- var createGoogleCompatibleJSONSchema = (schema) => {
258
- if (!GEMINI_PREFERRED_FORMAT) {
259
- return schema;
260
- }
261
- const { oneOf: _oneOf, allOf: _allOf, anyOf: _anyOf, ...cleanSchema } = schema;
262
- const removeAdditionalProperties = (obj) => {
263
- if (Array.isArray(obj)) {
264
- return obj.map(removeAdditionalProperties);
265
- }
266
- if (obj && typeof obj === "object") {
267
- const result = {};
268
- for (const [key, value] of Object.entries(obj)) {
269
- if (key !== "additionalProperties") {
270
- result[key] = removeAdditionalProperties(value);
271
- }
272
- }
273
- return result;
274
- }
275
- return obj;
276
- };
277
- return removeAdditionalProperties(cleanSchema);
278
- };
220
+ # Add MCP servers to config and save to ~/.mcpc/config.json
221
+ mcpc --add --mcp-stdio "npx -y @wonderwhy-er/desktop-commander"
222
+ # Edit ~/.mcpc/config.json if needed (add headers, etc.)
223
+ mcpc # Loads config from ~/.mcpc/config.json automatically
279
224
 
280
- // __mcpc__cli_latest/node_modules/@jsr/mcpc__core/src/utils/common/mcp.js
281
- import { cwd } from "node:process";
282
- import process3 from "node:process";
283
- import { createHash } from "node:crypto";
284
- var mcpClientPool = /* @__PURE__ */ new Map();
285
- var mcpClientConnecting = /* @__PURE__ */ new Map();
286
- var shortHash = (s) => createHash("sha256").update(s).digest("hex").slice(0, 8);
287
- function defSignature(def) {
288
- const defCopy = {
289
- ...def
290
- };
291
- if (defCopy.transportType === "memory" || defCopy.transport) {
292
- return `memory:${Date.now()}:${Math.random()}`;
293
- }
294
- return JSON.stringify(defCopy);
225
+ # Wrap and run immediately (one-time use, no config saved)
226
+ mcpc --wrap --mcp-stdio "npx -y @wonderwhy-er/desktop-commander"
227
+
228
+ # Multiple servers with different transports
229
+ mcpc --add --mcp-stdio "npx -y @wonderwhy-er/desktop-commander" --mcp-http "https://api.github.com/mcp" --mcp-sse "https://api.example.com/sse"
230
+
231
+ # Custom agent name
232
+ mcpc --add --name my-agent --mcp-stdio "npx shadcn@latest mcp"
233
+ mcpc --wrap --name my-agent --mcp-stdio "npx shadcn@latest mcp"
234
+
235
+ # Load from URL
236
+ mcpc --config-url \\
237
+ "https://raw.githubusercontent.com/mcpc-tech/mcpc/main/packages/cli/examples/configs/codex-fork.json"
238
+
239
+ # Load from URL with custom headers
240
+ mcpc \\
241
+ --config-url "https://api.example.com/config.json" \\
242
+ -H "Authorization: Bearer token123" \\
243
+ -H "X-Custom-Header: value"
244
+
245
+ # Load from file
246
+ mcpc --config-file ./my-config.json
247
+
248
+ # Override execution mode for all agents
249
+ mcpc --config-file ./my-config.json --mode agentic_workflow
250
+
251
+ # Using environment variable
252
+ export MCPC_CONFIG='[{"name":"agent","description":"..."}]'
253
+ mcpc
254
+
255
+ # Use default configuration (./mcpc.config.json)
256
+ mcpc
257
+
258
+ CONFIGURATION:
259
+ Configuration files support environment variable substitution using $VAR_NAME syntax.
260
+
261
+ Priority order:
262
+ 1. --config (inline JSON)
263
+ 2. MCPC_CONFIG environment variable
264
+ 3. --config-url or MCPC_CONFIG_URL
265
+ 4. --config-file or MCPC_CONFIG_FILE
266
+ 5. ./mcpc.config.json (default)
267
+
268
+ For more information, visit: https://github.com/mcpc-tech/mcpc
269
+ `);
295
270
  }
296
- function createTransport(def) {
297
- const defAny = def;
298
- const explicitType = defAny.transportType || defAny.type;
299
- if (explicitType === "memory") {
300
- if (!defAny.server) {
301
- throw new Error("In-memory transport requires a 'server' field with a Server instance");
302
- }
303
- const [clientTransport, serverTransport] = InMemoryTransport.createLinkedPair();
304
- defAny.server.connect(serverTransport).catch((err) => {
305
- console.error("Error connecting in-memory server:", err);
306
- });
307
- return clientTransport;
308
- }
309
- if (explicitType === "sse") {
310
- const options = {};
311
- if (defAny.headers) {
312
- options.requestInit = {
313
- headers: defAny.headers
314
- };
315
- options.eventSourceInit = {
316
- headers: defAny.headers
317
- };
318
- }
319
- return new SSEClientTransport(new URL(defAny.url), options);
320
- }
321
- if (defAny.url && typeof defAny.url === "string") {
322
- const options = {};
323
- if (defAny.headers) {
324
- options.requestInit = {
325
- headers: defAny.headers
326
- };
271
+ function parseArgs() {
272
+ const args = process2.argv.slice(2);
273
+ const result = {};
274
+ for (let i = 0; i < args.length; i++) {
275
+ const arg = args[i];
276
+ if (arg === "--config" && i + 1 < args.length) {
277
+ result.config = args[++i];
278
+ } else if (arg === "--config-url" && i + 1 < args.length) {
279
+ result.configUrl = args[++i];
280
+ } else if (arg === "--config-file" && i + 1 < args.length) {
281
+ result.configFile = args[++i];
282
+ } else if ((arg === "--request-headers" || arg === "-H") && i + 1 < args.length) {
283
+ const headerStr = args[++i];
284
+ const colonIdx = headerStr.indexOf(":");
285
+ const equalIdx = headerStr.indexOf("=");
286
+ const separatorIdx = colonIdx !== -1 ? equalIdx !== -1 ? Math.min(colonIdx, equalIdx) : colonIdx : equalIdx;
287
+ if (separatorIdx !== -1) {
288
+ const key = headerStr.substring(0, separatorIdx).trim();
289
+ const value = headerStr.substring(separatorIdx + 1).trim();
290
+ if (!result.requestHeaders) {
291
+ result.requestHeaders = {};
292
+ }
293
+ result.requestHeaders[key] = value;
294
+ }
295
+ } else if (arg === "--help" || arg === "-h") {
296
+ result.help = true;
297
+ } else if (arg === "--add") {
298
+ result.add = true;
299
+ } else if (arg === "--wrap") {
300
+ result.wrap = true;
301
+ } else if ((arg === "--mcp-stdio" || arg === "--mcp-http" || arg === "--mcp-sse") && i + 1 < args.length) {
302
+ const cmdString = args[++i];
303
+ const cmdParts = cmdString.split(/\s+/);
304
+ const command = cmdParts[0];
305
+ const cmdArgs = cmdParts.slice(1);
306
+ let transportType;
307
+ if (arg === "--mcp-stdio") {
308
+ transportType = "stdio";
309
+ } else if (arg === "--mcp-http") {
310
+ transportType = "streamable-http";
311
+ } else {
312
+ transportType = "sse";
313
+ }
314
+ if (!result.mcpServers) {
315
+ result.mcpServers = [];
316
+ }
317
+ result.mcpServers.push({
318
+ command,
319
+ args: cmdArgs,
320
+ transportType
321
+ });
322
+ } else if (arg === "--mode" && i + 1 < args.length) {
323
+ result.mode = args[++i];
324
+ } else if (arg === "--name" && i + 1 < args.length) {
325
+ result.name = args[++i];
327
326
  }
328
- return new StreamableHTTPClientTransport(new URL(defAny.url), options);
329
- }
330
- if (explicitType === "stdio" || defAny.command) {
331
- return new StdioClientTransport({
332
- command: defAny.command,
333
- args: defAny.args,
334
- env: {
335
- ...process3.env,
336
- ...defAny.env ?? {}
337
- },
338
- cwd: cwd()
339
- });
340
327
  }
341
- throw new Error(`Unsupported transport configuration: ${JSON.stringify(def)}`);
328
+ return result;
342
329
  }
343
- async function getOrCreateMcpClient(defKey, def) {
344
- const pooled = mcpClientPool.get(defKey);
345
- if (pooled) {
346
- pooled.refCount += 1;
347
- return pooled.client;
348
- }
349
- const existingConnecting = mcpClientConnecting.get(defKey);
350
- if (existingConnecting) {
351
- const client = await existingConnecting;
352
- const entry = mcpClientPool.get(defKey);
353
- if (entry) entry.refCount += 1;
354
- return client;
330
+ async function loadConfig() {
331
+ const args = parseArgs();
332
+ if (args.help) {
333
+ printHelp();
334
+ process2.exit(0);
355
335
  }
356
- const transport2 = createTransport(def);
357
- const connecting = (async () => {
358
- const client = new Client({
359
- name: `mcp_${shortHash(defSignature(def))}`,
360
- version: "1.0.0"
361
- });
362
- await client.connect(transport2, {
363
- timeout: 6e4 * 10
336
+ if (args.add) {
337
+ await createWrapConfig({
338
+ ...args,
339
+ saveConfig: true
364
340
  });
365
- return client;
366
- })();
367
- mcpClientConnecting.set(defKey, connecting);
368
- try {
369
- const client = await connecting;
370
- mcpClientPool.set(defKey, {
371
- client,
372
- refCount: 1
341
+ process2.exit(0);
342
+ }
343
+ if (args.wrap) {
344
+ return await createWrapConfig({
345
+ ...args,
346
+ saveConfig: false
373
347
  });
374
- return client;
375
- } finally {
376
- mcpClientConnecting.delete(defKey);
377
348
  }
378
- }
379
- async function releaseMcpClient(defKey) {
380
- const entry = mcpClientPool.get(defKey);
381
- if (!entry) return;
382
- entry.refCount -= 1;
383
- if (entry.refCount <= 0) {
384
- mcpClientPool.delete(defKey);
349
+ if (args.config) {
385
350
  try {
386
- await entry.client.close();
387
- } catch (err) {
388
- console.error("Error closing MCP client:", err);
351
+ const parsed = JSON.parse(args.config);
352
+ return applyModeOverride(normalizeConfig(parsed), args.mode);
353
+ } catch (error) {
354
+ console.error("Failed to parse --config argument:", error);
355
+ throw error;
389
356
  }
390
357
  }
391
- }
392
- var cleanupAllPooledClients = async () => {
393
- const entries = Array.from(mcpClientPool.entries());
394
- mcpClientPool.clear();
395
- await Promise.all(entries.map(async ([, { client }]) => {
358
+ if (process2.env.MCPC_CONFIG) {
396
359
  try {
397
- await client.close();
398
- } catch (err) {
399
- console.error("Error closing MCP client:", err);
360
+ const parsed = JSON.parse(process2.env.MCPC_CONFIG);
361
+ return applyModeOverride(normalizeConfig(parsed), args.mode);
362
+ } catch (error) {
363
+ console.error("Failed to parse MCPC_CONFIG environment variable:", error);
364
+ throw error;
400
365
  }
401
- }));
402
- };
403
- process3.once?.("exit", () => {
404
- cleanupAllPooledClients();
405
- });
406
- process3.once?.("SIGINT", () => {
407
- cleanupAllPooledClients().finally(() => process3.exit(0));
408
- });
409
- async function composeMcpDepTools(mcpConfig, filterIn) {
410
- const allTools = {};
411
- const allClients = {};
412
- const acquiredKeys = [];
413
- for (const [name, definition] of Object.entries(mcpConfig.mcpServers)) {
414
- const def = definition;
415
- if (def.disabled) continue;
416
- const defKey = shortHash(defSignature(def));
417
- const serverId = name;
366
+ }
367
+ const configUrl = args.configUrl || process2.env.MCPC_CONFIG_URL;
368
+ if (configUrl) {
418
369
  try {
419
- const client = await getOrCreateMcpClient(defKey, def);
420
- acquiredKeys.push(defKey);
421
- allClients[serverId] = client;
422
- const { tools } = await client.listTools();
423
- tools.forEach((tool) => {
424
- const { toolNameWithScope, toolName: internalToolName } = smitheryToolNameCompatibale(tool.name, name);
425
- const rawToolId = `${serverId}_${internalToolName}`;
426
- const toolId = sanitizePropertyKey(rawToolId);
427
- if (filterIn && !filterIn({
428
- action: internalToolName,
429
- tool,
430
- mcpName: name,
431
- toolNameWithScope,
432
- internalToolName,
433
- toolId
434
- })) {
435
- return;
436
- }
437
- const execute = (args) => allClients[serverId].callTool({
438
- name: internalToolName,
439
- arguments: args
440
- }, void 0, {
441
- timeout: def.toolCallTimeout
442
- });
443
- allTools[toolId] = {
444
- ...tool,
445
- execute,
446
- _originalName: toolNameWithScope
447
- };
370
+ const headers = {
371
+ "User-Agent": "MCPC-CLI/0.1.0",
372
+ ...args.requestHeaders
373
+ };
374
+ const response = await fetch(configUrl, {
375
+ headers
448
376
  });
377
+ if (!response.ok) {
378
+ throw new Error(`HTTP ${response.status}: ${response.statusText}`);
379
+ }
380
+ const content = await response.text();
381
+ const parsed = JSON.parse(content);
382
+ return applyModeOverride(normalizeConfig(parsed), args.mode);
449
383
  } catch (error) {
450
- console.error(`Error creating MCP client for ${name}:`, error);
384
+ console.error(`Failed to fetch config from ${configUrl}:`, error);
385
+ throw error;
451
386
  }
452
387
  }
453
- const cleanupClients = async () => {
454
- await Promise.all(acquiredKeys.map((k) => releaseMcpClient(k)));
455
- acquiredKeys.length = 0;
456
- Object.keys(allTools).forEach((key) => delete allTools[key]);
457
- Object.keys(allClients).forEach((key) => delete allClients[key]);
458
- };
459
- return {
460
- tools: allTools,
461
- clients: allClients,
462
- cleanupClients
463
- };
464
- }
465
-
466
- // __mcpc__cli_latest/node_modules/@jsr/mcpc__core/src/utils/common/tool-tag-processor.js
467
- var ALL_TOOLS_PLACEHOLDER = "__ALL__";
468
- function findToolId(toolName, tools, toolNameMapping) {
469
- const mappedId = toolNameMapping?.get(toolName);
470
- if (mappedId) {
471
- return mappedId;
472
- }
473
- return Object.keys(tools).find((id) => {
474
- const dotNotation = id.replace(/_/g, ".");
475
- return toolName === id || toolName === dotNotation;
476
- });
477
- }
478
- function processToolTags({ description, tagToResults, $, tools, toolOverrides, toolNameMapping }) {
479
- tagToResults.tool.forEach((toolEl) => {
480
- const toolName = toolEl.attribs.name;
481
- if (!toolName || toolName.includes(ALL_TOOLS_PLACEHOLDER)) {
482
- $(toolEl).remove();
483
- return;
484
- }
485
- const override = toolOverrides.get(toolName);
486
- if (override?.visibility?.hidden) {
487
- $(toolEl).remove();
488
- } else if (override?.visibility?.public) {
489
- $(toolEl).replaceWith(`<tool name="${toolName}"/>`);
490
- } else {
491
- const toolId = findToolId(toolName, tools, toolNameMapping);
492
- if (toolId) {
493
- $(toolEl).replaceWith(`<tool name="${toolId}"/>`);
388
+ const configFile = args.configFile || process2.env.MCPC_CONFIG_FILE;
389
+ if (configFile) {
390
+ try {
391
+ const content = await readFile(configFile, "utf-8");
392
+ const parsed = JSON.parse(content);
393
+ return applyModeOverride(normalizeConfig(parsed), args.mode);
394
+ } catch (error) {
395
+ if (error.code === "ENOENT") {
396
+ console.error(`Config file not found: ${configFile}`);
397
+ throw error;
494
398
  } else {
495
- $(toolEl).remove();
399
+ console.error(`Failed to load config from ${configFile}:`, error);
400
+ throw error;
496
401
  }
497
402
  }
498
- });
499
- return $.root().html() ?? description;
500
- }
501
-
502
- // __mcpc__cli_latest/node_modules/@jsr/mcpc__core/src/plugins/built-in/config-plugin.js
503
- var createConfigPlugin = () => ({
504
- name: "built-in-config",
505
- version: "1.0.0",
506
- enforce: "pre",
507
- transformTool: (tool, context2) => {
508
- const server2 = context2.server;
509
- const config2 = server2.findToolConfig?.(context2.toolName);
510
- if (config2?.description) {
511
- tool.description = config2.description;
512
- }
513
- return tool;
514
403
  }
515
- });
516
- var config_plugin_default = createConfigPlugin();
517
-
518
- // __mcpc__cli_latest/node_modules/@jsr/mcpc__core/src/plugins/built-in/tool-name-mapping-plugin.js
519
- var createToolNameMappingPlugin = () => ({
520
- name: "built-in-tool-name-mapping",
521
- version: "1.0.0",
522
- enforce: "pre",
523
- transformTool: (tool, context2) => {
524
- const server2 = context2.server;
525
- const toolName = context2.toolName;
526
- const originalName = tool._originalName || toolName;
527
- const dotNotation = originalName.replace(/_/g, ".");
528
- const underscoreNotation = originalName.replace(/\./g, "_");
529
- if (dotNotation !== originalName && server2.toolNameMapping) {
530
- server2.toolNameMapping.set(dotNotation, toolName);
531
- }
532
- if (underscoreNotation !== originalName && server2.toolNameMapping) {
533
- server2.toolNameMapping.set(underscoreNotation, toolName);
534
- }
535
- if (originalName !== toolName && server2.toolNameMapping) {
536
- server2.toolNameMapping.set(originalName, toolName);
404
+ const userConfigPath = getUserConfigPath();
405
+ try {
406
+ const content = await readFile(userConfigPath, "utf-8");
407
+ const parsed = JSON.parse(content);
408
+ return applyModeOverride(normalizeConfig(parsed), args.mode);
409
+ } catch (error) {
410
+ if (error.code !== "ENOENT") {
411
+ console.error(`Failed to load config from ${userConfigPath}:`, error);
412
+ throw error;
537
413
  }
538
- return tool;
539
- }
540
- });
541
- var tool_name_mapping_plugin_default = createToolNameMappingPlugin();
542
-
543
- // __mcpc__cli_latest/node_modules/@jsr/mcpc__core/src/utils/logger.js
544
- var LOG_LEVELS = {
545
- debug: 0,
546
- info: 1,
547
- notice: 2,
548
- warning: 3,
549
- error: 4,
550
- critical: 5,
551
- alert: 6,
552
- emergency: 7
553
- };
554
- var MCPLogger = class _MCPLogger {
555
- server;
556
- loggerName;
557
- minLevel = "debug";
558
- constructor(loggerName = "mcpc", server2) {
559
- this.loggerName = loggerName;
560
- this.server = server2;
561
- }
562
- setServer(server2) {
563
- this.server = server2;
564
- }
565
- setLevel(level) {
566
- this.minLevel = level;
567
414
  }
568
- async log(level, data) {
569
- if (LOG_LEVELS[level] < LOG_LEVELS[this.minLevel]) {
570
- return;
571
- }
572
- this.logToConsole(level, data);
573
- if (this.server) {
574
- try {
575
- await this.server.sendLoggingMessage({
576
- level,
577
- logger: this.loggerName,
578
- data
579
- });
580
- } catch {
581
- }
415
+ const defaultConfigPath = resolve(process2.cwd(), "mcpc.config.json");
416
+ try {
417
+ const content = await readFile(defaultConfigPath, "utf-8");
418
+ const parsed = JSON.parse(content);
419
+ return applyModeOverride(normalizeConfig(parsed), args.mode);
420
+ } catch (error) {
421
+ if (error.code === "ENOENT") {
422
+ return null;
423
+ } else {
424
+ console.error(`Failed to load config from ${defaultConfigPath}:`, error);
425
+ throw error;
582
426
  }
583
427
  }
584
- logToConsole(level, data) {
585
- const message = typeof data === "string" ? data : JSON.stringify(data);
586
- const prefix = `[${this.loggerName}:${level}]`;
587
- console.error(prefix, message);
588
- }
589
- debug(data) {
590
- return this.log("debug", data);
591
- }
592
- info(data) {
593
- return this.log("info", data);
594
- }
595
- notice(data) {
596
- return this.log("notice", data);
597
- }
598
- warning(data) {
599
- return this.log("warning", data);
600
- }
601
- error(data) {
602
- return this.log("error", data);
428
+ }
429
+ function replaceEnvVars(str) {
430
+ return str.replace(/\$([A-Z_][A-Z0-9_]*)/g, (_match, varName) => {
431
+ return process2.env[varName] || "";
432
+ });
433
+ }
434
+ function replaceEnvVarsInConfig(obj) {
435
+ if (typeof obj === "string") {
436
+ return replaceEnvVars(obj);
603
437
  }
604
- critical(data) {
605
- return this.log("critical", data);
438
+ if (Array.isArray(obj)) {
439
+ return obj.map((item) => replaceEnvVarsInConfig(item));
606
440
  }
607
- alert(data) {
608
- return this.log("alert", data);
441
+ if (obj && typeof obj === "object") {
442
+ const result = {};
443
+ for (const [key, value] of Object.entries(obj)) {
444
+ result[key] = replaceEnvVarsInConfig(value);
445
+ }
446
+ return result;
609
447
  }
610
- emergency(data) {
611
- return this.log("emergency", data);
448
+ return obj;
449
+ }
450
+ function applyModeOverride(config2, mode) {
451
+ if (!mode) return config2;
452
+ config2.agents.forEach((agent) => {
453
+ if (!agent.options) agent.options = {};
454
+ agent.options.mode = mode;
455
+ });
456
+ return config2;
457
+ }
458
+ function normalizeConfig(config2) {
459
+ config2 = replaceEnvVarsInConfig(config2);
460
+ if (Array.isArray(config2)) {
461
+ return {
462
+ name: "mcpc-server",
463
+ version: "0.1.0",
464
+ agents: normalizeAgents(config2)
465
+ };
612
466
  }
613
- child(name) {
614
- const child = new _MCPLogger(`${this.loggerName}.${name}`, this.server);
615
- child.setLevel(this.minLevel);
616
- return child;
467
+ if (config2 && typeof config2 === "object") {
468
+ const cfg = config2;
469
+ return {
470
+ name: cfg.name || "mcpc-server",
471
+ version: cfg.version || "0.1.0",
472
+ capabilities: cfg.capabilities,
473
+ agents: normalizeAgents(cfg.agents || [])
474
+ };
617
475
  }
618
- };
619
- var logger = new MCPLogger("mcpc");
620
- function createLogger(name, server2) {
621
- return new MCPLogger(name, server2);
476
+ throw new Error("Invalid configuration format");
477
+ }
478
+ function normalizeAgents(agents) {
479
+ return agents.map((agent) => {
480
+ if (agent.deps && !agent.deps.mcpServers) {
481
+ agent.deps.mcpServers = {};
482
+ }
483
+ return agent;
484
+ });
622
485
  }
623
486
 
624
- // __mcpc__cli_latest/node_modules/@jsr/mcpc__core/src/plugins/built-in/logging-plugin.js
625
- var createLoggingPlugin = (options = {}) => {
626
- const { enabled = true, verbose = false, compact: compact2 = true } = options;
487
+ // __mcpc__cli_latest/node_modules/@jsr/mcpc__core/src/compose.js
488
+ import { CallToolRequestSchema, ListToolsRequestSchema, SetLevelRequestSchema } from "@modelcontextprotocol/sdk/types.js";
489
+
490
+ // __mcpc__cli_latest/node_modules/@jsr/mcpc__core/src/utils/schema.js
491
+ var schemaSymbol = Symbol.for("mcpc.schema");
492
+ var vercelSchemaSymbol = Symbol.for("vercel.ai.schema");
493
+ var validatorSymbol = Symbol.for("mcpc.validator");
494
+ function jsonSchema(schema, options = {}) {
495
+ if (isWrappedSchema(schema)) {
496
+ return schema;
497
+ }
627
498
  return {
628
- name: "built-in-logging",
629
- version: "1.0.0",
630
- composeEnd: async (context2) => {
631
- if (!enabled) return;
632
- const logger2 = createLogger("mcpc.plugin.logging", context2.server);
633
- if (compact2) {
634
- const pluginCount = context2.pluginNames.length;
635
- const { stats } = context2;
636
- await logger2.info(`[${context2.toolName}] ${pluginCount} plugins \u2022 ${stats.publicTools} public \u2022 ${stats.hiddenTools} hidden`);
637
- } else if (verbose) {
638
- await logger2.info(`[${context2.toolName}] Composition complete`);
639
- await logger2.info(` \u251C\u2500 Plugins: ${context2.pluginNames.join(", ")}`);
640
- const { stats } = context2;
641
- const server2 = context2.server;
642
- const publicTools = Array.from(new Set(server2.getPublicToolNames().map(String)));
643
- const internalTools = Array.from(new Set(server2.getInternalToolNames().map(String)));
644
- const hiddenTools = Array.from(new Set(server2.getHiddenToolNames().map(String)));
645
- const normalInternal = internalTools.filter((name) => !hiddenTools.includes(name));
646
- if (publicTools.length > 0) {
647
- await logger2.info(` \u251C\u2500 Public: ${publicTools.join(", ")}`);
499
+ [schemaSymbol]: true,
500
+ [validatorSymbol]: true,
501
+ _type: void 0,
502
+ jsonSchema: schema,
503
+ validate: options.validate
504
+ };
505
+ }
506
+ function isWrappedSchema(value) {
507
+ return typeof value === "object" && value !== null && (schemaSymbol in value && value[schemaSymbol] === true || vercelSchemaSymbol in value && value[vercelSchemaSymbol] === true);
508
+ }
509
+ function extractJsonSchema(schema) {
510
+ if (isWrappedSchema(schema)) {
511
+ return schema.jsonSchema;
512
+ }
513
+ return schema;
514
+ }
515
+
516
+ // __mcpc__cli_latest/node_modules/@jsr/mcpc__core/src/compose.js
517
+ import { Server } from "@modelcontextprotocol/sdk/server/index.js";
518
+
519
+ // __mcpc__cli_latest/node_modules/@jsr/mcpc__utils/src/json.js
520
+ import { jsonrepair } from "jsonrepair";
521
+ function stripMarkdownAndText(text) {
522
+ text = text.trim();
523
+ text = text.replace(/^```(?:json)?\s*\n?/i, "");
524
+ text = text.replace(/\n?```\s*$/, "");
525
+ text = text.replace(/^(?:here is|here's|response|result|output|json):\s*/i, "");
526
+ const firstJsonIndex = text.search(/[\{\[]/);
527
+ if (firstJsonIndex >= 0) {
528
+ text = text.slice(firstJsonIndex);
529
+ let depth = 0;
530
+ let inString = false;
531
+ let escapeNext = false;
532
+ const startChar = text[0];
533
+ const endChar = startChar === "{" ? "}" : "]";
534
+ for (let i = 0; i < text.length; i++) {
535
+ const char = text[i];
536
+ if (escapeNext) {
537
+ escapeNext = false;
538
+ continue;
539
+ }
540
+ if (char === "\\") {
541
+ escapeNext = true;
542
+ continue;
543
+ }
544
+ if (char === '"' && !inString) {
545
+ inString = true;
546
+ continue;
547
+ }
548
+ if (char === '"' && inString) {
549
+ inString = false;
550
+ continue;
551
+ }
552
+ if (inString) continue;
553
+ if (char === startChar) {
554
+ depth++;
555
+ } else if (char === endChar) {
556
+ depth--;
557
+ if (depth === 0) {
558
+ return text.slice(0, i + 1);
648
559
  }
649
- if (internalTools.length > 0) {
650
- const parts = [];
651
- if (normalInternal.length > 0) {
652
- parts.push(normalInternal.join(", "));
653
- }
654
- if (hiddenTools.length > 0) {
655
- parts.push(`(${hiddenTools.join(", ")})`);
656
- }
657
- await logger2.info(` \u251C\u2500 Internal: ${parts.join(", ")}`);
560
+ }
561
+ }
562
+ }
563
+ return text.trim();
564
+ }
565
+ function parseJSON(text, throwError) {
566
+ try {
567
+ return JSON.parse(text);
568
+ } catch (_error) {
569
+ try {
570
+ const cleanedText = stripMarkdownAndText(text);
571
+ try {
572
+ return JSON.parse(cleanedText);
573
+ } catch {
574
+ const repairedText = jsonrepair(cleanedText);
575
+ console.warn(`Failed to parse JSON, cleaned and repaired. Original: ${text.slice(0, 100)}...`);
576
+ return JSON.parse(repairedText);
577
+ }
578
+ } catch (_repairError) {
579
+ if (throwError) {
580
+ throw new Error(`Failed to parse JSON after cleanup and repair. Original error: ${_error instanceof Error ? _error.message : String(_error)}`);
581
+ }
582
+ return null;
583
+ }
584
+ }
585
+ }
586
+
587
+ // __mcpc__cli_latest/node_modules/@jsr/mcpc__utils/src/ai.js
588
+ var p = (template, options = {}) => {
589
+ const { missingVariableHandling = "warn" } = options;
590
+ const names = /* @__PURE__ */ new Set();
591
+ const regex = /\{((\w|\.)+)\}/g;
592
+ let match;
593
+ while ((match = regex.exec(template)) !== null) {
594
+ names.add(match[1]);
595
+ }
596
+ const required = Array.from(names);
597
+ return (input) => {
598
+ let result = template;
599
+ for (const name of required) {
600
+ const key = name;
601
+ const value = input[key];
602
+ const re = new RegExp(`\\{${String(name)}\\}`, "g");
603
+ if (value !== void 0 && value !== null) {
604
+ result = result.replace(re, String(value));
605
+ } else {
606
+ switch (missingVariableHandling) {
607
+ case "error":
608
+ throw new Error(`Missing variable "${String(name)}" in input for template.`);
609
+ case "empty":
610
+ result = result.replace(re, "");
611
+ break;
612
+ case "warn":
613
+ case "ignore":
614
+ default:
615
+ break;
658
616
  }
659
- await logger2.info(` \u2514\u2500 Total: ${stats.totalTools} tools`);
660
617
  }
661
618
  }
619
+ return result;
662
620
  };
663
621
  };
664
- var logging_plugin_default = createLoggingPlugin({
665
- verbose: true,
666
- compact: false
667
- });
668
-
669
- // __mcpc__cli_latest/node_modules/@jsr/mcpc__core/src/prompts/index.js
670
- var SystemPrompts = {
671
- /**
672
- * Base system prompt for autonomous MCP execution
673
- */
674
- AUTONOMOUS_EXECUTION: `Agentic tool \`{toolName}\` that executes complex tasks by iteratively selecting and calling tools, gathering results, and continuing until completion. Use this tool when the task matches the manual below.
675
-
676
- You must follow the <manual/>, obey the <execution_rules/>, and use the <call_format/>.
677
-
678
- <manual>
679
- {description}
680
- </manual>
681
622
 
682
- <parameters>
683
- \`useTool\` - Which tool to execute this iteration
684
- \`hasDefinitions\` - Tool names whose schemas you already have
685
- \`definitionsOf\` - Tool names whose schemas you need
686
- </parameters>
623
+ // __mcpc__cli_latest/node_modules/@jsr/mcpc__utils/src/tool-tags.js
624
+ import { load } from "cheerio";
625
+ function parseTags(htmlString, tags) {
626
+ const $ = load(htmlString, {
627
+ xml: {
628
+ decodeEntities: false
629
+ }
630
+ });
631
+ const tagToResults = {};
632
+ for (const tag of tags) {
633
+ const elements = $(tag);
634
+ tagToResults[tag] = elements.toArray();
635
+ }
636
+ return {
637
+ tagToResults,
638
+ $
639
+ };
640
+ }
687
641
 
688
- <execution_rules>
689
- 1. **First call**: No tool definitions available\u2014you must request them via \`definitionsOf\`
690
- 2. **When executing tools**: Must provide \`hasDefinitions\` with ALL tools you have schemas for (avoid duplicate requests and reduce tokens)
691
- 3. **When requesting definitions**: Use \`definitionsOf\` to request tool schemas you need
692
- 4. **Both together**: Execute tool AND request new definitions in one call for efficiency
693
- 5. **Never request definitions you already have**
694
- 6. **Select** one tool to execute per call using \`useTool\`
695
- 7. **Provide** parameters matching the selected tool name
696
- 8. Note: You are an agent exposed as an MCP tool - **\`useTool\` is an internal parameter for choosing which tool to execute, NOT an external MCP tool you can call**
697
- </execution_rules>
642
+ // __mcpc__cli_latest/node_modules/@jsr/mcpc__core/src/utils/common/mcp.js
643
+ import { Client } from "@modelcontextprotocol/sdk/client/index.js";
644
+ import { StdioClientTransport } from "@modelcontextprotocol/sdk/client/stdio.js";
645
+ import { SSEClientTransport } from "@modelcontextprotocol/sdk/client/sse.js";
646
+ import { StreamableHTTPClientTransport } from "@modelcontextprotocol/sdk/client/streamableHttp.js";
647
+ import { InMemoryTransport } from "@modelcontextprotocol/sdk/inMemory.js";
698
648
 
699
- <call_format>
700
- Initial definition request:
701
- \`\`\`json
702
- {
703
- "hasDefinitions": [],
704
- "definitionsOf": ["tool1", "tool2"]
649
+ // __mcpc__cli_latest/node_modules/@jsr/mcpc__core/src/utils/common/registory.js
650
+ function connectToSmitheryServer(smitheryConfig) {
651
+ const serverUrl = new URL(smitheryConfig.deploymentUrl);
652
+ serverUrl.searchParams.set("config", btoa(JSON.stringify(smitheryConfig.config)));
653
+ serverUrl.searchParams.set("api_key", smitheryConfig?.smitheryApiKey ?? smitheryConfig?.config?.smitheryApiKey);
654
+ return {
655
+ url: serverUrl.toString()
656
+ };
705
657
  }
706
- \`\`\`
707
-
708
- Execute tool + get new definitions:
709
- \`\`\`json
710
- {
711
- "useTool": "tool1",
712
- "tool1": { /* parameters */ },
713
- "hasDefinitions": ["tool1", "tool2"],
714
- "definitionsOf": ["tool3"]
658
+ function smitheryToolNameCompatibale(name, scope) {
659
+ if (!name.startsWith("toolbox_")) {
660
+ return {
661
+ toolNameWithScope: `${scope}.${name}`,
662
+ toolName: name
663
+ };
664
+ }
665
+ const [, ...toolNames] = name.split("_");
666
+ const toolName = toolNames.join("_");
667
+ const toolNameWithScope = `${scope}.${toolName}`;
668
+ return {
669
+ toolNameWithScope,
670
+ toolName
671
+ };
715
672
  }
716
- \`\`\`
717
- </call_format>`,
718
- /**
719
- * Workflow execution system prompt
720
- */
721
- WORKFLOW_EXECUTION: `Workflow tool \`{toolName}\` that executes multi-step workflows. Use this when your task requires sequential steps.
722
673
 
723
- <manual>
724
- {description}
725
- </manual>
674
+ // __mcpc__cli_latest/node_modules/@jsr/mcpc__core/src/utils/common/config.js
675
+ import process3 from "node:process";
676
+ var GEMINI_PREFERRED_FORMAT = process3.env.GEMINI_PREFERRED_FORMAT === "0" ? false : true;
726
677
 
727
- <rules>
728
- 1. First call: {planningInstructions}
729
- 2. Subsequent calls: Provide only current step parameters
730
- 3. Use \`decision: "proceed"\` to advance, \`"retry"\` to retry, \`"complete"\` when done
731
- 4. Include \`steps\` ONLY with \`init: true\`, never during execution
732
- </rules>`,
733
- /**
734
- * JSON-only execution system prompt for autonomous sampling mode
735
- *
736
- * Note: Sampling mode runs an internal LLM loop that autonomously calls tools until complete.
737
- */
738
- SAMPLING_EXECUTION: `Agent \`{toolName}\` that completes tasks by calling tools in an autonomous loop.
678
+ // __mcpc__cli_latest/node_modules/@jsr/mcpc__core/src/utils/common/json.js
679
+ import { jsonrepair as jsonrepair2 } from "jsonrepair";
680
+
681
+ // __mcpc__cli_latest/node_modules/@jsr/mcpc__core/src/utils/common/provider.js
682
+ function sanitizePropertyKey(name) {
683
+ return name.replace(/[@.,/\\:;!?#$%^&*()[\]{}]/g, "_").substring(0, 64);
684
+ }
685
+ var createGoogleCompatibleJSONSchema = (schema) => {
686
+ if (!GEMINI_PREFERRED_FORMAT) {
687
+ return schema;
688
+ }
689
+ const { oneOf: _oneOf, allOf: _allOf, anyOf: _anyOf, ...cleanSchema } = schema;
690
+ const removeAdditionalProperties = (obj) => {
691
+ if (Array.isArray(obj)) {
692
+ return obj.map(removeAdditionalProperties);
693
+ }
694
+ if (obj && typeof obj === "object") {
695
+ const result = {};
696
+ for (const [key, value] of Object.entries(obj)) {
697
+ if (key !== "additionalProperties") {
698
+ result[key] = removeAdditionalProperties(value);
699
+ }
700
+ }
701
+ return result;
702
+ }
703
+ return obj;
704
+ };
705
+ return removeAdditionalProperties(cleanSchema);
706
+ };
707
+
708
+ // __mcpc__cli_latest/node_modules/@jsr/mcpc__core/src/utils/common/mcp.js
709
+ import { cwd } from "node:process";
710
+ import process4 from "node:process";
711
+ import { createHash } from "node:crypto";
712
+ var mcpClientPool = /* @__PURE__ */ new Map();
713
+ var mcpClientConnecting = /* @__PURE__ */ new Map();
714
+ var shortHash = (s) => createHash("sha256").update(s).digest("hex").slice(0, 8);
715
+ function defSignature(def) {
716
+ const defCopy = {
717
+ ...def
718
+ };
719
+ if (defCopy.transportType === "memory" || defCopy.transport) {
720
+ return `memory:${Date.now()}:${Math.random()}`;
721
+ }
722
+ return JSON.stringify(defCopy);
723
+ }
724
+ function createTransport(def) {
725
+ const defAny = def;
726
+ const explicitType = defAny.transportType || defAny.type;
727
+ if (explicitType === "memory") {
728
+ if (!defAny.server) {
729
+ throw new Error("In-memory transport requires a 'server' field with a Server instance");
730
+ }
731
+ const [clientTransport, serverTransport] = InMemoryTransport.createLinkedPair();
732
+ defAny.server.connect(serverTransport).catch((err) => {
733
+ console.error("Error connecting in-memory server:", err);
734
+ });
735
+ return clientTransport;
736
+ }
737
+ if (explicitType === "sse") {
738
+ const options = {};
739
+ if (defAny.headers) {
740
+ options.requestInit = {
741
+ headers: defAny.headers
742
+ };
743
+ options.eventSourceInit = {
744
+ headers: defAny.headers
745
+ };
746
+ }
747
+ return new SSEClientTransport(new URL(defAny.url), options);
748
+ }
749
+ if (defAny.url && typeof defAny.url === "string") {
750
+ const options = {};
751
+ if (defAny.headers) {
752
+ options.requestInit = {
753
+ headers: defAny.headers
754
+ };
755
+ }
756
+ return new StreamableHTTPClientTransport(new URL(defAny.url), options);
757
+ }
758
+ if (explicitType === "stdio" || defAny.command) {
759
+ return new StdioClientTransport({
760
+ command: defAny.command,
761
+ args: defAny.args,
762
+ env: {
763
+ ...process4.env,
764
+ ...defAny.env ?? {}
765
+ },
766
+ cwd: cwd()
767
+ });
768
+ }
769
+ throw new Error(`Unsupported transport configuration: ${JSON.stringify(def)}`);
770
+ }
771
+ async function getOrCreateMcpClient(defKey, def) {
772
+ const pooled = mcpClientPool.get(defKey);
773
+ if (pooled) {
774
+ pooled.refCount += 1;
775
+ return pooled.client;
776
+ }
777
+ const existingConnecting = mcpClientConnecting.get(defKey);
778
+ if (existingConnecting) {
779
+ const client = await existingConnecting;
780
+ const entry = mcpClientPool.get(defKey);
781
+ if (entry) entry.refCount += 1;
782
+ return client;
783
+ }
784
+ const transport2 = createTransport(def);
785
+ const connecting = (async () => {
786
+ const client = new Client({
787
+ name: `mcp_${shortHash(defSignature(def))}`,
788
+ version: "1.0.0"
789
+ });
790
+ await client.connect(transport2, {
791
+ timeout: 6e4 * 10
792
+ });
793
+ return client;
794
+ })();
795
+ mcpClientConnecting.set(defKey, connecting);
796
+ try {
797
+ const client = await connecting;
798
+ mcpClientPool.set(defKey, {
799
+ client,
800
+ refCount: 1
801
+ });
802
+ return client;
803
+ } finally {
804
+ mcpClientConnecting.delete(defKey);
805
+ }
806
+ }
807
+ async function releaseMcpClient(defKey) {
808
+ const entry = mcpClientPool.get(defKey);
809
+ if (!entry) return;
810
+ entry.refCount -= 1;
811
+ if (entry.refCount <= 0) {
812
+ mcpClientPool.delete(defKey);
813
+ try {
814
+ await entry.client.close();
815
+ } catch (err) {
816
+ console.error("Error closing MCP client:", err);
817
+ }
818
+ }
819
+ }
820
+ var cleanupAllPooledClients = async () => {
821
+ const entries = Array.from(mcpClientPool.entries());
822
+ mcpClientPool.clear();
823
+ await Promise.all(entries.map(async ([, { client }]) => {
824
+ try {
825
+ await client.close();
826
+ } catch (err) {
827
+ console.error("Error closing MCP client:", err);
828
+ }
829
+ }));
830
+ };
831
+ process4.once?.("exit", () => {
832
+ cleanupAllPooledClients();
833
+ });
834
+ process4.once?.("SIGINT", () => {
835
+ cleanupAllPooledClients().finally(() => process4.exit(0));
836
+ });
837
+ async function composeMcpDepTools(mcpConfig, filterIn) {
838
+ const allTools = {};
839
+ const allClients = {};
840
+ const acquiredKeys = [];
841
+ for (const [name, definition] of Object.entries(mcpConfig.mcpServers)) {
842
+ const def = definition;
843
+ if (def.disabled) continue;
844
+ const defKey = shortHash(defSignature(def));
845
+ const serverId = name;
846
+ try {
847
+ const client = await getOrCreateMcpClient(defKey, def);
848
+ acquiredKeys.push(defKey);
849
+ allClients[serverId] = client;
850
+ const { tools } = await client.listTools();
851
+ tools.forEach((tool) => {
852
+ const { toolNameWithScope, toolName: internalToolName } = smitheryToolNameCompatibale(tool.name, name);
853
+ const rawToolId = `${serverId}_${internalToolName}`;
854
+ const toolId = sanitizePropertyKey(rawToolId);
855
+ if (filterIn && !filterIn({
856
+ action: internalToolName,
857
+ tool,
858
+ mcpName: name,
859
+ toolNameWithScope,
860
+ internalToolName,
861
+ toolId
862
+ })) {
863
+ return;
864
+ }
865
+ const execute = (args) => allClients[serverId].callTool({
866
+ name: internalToolName,
867
+ arguments: args
868
+ }, void 0, {
869
+ timeout: def.toolCallTimeout
870
+ });
871
+ allTools[toolId] = {
872
+ ...tool,
873
+ execute,
874
+ _originalName: toolNameWithScope
875
+ };
876
+ });
877
+ } catch (error) {
878
+ console.error(`Error creating MCP client for ${name}:`, error);
879
+ }
880
+ }
881
+ const cleanupClients = async () => {
882
+ await Promise.all(acquiredKeys.map((k) => releaseMcpClient(k)));
883
+ acquiredKeys.length = 0;
884
+ Object.keys(allTools).forEach((key) => delete allTools[key]);
885
+ Object.keys(allClients).forEach((key) => delete allClients[key]);
886
+ };
887
+ return {
888
+ tools: allTools,
889
+ clients: allClients,
890
+ cleanupClients
891
+ };
892
+ }
893
+
894
+ // __mcpc__cli_latest/node_modules/@jsr/mcpc__core/src/utils/common/tool-tag-processor.js
895
+ var ALL_TOOLS_PLACEHOLDER = "__ALL__";
896
+ function findToolId(toolName, tools, toolNameMapping) {
897
+ const mappedId = toolNameMapping?.get(toolName);
898
+ if (mappedId) {
899
+ return mappedId;
900
+ }
901
+ return Object.keys(tools).find((id) => {
902
+ const dotNotation = id.replace(/_/g, ".");
903
+ return toolName === id || toolName === dotNotation;
904
+ });
905
+ }
906
+ function processToolTags({ description, tagToResults, $, tools, toolOverrides, toolNameMapping }) {
907
+ tagToResults.tool.forEach((toolEl) => {
908
+ const toolName = toolEl.attribs.name;
909
+ if (!toolName || toolName.includes(ALL_TOOLS_PLACEHOLDER)) {
910
+ $(toolEl).remove();
911
+ return;
912
+ }
913
+ const override = toolOverrides.get(toolName);
914
+ if (override?.visibility?.hidden) {
915
+ $(toolEl).remove();
916
+ } else if (override?.visibility?.public) {
917
+ $(toolEl).replaceWith(`<tool name="${toolName}"/>`);
918
+ } else {
919
+ const toolId = findToolId(toolName, tools, toolNameMapping);
920
+ if (toolId) {
921
+ $(toolEl).replaceWith(`<tool name="${toolId}"/>`);
922
+ } else {
923
+ $(toolEl).remove();
924
+ }
925
+ }
926
+ });
927
+ return $.root().html() ?? description;
928
+ }
929
+
930
+ // __mcpc__cli_latest/node_modules/@jsr/mcpc__core/src/plugins/built-in/config-plugin.js
931
+ var createConfigPlugin = () => ({
932
+ name: "built-in-config",
933
+ version: "1.0.0",
934
+ enforce: "pre",
935
+ transformTool: (tool, context2) => {
936
+ const server2 = context2.server;
937
+ const config2 = server2.findToolConfig?.(context2.toolName);
938
+ if (config2?.description) {
939
+ tool.description = config2.description;
940
+ }
941
+ return tool;
942
+ }
943
+ });
944
+ var config_plugin_default = createConfigPlugin();
945
+
946
+ // __mcpc__cli_latest/node_modules/@jsr/mcpc__core/src/plugins/built-in/tool-name-mapping-plugin.js
947
+ var createToolNameMappingPlugin = () => ({
948
+ name: "built-in-tool-name-mapping",
949
+ version: "1.0.0",
950
+ enforce: "pre",
951
+ transformTool: (tool, context2) => {
952
+ const server2 = context2.server;
953
+ const toolName = context2.toolName;
954
+ const originalName = tool._originalName || toolName;
955
+ const dotNotation = originalName.replace(/_/g, ".");
956
+ const underscoreNotation = originalName.replace(/\./g, "_");
957
+ if (dotNotation !== originalName && server2.toolNameMapping) {
958
+ server2.toolNameMapping.set(dotNotation, toolName);
959
+ }
960
+ if (underscoreNotation !== originalName && server2.toolNameMapping) {
961
+ server2.toolNameMapping.set(underscoreNotation, toolName);
962
+ }
963
+ if (originalName !== toolName && server2.toolNameMapping) {
964
+ server2.toolNameMapping.set(originalName, toolName);
965
+ }
966
+ return tool;
967
+ }
968
+ });
969
+ var tool_name_mapping_plugin_default = createToolNameMappingPlugin();
970
+
971
+ // __mcpc__cli_latest/node_modules/@jsr/mcpc__core/src/utils/logger.js
972
+ var LOG_LEVELS = {
973
+ debug: 0,
974
+ info: 1,
975
+ notice: 2,
976
+ warning: 3,
977
+ error: 4,
978
+ critical: 5,
979
+ alert: 6,
980
+ emergency: 7
981
+ };
982
+ var MCPLogger = class _MCPLogger {
983
+ server;
984
+ loggerName;
985
+ minLevel = "debug";
986
+ constructor(loggerName = "mcpc", server2) {
987
+ this.loggerName = loggerName;
988
+ this.server = server2;
989
+ }
990
+ setServer(server2) {
991
+ this.server = server2;
992
+ }
993
+ setLevel(level) {
994
+ this.minLevel = level;
995
+ }
996
+ async log(level, data) {
997
+ if (LOG_LEVELS[level] < LOG_LEVELS[this.minLevel]) {
998
+ return;
999
+ }
1000
+ this.logToConsole(level, data);
1001
+ if (this.server) {
1002
+ try {
1003
+ await this.server.sendLoggingMessage({
1004
+ level,
1005
+ logger: this.loggerName,
1006
+ data
1007
+ });
1008
+ } catch {
1009
+ }
1010
+ }
1011
+ }
1012
+ logToConsole(level, data) {
1013
+ const message = typeof data === "string" ? data : JSON.stringify(data);
1014
+ const prefix = `[${this.loggerName}:${level}]`;
1015
+ console.error(prefix, message);
1016
+ }
1017
+ debug(data) {
1018
+ return this.log("debug", data);
1019
+ }
1020
+ info(data) {
1021
+ return this.log("info", data);
1022
+ }
1023
+ notice(data) {
1024
+ return this.log("notice", data);
1025
+ }
1026
+ warning(data) {
1027
+ return this.log("warning", data);
1028
+ }
1029
+ error(data) {
1030
+ return this.log("error", data);
1031
+ }
1032
+ critical(data) {
1033
+ return this.log("critical", data);
1034
+ }
1035
+ alert(data) {
1036
+ return this.log("alert", data);
1037
+ }
1038
+ emergency(data) {
1039
+ return this.log("emergency", data);
1040
+ }
1041
+ child(name) {
1042
+ const child = new _MCPLogger(`${this.loggerName}.${name}`, this.server);
1043
+ child.setLevel(this.minLevel);
1044
+ return child;
1045
+ }
1046
+ };
1047
+ var logger = new MCPLogger("mcpc");
1048
+ function createLogger(name, server2) {
1049
+ return new MCPLogger(name, server2);
1050
+ }
1051
+
1052
+ // __mcpc__cli_latest/node_modules/@jsr/mcpc__core/src/plugins/built-in/logging-plugin.js
1053
+ var createLoggingPlugin = (options = {}) => {
1054
+ const { enabled = true, verbose = false, compact: compact2 = true } = options;
1055
+ return {
1056
+ name: "built-in-logging",
1057
+ version: "1.0.0",
1058
+ composeEnd: async (context2) => {
1059
+ if (!enabled) return;
1060
+ const logger2 = createLogger("mcpc.plugin.logging", context2.server);
1061
+ if (compact2) {
1062
+ const pluginCount = context2.pluginNames.length;
1063
+ const { stats } = context2;
1064
+ await logger2.info(`[${context2.toolName}] ${pluginCount} plugins \u2022 ${stats.publicTools} public \u2022 ${stats.hiddenTools} hidden`);
1065
+ } else if (verbose) {
1066
+ await logger2.info(`[${context2.toolName}] Composition complete`);
1067
+ await logger2.info(` \u251C\u2500 Plugins: ${context2.pluginNames.join(", ")}`);
1068
+ const { stats } = context2;
1069
+ const server2 = context2.server;
1070
+ const publicTools = Array.from(new Set(server2.getPublicToolNames().map(String)));
1071
+ const internalTools = Array.from(new Set(server2.getInternalToolNames().map(String)));
1072
+ const hiddenTools = Array.from(new Set(server2.getHiddenToolNames().map(String)));
1073
+ const normalInternal = internalTools.filter((name) => !hiddenTools.includes(name));
1074
+ if (publicTools.length > 0) {
1075
+ await logger2.info(` \u251C\u2500 Public: ${publicTools.join(", ")}`);
1076
+ }
1077
+ if (internalTools.length > 0) {
1078
+ const parts = [];
1079
+ if (normalInternal.length > 0) {
1080
+ parts.push(normalInternal.join(", "));
1081
+ }
1082
+ if (hiddenTools.length > 0) {
1083
+ parts.push(`(${hiddenTools.join(", ")})`);
1084
+ }
1085
+ await logger2.info(` \u251C\u2500 Internal: ${parts.join(", ")}`);
1086
+ }
1087
+ await logger2.info(` \u2514\u2500 Total: ${stats.totalTools} tools`);
1088
+ }
1089
+ }
1090
+ };
1091
+ };
1092
+ var logging_plugin_default = createLoggingPlugin({
1093
+ verbose: true,
1094
+ compact: false
1095
+ });
1096
+
1097
+ // __mcpc__cli_latest/node_modules/@jsr/mcpc__core/src/prompts/index.js
1098
+ var SystemPrompts = {
1099
+ /**
1100
+ * Base system prompt for autonomous MCP execution
1101
+ */
1102
+ AUTONOMOUS_EXECUTION: `Agentic tool \`{toolName}\` that executes complex tasks by iteratively selecting and calling tools, gathering results, and continuing until completion. Use this tool when the task matches the manual below.
1103
+
1104
+ You must follow the <manual/>, obey the <execution_rules/>, and use the <call_format/>.
1105
+
1106
+ <manual>
1107
+ {description}
1108
+ </manual>
1109
+
1110
+ <parameters>
1111
+ \`useTool\` - Which tool to execute this iteration
1112
+ \`hasDefinitions\` - Tool names whose schemas you already have
1113
+ \`definitionsOf\` - Tool names whose schemas you need
1114
+ </parameters>
1115
+
1116
+ <execution_rules>
1117
+ 1. **First call**: No tool definitions available\u2014you must request them via \`definitionsOf\`
1118
+ 2. **When executing tools**: Must provide \`hasDefinitions\` with ALL tools you have schemas for (avoid duplicate requests and reduce tokens)
1119
+ 3. **When requesting definitions**: Use \`definitionsOf\` to request tool schemas you need
1120
+ 4. **Both together**: Execute tool AND request new definitions in one call for efficiency
1121
+ 5. **Never request definitions you already have**
1122
+ 6. **Select** one tool to execute per call using \`useTool\`
1123
+ 7. **Provide** parameters matching the selected tool name
1124
+ 8. Note: You are an agent exposed as an MCP tool - **\`useTool\` is an internal parameter for choosing which tool to execute, NOT an external MCP tool you can call**
1125
+ </execution_rules>
1126
+
1127
+ <call_format>
1128
+ Initial definition request:
1129
+ \`\`\`json
1130
+ {
1131
+ "hasDefinitions": [],
1132
+ "definitionsOf": ["tool1", "tool2"]
1133
+ }
1134
+ \`\`\`
1135
+
1136
+ Execute tool + get new definitions:
1137
+ \`\`\`json
1138
+ {
1139
+ "useTool": "tool1",
1140
+ "tool1": { /* parameters */ },
1141
+ "hasDefinitions": ["tool1", "tool2"],
1142
+ "definitionsOf": ["tool3"]
1143
+ }
1144
+ \`\`\`
1145
+ </call_format>`,
1146
+ /**
1147
+ * Workflow execution system prompt
1148
+ */
1149
+ WORKFLOW_EXECUTION: `Workflow tool \`{toolName}\` that executes multi-step workflows. Use this when your task requires sequential steps.
1150
+
1151
+ <manual>
1152
+ {description}
1153
+ </manual>
1154
+
1155
+ <rules>
1156
+ 1. First call: {planningInstructions}
1157
+ 2. Subsequent calls: Provide only current step parameters
1158
+ 3. Use \`decision: "proceed"\` to advance, \`"retry"\` to retry, \`"complete"\` when done
1159
+ 4. Include \`steps\` ONLY with \`init: true\`, never during execution
1160
+ </rules>`,
1161
+ /**
1162
+ * JSON-only execution system prompt for autonomous sampling mode
1163
+ *
1164
+ * Note: Sampling mode runs an internal LLM loop that autonomously calls tools until complete.
1165
+ */
1166
+ SAMPLING_EXECUTION: `Agent \`{toolName}\` that completes tasks by calling tools in an autonomous loop.
739
1167
 
740
1168
  <manual>
741
1169
  {description}
@@ -1101,7 +1529,7 @@ function endSpan(span, error) {
1101
1529
  }
1102
1530
 
1103
1531
  // __mcpc__cli_latest/node_modules/@jsr/mcpc__core/src/executors/agentic/agentic-executor.js
1104
- import process4 from "node:process";
1532
+ import process5 from "node:process";
1105
1533
  var AgenticExecutor = class {
1106
1534
  name;
1107
1535
  allToolNames;
@@ -1119,13 +1547,13 @@ var AgenticExecutor = class {
1119
1547
  this.tracingEnabled = false;
1120
1548
  this.logger = createLogger(`mcpc.agentic.${name}`, server2);
1121
1549
  try {
1122
- this.tracingEnabled = process4.env.MCPC_TRACING_ENABLED === "true";
1550
+ this.tracingEnabled = process5.env.MCPC_TRACING_ENABLED === "true";
1123
1551
  if (this.tracingEnabled) {
1124
1552
  initializeTracing({
1125
1553
  enabled: true,
1126
1554
  serviceName: `mcpc-agentic-${name}`,
1127
- exportTo: process4.env.MCPC_TRACING_EXPORT ?? "otlp",
1128
- otlpEndpoint: process4.env.MCPC_TRACING_OTLP_ENDPOINT ?? "http://localhost:4318/v1/traces"
1555
+ exportTo: process5.env.MCPC_TRACING_EXPORT ?? "otlp",
1556
+ otlpEndpoint: process5.env.MCPC_TRACING_OTLP_ENDPOINT ?? "http://localhost:4318/v1/traces"
1129
1557
  });
1130
1558
  }
1131
1559
  } catch {
@@ -1168,7 +1596,21 @@ var AgenticExecutor = class {
1168
1596
  const useTool = args[this.USE_TOOL_KEY];
1169
1597
  const definitionsOf = args.definitionsOf || [];
1170
1598
  const hasDefinitions = args.hasDefinitions || [];
1171
- if (executeSpan && useTool) {
1599
+ if (!useTool) {
1600
+ if (executeSpan) {
1601
+ executeSpan.setAttributes({
1602
+ toolType: "none",
1603
+ completion: true
1604
+ });
1605
+ endSpan(executeSpan);
1606
+ }
1607
+ const result2 = {
1608
+ content: []
1609
+ };
1610
+ this.appendToolSchemas(result2, definitionsOf, hasDefinitions);
1611
+ return result2;
1612
+ }
1613
+ if (executeSpan) {
1172
1614
  try {
1173
1615
  const safeTool = String(useTool).replace(/\s+/g, "_");
1174
1616
  if (typeof executeSpan.updateName === "function") {
@@ -1254,14 +1696,14 @@ var AgenticExecutor = class {
1254
1696
  if (executeSpan) {
1255
1697
  executeSpan.setAttributes({
1256
1698
  toolType: "not_found",
1257
- useTool: useTool || "unknown",
1258
- completion: true
1699
+ useTool
1259
1700
  });
1260
1701
  endSpan(executeSpan);
1261
1702
  }
1262
- this.logger.debug({
1263
- message: "Tool not found, returning completion message",
1264
- useTool
1703
+ this.logger.warning({
1704
+ message: "Tool not found",
1705
+ useTool,
1706
+ availableTools: this.allToolNames
1265
1707
  });
1266
1708
  const result = {
1267
1709
  content: []
@@ -2265,7 +2707,7 @@ var createWorkflowModePlugin = () => ({
2265
2707
  var mode_workflow_plugin_default = createWorkflowModePlugin();
2266
2708
 
2267
2709
  // __mcpc__cli_latest/node_modules/@jsr/mcpc__core/src/executors/sampling/base-sampling-executor.js
2268
- import process5 from "node:process";
2710
+ import process6 from "node:process";
2269
2711
  var BaseSamplingExecutor = class {
2270
2712
  name;
2271
2713
  description;
@@ -2298,10 +2740,10 @@ var BaseSamplingExecutor = class {
2298
2740
  this.logger = createLogger(`mcpc.sampling.${name}`, server2);
2299
2741
  try {
2300
2742
  const tracingConfig = {
2301
- enabled: process5.env.MCPC_TRACING_ENABLED === "true",
2743
+ enabled: process6.env.MCPC_TRACING_ENABLED === "true",
2302
2744
  serviceName: `mcpc-sampling-${name}`,
2303
- exportTo: process5.env.MCPC_TRACING_EXPORT ?? "otlp",
2304
- otlpEndpoint: process5.env.MCPC_TRACING_OTLP_ENDPOINT ?? "http://localhost:4318/v1/traces"
2745
+ exportTo: process6.env.MCPC_TRACING_EXPORT ?? "otlp",
2746
+ otlpEndpoint: process6.env.MCPC_TRACING_OTLP_ENDPOINT ?? "http://localhost:4318/v1/traces"
2305
2747
  };
2306
2748
  this.tracingEnabled = tracingConfig.enabled;
2307
2749
  if (this.tracingEnabled) {
@@ -3864,9 +4306,16 @@ var ComposableMCPServer = class extends Server {
3864
4306
  const toolNameToIdMapping = /* @__PURE__ */ new Map();
3865
4307
  const requestedToolNames = /* @__PURE__ */ new Set();
3866
4308
  const availableToolNames = /* @__PURE__ */ new Set();
4309
+ const allPlaceholderUsages = [];
3867
4310
  tagToResults.tool.forEach((tool) => {
3868
4311
  if (tool.attribs.name) {
3869
- requestedToolNames.add(sanitizePropertyKey(tool.attribs.name));
4312
+ const originalName = tool.attribs.name;
4313
+ const toolName = sanitizePropertyKey(originalName);
4314
+ if (toolName.endsWith(`_${ALL_TOOLS_PLACEHOLDER2}`) || toolName === ALL_TOOLS_PLACEHOLDER2) {
4315
+ allPlaceholderUsages.push(originalName);
4316
+ } else {
4317
+ requestedToolNames.add(toolName);
4318
+ }
3870
4319
  }
3871
4320
  });
3872
4321
  const { tools, cleanupClients } = await composeMcpDepTools(depsConfig, ({ mcpName, toolNameWithScope, toolId }) => {
@@ -3907,6 +4356,14 @@ var ComposableMCPServer = class extends Server {
3907
4356
  }
3908
4357
  availableToolNames.add(toolName);
3909
4358
  });
4359
+ if (allPlaceholderUsages.length > 0) {
4360
+ await this.logger.warning(`Found ${allPlaceholderUsages.length} __ALL__ placeholder(s) for agent "${name}":`);
4361
+ allPlaceholderUsages.forEach((usage) => {
4362
+ this.logger.warning(` \u2022 "${usage}" - consider using specific tool names`);
4363
+ });
4364
+ const available = Array.from(availableToolNames).sort().join(", ");
4365
+ await this.logger.warning(` Available tools: ${available}`);
4366
+ }
3910
4367
  const unmatchedTools = Array.from(requestedToolNames).filter((toolName) => !allTools[toolName]);
3911
4368
  if (unmatchedTools.length > 0) {
3912
4369
  await this.logger.warning(`Tool matching warnings for agent "${name}":`);
@@ -3996,12 +4453,12 @@ var ComposableMCPServer = class extends Server {
3996
4453
  };
3997
4454
 
3998
4455
  // __mcpc__cli_latest/node_modules/@jsr/mcpc__core/src/utils/common/env.js
3999
- import process6 from "node:process";
4000
- var isSCF = () => Boolean(process6.env.SCF_RUNTIME || process6.env.PROD_SCF);
4456
+ import process7 from "node:process";
4457
+ var isSCF = () => Boolean(process7.env.SCF_RUNTIME || process7.env.PROD_SCF);
4001
4458
  if (isSCF()) {
4002
4459
  console.log({
4003
4460
  isSCF: isSCF(),
4004
- SCF_RUNTIME: process6.env.SCF_RUNTIME
4461
+ SCF_RUNTIME: process7.env.SCF_RUNTIME
4005
4462
  });
4006
4463
  }
4007
4464
 
@@ -4047,14 +4504,14 @@ async function mcpc(serverConf, composeConf, setupCallback) {
4047
4504
  }
4048
4505
 
4049
4506
  // __mcpc__cli_latest/node_modules/@jsr/mcpc__core/src/plugins/large-result.js
4050
- import { mkdtemp, writeFile } from "node:fs/promises";
4051
- import { join } from "node:path";
4507
+ import { mkdtemp, writeFile as writeFile2 } from "node:fs/promises";
4508
+ import { join as join2 } from "node:path";
4052
4509
  import { tmpdir as tmpdir2 } from "node:os";
4053
4510
 
4054
4511
  // __mcpc__cli_latest/node_modules/@jsr/mcpc__core/src/plugins/search-tool.js
4055
4512
  import rg from "@mcpc-tech/ripgrep-napi";
4056
4513
  import { tmpdir } from "node:os";
4057
- import { resolve } from "node:path";
4514
+ import { resolve as resolve2 } from "node:path";
4058
4515
  import { relative } from "node:path";
4059
4516
  function createSearchPlugin(options = {}) {
4060
4517
  const maxResults = options.maxResults || 20;
@@ -4114,8 +4571,8 @@ Only search within the allowed directory: ${allowedSearchDir}`, jsonSchema({
4114
4571
  const requestedPath = args.path || allowedSearchDir;
4115
4572
  const limit = args.maxResults || maxResults;
4116
4573
  if (args.path) {
4117
- const resolvedRequested = resolve(args.path);
4118
- const resolvedAllowed = resolve(allowedSearchDir);
4574
+ const resolvedRequested = resolve2(args.path);
4575
+ const resolvedAllowed = resolve2(allowedSearchDir);
4119
4576
  const relativePath = relative(resolvedAllowed, resolvedRequested);
4120
4577
  if (relativePath && relativePath.startsWith("..")) {
4121
4578
  return {
@@ -4285,447 +4742,112 @@ function createLargeResultPlugin(options = {}) {
4285
4742
  let tempDir = options.tempDir || null;
4286
4743
  const configuredServers = /* @__PURE__ */ new Map();
4287
4744
  const searchConfig = {
4288
- maxResults: options.search?.maxResults || 15,
4289
- maxOutputSize: options.search?.maxOutputSize || 4e3,
4290
- global: true
4291
- };
4292
- return {
4293
- name: "plugin-large-result-handler",
4294
- version: "1.0.0",
4295
- dependencies: [],
4296
- configureServer: async (server2) => {
4297
- if (!configuredServers.has(server2)) {
4298
- const searchPlugin = createSearchPlugin(searchConfig);
4299
- await server2.addPlugin(searchPlugin);
4300
- configuredServers.set(server2, true);
4301
- }
4302
- },
4303
- transformTool: (tool, context2) => {
4304
- const originalExecute = tool.execute;
4305
- tool.execute = async (args) => {
4306
- try {
4307
- const result = await originalExecute(args);
4308
- const resultText = JSON.stringify(result);
4309
- if (resultText.length <= maxSize) {
4310
- return result;
4311
- }
4312
- if (!tempDir) {
4313
- tempDir = await mkdtemp(join(tmpdir2(), "mcpc-results-"));
4314
- }
4315
- const safeToolName = encodeURIComponent(context2.toolName ?? "tool");
4316
- const fileName = `${safeToolName}-${Date.now()}.txt`;
4317
- const filePath = join(tempDir, fileName);
4318
- await writeFile(filePath, resultText);
4319
- const preview = resultText.slice(0, previewSize);
4320
- const sizeKB = (resultText.length / 1024).toFixed(1);
4321
- return {
4322
- content: [
4323
- {
4324
- type: "text",
4325
- text: `**Result too large (${resultText.length} chars), saved to file**
4326
-
4327
- \u{1F4C1} **File:** ${filePath}
4328
- \u{1F4CA} **Size:** ${sizeKB} KB
4329
-
4330
- **Preview (${previewSize} chars):**
4331
- \`\`\`
4332
- ${preview}
4333
- \`\`\`
4334
-
4335
- **To read/understand the full content:**
4336
- - Use the \`search-tool-result\` tool with pattern: \`search-tool-result {"pattern": "your-search-term"}\`
4337
- - Search supports regex patterns for advanced queries`
4338
- }
4339
- ]
4340
- };
4341
- } catch (error) {
4342
- const errorMsg = error instanceof Error ? error.message : String(error);
4343
- console.error(`Large result plugin error for ${context2.toolName}: ${errorMsg}`);
4344
- throw error;
4345
- }
4346
- };
4347
- return tool;
4348
- },
4349
- dispose: () => {
4350
- configuredServers.clear();
4351
- tempDir = null;
4352
- }
4353
- };
4354
- }
4355
- var defaultLargeResultPlugin = createLargeResultPlugin({
4356
- maxSize: 8e3,
4357
- previewSize: 4e3
4358
- });
4359
-
4360
- // __mcpc__cli_latest/node_modules/@mcpc/cli/src/app.js
4361
- var createServer = async (config2) => {
4362
- const serverConfig = config2 || {
4363
- name: "large-result-plugin-example",
4364
- version: "0.1.0",
4365
- agents: [
4366
- {
4367
- name: null,
4368
- description: "",
4369
- plugins: [
4370
- createLargeResultPlugin({})
4371
- ]
4372
- }
4373
- ]
4374
- };
4375
- return await mcpc([
4376
- {
4377
- name: serverConfig.name || "mcpc-server",
4378
- version: serverConfig.version || "0.1.0"
4379
- },
4380
- {
4381
- capabilities: serverConfig?.capabilities || {
4382
- tools: {},
4383
- sampling: {},
4384
- logging: {}
4385
- }
4386
- }
4387
- ], serverConfig.agents);
4388
- };
4389
-
4390
- // __mcpc__cli_latest/node_modules/@mcpc/cli/src/config/loader.js
4391
- import { readFile } from "node:fs/promises";
4392
- import { resolve as resolve2 } from "node:path";
4393
- import process7 from "node:process";
4394
- function extractServerName(command, commandArgs) {
4395
- for (const arg of commandArgs) {
4396
- if (!arg.startsWith("-")) {
4397
- const name2 = arg.replace(/[@.,/\\:;!?#$%^&*()[\]{}]/g, "_").substring(0, 64);
4398
- if (name2) return name2;
4399
- }
4400
- }
4401
- const name = command.replace(/[@.,/\\:;!?#$%^&*()[\]{}]/g, "_").substring(0, 64);
4402
- return name || "agentic-tool";
4403
- }
4404
- function createProxyConfig(args) {
4405
- if (!args.proxyCommand || args.proxyCommand.length === 0) {
4406
- console.error("Error: --proxy requires a command after --");
4407
- console.error("Example: mcpc --proxy --transport-type stdio -- npx -y @wonderwhy-er/desktop-commander");
4408
- process7.exit(1);
4409
- }
4410
- if (!args.transportType) {
4411
- console.error("Error: --proxy requires --transport-type to be specified");
4412
- console.error("Supported types: stdio, streamable-http, sse");
4413
- console.error("Example: mcpc --proxy --transport-type stdio -- npx -y @wonderwhy-er/desktop-commander");
4414
- process7.exit(1);
4415
- }
4416
- const validTransports = [
4417
- "stdio",
4418
- "streamable-http",
4419
- "sse"
4420
- ];
4421
- if (!validTransports.includes(args.transportType)) {
4422
- console.error(`Error: Invalid transport type '${args.transportType}'`);
4423
- console.error(`Supported types: ${validTransports.join(", ")}`);
4424
- process7.exit(1);
4425
- }
4426
- const command = args.proxyCommand[0];
4427
- const commandArgs = args.proxyCommand.slice(1);
4428
- const serverName = args.name || extractServerName(command, commandArgs);
4429
- const config2 = {
4430
- name: `${serverName}-proxy`,
4431
- version: "0.1.0",
4432
- capabilities: {
4433
- tools: {},
4434
- sampling: {}
4435
- },
4436
- agents: [
4437
- {
4438
- name: serverName,
4439
- description: `Orchestrate ${serverName} MCP server tools`,
4440
- deps: {
4441
- mcpServers: {
4442
- [serverName]: {
4443
- command,
4444
- args: commandArgs,
4445
- transportType: args.transportType
4446
- }
4447
- }
4448
- },
4449
- options: {
4450
- mode: args.mode || "agentic",
4451
- refs: [
4452
- `<tool name="${serverName}.__ALL__"/>`
4453
- ]
4454
- }
4455
- }
4456
- ]
4457
- };
4458
- console.error(`Created proxy configuration for ${serverName}`);
4459
- console.error(`Transport: ${args.transportType}`);
4460
- console.error(`Command: ${command} ${commandArgs.join(" ")}`);
4461
- if (args.mode) {
4462
- console.error(`Mode: ${args.mode}`);
4463
- }
4464
- return config2;
4465
- }
4466
- function printHelp() {
4467
- console.log(`
4468
- MCPC CLI - Model Context Protocol Composer
4469
-
4470
- USAGE:
4471
- mcpc [OPTIONS]
4472
-
4473
- OPTIONS:
4474
- --help, -h Show this help message
4475
- --config <json> Inline JSON configuration string
4476
- --config-url <url> Fetch configuration from URL
4477
- --config-file <path> Load configuration from file path
4478
- --request-headers <header>, -H <header>
4479
- Add custom HTTP header for URL fetching
4480
- Format: "Key: Value" or "Key=Value"
4481
- Can be used multiple times
4482
- --mode <mode> Set execution mode for all agents
4483
- Supported modes:
4484
- - agentic: Fully autonomous agent mode (default)
4485
- - agentic_workflow: Agent workflow mode with dynamic or predefined steps
4486
- - agentic_sampling: Autonomous sampling mode for agentic execution
4487
- - agentic_workflow_sampling: Autonomous sampling mode for workflow execution
4488
- - code_execution: Code execution mode for most efficient token usage
4489
- --proxy Proxy mode: automatically configure MCPC to wrap an MCP server
4490
- Use with --transport-type to specify the transport
4491
- Example: --proxy --transport-type stdio -- npx -y @wonderwhy-er/desktop-commander
4492
- --transport-type <type> Transport type for proxy mode
4493
- Supported types: stdio, streamable-http, sse
4494
- --name <name> Custom server name for proxy mode (overrides auto-detection)
4495
-
4496
- ENVIRONMENT VARIABLES:
4497
- MCPC_CONFIG Inline JSON configuration (same as --config)
4498
- MCPC_CONFIG_URL URL to fetch config from (same as --config-url)
4499
- MCPC_CONFIG_FILE Path to config file (same as --config-file)
4500
-
4501
- EXAMPLES:
4502
- # Show help
4503
- mcpc --help
4504
-
4505
- # Proxy mode - wrap an existing MCP server (stdio)
4506
- mcpc --proxy --transport-type stdio -- npx -y @wonderwhy-er/desktop-commander
4507
-
4508
- # Proxy mode with custom server name
4509
- mcpc --proxy --transport-type stdio --name my-server -- npx shadcn@latest mcp
4510
-
4511
- # Proxy mode - wrap an MCP server (streamable-http)
4512
- mcpc --proxy --transport-type streamable-http -- https://api.example.com/mcp
4513
-
4514
- # Proxy mode - wrap an MCP server (sse)
4515
- mcpc --proxy --transport-type sse -- https://api.example.com/sse
4516
-
4517
- # Load from URL
4518
- mcpc --config-url \\
4519
- "https://raw.githubusercontent.com/mcpc-tech/mcpc/main/packages/cli/examples/configs/codex-fork.json"
4520
-
4521
- # Load from URL with custom headers
4522
- mcpc \\
4523
- --config-url "https://api.example.com/config.json" \\
4524
- -H "Authorization: Bearer token123" \\
4525
- -H "X-Custom-Header: value"
4526
-
4527
- # Load from file
4528
- mcpc --config-file ./my-config.json
4529
-
4530
- # Override execution mode for all agents
4531
- mcpc --config-file ./my-config.json --mode agentic_workflow
4532
-
4533
- # Using environment variable
4534
- export MCPC_CONFIG='[{"name":"agent","description":"..."}]'
4535
- mcpc
4745
+ maxResults: options.search?.maxResults || 15,
4746
+ maxOutputSize: options.search?.maxOutputSize || 4e3,
4747
+ global: true
4748
+ };
4749
+ return {
4750
+ name: "plugin-large-result-handler",
4751
+ version: "1.0.0",
4752
+ dependencies: [],
4753
+ configureServer: async (server2) => {
4754
+ if (!configuredServers.has(server2)) {
4755
+ const searchPlugin = createSearchPlugin(searchConfig);
4756
+ await server2.addPlugin(searchPlugin);
4757
+ configuredServers.set(server2, true);
4758
+ }
4759
+ },
4760
+ transformTool: (tool, context2) => {
4761
+ const originalExecute = tool.execute;
4762
+ tool.execute = async (args) => {
4763
+ try {
4764
+ const result = await originalExecute(args);
4765
+ const resultText = JSON.stringify(result);
4766
+ if (resultText.length <= maxSize) {
4767
+ return result;
4768
+ }
4769
+ if (!tempDir) {
4770
+ tempDir = await mkdtemp(join2(tmpdir2(), "mcpc-results-"));
4771
+ }
4772
+ const safeToolName = encodeURIComponent(context2.toolName ?? "tool");
4773
+ const fileName = `${safeToolName}-${Date.now()}.txt`;
4774
+ const filePath = join2(tempDir, fileName);
4775
+ await writeFile2(filePath, resultText);
4776
+ const preview = resultText.slice(0, previewSize);
4777
+ const sizeKB = (resultText.length / 1024).toFixed(1);
4778
+ return {
4779
+ content: [
4780
+ {
4781
+ type: "text",
4782
+ text: `**Result too large (${resultText.length} chars), saved to file**
4536
4783
 
4537
- # Use default configuration (./mcpc.config.json)
4538
- mcpc
4784
+ \u{1F4C1} **File:** ${filePath}
4785
+ \u{1F4CA} **Size:** ${sizeKB} KB
4539
4786
 
4540
- CONFIGURATION:
4541
- Configuration files support environment variable substitution using $VAR_NAME syntax.
4542
-
4543
- Priority order:
4544
- 1. --config (inline JSON)
4545
- 2. MCPC_CONFIG environment variable
4546
- 3. --config-url or MCPC_CONFIG_URL
4547
- 4. --config-file or MCPC_CONFIG_FILE
4548
- 5. ./mcpc.config.json (default)
4787
+ **Preview (${previewSize} chars):**
4788
+ \`\`\`
4789
+ ${preview}
4790
+ \`\`\`
4549
4791
 
4550
- For more information, visit: https://github.com/mcpc-tech/mcpc
4551
- `);
4552
- }
4553
- function parseArgs() {
4554
- const args = process7.argv.slice(2);
4555
- const result = {};
4556
- for (let i = 0; i < args.length; i++) {
4557
- const arg = args[i];
4558
- if (arg === "--config" && i + 1 < args.length) {
4559
- result.config = args[++i];
4560
- } else if (arg === "--config-url" && i + 1 < args.length) {
4561
- result.configUrl = args[++i];
4562
- } else if (arg === "--config-file" && i + 1 < args.length) {
4563
- result.configFile = args[++i];
4564
- } else if ((arg === "--request-headers" || arg === "-H") && i + 1 < args.length) {
4565
- const headerStr = args[++i];
4566
- const colonIdx = headerStr.indexOf(":");
4567
- const equalIdx = headerStr.indexOf("=");
4568
- const separatorIdx = colonIdx !== -1 ? equalIdx !== -1 ? Math.min(colonIdx, equalIdx) : colonIdx : equalIdx;
4569
- if (separatorIdx !== -1) {
4570
- const key = headerStr.substring(0, separatorIdx).trim();
4571
- const value = headerStr.substring(separatorIdx + 1).trim();
4572
- if (!result.requestHeaders) {
4573
- result.requestHeaders = {};
4792
+ **To read/understand the full content:**
4793
+ - Use the \`search-tool-result\` tool with pattern: \`search-tool-result {"pattern": "your-search-term"}\`
4794
+ - Search supports regex patterns for advanced queries`
4795
+ }
4796
+ ]
4797
+ };
4798
+ } catch (error) {
4799
+ const errorMsg = error instanceof Error ? error.message : String(error);
4800
+ console.error(`Large result plugin error for ${context2.toolName}: ${errorMsg}`);
4801
+ throw error;
4574
4802
  }
4575
- result.requestHeaders[key] = value;
4576
- }
4577
- } else if (arg === "--help" || arg === "-h") {
4578
- result.help = true;
4579
- } else if (arg === "--proxy") {
4580
- result.proxy = true;
4581
- } else if (arg === "--transport-type" && i + 1 < args.length) {
4582
- result.transportType = args[++i];
4583
- } else if (arg === "--mode" && i + 1 < args.length) {
4584
- result.mode = args[++i];
4585
- } else if (arg === "--name" && i + 1 < args.length) {
4586
- result.name = args[++i];
4587
- } else if (arg === "--") {
4588
- result.proxyCommand = args.slice(i + 1);
4589
- break;
4803
+ };
4804
+ return tool;
4805
+ },
4806
+ dispose: () => {
4807
+ configuredServers.clear();
4808
+ tempDir = null;
4590
4809
  }
4591
- }
4592
- return result;
4810
+ };
4593
4811
  }
4594
- async function loadConfig() {
4595
- const args = parseArgs();
4596
- if (args.help) {
4597
- printHelp();
4598
- process7.exit(0);
4599
- }
4600
- if (args.proxy) {
4601
- return createProxyConfig(args);
4602
- }
4603
- if (args.config) {
4604
- try {
4605
- const parsed = JSON.parse(args.config);
4606
- return applyModeOverride(normalizeConfig(parsed), args.mode);
4607
- } catch (error) {
4608
- console.error("Failed to parse --config argument:", error);
4609
- throw error;
4610
- }
4611
- }
4612
- if (process7.env.MCPC_CONFIG) {
4613
- try {
4614
- const parsed = JSON.parse(process7.env.MCPC_CONFIG);
4615
- return applyModeOverride(normalizeConfig(parsed), args.mode);
4616
- } catch (error) {
4617
- console.error("Failed to parse MCPC_CONFIG environment variable:", error);
4618
- throw error;
4619
- }
4620
- }
4621
- const configUrl = args.configUrl || process7.env.MCPC_CONFIG_URL;
4622
- if (configUrl) {
4623
- try {
4624
- const headers = {
4625
- "User-Agent": "MCPC-CLI/0.1.0",
4626
- ...args.requestHeaders
4627
- };
4628
- const response = await fetch(configUrl, {
4629
- headers
4630
- });
4631
- if (!response.ok) {
4632
- throw new Error(`HTTP ${response.status}: ${response.statusText}`);
4812
+ var defaultLargeResultPlugin = createLargeResultPlugin({
4813
+ maxSize: 8e3,
4814
+ previewSize: 4e3
4815
+ });
4816
+
4817
+ // __mcpc__cli_latest/node_modules/@mcpc/cli/src/app.js
4818
+ import { codeExecutionPlugin } from "@mcpc-tech/plugin-code-execution";
4819
+ var createServer = async (config2) => {
4820
+ const serverConfig = config2 || {
4821
+ name: "mcpc-server",
4822
+ version: "0.1.0",
4823
+ agents: [
4824
+ {
4825
+ name: null,
4826
+ description: "",
4827
+ plugins: [
4828
+ createLargeResultPlugin({}),
4829
+ codeExecutionPlugin()
4830
+ ],
4831
+ options: {
4832
+ mode: "code_execution"
4833
+ }
4633
4834
  }
4634
- const content = await response.text();
4635
- const parsed = JSON.parse(content);
4636
- return applyModeOverride(normalizeConfig(parsed), args.mode);
4637
- } catch (error) {
4638
- console.error(`Failed to fetch config from ${configUrl}:`, error);
4639
- throw error;
4640
- }
4641
- }
4642
- const configFile = args.configFile || process7.env.MCPC_CONFIG_FILE;
4643
- if (configFile) {
4644
- try {
4645
- const content = await readFile(configFile, "utf-8");
4646
- const parsed = JSON.parse(content);
4647
- return applyModeOverride(normalizeConfig(parsed), args.mode);
4648
- } catch (error) {
4649
- if (error.code === "ENOENT") {
4650
- console.error(`Config file not found: ${configFile}`);
4651
- throw error;
4652
- } else {
4653
- console.error(`Failed to load config from ${configFile}:`, error);
4654
- throw error;
4835
+ ]
4836
+ };
4837
+ return await mcpc([
4838
+ {
4839
+ name: serverConfig.name || "mcpc-server",
4840
+ version: serverConfig.version || "0.1.0"
4841
+ },
4842
+ {
4843
+ capabilities: serverConfig?.capabilities || {
4844
+ tools: {},
4845
+ sampling: {},
4846
+ logging: {}
4655
4847
  }
4656
4848
  }
4657
- }
4658
- const defaultConfigPath = resolve2(process7.cwd(), "mcpc.config.json");
4659
- try {
4660
- const content = await readFile(defaultConfigPath, "utf-8");
4661
- const parsed = JSON.parse(content);
4662
- return applyModeOverride(normalizeConfig(parsed), args.mode);
4663
- } catch (error) {
4664
- if (error.code === "ENOENT") {
4665
- return null;
4666
- } else {
4667
- console.error(`Failed to load config from ${defaultConfigPath}:`, error);
4668
- throw error;
4669
- }
4670
- }
4671
- }
4672
- function replaceEnvVars(str) {
4673
- return str.replace(/\$([A-Z_][A-Z0-9_]*)/g, (_match, varName) => {
4674
- return process7.env[varName] || "";
4675
- });
4676
- }
4677
- function replaceEnvVarsInConfig(obj) {
4678
- if (typeof obj === "string") {
4679
- return replaceEnvVars(obj);
4680
- }
4681
- if (Array.isArray(obj)) {
4682
- return obj.map((item) => replaceEnvVarsInConfig(item));
4683
- }
4684
- if (obj && typeof obj === "object") {
4685
- const result = {};
4686
- for (const [key, value] of Object.entries(obj)) {
4687
- result[key] = replaceEnvVarsInConfig(value);
4688
- }
4689
- return result;
4690
- }
4691
- return obj;
4692
- }
4693
- function applyModeOverride(config2, mode) {
4694
- if (!mode) return config2;
4695
- config2.agents.forEach((agent) => {
4696
- if (!agent.options) agent.options = {};
4697
- agent.options.mode = mode;
4698
- });
4699
- return config2;
4700
- }
4701
- function normalizeConfig(config2) {
4702
- config2 = replaceEnvVarsInConfig(config2);
4703
- if (Array.isArray(config2)) {
4704
- return {
4705
- name: "mcpc-server",
4706
- version: "0.1.0",
4707
- agents: normalizeAgents(config2)
4708
- };
4709
- }
4710
- if (config2 && typeof config2 === "object") {
4711
- const cfg = config2;
4712
- return {
4713
- name: cfg.name || "mcpc-server",
4714
- version: cfg.version || "0.1.0",
4715
- capabilities: cfg.capabilities,
4716
- agents: normalizeAgents(cfg.agents || [])
4717
- };
4718
- }
4719
- throw new Error("Invalid configuration format");
4720
- }
4721
- function normalizeAgents(agents) {
4722
- return agents.map((agent) => {
4723
- if (agent.deps && !agent.deps.mcpServers) {
4724
- agent.deps.mcpServers = {};
4725
- }
4726
- return agent;
4727
- });
4728
- }
4849
+ ], serverConfig.agents);
4850
+ };
4729
4851
 
4730
4852
  // __mcpc__cli_latest/node_modules/@mcpc/cli/src/bin.ts
4731
4853
  import { createCodeExecutionPlugin } from "@mcpc-tech/plugin-code-execution";