@mcp-z/cli 1.0.4 ā 1.0.5
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/dist/cjs/commands/inspect.js +9 -2
- package/dist/cjs/commands/inspect.js.map +1 -1
- package/dist/cjs/commands/search.js +9 -2
- package/dist/cjs/commands/search.js.map +1 -1
- package/dist/cjs/commands/up.js +9 -2
- package/dist/cjs/commands/up.js.map +1 -1
- package/dist/cjs/lib/find-config-path.d.cts +23 -0
- package/dist/cjs/lib/find-config-path.d.ts +23 -0
- package/dist/cjs/lib/find-config-path.js +111 -0
- package/dist/cjs/lib/find-config-path.js.map +1 -0
- package/dist/cjs/lib/resolve-server-config.js +9 -2
- package/dist/cjs/lib/resolve-server-config.js.map +1 -1
- package/dist/esm/commands/inspect.js +4 -2
- package/dist/esm/commands/inspect.js.map +1 -1
- package/dist/esm/commands/search.js +4 -2
- package/dist/esm/commands/search.js.map +1 -1
- package/dist/esm/commands/up.js +4 -2
- package/dist/esm/commands/up.js.map +1 -1
- package/dist/esm/lib/find-config-path.d.ts +23 -0
- package/dist/esm/lib/find-config-path.js +58 -0
- package/dist/esm/lib/find-config-path.js.map +1 -0
- package/dist/esm/lib/resolve-server-config.js +4 -2
- package/dist/esm/lib/resolve-server-config.js.map +1 -1
- package/package.json +1 -1
- package/dist/cjs/lib/find-config.d.cts +0 -14
- package/dist/cjs/lib/find-config.d.ts +0 -14
- package/dist/cjs/lib/find-config.js +0 -93
- package/dist/cjs/lib/find-config.js.map +0 -1
- package/dist/esm/lib/find-config.d.ts +0 -14
- package/dist/esm/lib/find-config.js +0 -42
- package/dist/esm/lib/find-config.js.map +0 -1
|
@@ -6,7 +6,7 @@
|
|
|
6
6
|
*/ import { createServerRegistry } from '@mcp-z/client';
|
|
7
7
|
import * as fs from 'fs';
|
|
8
8
|
import * as path from 'path';
|
|
9
|
-
import
|
|
9
|
+
import findConfigPath from '../lib/find-config-path.js';
|
|
10
10
|
import { isHttpServer } from '../types.js';
|
|
11
11
|
const MAX_DESCRIPTION = 100;
|
|
12
12
|
/**
|
|
@@ -29,7 +29,9 @@ const MAX_DESCRIPTION = 100;
|
|
|
29
29
|
let registry;
|
|
30
30
|
try {
|
|
31
31
|
var _ref, _raw_mcpServers;
|
|
32
|
-
const configPath = findConfigPath(
|
|
32
|
+
const configPath = findConfigPath({
|
|
33
|
+
config: opts.config
|
|
34
|
+
});
|
|
33
35
|
const raw = JSON.parse(fs.readFileSync(configPath, 'utf8'));
|
|
34
36
|
const servers = (_ref = (_raw_mcpServers = raw.mcpServers) !== null && _raw_mcpServers !== void 0 ? _raw_mcpServers : raw.servers) !== null && _ref !== void 0 ? _ref : raw;
|
|
35
37
|
const configDir = path.dirname(configPath);
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"sources":["/Users/kevin/Dev/Projects/mcp-z/cli/src/commands/inspect.ts"],"sourcesContent":["/**\n * inspect.ts\n *\n * Inspect MCP servers: explore tools, resources, prompts, and health status.\n * Supports stdio (spawned) and http (remote) servers per MCP spec.\n */\n\nimport { createServerRegistry, type PromptArgument, type ServerRegistry, type ServersConfig } from '@mcp-z/client';\nimport * as fs from 'fs';\nimport * as path from 'path';\nimport { findConfigPath } from '../lib/find-config.ts';\nimport { isHttpServer, type ServerConfig } from '../types.ts';\n\nconst MAX_DESCRIPTION = 100;\n\nexport interface InspectOptions {\n config?: string; // --config custom.json\n servers?: string; // --servers echo-server-1,echo-server-2 (comma-separated)\n tools?: boolean; // --tools\n resources?: boolean; // --resources\n prompts?: boolean; // --prompts\n health?: boolean; // --health\n json?: boolean; // --json\n verbose?: boolean; // --verbose\n attach?: boolean; // --attach (connect to running servers instead of spawning)\n}\n\ninterface ServerInfo {\n name: string;\n status: 'ready' | 'failed';\n startupTime: number | undefined;\n error: string | undefined;\n tools: ToolInfo[] | undefined;\n resources: ResourceInfo[] | undefined;\n prompts: PromptInfo[] | undefined;\n}\n\ninterface ToolInfo {\n name: string;\n description: string | undefined;\n inputSchema: unknown;\n}\n\ninterface ResourceInfo {\n uri: string;\n name: string;\n description: string | undefined;\n mimeType: string | undefined;\n}\n\ninterface PromptInfo {\n name: string;\n description: string | undefined;\n arguments: PromptArgument[] | undefined;\n}\n\n/**\n * Main inspect command implementation.\n *\n * @param opts - Inspect options from CLI flags\n *\n * @example\n * // Show summary of .mcp.json servers (spawns servers)\n * await inspectCommand({});\n *\n * @example\n * // Show all tools from echo server (spawns server)\n * await inspectCommand({ servers: 'echo', tools: true });\n *\n * @example\n * // Connect to running servers (attach mode)\n * await inspectCommand({ config: 'http-servers.json', attach: true, health: true });\n */\nexport async function inspectCommand(opts: InspectOptions = {}): Promise<void> {\n let registry: ServerRegistry | undefined;\n\n try {\n const configPath = findConfigPath(opts.config);\n const raw = JSON.parse(fs.readFileSync(configPath, 'utf8'));\n const servers = raw.mcpServers ?? raw.servers ?? raw;\n const configDir = path.dirname(configPath);\n const serverNames = Object.keys(servers || {});\n const serversToInspect = filterServers(serverNames, opts.servers);\n\n // Create registry (spawns stdio servers, registers HTTP servers)\n // In attach mode, don't spawn - just register for connection\n registry = createServerRegistry(servers, {\n cwd: configDir,\n dialects: opts.attach ? [] : ['servers', 'start'], // Empty dialects = no spawning\n });\n\n const serverInfos: ServerInfo[] = [];\n for (const serverName of serversToInspect) {\n const info = await inspectServer(serverName, servers, registry, opts);\n serverInfos.push(info);\n }\n\n // 5. Output results\n if (opts.json) {\n outputJSON(serverInfos);\n } else {\n outputPretty(serverInfos, opts);\n }\n } finally {\n // 6. Cleanup - registry.close() handles all clients and servers\n if (registry) {\n try {\n await registry.close();\n } catch (_) {\n // Ignore close errors\n }\n }\n }\n}\n\n/**\n * Filter servers based on --servers flag.\n */\nfunction filterServers(allServers: string[], serversFlag?: string): string[] {\n if (!serversFlag) {\n return allServers;\n }\n\n const requested = serversFlag.split(',').map((s) => s.trim());\n const missing = requested.filter((s) => !allServers.includes(s));\n\n if (missing.length > 0) {\n throw new Error(`Server(s) not found in config: ${missing.join(', ')}\\n\\nAvailable servers: ${allServers.join(', ')}`);\n }\n\n return requested;\n}\n\n/**\n * Inspect a single server: collect tools, resources, prompts, health.\n */\nasync function inspectServer(serverName: string, servers: ServersConfig, registry: ServerRegistry, opts: InspectOptions): Promise<ServerInfo> {\n const start = Date.now();\n\n try {\n // Connect to server via registry\n const serverConfig = servers?.[serverName];\n if (!serverConfig) {\n throw new Error(`Server ${serverName} not found in config`);\n }\n\n if (!isHttpServer(serverConfig as ServerConfig) && !serverConfig.command) {\n throw new Error(`Stdio server ${serverName} missing required \"command\" field`);\n }\n\n const client = await registry.connect(serverName);\n\n // Collect content based on flags\n const needsTools = opts.tools || shouldShowSummary(opts);\n const needsResources = opts.resources || shouldShowSummary(opts);\n const needsPrompts = opts.prompts || shouldShowSummary(opts);\n\n // Handle each capability independently - servers may not implement all methods\n const [toolsResult, resourcesResult, promptsResult] = await Promise.all([needsTools ? client.listTools().catch(() => null) : Promise.resolve(null), needsResources ? client.listResources().catch(() => null) : Promise.resolve(null), needsPrompts ? client.listPrompts().catch(() => null) : Promise.resolve(null)]);\n\n const startupTime = Date.now() - start;\n\n return {\n name: serverName,\n status: 'ready',\n startupTime,\n error: undefined,\n tools: toolsResult?.tools\n ? toolsResult.tools.map((t) => ({\n name: t.name,\n description: t.description,\n inputSchema: t.inputSchema,\n }))\n : undefined,\n resources: resourcesResult?.resources\n ? resourcesResult.resources.map((r) => ({\n uri: r.uri,\n name: r.name,\n description: r.description,\n mimeType: r.mimeType,\n }))\n : undefined,\n prompts: promptsResult?.prompts\n ? promptsResult.prompts.map((p) => ({\n name: p.name,\n description: p.description,\n arguments: p.arguments,\n }))\n : undefined,\n };\n } catch (error) {\n // Format error message with context\n let errorMessage = error instanceof Error ? error.message : String(error);\n\n // For fetch errors, dig into the cause for more details\n if (error instanceof Error && error.message === 'fetch failed' && 'cause' in error) {\n const cause = error.cause as { code?: string; message?: string } | undefined;\n if (cause?.code === 'ECONNREFUSED') {\n const serverConfig = servers?.[serverName];\n const url = serverConfig && 'url' in serverConfig ? serverConfig.url : undefined;\n errorMessage = url ? `Connection refused (server not running at ${url})` : 'Connection refused (server not running)';\n } else if (cause?.message) {\n errorMessage = `${error.message}: ${cause.message}`;\n }\n }\n\n return {\n name: serverName,\n status: 'failed',\n startupTime: undefined,\n error: errorMessage,\n tools: undefined,\n resources: undefined,\n prompts: undefined,\n };\n }\n}\n\n/**\n * Determine if we should show summary (no specific content flags).\n */\nfunction shouldShowSummary(opts: InspectOptions): boolean {\n return !opts.tools && !opts.resources && !opts.prompts && !opts.health;\n}\n\n/**\n * Truncate description to max length with ellipsis.\n */\nfunction truncateDescription(desc: string, _maxLength = MAX_DESCRIPTION): string {\n return desc;\n // if (!desc || desc.length <= maxLength) {\n // return desc;\n // }\n // return `${desc.slice(0, maxLength - 3)}...`;\n}\n\n/**\n * Render verbose details for a tool (parameters with types and descriptions)\n */\nfunction renderToolVerbose(tool: ToolInfo, indent: string): void {\n // Description is already shown inline, so skip it here\n const schema = tool.inputSchema as { properties?: Record<string, unknown>; required?: string[] } | undefined;\n if (!schema || !schema.properties) {\n return;\n }\n\n const properties = schema.properties;\n const required = schema.required || [];\n\n // Separate required and optional parameters\n const requiredParams: string[] = [];\n const optionalParams: string[] = [];\n\n for (const [name, _prop] of Object.entries(properties)) {\n if (required.includes(name)) {\n requiredParams.push(name);\n } else {\n optionalParams.push(name);\n }\n }\n\n // Show required parameters\n if (requiredParams.length > 0) {\n console.log(`${indent}Required Parameters:`);\n for (const name of requiredParams) {\n renderParameter(name, properties[name], `${indent} `);\n }\n console.log('');\n }\n\n // Show optional parameters\n if (optionalParams.length > 0) {\n console.log(`${indent}Optional Parameters:`);\n for (const name of optionalParams) {\n renderParameter(name, properties[name], `${indent} `);\n }\n console.log('');\n }\n}\n\n/**\n * Render verbose details for a resource\n */\nfunction renderResourceVerbose(resource: ResourceInfo, indent: string): void {\n // Description is already shown inline, so only show URI and MIME type\n if (resource.uri) {\n console.log(`${indent}URI: ${resource.uri}`);\n }\n if (resource.mimeType) {\n console.log(`${indent}MIME Type: ${resource.mimeType}`);\n }\n if (resource.uri || resource.mimeType) {\n console.log('');\n }\n}\n\n/**\n * Render verbose details for a prompt\n */\nfunction renderPromptVerbose(prompt: PromptInfo, indent: string): void {\n // Description is already shown inline, so only show arguments\n if (prompt.arguments && Array.isArray(prompt.arguments) && prompt.arguments.length > 0) {\n console.log(`${indent}Arguments:`);\n for (const arg of prompt.arguments) {\n const argObj = arg as { name?: string; description?: string; required?: boolean };\n const name = argObj.name || 'unknown';\n const description = argObj.description || '';\n const required = argObj.required ? ' (required)' : ' (optional)';\n const desc = description ? ` - ${description}` : '';\n console.log(`${indent} ${name}${required}${desc}`);\n }\n console.log('');\n }\n}\n\n/**\n * Render a single parameter with type and description\n */\nfunction renderParameter(name: string, prop: unknown, indent: string): void {\n const p = prop as { description?: string; enum?: unknown[] };\n const type = getParameterType(prop);\n const constraints = getParameterConstraints(prop);\n const typeInfo = constraints ? `(${type}) ${constraints}` : `(${type})`;\n const desc = p.description ? ` - ${p.description}` : '';\n\n console.log(`${indent}${name} ${typeInfo}${desc}`);\n\n // Show enum options on separate line if present\n if (p.enum && Array.isArray(p.enum)) {\n console.log(`${indent} Options: ${p.enum.join(', ')}`);\n }\n}\n\n/**\n * Get human-readable type from JSON Schema property\n */\nfunction getParameterType(prop: unknown): string {\n const p = prop as { type?: string | string[]; items?: { type?: string }; anyOf?: Array<{ type?: string }>; enum?: unknown[] };\n if (p.type) {\n if (Array.isArray(p.type)) {\n return p.type.join(' | ');\n }\n if (p.type === 'array' && p.items) {\n const itemType = p.items.type || 'any';\n return `array of ${itemType}`;\n }\n return p.type;\n }\n\n if (p.anyOf) {\n return p.anyOf.map((s) => s.type || 'any').join(' | ');\n }\n\n if (p.enum) {\n return 'enum';\n }\n\n return 'any';\n}\n\n/**\n * Get parameter constraints (default, min, max, etc.)\n */\nfunction getParameterConstraints(prop: unknown): string {\n const p = prop as {\n default?: unknown;\n minimum?: number;\n maximum?: number;\n minLength?: number;\n maxLength?: number;\n minItems?: number;\n maxItems?: number;\n };\n const constraints: string[] = [];\n\n if (p.default !== undefined) {\n const defaultValue = typeof p.default === 'string' ? `\"${p.default}\"` : String(p.default);\n constraints.push(`default: ${defaultValue}`);\n }\n\n if (p.minimum !== undefined) {\n constraints.push(`min: ${p.minimum}`);\n }\n\n if (p.maximum !== undefined) {\n constraints.push(`max: ${p.maximum}`);\n }\n\n if (p.minLength !== undefined) {\n constraints.push(`minLength: ${p.minLength}`);\n }\n\n if (p.maxLength !== undefined) {\n constraints.push(`maxLength: ${p.maxLength}`);\n }\n\n if (p.minItems !== undefined) {\n constraints.push(`minItems: ${p.minItems}`);\n }\n\n if (p.maxItems !== undefined) {\n constraints.push(`maxItems: ${p.maxItems}`);\n }\n\n return constraints.length > 0 ? `[${constraints.join(', ')}]` : '';\n}\n\n/**\n * Output results as JSON.\n */\nfunction outputJSON(serverInfos: ServerInfo[]): void {\n const output = {\n servers: serverInfos.reduce(\n (acc, info) => {\n acc[info.name] = {\n status: info.status,\n startupTime: info.startupTime ? `${(info.startupTime / 1000).toFixed(1)}s` : undefined,\n error: info.error,\n tools: info.tools,\n resources: info.resources,\n prompts: info.prompts,\n };\n return acc;\n },\n {} as Record<string, unknown>\n ),\n };\n\n console.log(JSON.stringify(output, null, 2));\n}\n\n/**\n * Output results in human-readable format.\n */\nfunction outputPretty(serverInfos: ServerInfo[], opts: InspectOptions): void {\n const showSummary = shouldShowSummary(opts);\n\n for (const info of serverInfos) {\n // Summary mode\n if (showSummary) {\n if (info.status === 'ready') {\n const toolCount = info.tools?.length || 0;\n const resourceCount = info.resources?.length || 0;\n const promptCount = info.prompts?.length || 0;\n const time = info.startupTime ? `(${(info.startupTime / 1000).toFixed(1)}s)` : '';\n console.log(`š¦ ${info.name}: ${time}`);\n\n // Show detailed list of tools\n console.log(`tools: ${toolCount}`);\n if (info.tools && info.tools.length > 0) {\n for (let i = 0; i < info.tools.length; i++) {\n const tool = info.tools[i];\n if (!tool) continue; // Array indexing can return undefined with noUncheckedIndexedAccess\n const desc = tool.description ? ` - ${opts.verbose ? tool.description : truncateDescription(tool.description)}` : '';\n console.log(`${i + 1}. ${tool.name}${desc}`);\n if (opts.verbose) {\n renderToolVerbose(tool, ' ');\n }\n }\n }\n\n // Show detailed list of resources\n console.log(`resources: ${resourceCount}`);\n if (info.resources && info.resources.length > 0) {\n for (let i = 0; i < info.resources.length; i++) {\n const resource = info.resources[i];\n if (!resource) continue; // Array indexing can return undefined with noUncheckedIndexedAccess\n const desc = resource.description ? ` - ${opts.verbose ? resource.description : truncateDescription(resource.description)}` : '';\n console.log(`${i + 1}. ${resource.name}${desc}`);\n if (opts.verbose) {\n renderResourceVerbose(resource, ' ');\n }\n }\n }\n\n // Show detailed list of prompts\n console.log(`prompts: ${promptCount}`);\n if (info.prompts && info.prompts.length > 0) {\n for (let i = 0; i < info.prompts.length; i++) {\n const prompt = info.prompts[i];\n if (!prompt) continue; // Array indexing can return undefined with noUncheckedIndexedAccess\n const desc = prompt.description ? ` - ${opts.verbose ? prompt.description : truncateDescription(prompt.description)}` : '';\n console.log(`${i + 1}. ${prompt.name}${desc}`);\n if (opts.verbose) {\n renderPromptVerbose(prompt, ' ');\n }\n }\n }\n } else {\n console.log(`š¦ ${info.name}: ā failed - ${info.error}`);\n }\n continue;\n }\n\n // Health mode\n if (opts.health) {\n if (info.status === 'ready') {\n const time = info.startupTime ? `(${(info.startupTime / 1000).toFixed(1)}s)` : '';\n console.log(`ā ${info.name} - ready ${time}`);\n } else {\n console.log(`ā ${info.name} - failed`);\n console.log(` Error: ${info.error}`);\n }\n continue;\n }\n\n // Tools mode\n if (opts.tools) {\n console.log(`\\nš¦ ${info.name} (${info.tools?.length || 0} tools)`);\n if (info.tools && info.tools.length > 0) {\n for (let i = 0; i < info.tools.length; i++) {\n const tool = info.tools[i];\n if (!tool) continue; // Array indexing can return undefined with noUncheckedIndexedAccess\n const desc = tool.description ? ` - ${opts.verbose ? tool.description : truncateDescription(tool.description)}` : '';\n console.log(` ${i + 1}. ${tool.name}${desc}`);\n if (opts.verbose) {\n renderToolVerbose(tool, ' ');\n }\n }\n }\n }\n\n // Resources mode\n if (opts.resources) {\n console.log(`\\nš¦ ${info.name} (${info.resources?.length || 0} resources)`);\n if (info.resources && info.resources.length > 0) {\n for (let i = 0; i < info.resources.length; i++) {\n const resource = info.resources[i];\n if (!resource) continue; // Array indexing can return undefined with noUncheckedIndexedAccess\n const desc = resource.description ? ` - ${opts.verbose ? resource.description : truncateDescription(resource.description)}` : '';\n console.log(` ${i + 1}. ${resource.name}${desc}`);\n if (opts.verbose) {\n renderResourceVerbose(resource, ' ');\n }\n }\n }\n }\n\n // Prompts mode\n if (opts.prompts) {\n console.log(`\\nš¦ ${info.name} (${info.prompts?.length || 0} prompts)`);\n if (info.prompts && info.prompts.length > 0) {\n for (let i = 0; i < info.prompts.length; i++) {\n const prompt = info.prompts[i];\n if (!prompt) continue; // Array indexing can return undefined with noUncheckedIndexedAccess\n const desc = prompt.description ? ` - ${opts.verbose ? prompt.description : truncateDescription(prompt.description)}` : '';\n console.log(` ${i + 1}. ${prompt.name}${desc}`);\n if (opts.verbose) {\n renderPromptVerbose(prompt, ' ');\n }\n }\n }\n }\n }\n\n console.log('');\n}\n"],"names":["createServerRegistry","fs","path","findConfigPath","isHttpServer","MAX_DESCRIPTION","inspectCommand","opts","registry","raw","configPath","config","JSON","parse","readFileSync","servers","mcpServers","configDir","dirname","serverNames","Object","keys","serversToInspect","filterServers","cwd","dialects","attach","serverInfos","serverName","info","inspectServer","push","json","outputJSON","outputPretty","close","_","allServers","serversFlag","requested","split","map","s","trim","missing","filter","includes","length","Error","join","start","Date","now","serverConfig","command","client","connect","needsTools","tools","shouldShowSummary","needsResources","resources","needsPrompts","prompts","toolsResult","resourcesResult","promptsResult","Promise","all","listTools","catch","resolve","listResources","listPrompts","startupTime","name","status","error","undefined","t","description","inputSchema","r","uri","mimeType","p","arguments","errorMessage","message","String","cause","code","url","health","truncateDescription","desc","_maxLength","renderToolVerbose","tool","indent","schema","properties","required","requiredParams","optionalParams","_prop","entries","console","log","renderParameter","renderResourceVerbose","resource","renderPromptVerbose","prompt","Array","isArray","arg","argObj","prop","type","getParameterType","constraints","getParameterConstraints","typeInfo","enum","items","itemType","anyOf","default","defaultValue","minimum","maximum","minLength","maxLength","minItems","maxItems","output","reduce","acc","toFixed","stringify","showSummary","toolCount","resourceCount","promptCount","time","i","verbose"],"mappings":"AAAA;;;;;CAKC,GAED,SAASA,oBAAoB,QAAsE,gBAAgB;AACnH,YAAYC,QAAQ,KAAK;AACzB,YAAYC,UAAU,OAAO;AAC7B,SAASC,cAAc,QAAQ,wBAAwB;AACvD,SAASC,YAAY,QAA2B,cAAc;AAE9D,MAAMC,kBAAkB;AA2CxB;;;;;;;;;;;;;;;;CAgBC,GACD,OAAO,eAAeC,eAAeC,OAAuB,CAAC,CAAC;IAC5D,IAAIC;IAEJ,IAAI;YAGcC,MAAAA;QAFhB,MAAMC,aAAaP,eAAeI,KAAKI,MAAM;QAC7C,MAAMF,MAAMG,KAAKC,KAAK,CAACZ,GAAGa,YAAY,CAACJ,YAAY;QACnD,MAAMK,WAAUN,QAAAA,kBAAAA,IAAIO,UAAU,cAAdP,6BAAAA,kBAAkBA,IAAIM,OAAO,cAA7BN,kBAAAA,OAAiCA;QACjD,MAAMQ,YAAYf,KAAKgB,OAAO,CAACR;QAC/B,MAAMS,cAAcC,OAAOC,IAAI,CAACN,WAAW,CAAC;QAC5C,MAAMO,mBAAmBC,cAAcJ,aAAaZ,KAAKQ,OAAO;QAEhE,iEAAiE;QACjE,6DAA6D;QAC7DP,WAAWR,qBAAqBe,SAAS;YACvCS,KAAKP;YACLQ,UAAUlB,KAAKmB,MAAM,GAAG,EAAE,GAAG;gBAAC;gBAAW;aAAQ;QACnD;QAEA,MAAMC,cAA4B,EAAE;QACpC,KAAK,MAAMC,cAAcN,iBAAkB;YACzC,MAAMO,OAAO,MAAMC,cAAcF,YAAYb,SAAS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rC,sBAAsBC,UAAU;oBAClC;gBACF;YACF;QACF;QAEA,eAAe;QACf,IAAIxG,KAAKwD,OAAO,EAAE;gBACkBlC;YAAlC8E,QAAQC,GAAG,CAAC,CAAC,KAAK,EAAE/E,KAAK8C,IAAI,CAAC,EAAE,EAAE9C,EAAAA,iBAAAA,KAAKkC,OAAO,cAAZlC,qCAAAA,eAAckB,MAAM,KAAI,EAAE,SAAS,CAAC;YACtE,IAAIlB,KAAKkC,OAAO,IAAIlC,KAAKkC,OAAO,CAAChB,MAAM,GAAG,GAAG;gBAC3C,IAAK,IAAImG,IAAI,GAAGA,IAAIrH,KAAKkC,OAAO,CAAChB,MAAM,EAAEmG,IAAK;oBAC5C,MAAMjC,SAASpF,KAAKkC,OAAO,CAACmF,EAAE;oBAC9B,IAAI,CAACjC,QAAQ,UAAU,oEAAoE;oBAC3F,MAAMlB,OAAOkB,OAAOjC,WAAW,GAAG,CAAC,GAAG,EAAEzE,KAAK4I,OAAO,GAAGlC,OAAOjC,WAAW,GAAGc,oBAAoBmB,OAAOjC,WAAW,GAAG,GAAG;oBACxH2B,QAAQC,GAAG,CAAC,CAAC,EAAE,EAAEsC,IAAI,EAAE,EAAE,EAAEjC,OAAOtC,IAAI,GAAGoB,MAAM;oBAC/C,IAAIxF,KAAK4I,OAAO,EAAE;wBAChBnC,oBAAoBC,QAAQ;oBAC9B;gBACF;YACF;QACF;IACF;IAEAN,QAAQC,GAAG,CAAC;AACd"}
|
|
1
|
+
{"version":3,"sources":["/Users/kevin/Dev/Projects/mcp-z/cli/src/commands/inspect.ts"],"sourcesContent":["/**\n * inspect.ts\n *\n * Inspect MCP servers: explore tools, resources, prompts, and health status.\n * Supports stdio (spawned) and http (remote) servers per MCP spec.\n */\n\nimport { createServerRegistry, type PromptArgument, type ServerRegistry, type ServersConfig } from '@mcp-z/client';\nimport * as fs from 'fs';\nimport * as path from 'path';\nimport findConfigPath from '../lib/find-config-path.ts';\nimport { isHttpServer, type ServerConfig } from '../types.ts';\n\nconst MAX_DESCRIPTION = 100;\n\nexport interface InspectOptions {\n config?: string; // --config custom.json\n servers?: string; // --servers echo-server-1,echo-server-2 (comma-separated)\n tools?: boolean; // --tools\n resources?: boolean; // --resources\n prompts?: boolean; // --prompts\n health?: boolean; // --health\n json?: boolean; // --json\n verbose?: boolean; // --verbose\n attach?: boolean; // --attach (connect to running servers instead of spawning)\n}\n\ninterface ServerInfo {\n name: string;\n status: 'ready' | 'failed';\n startupTime: number | undefined;\n error: string | undefined;\n tools: ToolInfo[] | undefined;\n resources: ResourceInfo[] | undefined;\n prompts: PromptInfo[] | undefined;\n}\n\ninterface ToolInfo {\n name: string;\n description: string | undefined;\n inputSchema: unknown;\n}\n\ninterface ResourceInfo {\n uri: string;\n name: string;\n description: string | undefined;\n mimeType: string | undefined;\n}\n\ninterface PromptInfo {\n name: string;\n description: string | undefined;\n arguments: PromptArgument[] | undefined;\n}\n\n/**\n * Main inspect command implementation.\n *\n * @param opts - Inspect options from CLI flags\n *\n * @example\n * // Show summary of .mcp.json servers (spawns servers)\n * await inspectCommand({});\n *\n * @example\n * // Show all tools from echo server (spawns server)\n * await inspectCommand({ servers: 'echo', tools: true });\n *\n * @example\n * // Connect to running servers (attach mode)\n * await inspectCommand({ config: 'http-servers.json', attach: true, health: true });\n */\nexport async function inspectCommand(opts: InspectOptions = {}): Promise<void> {\n let registry: ServerRegistry | undefined;\n\n try {\n const configPath = findConfigPath({ config: opts.config });\n const raw = JSON.parse(fs.readFileSync(configPath, 'utf8'));\n const servers = raw.mcpServers ?? raw.servers ?? raw;\n const configDir = path.dirname(configPath);\n const serverNames = Object.keys(servers || {});\n const serversToInspect = filterServers(serverNames, opts.servers);\n\n // Create registry (spawns stdio servers, registers HTTP servers)\n // In attach mode, don't spawn - just register for connection\n registry = createServerRegistry(servers, {\n cwd: configDir,\n dialects: opts.attach ? [] : ['servers', 'start'], // Empty dialects = no spawning\n });\n\n const serverInfos: ServerInfo[] = [];\n for (const serverName of serversToInspect) {\n const info = await inspectServer(serverName, servers, registry, opts);\n serverInfos.push(info);\n }\n\n // 5. Output results\n if (opts.json) {\n outputJSON(serverInfos);\n } else {\n outputPretty(serverInfos, opts);\n }\n } finally {\n // 6. Cleanup - registry.close() handles all clients and servers\n if (registry) {\n try {\n await registry.close();\n } catch (_) {\n // Ignore close errors\n }\n }\n }\n}\n\n/**\n * Filter servers based on --servers flag.\n */\nfunction filterServers(allServers: string[], serversFlag?: string): string[] {\n if (!serversFlag) {\n return allServers;\n }\n\n const requested = serversFlag.split(',').map((s) => s.trim());\n const missing = requested.filter((s) => !allServers.includes(s));\n\n if (missing.length > 0) {\n throw new Error(`Server(s) not found in config: ${missing.join(', ')}\\n\\nAvailable servers: ${allServers.join(', ')}`);\n }\n\n return requested;\n}\n\n/**\n * Inspect a single server: collect tools, resources, prompts, health.\n */\nasync function inspectServer(serverName: string, servers: ServersConfig, registry: ServerRegistry, opts: InspectOptions): Promise<ServerInfo> {\n const start = Date.now();\n\n try {\n // Connect to server via registry\n const serverConfig = servers?.[serverName];\n if (!serverConfig) {\n throw new Error(`Server ${serverName} not found in config`);\n }\n\n if (!isHttpServer(serverConfig as ServerConfig) && !serverConfig.command) {\n throw new Error(`Stdio server ${serverName} missing required \"command\" field`);\n }\n\n const client = await registry.connect(serverName);\n\n // Collect content based on flags\n const needsTools = opts.tools || shouldShowSummary(opts);\n const needsResources = opts.resources || shouldShowSummary(opts);\n const needsPrompts = opts.prompts || shouldShowSummary(opts);\n\n // Handle each capability independently - servers may not implement all methods\n const [toolsResult, resourcesResult, promptsResult] = await Promise.all([needsTools ? client.listTools().catch(() => null) : Promise.resolve(null), needsResources ? client.listResources().catch(() => null) : Promise.resolve(null), needsPrompts ? client.listPrompts().catch(() => null) : Promise.resolve(null)]);\n\n const startupTime = Date.now() - start;\n\n return {\n name: serverName,\n status: 'ready',\n startupTime,\n error: undefined,\n tools: toolsResult?.tools\n ? toolsResult.tools.map((t) => ({\n name: t.name,\n description: t.description,\n inputSchema: t.inputSchema,\n }))\n : undefined,\n resources: resourcesResult?.resources\n ? resourcesResult.resources.map((r) => ({\n uri: r.uri,\n name: r.name,\n description: r.description,\n mimeType: r.mimeType,\n }))\n : undefined,\n prompts: promptsResult?.prompts\n ? promptsResult.prompts.map((p) => ({\n name: p.name,\n description: p.description,\n arguments: p.arguments,\n }))\n : undefined,\n };\n } catch (error) {\n // Format error message with context\n let errorMessage = error instanceof Error ? error.message : String(error);\n\n // For fetch errors, dig into the cause for more details\n if (error instanceof Error && error.message === 'fetch failed' && 'cause' in error) {\n const cause = error.cause as { code?: string; message?: string } | undefined;\n if (cause?.code === 'ECONNREFUSED') {\n const serverConfig = servers?.[serverName];\n const url = serverConfig && 'url' in serverConfig ? serverConfig.url : undefined;\n errorMessage = url ? `Connection refused (server not running at ${url})` : 'Connection refused (server not running)';\n } else if (cause?.message) {\n errorMessage = `${error.message}: ${cause.message}`;\n }\n }\n\n return {\n name: serverName,\n status: 'failed',\n startupTime: undefined,\n error: errorMessage,\n tools: undefined,\n resources: undefined,\n prompts: undefined,\n };\n }\n}\n\n/**\n * Determine if we should show summary (no specific content flags).\n */\nfunction shouldShowSummary(opts: InspectOptions): boolean {\n return !opts.tools && !opts.resources && !opts.prompts && !opts.health;\n}\n\n/**\n * Truncate description to max length with ellipsis.\n */\nfunction truncateDescription(desc: string, _maxLength = MAX_DESCRIPTION): string {\n return desc;\n // if (!desc || desc.length <= maxLength) {\n // return desc;\n // }\n // return `${desc.slice(0, maxLength - 3)}...`;\n}\n\n/**\n * Render verbose details for a tool (parameters with types and descriptions)\n */\nfunction renderToolVerbose(tool: ToolInfo, indent: string): void {\n // Description is already shown inline, so skip it here\n const schema = tool.inputSchema as { properties?: Record<string, unknown>; required?: string[] } | undefined;\n if (!schema || !schema.properties) {\n return;\n }\n\n const properties = schema.properties;\n const required = schema.required || [];\n\n // Separate required and optional parameters\n const requiredParams: string[] = [];\n const optionalParams: string[] = [];\n\n for (const [name, _prop] of Object.entries(properties)) {\n if (required.includes(name)) {\n requiredParams.push(name);\n } else {\n optionalParams.push(name);\n }\n }\n\n // Show required parameters\n if (requiredParams.length > 0) {\n console.log(`${indent}Required Parameters:`);\n for (const name of requiredParams) {\n renderParameter(name, properties[name], `${indent} `);\n }\n console.log('');\n }\n\n // Show optional parameters\n if (optionalParams.length > 0) {\n console.log(`${indent}Optional Parameters:`);\n for (const name of optionalParams) {\n renderParameter(name, properties[name], `${indent} `);\n }\n console.log('');\n }\n}\n\n/**\n * Render verbose details for a resource\n */\nfunction renderResourceVerbose(resource: ResourceInfo, indent: string): void {\n // Description is already shown inline, so only show URI and MIME type\n if (resource.uri) {\n console.log(`${indent}URI: ${resource.uri}`);\n }\n if (resource.mimeType) {\n console.log(`${indent}MIME Type: ${resource.mimeType}`);\n }\n if (resource.uri || resource.mimeType) {\n console.log('');\n }\n}\n\n/**\n * Render verbose details for a prompt\n */\nfunction renderPromptVerbose(prompt: PromptInfo, indent: string): void {\n // Description is already shown inline, so only show arguments\n if (prompt.arguments && Array.isArray(prompt.arguments) && prompt.arguments.length > 0) {\n console.log(`${indent}Arguments:`);\n for (const arg of prompt.arguments) {\n const argObj = arg as { name?: string; description?: string; required?: boolean };\n const name = argObj.name || 'unknown';\n const description = argObj.description || '';\n const required = argObj.required ? ' (required)' : ' (optional)';\n const desc = description ? ` - ${description}` : '';\n console.log(`${indent} ${name}${required}${desc}`);\n }\n console.log('');\n }\n}\n\n/**\n * Render a single parameter with type and description\n */\nfunction renderParameter(name: string, prop: unknown, indent: string): void {\n const p = prop as { description?: string; enum?: unknown[] };\n const type = getParameterType(prop);\n const constraints = getParameterConstraints(prop);\n const typeInfo = constraints ? `(${type}) ${constraints}` : `(${type})`;\n const desc = p.description ? ` - ${p.description}` : '';\n\n console.log(`${indent}${name} ${typeInfo}${desc}`);\n\n // Show enum options on separate line if present\n if (p.enum && Array.isArray(p.enum)) {\n console.log(`${indent} Options: ${p.enum.join(', ')}`);\n }\n}\n\n/**\n * Get human-readable type from JSON Schema property\n */\nfunction getParameterType(prop: unknown): string {\n const p = prop as { type?: string | string[]; items?: { type?: string }; anyOf?: Array<{ type?: string }>; enum?: unknown[] };\n if (p.type) {\n if (Array.isArray(p.type)) {\n return p.type.join(' | ');\n }\n if (p.type === 'array' && p.items) {\n const itemType = p.items.type || 'any';\n return `array of ${itemType}`;\n }\n return p.type;\n }\n\n if (p.anyOf) {\n return p.anyOf.map((s) => s.type || 'any').join(' | ');\n }\n\n if (p.enum) {\n return 'enum';\n }\n\n return 'any';\n}\n\n/**\n * Get parameter constraints (default, min, max, etc.)\n */\nfunction getParameterConstraints(prop: unknown): string {\n const p = prop as {\n default?: unknown;\n minimum?: number;\n maximum?: number;\n minLength?: number;\n maxLength?: number;\n minItems?: number;\n maxItems?: number;\n };\n const constraints: string[] = [];\n\n if (p.default !== undefined) {\n const defaultValue = typeof p.default === 'string' ? `\"${p.default}\"` : String(p.default);\n constraints.push(`default: ${defaultValue}`);\n }\n\n if (p.minimum !== undefined) {\n constraints.push(`min: ${p.minimum}`);\n }\n\n if (p.maximum !== undefined) {\n constraints.push(`max: ${p.maximum}`);\n }\n\n if (p.minLength !== undefined) {\n constraints.push(`minLength: ${p.minLength}`);\n }\n\n if (p.maxLength !== undefined) {\n constraints.push(`maxLength: ${p.maxLength}`);\n }\n\n if (p.minItems !== undefined) {\n constraints.push(`minItems: ${p.minItems}`);\n }\n\n if (p.maxItems !== undefined) {\n constraints.push(`maxItems: ${p.maxItems}`);\n }\n\n return constraints.length > 0 ? `[${constraints.join(', ')}]` : '';\n}\n\n/**\n * Output results as JSON.\n */\nfunction outputJSON(serverInfos: ServerInfo[]): void {\n const output = {\n servers: serverInfos.reduce(\n (acc, info) => {\n acc[info.name] = {\n status: info.status,\n startupTime: info.startupTime ? `${(info.startupTime / 1000).toFixed(1)}s` : undefined,\n error: info.error,\n tools: info.tools,\n resources: info.resources,\n prompts: info.prompts,\n };\n return acc;\n },\n {} as Record<string, unknown>\n ),\n };\n\n console.log(JSON.stringify(output, null, 2));\n}\n\n/**\n * Output results in human-readable format.\n */\nfunction outputPretty(serverInfos: ServerInfo[], opts: InspectOptions): void {\n const showSummary = shouldShowSummary(opts);\n\n for (const info of serverInfos) {\n // Summary mode\n if (showSummary) {\n if (info.status === 'ready') {\n const toolCount = info.tools?.length || 0;\n const resourceCount = info.resources?.length || 0;\n const promptCount = info.prompts?.length || 0;\n const time = info.startupTime ? `(${(info.startupTime / 1000).toFixed(1)}s)` : '';\n console.log(`š¦ ${info.name}: ${time}`);\n\n // Show detailed list of tools\n console.log(`tools: ${toolCount}`);\n if (info.tools && info.tools.length > 0) {\n for (let i = 0; i < info.tools.length; i++) {\n const tool = info.tools[i];\n if (!tool) continue; // Array indexing can return undefined with noUncheckedIndexedAccess\n const desc = tool.description ? ` - ${opts.verbose ? tool.description : truncateDescription(tool.description)}` : '';\n console.log(`${i + 1}. ${tool.name}${desc}`);\n if (opts.verbose) {\n renderToolVerbose(tool, ' ');\n }\n }\n }\n\n // Show detailed list of resources\n console.log(`resources: ${resourceCount}`);\n if (info.resources && info.resources.length > 0) {\n for (let i = 0; i < info.resources.length; i++) {\n const resource = info.resources[i];\n if (!resource) continue; // Array indexing can return undefined with noUncheckedIndexedAccess\n const desc = resource.description ? ` - ${opts.verbose ? resource.description : truncateDescription(resource.description)}` : '';\n console.log(`${i + 1}. ${resource.name}${desc}`);\n if (opts.verbose) {\n renderResourceVerbose(resource, ' ');\n }\n }\n }\n\n // Show detailed list of prompts\n console.log(`prompts: ${promptCount}`);\n if (info.prompts && info.prompts.length > 0) {\n for (let i = 0; i < info.prompts.length; i++) {\n const prompt = info.prompts[i];\n if (!prompt) continue; // Array indexing can return undefined with noUncheckedIndexedAccess\n const desc = prompt.description ? ` - ${opts.verbose ? prompt.description : truncateDescription(prompt.description)}` : '';\n console.log(`${i + 1}. ${prompt.name}${desc}`);\n if (opts.verbose) {\n renderPromptVerbose(prompt, ' ');\n }\n }\n }\n } else {\n console.log(`š¦ ${info.name}: ā failed - ${info.error}`);\n }\n continue;\n }\n\n // Health mode\n if (opts.health) {\n if (info.status === 'ready') {\n const time = info.startupTime ? `(${(info.startupTime / 1000).toFixed(1)}s)` : '';\n console.log(`ā ${info.name} - ready ${time}`);\n } else {\n console.log(`ā ${info.name} - failed`);\n console.log(` Error: ${info.error}`);\n }\n continue;\n }\n\n // Tools mode\n if (opts.tools) {\n console.log(`\\nš¦ ${info.name} (${info.tools?.length || 0} tools)`);\n if (info.tools && info.tools.length > 0) {\n for (let i = 0; i < info.tools.length; i++) {\n const tool = info.tools[i];\n if (!tool) continue; // Array indexing can return undefined with noUncheckedIndexedAccess\n const desc = tool.description ? ` - ${opts.verbose ? tool.description : truncateDescription(tool.description)}` : '';\n console.log(` ${i + 1}. ${tool.name}${desc}`);\n if (opts.verbose) {\n renderToolVerbose(tool, ' ');\n }\n }\n }\n }\n\n // Resources mode\n if (opts.resources) {\n console.log(`\\nš¦ ${info.name} (${info.resources?.length || 0} resources)`);\n if (info.resources && info.resources.length > 0) {\n for (let i = 0; i < info.resources.length; i++) {\n const resource = info.resources[i];\n if (!resource) continue; // Array indexing can return undefined with noUncheckedIndexedAccess\n const desc = resource.description ? ` - ${opts.verbose ? resource.description : truncateDescription(resource.description)}` : '';\n console.log(` ${i + 1}. ${resource.name}${desc}`);\n if (opts.verbose) {\n renderResourceVerbose(resource, ' ');\n }\n }\n }\n }\n\n // Prompts mode\n if (opts.prompts) {\n console.log(`\\nš¦ ${info.name} (${info.prompts?.length || 0} prompts)`);\n if (info.prompts && info.prompts.length > 0) {\n for (let i = 0; i < info.prompts.length; i++) {\n const prompt = info.prompts[i];\n if (!prompt) continue; // Array indexing can return undefined with noUncheckedIndexedAccess\n const desc = prompt.description ? ` - ${opts.verbose ? prompt.description : truncateDescription(prompt.description)}` : '';\n console.log(` ${i + 1}. ${prompt.name}${desc}`);\n if (opts.verbose) {\n renderPromptVerbose(prompt, ' ');\n }\n }\n }\n }\n }\n\n console.log('');\n}\n"],"names":["createServerRegistry","fs","path","findConfigPath","isHttpServer","MAX_DESCRIPTION","inspectCommand","opts","registry","raw","configPath","config","JSON","parse","readFileSync","servers","mcpServers","configDir","dirname","serverNames","Object","keys","serversToInspect","filterServers","cwd","dialects","attach","serverInfos","serverName","info","inspectServer","push","json","outputJSON","outputPretty","close","_","allServers","serversFlag","requested","split","map","s","trim","missing","filter","includes","length","Error","join","start","Date","now","serverConfig","command","client","connect","needsTools","tools","shouldShowSummary","needsResources","resources","needsPrompts","prompts","toolsResult","resourcesResult","promptsResult","Promise","all","listTools","catch","resolve","listResources","listPrompts","startupTime","name","status","error","undefined","t","description","inputSchema","r","uri","mimeType","p","arguments","errorMessage","message","String","cause","code","url","health","truncateDescription","desc","_maxLength","renderToolVerbose","tool","indent","schema","properties","required","requiredParams","optionalParams","_prop","entries","console","log","renderParameter","renderResourceVerbose","resource","renderPromptVerbose","prompt","Array","isArray","arg","argObj","prop","type","getParameterType","constraints","getParameterConstraints","typeInfo","enum","items","itemType","anyOf","default","defaultValue","minimum","maximum","minLength","maxLength","minItems","maxItems","output","reduce","acc","toFixed","stringify","showSummary","toolCount","resourceCount","promptCount","time","i","verbose"],"mappings":"AAAA;;;;;CAKC,GAED,SAASA,oBAAoB,QAAsE,gBAAgB;AACnH,YAAYC,QAAQ,KAAK;AACzB,YAAYC,UAAU,OAAO;AAC7B,OAAOC,oBAAoB,6BAA6B;AACxD,SAASC,YAAY,QAA2B,cAAc;AAE9D,MAAMC,kBAAkB;AA2CxB;;;;;;;;;;;;;;;;CAgBC,GACD,OAAO,eAAeC,eAAeC,OAAuB,CAAC,CAAC;IAC5D,IAAIC;IAEJ,IAAI;YAGcC,MAAAA;QAFhB,MAAMC,aAAaP,eAAe;YAAEQ,QAAQJ,KAAKI,MAAM;QAAC;QACxD,MAAMF,MAAMG,KAAKC,KAAK,CAACZ,GAAGa,YAAY,CAACJ,YAAY;QACnD,MAAMK,WAAUN,QAAAA,kBAAAA,IAAIO,UAAU,cAAdP,6BAAAA,kBAAkBA,IAAIM,OAAO,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I,OAAO,EAAE;wBAChBnC,oBAAoBC,QAAQ;oBAC9B;gBACF;YACF;QACF;IACF;IAEAN,QAAQC,GAAG,CAAC;AACd"}
|
|
@@ -6,7 +6,7 @@
|
|
|
6
6
|
*/ import { createServerRegistry } from '@mcp-z/client';
|
|
7
7
|
import * as fs from 'fs';
|
|
8
8
|
import * as path from 'path';
|
|
9
|
-
import
|
|
9
|
+
import findConfigPath from '../lib/find-config-path.js';
|
|
10
10
|
/**
|
|
11
11
|
* Main search command implementation.
|
|
12
12
|
*
|
|
@@ -24,7 +24,9 @@ import { findConfigPath } from '../lib/find-config.js';
|
|
|
24
24
|
let registry;
|
|
25
25
|
try {
|
|
26
26
|
var _ref, _raw_mcpServers, _opts_limit, _opts_threshold, _searchOptions_servers;
|
|
27
|
-
const configPath = findConfigPath(
|
|
27
|
+
const configPath = findConfigPath({
|
|
28
|
+
config: opts.config
|
|
29
|
+
});
|
|
28
30
|
const raw = JSON.parse(fs.readFileSync(configPath, 'utf8'));
|
|
29
31
|
const servers = (_ref = (_raw_mcpServers = raw.mcpServers) !== null && _raw_mcpServers !== void 0 ? _raw_mcpServers : raw.servers) !== null && _ref !== void 0 ? _ref : raw;
|
|
30
32
|
const configDir = path.dirname(configPath);
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"sources":["/Users/kevin/Dev/Projects/mcp-z/cli/src/commands/search.ts"],"sourcesContent":["/**\n * search.ts\n *\n * Search MCP server capabilities (tools, prompts, resources) without loading full schemas.\n * Designed for agent discovery workflows.\n */\n\nimport { type CapabilityType, createServerRegistry, type SearchField, type SearchOptions, type SearchResponse, type ServerRegistry } from '@mcp-z/client';\nimport * as fs from 'fs';\nimport * as path from 'path';\nimport { findConfigPath } from '../lib/find-config.ts';\n\nexport interface SearchCommandOptions {\n config?: string;\n servers?: string;\n types?: string;\n fields?: string;\n limit?: number;\n threshold?: number;\n json?: boolean;\n attach?: boolean;\n}\n\n/**\n * Main search command implementation.\n *\n * @param query - The search query string\n * @param opts - Search options from CLI flags\n *\n * @example\n * // Search for email-related capabilities\n * await searchCommand('send email', {});\n *\n * @example\n * // Search only tools in specific servers\n * await searchCommand('spreadsheet', { types: 'tool', servers: 'sheets,drive' });\n */\nexport async function searchCommand(query: string, opts: SearchCommandOptions = {}): Promise<void> {\n let registry: ServerRegistry | undefined;\n\n try {\n const configPath = findConfigPath(opts.config);\n const raw = JSON.parse(fs.readFileSync(configPath, 'utf8'));\n const servers = raw.mcpServers ?? raw.servers ?? raw;\n const configDir = path.dirname(configPath);\n\n // Parse options\n const searchOptions: SearchOptions = {\n types: parseTypes(opts.types),\n servers: parseServers(opts.servers),\n searchFields: parseFields(opts.fields),\n limit: opts.limit ?? 20,\n threshold: opts.threshold ?? 0,\n };\n\n // Create registry (spawns stdio servers, registers HTTP servers)\n // In attach mode, don't spawn - just register for connection\n registry = createServerRegistry(servers, {\n cwd: configDir,\n dialects: opts.attach ? [] : ['servers', 'start'], // Empty dialects = no spawning\n });\n\n // Connect to all servers (or filtered subset)\n const serverNames = searchOptions.servers ?? Object.keys(servers || {});\n\n for (const serverName of serverNames) {\n try {\n await registry.connect(serverName);\n } catch (error) {\n // Log connection errors but continue with other servers\n if (!opts.json) {\n console.error(`ā Failed to connect to ${serverName}: ${error instanceof Error ? error.message : String(error)}`);\n }\n }\n }\n\n // Search across connected clients\n const response = await registry.searchCapabilities(query, searchOptions);\n\n // Output results\n if (opts.json) {\n outputJSON(response);\n } else {\n outputPretty(response);\n }\n } finally {\n // Cleanup - registry.close() handles all clients and servers\n if (registry) {\n try {\n await registry.close();\n } catch (_) {\n // Ignore close errors\n }\n }\n }\n}\n\n/**\n * Parse comma-separated types into CapabilityType array\n */\nfunction parseTypes(typesStr?: string): CapabilityType[] | undefined {\n if (!typesStr) return undefined;\n\n const validTypes: CapabilityType[] = ['tool', 'prompt', 'resource'];\n const parsed = typesStr.split(',').map((t) => t.trim().toLowerCase()) as CapabilityType[];\n\n const invalid = parsed.filter((t) => !validTypes.includes(t));\n if (invalid.length > 0) {\n throw new Error(`Invalid types: ${invalid.join(', ')}. Valid types: ${validTypes.join(', ')}`);\n }\n\n return parsed;\n}\n\n/**\n * Parse comma-separated server names\n */\nfunction parseServers(serversStr?: string): string[] | undefined {\n if (!serversStr) return undefined;\n return serversStr.split(',').map((s) => s.trim());\n}\n\n/**\n * Parse comma-separated search fields\n */\nfunction parseFields(fieldsStr?: string): SearchField[] | undefined {\n if (!fieldsStr) return undefined;\n\n const validFields: SearchField[] = ['name', 'description', 'schema', 'server'];\n const parsed = fieldsStr.split(',').map((f) => f.trim().toLowerCase()) as SearchField[];\n\n const invalid = parsed.filter((f) => !validFields.includes(f));\n if (invalid.length > 0) {\n throw new Error(`Invalid fields: ${invalid.join(', ')}. Valid fields: ${validFields.join(', ')}`);\n }\n\n return parsed;\n}\n\n/**\n * Output results as JSON\n */\nfunction outputJSON(response: SearchResponse): void {\n console.log(JSON.stringify(response, null, 2));\n}\n\n/**\n * Output results in human-readable format\n */\nfunction outputPretty(response: SearchResponse): void {\n if (response.results.length === 0) {\n console.log(`No results found for \"${response.query}\"`);\n return;\n }\n\n console.log(`Found ${response.total} result${response.total !== 1 ? 's' : ''} for \"${response.query}\"${response.total > response.results.length ? ` (showing ${response.results.length})` : ''}:\\n`);\n\n for (const result of response.results) {\n const typeIcon = result.type === 'tool' ? 'š§' : result.type === 'prompt' ? 'š¬' : 'š';\n const score = (result.score * 100).toFixed(0);\n\n console.log(`${typeIcon} ${result.name} [${result.type}] (${score}%)`);\n console.log(` Server: ${result.server}`);\n\n if (result.description) {\n const desc = result.description.length > 100 ? `${result.description.slice(0, 97)}...` : result.description;\n console.log(` ${desc}`);\n }\n\n if (result.matchedOn.length > 0) {\n console.log(` Matched: ${result.matchedOn.join(', ')}`);\n }\n\n console.log('');\n }\n}\n"],"names":["createServerRegistry","fs","path","findConfigPath","searchCommand","query","opts","registry","raw","searchOptions","configPath","config","JSON","parse","readFileSync","servers","mcpServers","configDir","dirname","types","parseTypes","parseServers","searchFields","parseFields","fields","limit","threshold","cwd","dialects","attach","serverNames","Object","keys","serverName","connect","error","json","console","Error","message","String","response","searchCapabilities","outputJSON","outputPretty","close","_","typesStr","undefined","validTypes","parsed","split","map","t","trim","toLowerCase","invalid","filter","includes","length","join","serversStr","s","fieldsStr","validFields","f","log","stringify","results","total","result","typeIcon","type","score","toFixed","name","server","description","desc","slice","matchedOn"],"mappings":"AAAA;;;;;CAKC,GAED,SAA8BA,oBAAoB,QAAwF,gBAAgB;AAC1J,YAAYC,QAAQ,KAAK;AACzB,YAAYC,UAAU,OAAO;AAC7B,SAASC,cAAc,QAAQ,wBAAwB;AAavD;;;;;;;;;;;;;CAaC,GACD,OAAO,eAAeC,cAAcC,KAAa,EAAEC,OAA6B,CAAC,CAAC;IAChF,IAAIC;IAEJ,IAAI;YAGcC,MAAAA,iBAQPF,aACIA,iBAWOG;QAtBpB,MAAMC,aAAaP,eAAeG,KAAKK,MAAM;QAC7C,MAAMH,MAAMI,KAAKC,KAAK,CAACZ,GAAGa,YAAY,CAACJ,YAAY;QACnD,MAAMK,WAAUP,QAAAA,kBAAAA,IAAIQ,UAAU,cAAdR,6BAAAA,kBAAkBA,IAAIO,OAAO,cAA7BP,kBAAAA,OAAiCA;QACjD,MAAMS,YAAYf,KAAKgB,OAAO,CAACR;QAE/B,gBAAgB;QAChB,MAAMD,gBAA+B;YACnCU,OAAOC,WAAWd,KAAKa,KAAK;YAC5BJ,SAASM,aAAaf,KAAKS,OAAO;YAClCO,cAAcC,YAAYjB,KAAKkB,MAAM;YACrCC,KAAK,GAAEnB,cAAAA,KAAKmB,KAAK,cAAVnB,yBAAAA,cAAc;YACrBoB,SAAS,GAAEpB,kBAAAA,KAAKoB,SAAS,cAAdpB,6BAAAA,kBAAkB;QAC/B;QAEA,iEAAiE;QACjE,6DAA6D;QAC7DC,WAAWP,qBAAqBe,SAAS;YACvCY,KAAKV;YACLW,UAAUtB,KAAKuB,MAAM,GAAG,EAAE,GAAG;gBAAC;gBAAW;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AC;IAEnM,KAAK,MAAMW,UAAU7B,SAAS2B,OAAO,CAAE;QACrC,MAAMG,WAAWD,OAAOE,IAAI,KAAK,SAAS,OAAOF,OAAOE,IAAI,KAAK,WAAW,OAAO;QACnF,MAAMC,QAAQ,AAACH,CAAAA,OAAOG,KAAK,GAAG,GAAE,EAAGC,OAAO,CAAC;QAE3CrC,QAAQ6B,GAAG,CAAC,GAAGK,SAAS,CAAC,EAAED,OAAOK,IAAI,CAAC,EAAE,EAAEL,OAAOE,IAAI,CAAC,GAAG,EAAEC,MAAM,EAAE,CAAC;QACrEpC,QAAQ6B,GAAG,CAAC,CAAC,WAAW,EAAEI,OAAOM,MAAM,EAAE;QAEzC,IAAIN,OAAOO,WAAW,EAAE;YACtB,MAAMC,OAAOR,OAAOO,WAAW,CAAClB,MAAM,GAAG,MAAM,GAAGW,OAAOO,WAAW,CAACE,KAAK,CAAC,GAAG,IAAI,GAAG,CAAC,GAAGT,OAAOO,WAAW;YAC3GxC,QAAQ6B,GAAG,CAAC,CAAC,GAAG,EAAEY,MAAM;QAC1B;QAEA,IAAIR,OAAOU,SAAS,CAACrB,MAAM,GAAG,GAAG;YAC/BtB,QAAQ6B,GAAG,CAAC,CAAC,YAAY,EAAEI,OAAOU,SAAS,CAACpB,IAAI,CAAC,OAAO;QAC1D;QAEAvB,QAAQ6B,GAAG,CAAC;IACd;AACF"}
|
|
1
|
+
{"version":3,"sources":["/Users/kevin/Dev/Projects/mcp-z/cli/src/commands/search.ts"],"sourcesContent":["/**\n * search.ts\n *\n * Search MCP server capabilities (tools, prompts, resources) without loading full schemas.\n * Designed for agent discovery workflows.\n */\n\nimport { type CapabilityType, createServerRegistry, type SearchField, type SearchOptions, type SearchResponse, type ServerRegistry } from '@mcp-z/client';\nimport * as fs from 'fs';\nimport * as path from 'path';\nimport findConfigPath from '../lib/find-config-path.ts';\n\nexport interface SearchCommandOptions {\n config?: string;\n servers?: string;\n types?: string;\n fields?: string;\n limit?: number;\n threshold?: number;\n json?: boolean;\n attach?: boolean;\n}\n\n/**\n * Main search command implementation.\n *\n * @param query - The search query string\n * @param opts - Search options from CLI flags\n *\n * @example\n * // Search for email-related capabilities\n * await searchCommand('send email', {});\n *\n * @example\n * // Search only tools in specific servers\n * await searchCommand('spreadsheet', { types: 'tool', servers: 'sheets,drive' });\n */\nexport async function searchCommand(query: string, opts: SearchCommandOptions = {}): Promise<void> {\n let registry: ServerRegistry | undefined;\n\n try {\n const configPath = findConfigPath({ config: opts.config });\n const raw = JSON.parse(fs.readFileSync(configPath, 'utf8'));\n const servers = raw.mcpServers ?? raw.servers ?? raw;\n const configDir = path.dirname(configPath);\n\n // Parse options\n const searchOptions: SearchOptions = {\n types: parseTypes(opts.types),\n servers: parseServers(opts.servers),\n searchFields: parseFields(opts.fields),\n limit: opts.limit ?? 20,\n threshold: opts.threshold ?? 0,\n };\n\n // Create registry (spawns stdio servers, registers HTTP servers)\n // In attach mode, don't spawn - just register for connection\n registry = createServerRegistry(servers, {\n cwd: configDir,\n dialects: opts.attach ? [] : ['servers', 'start'], // Empty dialects = no spawning\n });\n\n // Connect to all servers (or filtered subset)\n const serverNames = searchOptions.servers ?? Object.keys(servers || {});\n\n for (const serverName of serverNames) {\n try {\n await registry.connect(serverName);\n } catch (error) {\n // Log connection errors but continue with other servers\n if (!opts.json) {\n console.error(`ā Failed to connect to ${serverName}: ${error instanceof Error ? error.message : String(error)}`);\n }\n }\n }\n\n // Search across connected clients\n const response = await registry.searchCapabilities(query, searchOptions);\n\n // Output results\n if (opts.json) {\n outputJSON(response);\n } else {\n outputPretty(response);\n }\n } finally {\n // Cleanup - registry.close() handles all clients and servers\n if (registry) {\n try {\n await registry.close();\n } catch (_) {\n // Ignore close errors\n }\n }\n }\n}\n\n/**\n * Parse comma-separated types into CapabilityType array\n */\nfunction parseTypes(typesStr?: string): CapabilityType[] | undefined {\n if (!typesStr) return undefined;\n\n const validTypes: CapabilityType[] = ['tool', 'prompt', 'resource'];\n const parsed = typesStr.split(',').map((t) => t.trim().toLowerCase()) as CapabilityType[];\n\n const invalid = parsed.filter((t) => !validTypes.includes(t));\n if (invalid.length > 0) {\n throw new Error(`Invalid types: ${invalid.join(', ')}. Valid types: ${validTypes.join(', ')}`);\n }\n\n return parsed;\n}\n\n/**\n * Parse comma-separated server names\n */\nfunction parseServers(serversStr?: string): string[] | undefined {\n if (!serversStr) return undefined;\n return serversStr.split(',').map((s) => s.trim());\n}\n\n/**\n * Parse comma-separated search fields\n */\nfunction parseFields(fieldsStr?: string): SearchField[] | undefined {\n if (!fieldsStr) return undefined;\n\n const validFields: SearchField[] = ['name', 'description', 'schema', 'server'];\n const parsed = fieldsStr.split(',').map((f) => f.trim().toLowerCase()) as SearchField[];\n\n const invalid = parsed.filter((f) => !validFields.includes(f));\n if (invalid.length > 0) {\n throw new Error(`Invalid fields: ${invalid.join(', ')}. Valid fields: ${validFields.join(', ')}`);\n }\n\n return parsed;\n}\n\n/**\n * Output results as JSON\n */\nfunction outputJSON(response: SearchResponse): void {\n console.log(JSON.stringify(response, null, 2));\n}\n\n/**\n * Output results in human-readable format\n */\nfunction outputPretty(response: SearchResponse): void {\n if (response.results.length === 0) {\n console.log(`No results found for \"${response.query}\"`);\n return;\n }\n\n console.log(`Found ${response.total} result${response.total !== 1 ? 's' : ''} for \"${response.query}\"${response.total > response.results.length ? ` (showing ${response.results.length})` : ''}:\\n`);\n\n for (const result of response.results) {\n const typeIcon = result.type === 'tool' ? 'š§' : result.type === 'prompt' ? 'š¬' : 'š';\n const score = (result.score * 100).toFixed(0);\n\n console.log(`${typeIcon} ${result.name} [${result.type}] (${score}%)`);\n console.log(` Server: ${result.server}`);\n\n if (result.description) {\n const desc = result.description.length > 100 ? `${result.description.slice(0, 97)}...` : result.description;\n console.log(` ${desc}`);\n }\n\n if (result.matchedOn.length > 0) {\n console.log(` Matched: ${result.matchedOn.join(', ')}`);\n }\n\n console.log('');\n }\n}\n"],"names":["createServerRegistry","fs","path","findConfigPath","searchCommand","query","opts","registry","raw","searchOptions","configPath","config","JSON","parse","readFileSync","servers","mcpServers","configDir","dirname","types","parseTypes","parseServers","searchFields","parseFields","fields","limit","threshold","cwd","dialects","attach","serverNames","Object","keys","serverName","connect","error","json","console","Error","message","String","response","searchCapabilities","outputJSON","outputPretty","close","_","typesStr","undefined","validTypes","parsed","split","map","t","trim","toLowerCase","invalid","filter","includes","length","join","serversStr","s","fieldsStr","validFields","f","log","stringify","results","total","result","typeIcon","type","score","toFixed","name","server","description","desc","slice","matchedOn"],"mappings":"AAAA;;;;;CAKC,GAED,SAA8BA,oBAAoB,QAAwF,gBAAgB;AAC1J,YAAYC,QAAQ,KAAK;AACzB,YAAYC,UAAU,OAAO;AAC7B,OAAOC,oBAAoB,6BAA6B;AAaxD;;;;;;;;;;;;;CAaC,GACD,OAAO,eAAeC,cAAcC,KAAa,EAAEC,OAA6B,CAAC,CAAC;IAChF,IAAIC;IAEJ,IAAI;YAGcC,MAAAA,iBAQPF,aACIA,iBAWOG;QAtBpB,MAAMC,aAAaP,eAAe;YAAEQ,QAAQL,KAAKK,MAAM;QAAC;QACxD,MAAMH,MAAMI,KAAKC,KAAK,CAACZ,GAAGa,YAAY,CAACJ,YAAY;QACnD,MAAMK,WAAUP,QAAAA,kBAAAA,IAAIQ,UAAU,cAAdR,6BAAAA,kBAAkBA,IAAIO,OAAO,cAA7BP,kBAAAA,OAAiCA;QACjD,MAAMS,YAAYf,KAAKgB,OAAO,CAACR;QAE/B,gBAAgB;QAChB,MAAMD,gBAA+B;YACnCU,OAAOC,WAAWd,KAAKa,KAAK;YAC5BJ,SAASM,aAAaf,KAAKS,OAAO;YAClCO,cAAcC,YAAYjB,KAAKkB,MAAM;YACrCC,KAAK,GAAEnB,cAAAA,KAAKmB,KAAK,cAAVnB,yBAAAA,cAAc;YACrBoB,SAAS,GAAEpB,kBAAAA,KAAKoB,SAAS,cAAdpB,6BAAAA,kBAAkB;QAC/B;QAEA,iEAAiE;QACjE,6DAA6D;QAC7DC,WAAWP,qBAAqBe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AAC,UAAU,EAAElB,SAAS2B,OAAO,CAACT,MAAM,CAAC,CAAC,CAAC,GAAG,GAAG,GAAG,CAAC;IAEnM,KAAK,MAAMW,UAAU7B,SAAS2B,OAAO,CAAE;QACrC,MAAMG,WAAWD,OAAOE,IAAI,KAAK,SAAS,OAAOF,OAAOE,IAAI,KAAK,WAAW,OAAO;QACnF,MAAMC,QAAQ,AAACH,CAAAA,OAAOG,KAAK,GAAG,GAAE,EAAGC,OAAO,CAAC;QAE3CrC,QAAQ6B,GAAG,CAAC,GAAGK,SAAS,CAAC,EAAED,OAAOK,IAAI,CAAC,EAAE,EAAEL,OAAOE,IAAI,CAAC,GAAG,EAAEC,MAAM,EAAE,CAAC;QACrEpC,QAAQ6B,GAAG,CAAC,CAAC,WAAW,EAAEI,OAAOM,MAAM,EAAE;QAEzC,IAAIN,OAAOO,WAAW,EAAE;YACtB,MAAMC,OAAOR,OAAOO,WAAW,CAAClB,MAAM,GAAG,MAAM,GAAGW,OAAOO,WAAW,CAACE,KAAK,CAAC,GAAG,IAAI,GAAG,CAAC,GAAGT,OAAOO,WAAW;YAC3GxC,QAAQ6B,GAAG,CAAC,CAAC,GAAG,EAAEY,MAAM;QAC1B;QAEA,IAAIR,OAAOU,SAAS,CAACrB,MAAM,GAAG,GAAG;YAC/BtB,QAAQ6B,GAAG,CAAC,CAAC,YAAY,EAAEI,OAAOU,SAAS,CAACpB,IAAI,CAAC,OAAO;QAC1D;QAEAvB,QAAQ6B,GAAG,CAAC;IACd;AACF"}
|
package/dist/esm/commands/up.js
CHANGED
|
@@ -1,7 +1,7 @@
|
|
|
1
1
|
import { createServerRegistry } from '@mcp-z/client';
|
|
2
2
|
import * as fs from 'fs';
|
|
3
3
|
import * as path from 'path';
|
|
4
|
-
import
|
|
4
|
+
import findConfigPath from '../lib/find-config-path.js';
|
|
5
5
|
import { hasStartBlock } from '../types.js';
|
|
6
6
|
/**
|
|
7
7
|
* MCP server configuration entry per MCP specification.
|
|
@@ -38,7 +38,9 @@ import { hasStartBlock } from '../types.js';
|
|
|
38
38
|
* });
|
|
39
39
|
*/ export async function upCommand(opts = {}) {
|
|
40
40
|
var _ref, _raw_mcpServers;
|
|
41
|
-
const configPath = findConfigPath(
|
|
41
|
+
const configPath = findConfigPath({
|
|
42
|
+
config: opts.config
|
|
43
|
+
});
|
|
42
44
|
const raw = JSON.parse(fs.readFileSync(configPath, 'utf8'));
|
|
43
45
|
const servers = (_ref = (_raw_mcpServers = raw.mcpServers) !== null && _raw_mcpServers !== void 0 ? _raw_mcpServers : raw.servers) !== null && _ref !== void 0 ? _ref : raw;
|
|
44
46
|
const configDir = path.dirname(configPath);
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"sources":["/Users/kevin/Dev/Projects/mcp-z/cli/src/commands/up.ts"],"sourcesContent":["import { createServerRegistry, type Dialect, type ServerRegistry } from '@mcp-z/client';\nimport * as fs from 'fs';\nimport * as path from 'path';\nimport
|
|
1
|
+
{"version":3,"sources":["/Users/kevin/Dev/Projects/mcp-z/cli/src/commands/up.ts"],"sourcesContent":["import { createServerRegistry, type Dialect, type ServerRegistry } from '@mcp-z/client';\nimport * as fs from 'fs';\nimport * as path from 'path';\nimport findConfigPath from '../lib/find-config-path.ts';\nimport { hasStartBlock, type ServerConfig } from '../types.ts';\n\n/**\n * Configuration options for the upCommand function\n * @public\n */\nexport interface UpOptions {\n /** Optional path to custom .mcp.json configuration file */\n config?: string;\n /** Start only stdio servers (Claude Code compatible mode) */\n stdioOnly?: boolean;\n /** Start only HTTP servers with start blocks (for Claude Code Desktop) */\n httpOnly?: boolean;\n}\n\n/**\n * MCP server configuration entry per MCP specification.\n *\n * Supports two transport types:\n * - stdio (default if no type): spawned process with stdin/stdout\n * - http: remote HTTP server\n *\n * Transport can be inferred from URL protocol:\n * - http:// or https:// ā http\n *\n * @see https://modelcontextprotocol.io/specification/2025-06-18/basic/transports\n */\n\n/**\n * Start a cluster of MCP servers from a configuration file or object.\n *\n * @param opts - Configuration options\n * @param opts.config - Optional path to custom .mcp.json file\n * @returns ServerRegistry with servers map, config, connect method, and close function\n *\n * @example\n * // Auto-discover .mcp.json in current directory\n * const registry = await upCommand();\n *\n * @example\n * // Load from specific config\n * const registry = await upCommand({ config: '/path/to/.mcp.json' });\n *\n * @example\n * // Use in-memory config\n * const registry = await upCommand({\n * mcpServers: {\n * 'echo-stdio': { command: 'node', args: ['test/lib/servers/echo-stdio.ts'] }\n * }\n * });\n */\nexport async function upCommand(opts: UpOptions = {}): Promise<ServerRegistry> {\n const configPath = findConfigPath({ config: opts.config });\n const raw = JSON.parse(fs.readFileSync(configPath, 'utf8'));\n const servers = raw.mcpServers ?? raw.servers ?? raw;\n const configDir = path.dirname(configPath);\n\n // Determine dialects based on flags\n // Default is ['servers', 'start'] (spawns everything)\n let dialects: Dialect[] = ['servers', 'start'];\n if (opts.stdioOnly) {\n dialects = ['servers'];\n } else if (opts.httpOnly) {\n dialects = ['start'];\n // In http-only mode, check if there are any servers with start blocks\n const hasStartBlocks = Object.values(servers || {}).some((entry) => entry && hasStartBlock(entry as ServerConfig));\n if (!hasStartBlocks) {\n console.log(' No HTTP servers found with start configuration');\n console.log(' (stdio servers are spawned automatically by Claude Code)');\n // Return empty registry\n return createServerRegistry({}, { cwd: configDir });\n }\n }\n\n return createServerRegistry(servers, {\n cwd: configDir,\n dialects,\n });\n}\n"],"names":["createServerRegistry","fs","path","findConfigPath","hasStartBlock","upCommand","opts","raw","configPath","config","JSON","parse","readFileSync","servers","mcpServers","configDir","dirname","dialects","stdioOnly","httpOnly","hasStartBlocks","Object","values","some","entry","console","log","cwd"],"mappings":"AAAA,SAASA,oBAAoB,QAA2C,gBAAgB;AACxF,YAAYC,QAAQ,KAAK;AACzB,YAAYC,UAAU,OAAO;AAC7B,OAAOC,oBAAoB,6BAA6B;AACxD,SAASC,aAAa,QAA2B,cAAc;AAe/D;;;;;;;;;;;CAWC,GAED;;;;;;;;;;;;;;;;;;;;;;CAsBC,GACD,OAAO,eAAeC,UAAUC,OAAkB,CAAC,CAAC;QAGlCC,MAAAA;IAFhB,MAAMC,aAAaL,eAAe;QAAEM,QAAQH,KAAKG,MAAM;IAAC;IACxD,MAAMF,MAAMG,KAAKC,KAAK,CAACV,GAAGW,YAAY,CAACJ,YAAY;IACnD,MAAMK,WAAUN,QAAAA,kBAAAA,IAAIO,UAAU,cAAdP,6BAAAA,kBAAkBA,IAAIM,OAAO,cAA7BN,kBAAAA,OAAiCA;IACjD,MAAMQ,YAAYb,KAAKc,OAAO,CAACR;IAE/B,oCAAoC;IACpC,sDAAsD;IACtD,IAAIS,WAAsB;QAAC;QAAW;KAAQ;IAC9C,IAAIX,KAAKY,SAAS,EAAE;QAClBD,WAAW;YAAC;SAAU;IACxB,OAAO,IAAIX,KAAKa,QAAQ,EAAE;QACxBF,WAAW;YAAC;SAAQ;QACpB,sEAAsE;QACtE,MAAMG,iBAAiBC,OAAOC,MAAM,CAACT,WAAW,CAAC,GAAGU,IAAI,CAAC,CAACC,QAAUA,SAASpB,cAAcoB;QAC3F,IAAI,CAACJ,gBAAgB;YACnBK,QAAQC,GAAG,CAAC;YACZD,QAAQC,GAAG,CAAC;YACZ,wBAAwB;YACxB,OAAO1B,qBAAqB,CAAC,GAAG;gBAAE2B,KAAKZ;YAAU;QACnD;IACF;IAEA,OAAOf,qBAAqBa,SAAS;QACnCc,KAAKZ;QACLE;IACF;AACF"}
|
|
@@ -0,0 +1,23 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* find-config-path.ts
|
|
3
|
+
*
|
|
4
|
+
* Find config file by searching up the directory tree.
|
|
5
|
+
* Searches from cwd up to stopDir (default: home directory).
|
|
6
|
+
*/
|
|
7
|
+
export interface FindConfigOptions {
|
|
8
|
+
/** Config filename or path (default: ".mcp.json") */
|
|
9
|
+
config?: string;
|
|
10
|
+
/** Directory to start searching from (default: process.cwd()) */
|
|
11
|
+
cwd?: string;
|
|
12
|
+
/** Directory to stop searching at, inclusive (default: os.homedir()) */
|
|
13
|
+
stopDir?: string;
|
|
14
|
+
}
|
|
15
|
+
/**
|
|
16
|
+
* Find a config file by searching up directory tree from cwd to stopDir.
|
|
17
|
+
*
|
|
18
|
+
* If config includes a path separator or is absolute, it is treated as a path.
|
|
19
|
+
* Otherwise it is treated as a filename and searched upwards.
|
|
20
|
+
*
|
|
21
|
+
* @throws Error if config file not found
|
|
22
|
+
*/
|
|
23
|
+
export default function findConfigPath(options?: FindConfigOptions): string;
|
|
@@ -0,0 +1,58 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* find-config-path.ts
|
|
3
|
+
*
|
|
4
|
+
* Find config file by searching up the directory tree.
|
|
5
|
+
* Searches from cwd up to stopDir (default: home directory).
|
|
6
|
+
*/ import * as fs from 'fs';
|
|
7
|
+
import * as os from 'os';
|
|
8
|
+
import * as path from 'path';
|
|
9
|
+
/**
|
|
10
|
+
* Find a config file by searching up directory tree from cwd to stopDir.
|
|
11
|
+
*
|
|
12
|
+
* If config includes a path separator or is absolute, it is treated as a path.
|
|
13
|
+
* Otherwise it is treated as a filename and searched upwards.
|
|
14
|
+
*
|
|
15
|
+
* @throws Error if config file not found
|
|
16
|
+
*/ export default function findConfigPath(options = {}) {
|
|
17
|
+
var _options_config, _options_cwd, _options_stopDir;
|
|
18
|
+
const config = (_options_config = options.config) !== null && _options_config !== void 0 ? _options_config : '.mcp.json';
|
|
19
|
+
const cwd = (_options_cwd = options.cwd) !== null && _options_cwd !== void 0 ? _options_cwd : process.cwd();
|
|
20
|
+
const stopDir = (_options_stopDir = options.stopDir) !== null && _options_stopDir !== void 0 ? _options_stopDir : os.homedir();
|
|
21
|
+
if (isPathLike(config)) {
|
|
22
|
+
const resolved = path.isAbsolute(config) ? config : path.resolve(cwd, config);
|
|
23
|
+
if (!fs.existsSync(resolved)) {
|
|
24
|
+
throw new Error(`Config file not found: ${resolved}`);
|
|
25
|
+
}
|
|
26
|
+
const stat = fs.statSync(resolved);
|
|
27
|
+
if (stat.isDirectory()) {
|
|
28
|
+
const candidate = path.join(resolved, '.mcp.json');
|
|
29
|
+
if (!fs.existsSync(candidate)) {
|
|
30
|
+
throw new Error(`Config file not found: ${candidate}`);
|
|
31
|
+
}
|
|
32
|
+
return candidate;
|
|
33
|
+
}
|
|
34
|
+
return resolved;
|
|
35
|
+
}
|
|
36
|
+
const root = path.parse(cwd).root;
|
|
37
|
+
let dir = cwd;
|
|
38
|
+
while(true){
|
|
39
|
+
const candidate = path.join(dir, config);
|
|
40
|
+
if (fs.existsSync(candidate)) return candidate;
|
|
41
|
+
if (dir === root) break;
|
|
42
|
+
if (isSamePath(dir, stopDir)) break;
|
|
43
|
+
// Stop after checking stopDir if it's an ancestor.
|
|
44
|
+
if (!isWithin(dir, stopDir)) break;
|
|
45
|
+
dir = path.dirname(dir);
|
|
46
|
+
}
|
|
47
|
+
throw new Error(`Config file not found: ${config}\n\nSearched from ${cwd} up to ${stopDir}`);
|
|
48
|
+
}
|
|
49
|
+
function isPathLike(value) {
|
|
50
|
+
return path.isAbsolute(value) || /[\\/]/.test(value);
|
|
51
|
+
}
|
|
52
|
+
function isWithin(child, parent) {
|
|
53
|
+
const rel = path.relative(parent, child);
|
|
54
|
+
return rel === '' || !rel.startsWith('..') && !path.isAbsolute(rel);
|
|
55
|
+
}
|
|
56
|
+
function isSamePath(a, b) {
|
|
57
|
+
return path.resolve(a) === path.resolve(b);
|
|
58
|
+
}
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"sources":["/Users/kevin/Dev/Projects/mcp-z/cli/src/lib/find-config-path.ts"],"sourcesContent":["/**\n * find-config-path.ts\n *\n * Find config file by searching up the directory tree.\n * Searches from cwd up to stopDir (default: home directory).\n */\n\nimport * as fs from 'fs';\nimport * as os from 'os';\nimport * as path from 'path';\n\nexport interface FindConfigOptions {\n /** Config filename or path (default: \".mcp.json\") */\n config?: string;\n /** Directory to start searching from (default: process.cwd()) */\n cwd?: string;\n /** Directory to stop searching at, inclusive (default: os.homedir()) */\n stopDir?: string;\n}\n\n/**\n * Find a config file by searching up directory tree from cwd to stopDir.\n *\n * If config includes a path separator or is absolute, it is treated as a path.\n * Otherwise it is treated as a filename and searched upwards.\n *\n * @throws Error if config file not found\n */\nexport default function findConfigPath(options: FindConfigOptions = {}): string {\n const config = options.config ?? '.mcp.json';\n const cwd = options.cwd ?? process.cwd();\n const stopDir = options.stopDir ?? os.homedir();\n\n if (isPathLike(config)) {\n const resolved = path.isAbsolute(config) ? config : path.resolve(cwd, config);\n if (!fs.existsSync(resolved)) {\n throw new Error(`Config file not found: ${resolved}`);\n }\n const stat = fs.statSync(resolved);\n if (stat.isDirectory()) {\n const candidate = path.join(resolved, '.mcp.json');\n if (!fs.existsSync(candidate)) {\n throw new Error(`Config file not found: ${candidate}`);\n }\n return candidate;\n }\n return resolved;\n }\n\n const root = path.parse(cwd).root;\n let dir = cwd;\n\n while (true) {\n const candidate = path.join(dir, config);\n if (fs.existsSync(candidate)) return candidate;\n\n if (dir === root) break;\n if (isSamePath(dir, stopDir)) break;\n\n // Stop after checking stopDir if it's an ancestor.\n if (!isWithin(dir, stopDir)) break;\n\n dir = path.dirname(dir);\n }\n\n throw new Error(`Config file not found: ${config}\\n\\nSearched from ${cwd} up to ${stopDir}`);\n}\n\nfunction isPathLike(value: string): boolean {\n return path.isAbsolute(value) || /[\\\\/]/.test(value);\n}\n\nfunction isWithin(child: string, parent: string): boolean {\n const rel = path.relative(parent, child);\n return rel === '' || (!rel.startsWith('..') && !path.isAbsolute(rel));\n}\n\nfunction isSamePath(a: string, b: string): boolean {\n return path.resolve(a) === path.resolve(b);\n}\n"],"names":["fs","os","path","findConfigPath","options","config","cwd","process","stopDir","homedir","isPathLike","resolved","isAbsolute","resolve","existsSync","Error","stat","statSync","isDirectory","candidate","join","root","parse","dir","isSamePath","isWithin","dirname","value","test","child","parent","rel","relative","startsWith","a","b"],"mappings":"AAAA;;;;;CAKC,GAED,YAAYA,QAAQ,KAAK;AACzB,YAAYC,QAAQ,KAAK;AACzB,YAAYC,UAAU,OAAO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AAEA,SAASE,WAAWiB,KAAa;IAC/B,OAAOzB,KAAKU,UAAU,CAACe,UAAU,QAAQC,IAAI,CAACD;AAChD;AAEA,SAASF,SAASI,KAAa,EAAEC,MAAc;IAC7C,MAAMC,MAAM7B,KAAK8B,QAAQ,CAACF,QAAQD;IAClC,OAAOE,QAAQ,MAAO,CAACA,IAAIE,UAAU,CAAC,SAAS,CAAC/B,KAAKU,UAAU,CAACmB;AAClE;AAEA,SAASP,WAAWU,CAAS,EAAEC,CAAS;IACtC,OAAOjC,KAAKW,OAAO,CAACqB,OAAOhC,KAAKW,OAAO,CAACsB;AAC1C"}
|
|
@@ -6,7 +6,7 @@
|
|
|
6
6
|
*/ import { validateServers } from '@mcp-z/client';
|
|
7
7
|
import * as fs from 'fs';
|
|
8
8
|
import * as path from 'path';
|
|
9
|
-
import
|
|
9
|
+
import findConfigPath from './find-config-path.js';
|
|
10
10
|
/**
|
|
11
11
|
* Resolve server configuration from CLI options.
|
|
12
12
|
*
|
|
@@ -80,7 +80,9 @@ import { findConfigPath } from './find-config.js';
|
|
|
80
80
|
if (!opts.server) {
|
|
81
81
|
throw new Error('Server name is required when using config file');
|
|
82
82
|
}
|
|
83
|
-
const cfgPath = findConfigPath(
|
|
83
|
+
const cfgPath = findConfigPath({
|
|
84
|
+
config: opts.config
|
|
85
|
+
});
|
|
84
86
|
const raw = JSON.parse(fs.readFileSync(cfgPath, 'utf8'));
|
|
85
87
|
const servers = (_ref = (_raw_mcpServers = raw.mcpServers) !== null && _raw_mcpServers !== void 0 ? _raw_mcpServers : raw.servers) !== null && _ref !== void 0 ? _ref : raw;
|
|
86
88
|
const serverNames = Object.keys(servers || {});
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"sources":["/Users/kevin/Dev/Projects/mcp-z/cli/src/lib/resolve-server-config.ts"],"sourcesContent":["/**\n * resolve-server-config.ts\n *\n * Shared config resolution for CLI commands.\n * Supports both config file-based and inline server configurations.\n */\n\nimport type { McpServerEntry, ServersConfig } from '@mcp-z/client';\nimport { validateServers } from '@mcp-z/client';\nimport * as fs from 'fs';\nimport * as path from 'path';\nimport type { ServerConfig } from '../types.ts';\nimport { findConfigPath } from './find-config.ts';\n\n/**\n * Options for inline server configuration.\n */\nexport interface InlineConfigOptions {\n /** Server name (optional when inline config provided) */\n server?: string;\n /** Config file path (mutually exclusive with inline options) */\n config?: string;\n /** Stdio run command string (e.g., \"npx -y @echo/server\") */\n run?: string;\n /** HTTP server URL */\n url?: string;\n /** Full server config as JSON string */\n serverConfig?: string;\n}\n\n/**\n * Resolved server configuration.\n */\nexport interface ResolvedServerConfig {\n /** Server name for display purposes */\n serverName: string;\n /** The server configuration object */\n serverConfig: ServerConfig;\n /** Working directory for the server (cwd for inline, config dir for file) */\n configDir: string;\n /** Full servers config (for HTTP auth flow that needs full config) */\n fullConfig: ServersConfig;\n}\n\n/**\n * Resolve server configuration from CLI options.\n *\n * Supports three modes:\n * 1. Config file: --config path + server positional\n * 2. Inline stdio: --run \"npx server\"\n * 3. Inline HTTP: --url \"https://...\"\n * 4. Full JSON: --server '{\"command\":\"npx\",...}'\n *\n * @param opts - CLI options for config resolution\n * @returns Resolved server configuration\n * @throws Error if configuration is invalid\n */\nexport function resolveServerConfig(opts: InlineConfigOptions): ResolvedServerConfig {\n // Validate mutual exclusivity of inline options\n const inlineOptions = [opts.run, opts.url, opts.serverConfig].filter(Boolean);\n if (inlineOptions.length > 1) {\n throw new Error('Cannot use multiple inline config options. Use only one of: --run, --url, or --server');\n }\n\n const hasInlineConfig = inlineOptions.length > 0;\n\n // Validate mutual exclusivity with config file\n if (hasInlineConfig && opts.config) {\n throw new Error('Cannot use --config with inline config options (--run, --url, --server)');\n }\n\n // Handle inline configuration\n if (hasInlineConfig) {\n return resolveInlineConfig(opts);\n }\n\n // Handle config file-based configuration\n return resolveFileConfig(opts);\n}\n\n/**\n * Resolve inline server configuration.\n */\nfunction resolveInlineConfig(opts: InlineConfigOptions): ResolvedServerConfig {\n const serverName = opts.server || 'inline';\n const configDir = process.cwd();\n let serverConfig: ServerConfig;\n\n if (opts.run) {\n // Parse run string into command + args (simple helper, no schema validation needed)\n serverConfig = parseRunString(opts.run);\n } else if (opts.url) {\n // Create HTTP server config (simple helper, no schema validation needed)\n serverConfig = {\n type: 'http',\n url: opts.url,\n };\n } else if (opts.serverConfig) {\n // Parse full JSON config with schema validation\n serverConfig = parseServerConfigJson(opts.serverConfig, serverName);\n } else {\n throw new Error('No inline config provided');\n }\n\n // Create a minimal servers config for the resolved server\n const fullConfig: ServersConfig = {\n [serverName]: serverConfig,\n };\n\n return {\n serverName,\n serverConfig,\n configDir,\n fullConfig,\n };\n}\n\n/**\n * Resolve config file-based server configuration.\n */\nfunction resolveFileConfig(opts: InlineConfigOptions): ResolvedServerConfig {\n if (!opts.server) {\n throw new Error('Server name is required when using config file');\n }\n\n const cfgPath = findConfigPath(opts.config);\n const raw = JSON.parse(fs.readFileSync(cfgPath, 'utf8'));\n const servers: ServersConfig = raw.mcpServers ?? raw.servers ?? raw;\n\n const serverNames = Object.keys(servers || {});\n if (!serverNames.includes(opts.server)) {\n throw new Error(`Server '${opts.server}' not found in config\\n\\nAvailable servers: ${serverNames.join(', ')}`);\n }\n\n const serverConfig = servers[opts.server];\n if (!serverConfig) {\n throw new Error(`Server ${opts.server} not found in config`);\n }\n\n return {\n serverName: opts.server,\n serverConfig: serverConfig as ServerConfig,\n configDir: path.dirname(cfgPath),\n fullConfig: servers,\n };\n}\n\n/**\n * Parse a run string into a ServerConfigStdio.\n *\n * @example\n * parseRunString(\"npx -y @echo/server\")\n * // => { command: \"npx\", args: [\"-y\", \"@echo/server\"] }\n */\nfunction parseRunString(runStr: string): ServerConfig {\n const parts = runStr.trim().split(/\\s+/);\n if (parts.length === 0 || !parts[0]) {\n throw new Error('Run string cannot be empty');\n }\n\n return {\n command: parts[0],\n args: parts.slice(1),\n };\n}\n\n/**\n * Parse and validate a full server config JSON string against the MCP schema.\n *\n * @example\n * parseServerConfigJson('{\"command\":\"npx\",\"args\":[\"-y\",\"@echo/server\"]}')\n * parseServerConfigJson('{\"url\":\"https://example.com/mcp\",\"type\":\"http\"}')\n */\nfunction parseServerConfigJson(jsonStr: string, serverName: string): ServerConfig {\n let parsed: unknown;\n try {\n parsed = JSON.parse(jsonStr);\n } catch (error) {\n throw new Error(`Failed to parse server config JSON: ${error instanceof Error ? error.message : String(error)}`);\n }\n\n if (typeof parsed !== 'object' || parsed === null) {\n throw new Error('Server config must be a JSON object');\n }\n\n const config = parsed as McpServerEntry;\n\n // Validate: must have either 'command' (stdio) or 'url' (http)\n if (!config.command && !config.url) {\n throw new Error('Server config must have either \"command\" (for stdio) or \"url\" (for http)');\n }\n\n // Normalize: if url is present without explicit type, set type to 'http'\n if (config.url && !config.type) {\n config.type = 'http';\n }\n\n // Validate against the MCP servers schema\n const serversMap = { [serverName]: config };\n const validation = validateServers(serversMap);\n if (!validation.valid) {\n const errorDetails = validation.errors?.join('\\n ') || 'Unknown validation error';\n throw new Error(`Invalid server config:\\n ${errorDetails}`);\n }\n\n // Return as ServerConfig (compatible with McpServerEntry)\n return config as ServerConfig;\n}\n"],"names":["validateServers","fs","path","findConfigPath","resolveServerConfig","opts","inlineOptions","run","url","serverConfig","filter","Boolean","length","Error","hasInlineConfig","config","resolveInlineConfig","resolveFileConfig","serverName","server","configDir","process","cwd","parseRunString","type","parseServerConfigJson","fullConfig","raw","cfgPath","JSON","parse","readFileSync","servers","mcpServers","serverNames","Object","keys","includes","join","dirname","runStr","parts","trim","split","command","args","slice","jsonStr","parsed","error","message","String","serversMap","validation","valid","errorDetails","errors"],"mappings":"AAAA;;;;;CAKC,GAGD,SAASA,eAAe,QAAQ,gBAAgB;AAChD,YAAYC,QAAQ,KAAK;AACzB,YAAYC,UAAU,OAAO;AAE7B,SAASC,cAAc,QAAQ,mBAAmB;AAgClD;;;;;;;;;;;;CAYC,GACD,OAAO,SAASC,oBAAoBC,IAAyB;IAC3D,gDAAgD;IAChD,MAAMC,gBAAgB;QA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AASiC;IAEf,+DAA+D;IAC/D,IAAI,CAACjC,OAAO6B,OAAO,IAAI,CAAC7B,OAAOP,GAAG,EAAE;QAClC,MAAM,IAAIK,MAAM;IAClB;IAEA,yEAAyE;IACzE,IAAIE,OAAOP,GAAG,IAAI,CAACO,OAAOS,IAAI,EAAE;QAC9BT,OAAOS,IAAI,GAAG;IAChB;IAEA,0CAA0C;IAC1C,MAAM4B,aAAa;QAAE,CAAClC,WAAW,EAAEH;IAAO;IAC1C,MAAMsC,aAAarD,gBAAgBoD;IACnC,IAAI,CAACC,WAAWC,KAAK,EAAE;YACAD;QAArB,MAAME,eAAeF,EAAAA,qBAAAA,WAAWG,MAAM,cAAjBH,yCAAAA,mBAAmBf,IAAI,CAAC,YAAW;QACxD,MAAM,IAAIzB,MAAM,CAAC,0BAA0B,EAAE0C,cAAc;IAC7D;IAEA,0DAA0D;IAC1D,OAAOxC;AACT"}
|
|
1
|
+
{"version":3,"sources":["/Users/kevin/Dev/Projects/mcp-z/cli/src/lib/resolve-server-config.ts"],"sourcesContent":["/**\n * resolve-server-config.ts\n *\n * Shared config resolution for CLI commands.\n * Supports both config file-based and inline server configurations.\n */\n\nimport type { McpServerEntry, ServersConfig } from '@mcp-z/client';\nimport { validateServers } from '@mcp-z/client';\nimport * as fs from 'fs';\nimport * as path from 'path';\nimport type { ServerConfig } from '../types.ts';\nimport findConfigPath from './find-config-path.ts';\n\n/**\n * Options for inline server configuration.\n */\nexport interface InlineConfigOptions {\n /** Server name (optional when inline config provided) */\n server?: string;\n /** Config file path (mutually exclusive with inline options) */\n config?: string;\n /** Stdio run command string (e.g., \"npx -y @echo/server\") */\n run?: string;\n /** HTTP server URL */\n url?: string;\n /** Full server config as JSON string */\n serverConfig?: string;\n}\n\n/**\n * Resolved server configuration.\n */\nexport interface ResolvedServerConfig {\n /** Server name for display purposes */\n serverName: string;\n /** The server configuration object */\n serverConfig: ServerConfig;\n /** Working directory for the server (cwd for inline, config dir for file) */\n configDir: string;\n /** Full servers config (for HTTP auth flow that needs full config) */\n fullConfig: ServersConfig;\n}\n\n/**\n * Resolve server configuration from CLI options.\n *\n * Supports three modes:\n * 1. Config file: --config path + server positional\n * 2. Inline stdio: --run \"npx server\"\n * 3. Inline HTTP: --url \"https://...\"\n * 4. Full JSON: --server '{\"command\":\"npx\",...}'\n *\n * @param opts - CLI options for config resolution\n * @returns Resolved server configuration\n * @throws Error if configuration is invalid\n */\nexport function resolveServerConfig(opts: InlineConfigOptions): ResolvedServerConfig {\n // Validate mutual exclusivity of inline options\n const inlineOptions = [opts.run, opts.url, opts.serverConfig].filter(Boolean);\n if (inlineOptions.length > 1) {\n throw new Error('Cannot use multiple inline config options. Use only one of: --run, --url, or --server');\n }\n\n const hasInlineConfig = inlineOptions.length > 0;\n\n // Validate mutual exclusivity with config file\n if (hasInlineConfig && opts.config) {\n throw new Error('Cannot use --config with inline config options (--run, --url, --server)');\n }\n\n // Handle inline configuration\n if (hasInlineConfig) {\n return resolveInlineConfig(opts);\n }\n\n // Handle config file-based configuration\n return resolveFileConfig(opts);\n}\n\n/**\n * Resolve inline server configuration.\n */\nfunction resolveInlineConfig(opts: InlineConfigOptions): ResolvedServerConfig {\n const serverName = opts.server || 'inline';\n const configDir = process.cwd();\n let serverConfig: ServerConfig;\n\n if (opts.run) {\n // Parse run string into command + args (simple helper, no schema validation needed)\n serverConfig = parseRunString(opts.run);\n } else if (opts.url) {\n // Create HTTP server config (simple helper, no schema validation needed)\n serverConfig = {\n type: 'http',\n url: opts.url,\n };\n } else if (opts.serverConfig) {\n // Parse full JSON config with schema validation\n serverConfig = parseServerConfigJson(opts.serverConfig, serverName);\n } else {\n throw new Error('No inline config provided');\n }\n\n // Create a minimal servers config for the resolved server\n const fullConfig: ServersConfig = {\n [serverName]: serverConfig,\n };\n\n return {\n serverName,\n serverConfig,\n configDir,\n fullConfig,\n };\n}\n\n/**\n * Resolve config file-based server configuration.\n */\nfunction resolveFileConfig(opts: InlineConfigOptions): ResolvedServerConfig {\n if (!opts.server) {\n throw new Error('Server name is required when using config file');\n }\n\n const cfgPath = findConfigPath({ config: opts.config });\n const raw = JSON.parse(fs.readFileSync(cfgPath, 'utf8'));\n const servers: ServersConfig = raw.mcpServers ?? raw.servers ?? raw;\n\n const serverNames = Object.keys(servers || {});\n if (!serverNames.includes(opts.server)) {\n throw new Error(`Server '${opts.server}' not found in config\\n\\nAvailable servers: ${serverNames.join(', ')}`);\n }\n\n const serverConfig = servers[opts.server];\n if (!serverConfig) {\n throw new Error(`Server ${opts.server} not found in config`);\n }\n\n return {\n serverName: opts.server,\n serverConfig: serverConfig as ServerConfig,\n configDir: path.dirname(cfgPath),\n fullConfig: servers,\n };\n}\n\n/**\n * Parse a run string into a ServerConfigStdio.\n *\n * @example\n * parseRunString(\"npx -y @echo/server\")\n * // => { command: \"npx\", args: [\"-y\", \"@echo/server\"] }\n */\nfunction parseRunString(runStr: string): ServerConfig {\n const parts = runStr.trim().split(/\\s+/);\n if (parts.length === 0 || !parts[0]) {\n throw new Error('Run string cannot be empty');\n }\n\n return {\n command: parts[0],\n args: parts.slice(1),\n };\n}\n\n/**\n * Parse and validate a full server config JSON string against the MCP schema.\n *\n * @example\n * parseServerConfigJson('{\"command\":\"npx\",\"args\":[\"-y\",\"@echo/server\"]}')\n * parseServerConfigJson('{\"url\":\"https://example.com/mcp\",\"type\":\"http\"}')\n */\nfunction parseServerConfigJson(jsonStr: string, serverName: string): ServerConfig {\n let parsed: unknown;\n try {\n parsed = JSON.parse(jsonStr);\n } catch (error) {\n throw new Error(`Failed to parse server config JSON: ${error instanceof Error ? error.message : String(error)}`);\n }\n\n if (typeof parsed !== 'object' || parsed === null) {\n throw new Error('Server config must be a JSON object');\n }\n\n const config = parsed as McpServerEntry;\n\n // Validate: must have either 'command' (stdio) or 'url' (http)\n if (!config.command && !config.url) {\n throw new Error('Server config must have either \"command\" (for stdio) or \"url\" (for http)');\n }\n\n // Normalize: if url is present without explicit type, set type to 'http'\n if (config.url && !config.type) {\n config.type = 'http';\n }\n\n // Validate against the MCP servers schema\n const serversMap = { [serverName]: config };\n const validation = validateServers(serversMap);\n if (!validation.valid) {\n const errorDetails = validation.errors?.join('\\n ') || 'Unknown validation error';\n throw new Error(`Invalid server config:\\n ${errorDetails}`);\n }\n\n // Return as ServerConfig (compatible with McpServerEntry)\n return config as ServerConfig;\n}\n"],"names":["validateServers","fs","path","findConfigPath","resolveServerConfig","opts","inlineOptions","run","url","serverConfig","filter","Boolean","length","Error","hasInlineConfig","config","resolveInlineConfig","resolveFileConfig","serverName","server","configDir","process","cwd","parseRunString","type","parseServerConfigJson","fullConfig","raw","cfgPath","JSON","parse","readFileSync","servers","mcpServers","serverNames","Object","keys","includes","join","dirname","runStr","parts","trim","split","command","args","slice","jsonStr","parsed","error","message","String","serversMap","validation","valid","errorDetails","errors"],"mappings":"AAAA;;;;;CAKC,GAGD,SAASA,eAAe,QAAQ,gBAAgB;AAChD,YAAYC,QAAQ,KAAK;AACzB,YAAYC,UAAU,OAAO;AAE7B,OAAOC,oBAAoB,wBAAwB;AAgCnD;;;;;;;;;;;;CAYC,GACD,OAAO,SAASC,oBAAoBC,IAAyB;IAC3D,gDAAgD;IAChD,MAAMC,gBAAgB;QAACD,KAAKE,GAAG;QAAEF,KAAKG,GAAG;QAAEH,KAAKI,YAAY;KAAC,CAACC,MAAM,CAACC;IACrE,IAAIL,cAAcM,MAAM,GAAG,GAAG;QAC5B,MAAM,IAAIC,MAAM;IAClB;IAEA,MAAMC,kBAAkBR,cAAcM,MAAM,GAAG;IAE/C,+CAA+C;IAC/C,IAAIE,mBAAmBT,KAAKU,MAAM,EAAE;QAClC,MAAM,IAAIF,MAAM;IAClB;IAEA,8BAA8B;IAC9B,IAAIC,iBAAiB;QACnB,OAAOE,oBAAoBX;IAC7B;IAEA,yCAAyC;IACzC,OAAOY,kBAAkBZ;AAC3B;AAEA;;CAEC,GACD,SAASW,oBAAoBX,IAAyB;IACpD,MAAMa,aAAab,KAAKc,MAAM,IAAI;IAClC,MAA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,MAAM,IAAIzB,MAAM,CAAC,0BAA0B,EAAE0C,cAAc;IAC7D;IAEA,0DAA0D;IAC1D,OAAOxC;AACT"}
|
package/package.json
CHANGED
|
@@ -1,14 +0,0 @@
|
|
|
1
|
-
/**
|
|
2
|
-
* find-config.ts
|
|
3
|
-
*
|
|
4
|
-
* Find .mcp.json config file by searching up the directory tree.
|
|
5
|
-
* Searches from cwd up to home directory (like Claude Code).
|
|
6
|
-
*/
|
|
7
|
-
/**
|
|
8
|
-
* Find .mcp.json by searching up directory tree from cwd to home directory.
|
|
9
|
-
*
|
|
10
|
-
* @param explicitPath - If provided, validates and returns this path (for --config flag)
|
|
11
|
-
* @returns The resolved path to the config file
|
|
12
|
-
* @throws Error if config file not found
|
|
13
|
-
*/
|
|
14
|
-
export declare function findConfigPath(explicitPath?: string): string;
|
|
@@ -1,14 +0,0 @@
|
|
|
1
|
-
/**
|
|
2
|
-
* find-config.ts
|
|
3
|
-
*
|
|
4
|
-
* Find .mcp.json config file by searching up the directory tree.
|
|
5
|
-
* Searches from cwd up to home directory (like Claude Code).
|
|
6
|
-
*/
|
|
7
|
-
/**
|
|
8
|
-
* Find .mcp.json by searching up directory tree from cwd to home directory.
|
|
9
|
-
*
|
|
10
|
-
* @param explicitPath - If provided, validates and returns this path (for --config flag)
|
|
11
|
-
* @returns The resolved path to the config file
|
|
12
|
-
* @throws Error if config file not found
|
|
13
|
-
*/
|
|
14
|
-
export declare function findConfigPath(explicitPath?: string): string;
|