@evantahler/mcpcli 0.1.1

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.
@@ -0,0 +1,104 @@
1
+ import type { Command } from "commander";
2
+ import { getContext } from "../context.ts";
3
+ import {
4
+ formatCallResult,
5
+ formatError,
6
+ formatServerTools,
7
+ formatToolHelp,
8
+ formatValidationErrors,
9
+ } from "../output/formatter.ts";
10
+ import { startSpinner } from "../output/spinner.ts";
11
+ import { validateToolInput } from "../validation/schema.ts";
12
+
13
+ export function registerCallCommand(program: Command) {
14
+ program
15
+ .command("call <server> [tool] [args]")
16
+ .description("execute a tool (omit tool name to list available tools)")
17
+ .action(async (server: string, tool: string | undefined, argsStr: string | undefined) => {
18
+ const { manager, formatOptions } = await getContext(program);
19
+
20
+ if (!tool) {
21
+ try {
22
+ const tools = await manager.listTools(server);
23
+ console.log(formatServerTools(server, tools, formatOptions));
24
+ } catch (err) {
25
+ console.error(formatError(String(err), formatOptions));
26
+ process.exit(1);
27
+ } finally {
28
+ await manager.close();
29
+ }
30
+ return;
31
+ }
32
+ try {
33
+ // No args + interactive terminal → show tool help with example payload
34
+ const hasArgs = !!argsStr;
35
+ const hasStdin = !process.stdin.isTTY;
36
+ if (!hasArgs && !hasStdin) {
37
+ const toolSchema = await manager.getToolSchema(server, tool);
38
+ if (toolSchema) {
39
+ console.log(formatToolHelp(server, toolSchema, formatOptions));
40
+ await manager.close();
41
+ return;
42
+ }
43
+ }
44
+
45
+ // Parse args from argument, stdin, or empty
46
+ let args: Record<string, unknown> = {};
47
+
48
+ if (argsStr) {
49
+ args = parseJsonArgs(argsStr);
50
+ } else if (!process.stdin.isTTY) {
51
+ // Read from stdin
52
+ const stdin = await readStdin();
53
+ if (stdin.trim()) {
54
+ args = parseJsonArgs(stdin);
55
+ }
56
+ }
57
+
58
+ // Validate args against tool inputSchema before calling
59
+ const toolSchema = await manager.getToolSchema(server, tool);
60
+ if (toolSchema) {
61
+ const validation = validateToolInput(server, toolSchema, args);
62
+ if (!validation.valid) {
63
+ console.error(formatValidationErrors(server, tool, validation.errors, formatOptions));
64
+ process.exit(1);
65
+ }
66
+ }
67
+
68
+ const spinner = startSpinner(`Calling ${server}/${tool}...`, formatOptions);
69
+ const result = await manager.callTool(server, tool, args);
70
+ spinner.stop();
71
+ console.log(formatCallResult(result, formatOptions));
72
+ } catch (err) {
73
+ console.error(formatError(String(err), formatOptions));
74
+ process.exit(1);
75
+ } finally {
76
+ await manager.close();
77
+ }
78
+ });
79
+ }
80
+
81
+ function parseJsonArgs(str: string): Record<string, unknown> {
82
+ try {
83
+ const parsed = JSON.parse(str);
84
+ if (typeof parsed !== "object" || parsed === null || Array.isArray(parsed)) {
85
+ throw new Error("Tool arguments must be a JSON object");
86
+ }
87
+ return parsed as Record<string, unknown>;
88
+ } catch (err) {
89
+ if (err instanceof SyntaxError) {
90
+ throw new Error(`Invalid JSON: ${err.message}`);
91
+ }
92
+ throw err;
93
+ }
94
+ }
95
+
96
+ async function readStdin(): Promise<string> {
97
+ const chunks: string[] = [];
98
+ const reader = process.stdin;
99
+ reader.setEncoding("utf-8");
100
+ for await (const chunk of reader) {
101
+ chunks.push(chunk as string);
102
+ }
103
+ return chunks.join("");
104
+ }
@@ -0,0 +1,53 @@
1
+ import type { Command } from "commander";
2
+ import { dim } from "ansis";
3
+ import { getContext } from "../context.ts";
4
+ import { buildSearchIndex } from "../search/indexer.ts";
5
+ import { saveSearchIndex } from "../config/loader.ts";
6
+ import { formatError } from "../output/formatter.ts";
7
+ import { startSpinner } from "../output/spinner.ts";
8
+
9
+ export function registerIndexCommand(program: Command) {
10
+ program
11
+ .command("index")
12
+ .description("build the search index from all configured servers")
13
+ .option("-i, --status", "show index status")
14
+ .action(async (options: { status?: boolean }) => {
15
+ const { config, manager, formatOptions } = await getContext(program);
16
+
17
+ if (options.status) {
18
+ const idx = config.searchIndex;
19
+ if (idx.tools.length === 0) {
20
+ console.log("No search index. Run: mcpcli index");
21
+ } else {
22
+ console.log(`Tools: ${idx.tools.length}`);
23
+ console.log(`Model: ${idx.embedding_model}`);
24
+ console.log(`Indexed: ${idx.indexed_at}`);
25
+ }
26
+ await manager.close();
27
+ return;
28
+ }
29
+
30
+ const spinner = startSpinner("Connecting to servers...", formatOptions);
31
+
32
+ try {
33
+ const start = performance.now();
34
+ const index = await buildSearchIndex(manager, (progress) => {
35
+ spinner.update(`Indexing ${progress.current}/${progress.total}: ${progress.tool}`);
36
+ });
37
+ const elapsed = ((performance.now() - start) / 1000).toFixed(1);
38
+
39
+ await saveSearchIndex(config.configDir, index);
40
+ spinner.success(`Indexed ${index.tools.length} tools in ${elapsed}s`);
41
+
42
+ if (process.stderr.isTTY) {
43
+ process.stderr.write(dim(`Saved to ${config.configDir}/search.json\n`));
44
+ }
45
+ } catch (err) {
46
+ spinner.error("Indexing failed");
47
+ console.error(formatError(String(err), formatOptions));
48
+ process.exit(1);
49
+ } finally {
50
+ await manager.close();
51
+ }
52
+ });
53
+ }
@@ -0,0 +1,42 @@
1
+ import type { Command } from "commander";
2
+ import { getContext } from "../context.ts";
3
+ import { formatServerTools, formatToolSchema, formatError } from "../output/formatter.ts";
4
+ import { startSpinner } from "../output/spinner.ts";
5
+
6
+ export function registerInfoCommand(program: Command) {
7
+ program
8
+ .command("info <target>")
9
+ .description("show tools for a server, or schema for a specific tool")
10
+ .action(async (target: string) => {
11
+ const { manager, formatOptions } = await getContext(program);
12
+ const spinner = startSpinner(`Connecting to ${target}...`, formatOptions);
13
+ try {
14
+ // Parse "server/tool" or "server tool" format
15
+ const slashIndex = target.indexOf("/");
16
+ if (slashIndex !== -1) {
17
+ const serverName = target.slice(0, slashIndex);
18
+ const toolName = target.slice(slashIndex + 1);
19
+ const tool = await manager.getToolSchema(serverName, toolName);
20
+ spinner.stop();
21
+ if (!tool) {
22
+ console.error(
23
+ formatError(`Tool "${toolName}" not found on server "${serverName}"`, formatOptions),
24
+ );
25
+ process.exit(1);
26
+ }
27
+ console.log(formatToolSchema(serverName, tool, formatOptions));
28
+ } else {
29
+ // Just a server name — list its tools
30
+ const tools = await manager.listTools(target);
31
+ spinner.stop();
32
+ console.log(formatServerTools(target, tools, formatOptions));
33
+ }
34
+ } catch (err) {
35
+ spinner.error(`Failed to connect to ${target}`);
36
+ console.error(formatError(String(err), formatOptions));
37
+ process.exit(1);
38
+ } finally {
39
+ await manager.close();
40
+ }
41
+ });
42
+ }
@@ -0,0 +1,30 @@
1
+ import type { Command } from "commander";
2
+ import { getContext } from "../context.ts";
3
+ import { formatToolList, formatError } from "../output/formatter.ts";
4
+ import { startSpinner } from "../output/spinner.ts";
5
+
6
+ export function registerListCommand(program: Command) {
7
+ program.action(async () => {
8
+ const { manager, formatOptions } = await getContext(program);
9
+ const spinner = startSpinner("Connecting to servers...", formatOptions);
10
+ try {
11
+ const { tools, errors } = await manager.getAllTools();
12
+ spinner.stop();
13
+
14
+ if (errors.length > 0) {
15
+ for (const err of errors) {
16
+ console.error(`"${err.server}": ${err.message}`);
17
+ }
18
+ if (tools.length > 0) console.log("");
19
+ }
20
+
21
+ console.log(formatToolList(tools, formatOptions));
22
+ } catch (err) {
23
+ spinner.error("Failed to list tools");
24
+ console.error(formatError(String(err), formatOptions));
25
+ process.exit(1);
26
+ } finally {
27
+ await manager.close();
28
+ }
29
+ });
30
+ }
@@ -0,0 +1,37 @@
1
+ import type { Command } from "commander";
2
+ import { getContext } from "../context.ts";
3
+ import { search } from "../search/index.ts";
4
+ import { formatError, formatSearchResults } from "../output/formatter.ts";
5
+ import { startSpinner } from "../output/spinner.ts";
6
+
7
+ export function registerSearchCommand(program: Command) {
8
+ program
9
+ .command("search <terms...>")
10
+ .description("search tools by keyword and/or semantic similarity")
11
+ .option("-k, --keyword", "keyword/glob search only")
12
+ .option("-q, --query", "semantic search only")
13
+ .action(async (terms: string[], options: { keyword?: boolean; query?: boolean }) => {
14
+ const query = terms.join(" ");
15
+ const { config, formatOptions } = await getContext(program);
16
+
17
+ if (config.searchIndex.tools.length === 0) {
18
+ console.error(formatError("No search index found. Run: mcpcli index", formatOptions));
19
+ process.exit(1);
20
+ }
21
+
22
+ const spinner = startSpinner("Searching...", formatOptions);
23
+
24
+ try {
25
+ const results = await search(query, config.searchIndex, {
26
+ keywordOnly: options.keyword,
27
+ semanticOnly: options.query,
28
+ });
29
+ spinner.stop();
30
+ console.log(formatSearchResults(results, formatOptions));
31
+ } catch (err) {
32
+ spinner.stop();
33
+ console.error(formatError(String(err), formatOptions));
34
+ process.exit(1);
35
+ }
36
+ });
37
+ }
@@ -0,0 +1,41 @@
1
+ const ENV_VAR_PATTERN = /\$\{([^}]+)\}/g;
2
+
3
+ /** Whether to throw on missing env vars (default: true) */
4
+ function isStrictEnv(): boolean {
5
+ return process.env.MCP_STRICT_ENV !== "false";
6
+ }
7
+
8
+ /** Replace ${VAR_NAME} in a string with the corresponding env var value */
9
+ export function interpolateEnvString(value: string): string {
10
+ return value.replace(ENV_VAR_PATTERN, (_match, varName: string) => {
11
+ const envValue = process.env[varName];
12
+ if (envValue === undefined) {
13
+ if (isStrictEnv()) {
14
+ throw new Error(
15
+ `Environment variable "${varName}" is not set (set MCP_STRICT_ENV=false to warn instead)`,
16
+ );
17
+ }
18
+ console.warn(`Warning: environment variable "${varName}" is not set`);
19
+ return "";
20
+ }
21
+ return envValue;
22
+ });
23
+ }
24
+
25
+ /** Recursively interpolate env vars in all string values of an object */
26
+ export function interpolateEnv<T>(obj: T): T {
27
+ if (typeof obj === "string") {
28
+ return interpolateEnvString(obj) as T;
29
+ }
30
+ if (Array.isArray(obj)) {
31
+ return obj.map((item) => interpolateEnv(item)) as T;
32
+ }
33
+ if (typeof obj === "object" && obj !== null) {
34
+ const result: Record<string, unknown> = {};
35
+ for (const [key, value] of Object.entries(obj)) {
36
+ result[key] = interpolateEnv(value);
37
+ }
38
+ return result as T;
39
+ }
40
+ return obj;
41
+ }
@@ -0,0 +1,118 @@
1
+ import { join, resolve } from "path";
2
+ import { homedir } from "os";
3
+ import { interpolateEnv } from "./env.ts";
4
+ import {
5
+ type Config,
6
+ type ServersFile,
7
+ type AuthFile,
8
+ type SearchIndex,
9
+ validateServersFile,
10
+ validateAuthFile,
11
+ validateSearchIndex,
12
+ } from "./schemas.ts";
13
+
14
+ const DEFAULT_CONFIG_DIR = join(homedir(), ".config", "mcpcli");
15
+
16
+ const EMPTY_SERVERS: ServersFile = { mcpServers: {} };
17
+ const EMPTY_AUTH: AuthFile = {};
18
+ const EMPTY_SEARCH_INDEX: SearchIndex = {
19
+ version: 1,
20
+ indexed_at: "",
21
+ embedding_model: "claude",
22
+ tools: [],
23
+ };
24
+
25
+ /** Read and parse a JSON file, returning undefined if it doesn't exist */
26
+ async function readJsonFile(path: string): Promise<unknown | undefined> {
27
+ const file = Bun.file(path);
28
+ if (!(await file.exists())) return undefined;
29
+ const text = await file.text();
30
+ return JSON.parse(text);
31
+ }
32
+
33
+ /** Resolve the config directory from options, env, cwd, or default */
34
+ function resolveConfigDir(configFlag?: string): string {
35
+ // 1. -c / --config flag
36
+ if (configFlag) return resolve(configFlag);
37
+
38
+ // 2. MCP_CONFIG_PATH env var
39
+ const envPath = process.env.MCP_CONFIG_PATH;
40
+ if (envPath) return resolve(envPath);
41
+
42
+ // 3. ./servers.json exists in cwd → use cwd
43
+ // (checked at load time, not here — we return the candidate dir)
44
+
45
+ // 4. Default ~/.config/mcpcli/
46
+ return DEFAULT_CONFIG_DIR;
47
+ }
48
+
49
+ /** Check if servers.json exists in the given directory */
50
+ async function hasServersFile(dir: string): Promise<boolean> {
51
+ return Bun.file(join(dir, "servers.json")).exists();
52
+ }
53
+
54
+ export interface LoadConfigOptions {
55
+ configFlag?: string;
56
+ }
57
+
58
+ /** Load and validate all config files */
59
+ export async function loadConfig(options: LoadConfigOptions = {}): Promise<Config> {
60
+ // Resolve config directory
61
+ let configDir = resolveConfigDir(options.configFlag);
62
+
63
+ // If the resolved dir doesn't have servers.json, check cwd
64
+ if (!(await hasServersFile(configDir))) {
65
+ const cwd = process.cwd();
66
+ if (await hasServersFile(cwd)) {
67
+ configDir = cwd;
68
+ }
69
+ }
70
+
71
+ // Ensure config directory exists
72
+ await Bun.write(join(configDir, ".keep"), "").catch(() => {});
73
+ // Remove the .keep file, it was just to ensure the dir
74
+ Bun.file(join(configDir, ".keep"))
75
+ .exists()
76
+ .then((exists) => {
77
+ if (exists) Bun.write(join(configDir, ".keep"), "");
78
+ });
79
+
80
+ // Load servers.json
81
+ const serversPath = join(configDir, "servers.json");
82
+ const rawServers = await readJsonFile(serversPath);
83
+ let servers: ServersFile;
84
+ if (rawServers === undefined) {
85
+ servers = EMPTY_SERVERS;
86
+ } else {
87
+ servers = validateServersFile(rawServers);
88
+ // Interpolate env vars in server configs
89
+ servers = {
90
+ mcpServers: Object.fromEntries(
91
+ Object.entries(servers.mcpServers).map(([name, config]) => [name, interpolateEnv(config)]),
92
+ ),
93
+ };
94
+ }
95
+
96
+ // Load auth.json
97
+ const authPath = join(configDir, "auth.json");
98
+ const rawAuth = await readJsonFile(authPath);
99
+ const auth: AuthFile = rawAuth !== undefined ? validateAuthFile(rawAuth) : EMPTY_AUTH;
100
+
101
+ // Load search.json
102
+ const searchPath = join(configDir, "search.json");
103
+ const rawSearch = await readJsonFile(searchPath);
104
+ const searchIndex: SearchIndex =
105
+ rawSearch !== undefined ? validateSearchIndex(rawSearch) : EMPTY_SEARCH_INDEX;
106
+
107
+ return { configDir, servers, auth, searchIndex };
108
+ }
109
+
110
+ /** Save auth.json to the config directory */
111
+ export async function saveAuth(configDir: string, auth: AuthFile): Promise<void> {
112
+ await Bun.write(join(configDir, "auth.json"), JSON.stringify(auth, null, 2) + "\n");
113
+ }
114
+
115
+ /** Save search.json to the config directory */
116
+ export async function saveSearchIndex(configDir: string, index: SearchIndex): Promise<void> {
117
+ await Bun.write(join(configDir, "search.json"), JSON.stringify(index, null, 2) + "\n");
118
+ }
@@ -0,0 +1,137 @@
1
+ import type { Tool } from "@modelcontextprotocol/sdk/types.js";
2
+ import type {
3
+ OAuthTokens,
4
+ OAuthClientInformation,
5
+ OAuthClientInformationMixed,
6
+ } from "@modelcontextprotocol/sdk/shared/auth.js";
7
+
8
+ // Re-export SDK types we use throughout the codebase
9
+ export type { Tool, OAuthTokens, OAuthClientInformation, OAuthClientInformationMixed };
10
+
11
+ // --- Server config (our format, not MCP spec) ---
12
+
13
+ /** Stdio MCP server config */
14
+ export interface StdioServerConfig {
15
+ command: string;
16
+ args?: string[];
17
+ env?: Record<string, string>;
18
+ cwd?: string;
19
+ allowedTools?: string[];
20
+ disabledTools?: string[];
21
+ }
22
+
23
+ /** HTTP MCP server config */
24
+ export interface HttpServerConfig {
25
+ url: string;
26
+ headers?: Record<string, string>;
27
+ allowedTools?: string[];
28
+ disabledTools?: string[];
29
+ }
30
+
31
+ export type ServerConfig = StdioServerConfig | HttpServerConfig;
32
+
33
+ export function isStdioServer(config: ServerConfig): config is StdioServerConfig {
34
+ return "command" in config;
35
+ }
36
+
37
+ export function isHttpServer(config: ServerConfig): config is HttpServerConfig {
38
+ return "url" in config;
39
+ }
40
+
41
+ /** Top-level servers.json shape */
42
+ export interface ServersFile {
43
+ mcpServers: Record<string, ServerConfig>;
44
+ }
45
+
46
+ // --- Auth storage (wraps SDK's OAuthTokens with our persistence fields) ---
47
+
48
+ /** Per-server auth entry stored in auth.json */
49
+ export interface AuthEntry {
50
+ tokens: OAuthTokens;
51
+ expires_at?: string;
52
+ client_info?: OAuthClientInformationMixed;
53
+ complete?: boolean;
54
+ }
55
+
56
+ /** Top-level auth.json shape */
57
+ export type AuthFile = Record<string, AuthEntry>;
58
+
59
+ // --- Search index (entirely our format) ---
60
+
61
+ /** A single tool entry in the search index */
62
+ export interface IndexedTool {
63
+ server: string;
64
+ tool: string;
65
+ description: string;
66
+ input_schema?: Tool["inputSchema"];
67
+ scenarios: string[];
68
+ keywords: string[];
69
+ embedding: number[];
70
+ }
71
+
72
+ /** Top-level search.json shape */
73
+ export interface SearchIndex {
74
+ version: number;
75
+ indexed_at: string;
76
+ embedding_model: string;
77
+ tools: IndexedTool[];
78
+ }
79
+
80
+ // --- Combined config ---
81
+
82
+ /** Validated config returned by loadConfig */
83
+ export interface Config {
84
+ configDir: string;
85
+ servers: ServersFile;
86
+ auth: AuthFile;
87
+ searchIndex: SearchIndex;
88
+ }
89
+
90
+ // --- Validation ---
91
+
92
+ /** Validate that a parsed object looks like a valid servers.json */
93
+ export function validateServersFile(data: unknown): ServersFile {
94
+ if (typeof data !== "object" || data === null) {
95
+ throw new Error("servers.json must be a JSON object");
96
+ }
97
+
98
+ const obj = data as Record<string, unknown>;
99
+ if (typeof obj.mcpServers !== "object" || obj.mcpServers === null) {
100
+ throw new Error('servers.json must have a "mcpServers" object');
101
+ }
102
+
103
+ const servers = obj.mcpServers as Record<string, unknown>;
104
+ for (const [name, config] of Object.entries(servers)) {
105
+ if (typeof config !== "object" || config === null) {
106
+ throw new Error(`Server "${name}" must be an object`);
107
+ }
108
+ const c = config as Record<string, unknown>;
109
+ const hasCommand = typeof c.command === "string";
110
+ const hasUrl = typeof c.url === "string";
111
+ if (!hasCommand && !hasUrl) {
112
+ throw new Error(`Server "${name}" must have either "command" (stdio) or "url" (http)`);
113
+ }
114
+ }
115
+
116
+ return data as ServersFile;
117
+ }
118
+
119
+ /** Validate auth.json — lenient, just check shape */
120
+ export function validateAuthFile(data: unknown): AuthFile {
121
+ if (typeof data !== "object" || data === null) {
122
+ throw new Error("auth.json must be a JSON object");
123
+ }
124
+ return data as AuthFile;
125
+ }
126
+
127
+ /** Validate search.json — lenient, just check shape */
128
+ export function validateSearchIndex(data: unknown): SearchIndex {
129
+ if (typeof data !== "object" || data === null) {
130
+ throw new Error("search.json must be a JSON object");
131
+ }
132
+ const obj = data as Record<string, unknown>;
133
+ if (!Array.isArray(obj.tools)) {
134
+ throw new Error('search.json must have a "tools" array');
135
+ }
136
+ return data as SearchIndex;
137
+ }
package/src/context.ts ADDED
@@ -0,0 +1,41 @@
1
+ import type { Command } from "commander";
2
+ import { loadConfig, type LoadConfigOptions } from "./config/loader.ts";
3
+ import { ServerManager } from "./client/manager.ts";
4
+ import type { Config } from "./config/schemas.ts";
5
+ import type { FormatOptions } from "./output/formatter.ts";
6
+
7
+ export interface AppContext {
8
+ config: Config;
9
+ manager: ServerManager;
10
+ formatOptions: FormatOptions;
11
+ }
12
+
13
+ /** Build the app context from the root commander program options */
14
+ export async function getContext(program: Command): Promise<AppContext> {
15
+ const opts = program.opts();
16
+
17
+ const config = await loadConfig({
18
+ configFlag: opts.config as string | undefined,
19
+ });
20
+
21
+ const verbose = !!(opts.verbose as boolean | undefined);
22
+ const showSecrets = !!(opts.showSecrets as boolean | undefined);
23
+ const concurrency = Number(process.env.MCP_CONCURRENCY ?? 5);
24
+ const manager = new ServerManager(
25
+ config.servers,
26
+ config.configDir,
27
+ config.auth,
28
+ concurrency,
29
+ verbose,
30
+ showSecrets,
31
+ );
32
+
33
+ const formatOptions: FormatOptions = {
34
+ json: opts.json as boolean | undefined,
35
+ withDescriptions: opts.withDescriptions as boolean | undefined,
36
+ verbose,
37
+ showSecrets,
38
+ };
39
+
40
+ return { config, manager, formatOptions };
41
+ }