Merge branch 'main' into reverse-env-order-for-cli-stdio
This commit is contained in:
commit
44b4417951
4 changed files with 10137 additions and 1426 deletions
194
cli/src/cli.ts
194
cli/src/cli.ts
|
|
@ -14,6 +14,8 @@ type Args = {
|
|||
args: string[];
|
||||
envArgs: Record<string, string>;
|
||||
cli: boolean;
|
||||
transport?: "stdio" | "sse" | "streamable-http";
|
||||
serverUrl?: string;
|
||||
};
|
||||
|
||||
type CliOptions = {
|
||||
|
|
@ -21,13 +23,22 @@ type CliOptions = {
|
|||
config?: string;
|
||||
server?: string;
|
||||
cli?: boolean;
|
||||
transport?: string;
|
||||
serverUrl?: string;
|
||||
};
|
||||
|
||||
type ServerConfig = {
|
||||
command: string;
|
||||
args?: string[];
|
||||
env?: Record<string, string>;
|
||||
};
|
||||
type ServerConfig =
|
||||
| {
|
||||
type: "stdio";
|
||||
command: string;
|
||||
args?: string[];
|
||||
env?: Record<string, string>;
|
||||
}
|
||||
| {
|
||||
type: "sse" | "streamable-http";
|
||||
url: string;
|
||||
note?: string;
|
||||
};
|
||||
|
||||
function handleError(error: unknown): never {
|
||||
let message: string;
|
||||
|
|
@ -50,28 +61,15 @@ function delay(ms: number): Promise<void> {
|
|||
}
|
||||
|
||||
async function runWebClient(args: Args): Promise<void> {
|
||||
const inspectorServerPath = resolve(
|
||||
__dirname,
|
||||
"../../",
|
||||
"server",
|
||||
"build",
|
||||
"index.js",
|
||||
);
|
||||
|
||||
// Path to the client entry point
|
||||
const inspectorClientPath = resolve(
|
||||
__dirname,
|
||||
"../../",
|
||||
"client",
|
||||
"bin",
|
||||
"client.js",
|
||||
"start.js",
|
||||
);
|
||||
|
||||
const CLIENT_PORT: string = process.env.CLIENT_PORT ?? "6274";
|
||||
const SERVER_PORT: string = process.env.SERVER_PORT ?? "6277";
|
||||
|
||||
console.log("Starting MCP inspector...");
|
||||
|
||||
const abort = new AbortController();
|
||||
let cancelled: boolean = false;
|
||||
process.on("SIGINT", () => {
|
||||
|
|
@ -79,42 +77,36 @@ async function runWebClient(args: Args): Promise<void> {
|
|||
abort.abort();
|
||||
});
|
||||
|
||||
let server: ReturnType<typeof spawnPromise>;
|
||||
let serverOk: unknown;
|
||||
// Build arguments to pass to start.js
|
||||
const startArgs: string[] = [];
|
||||
|
||||
// Pass environment variables
|
||||
for (const [key, value] of Object.entries(args.envArgs)) {
|
||||
startArgs.push("-e", `${key}=${value}`);
|
||||
}
|
||||
|
||||
// Pass transport type if specified
|
||||
if (args.transport) {
|
||||
startArgs.push("--transport", args.transport);
|
||||
}
|
||||
|
||||
// Pass server URL if specified
|
||||
if (args.serverUrl) {
|
||||
startArgs.push("--server-url", args.serverUrl);
|
||||
}
|
||||
|
||||
// Pass command and args (using -- to separate them)
|
||||
if (args.command) {
|
||||
startArgs.push("--", args.command, ...args.args);
|
||||
}
|
||||
|
||||
try {
|
||||
server = spawnPromise(
|
||||
"node",
|
||||
[
|
||||
inspectorServerPath,
|
||||
...(args.command ? [`--env`, args.command] : []),
|
||||
...(args.args ? [`--args=${args.args.join(" ")}`] : []),
|
||||
],
|
||||
{
|
||||
env: {
|
||||
...process.env,
|
||||
PORT: SERVER_PORT,
|
||||
MCP_ENV_VARS: JSON.stringify(args.envArgs),
|
||||
},
|
||||
signal: abort.signal,
|
||||
echoOutput: true,
|
||||
},
|
||||
);
|
||||
|
||||
// Make sure server started before starting client
|
||||
serverOk = await Promise.race([server, delay(2 * 1000)]);
|
||||
} catch (error) {}
|
||||
|
||||
if (serverOk) {
|
||||
try {
|
||||
await spawnPromise("node", [inspectorClientPath], {
|
||||
env: { ...process.env, PORT: CLIENT_PORT },
|
||||
signal: abort.signal,
|
||||
echoOutput: true,
|
||||
});
|
||||
} catch (e) {
|
||||
if (!cancelled || process.env.DEBUG) throw e;
|
||||
}
|
||||
await spawnPromise("node", [inspectorClientPath, ...startArgs], {
|
||||
signal: abort.signal,
|
||||
echoOutput: true,
|
||||
});
|
||||
} catch (e) {
|
||||
if (!cancelled || process.env.DEBUG) throw e;
|
||||
}
|
||||
}
|
||||
|
||||
|
|
@ -132,7 +124,21 @@ async function runCli(args: Args): Promise<void> {
|
|||
});
|
||||
|
||||
try {
|
||||
await spawnPromise("node", [cliPath, args.command, ...args.args], {
|
||||
// Build CLI arguments
|
||||
const cliArgs = [cliPath];
|
||||
|
||||
// Add transport flag if specified
|
||||
if (args.transport && args.transport !== "stdio") {
|
||||
// Convert streamable-http back to http for CLI mode
|
||||
const cliTransport =
|
||||
args.transport === "streamable-http" ? "http" : args.transport;
|
||||
cliArgs.push("--transport", cliTransport);
|
||||
}
|
||||
|
||||
// Add command and remaining args
|
||||
cliArgs.push(args.command, ...args.args);
|
||||
|
||||
await spawnPromise("node", cliArgs, {
|
||||
env: { ...process.env, ...args.envArgs },
|
||||
signal: abort.signal,
|
||||
echoOutput: true,
|
||||
|
|
@ -219,7 +225,9 @@ function parseArgs(): Args {
|
|||
)
|
||||
.option("--config <path>", "config file path")
|
||||
.option("--server <n>", "server name from config file")
|
||||
.option("--cli", "enable CLI mode");
|
||||
.option("--cli", "enable CLI mode")
|
||||
.option("--transport <type>", "transport type (stdio, sse, http)")
|
||||
.option("--server-url <url>", "server URL for SSE/HTTP transport");
|
||||
|
||||
// Parse only the arguments before --
|
||||
program.parse(preArgs);
|
||||
|
|
@ -230,14 +238,33 @@ function parseArgs(): Args {
|
|||
// Add back any arguments that came after --
|
||||
const finalArgs = [...remainingArgs, ...postArgs];
|
||||
|
||||
// Validate that config and server are provided together
|
||||
if (
|
||||
(options.config && !options.server) ||
|
||||
(!options.config && options.server)
|
||||
) {
|
||||
throw new Error(
|
||||
"Both --config and --server must be provided together. If you specify one, you must specify the other.",
|
||||
// Validate config and server options
|
||||
if (!options.config && options.server) {
|
||||
throw new Error("--server requires --config to be specified");
|
||||
}
|
||||
|
||||
// If config is provided without server, try to auto-select
|
||||
if (options.config && !options.server) {
|
||||
const configContent = fs.readFileSync(
|
||||
path.isAbsolute(options.config)
|
||||
? options.config
|
||||
: path.resolve(process.cwd(), options.config),
|
||||
"utf8",
|
||||
);
|
||||
const parsedConfig = JSON.parse(configContent);
|
||||
const servers = Object.keys(parsedConfig.mcpServers || {});
|
||||
|
||||
if (servers.length === 1) {
|
||||
// Use the only server if there's just one
|
||||
options.server = servers[0];
|
||||
} else if (servers.length === 0) {
|
||||
throw new Error("No servers found in config file");
|
||||
} else {
|
||||
// Multiple servers, require explicit selection
|
||||
throw new Error(
|
||||
`Multiple servers found in config file. Please specify one with --server.\nAvailable servers: ${servers.join(", ")}`,
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
// If config file is specified, load and use the options from the file. We must merge the args
|
||||
|
|
@ -246,23 +273,52 @@ function parseArgs(): Args {
|
|||
if (options.config && options.server) {
|
||||
const config = loadConfigFile(options.config, options.server);
|
||||
|
||||
return {
|
||||
command: config.command,
|
||||
args: [...(config.args || []), ...finalArgs],
|
||||
envArgs: { ...(config.env || {}), ...(options.e || {}) },
|
||||
cli: options.cli || false,
|
||||
};
|
||||
if (config.type === "stdio") {
|
||||
return {
|
||||
command: config.command,
|
||||
args: [...(config.args || []), ...finalArgs],
|
||||
envArgs: { ...(config.env || {}), ...(options.e || {}) },
|
||||
cli: options.cli || false,
|
||||
transport: "stdio",
|
||||
};
|
||||
} else if (config.type === "sse" || config.type === "streamable-http") {
|
||||
return {
|
||||
command: config.url,
|
||||
args: finalArgs,
|
||||
envArgs: options.e || {},
|
||||
cli: options.cli || false,
|
||||
transport: config.type,
|
||||
serverUrl: config.url,
|
||||
};
|
||||
} else {
|
||||
// Backwards compatibility: if no type field, assume stdio
|
||||
return {
|
||||
command: (config as any).command || "",
|
||||
args: [...((config as any).args || []), ...finalArgs],
|
||||
envArgs: { ...((config as any).env || {}), ...(options.e || {}) },
|
||||
cli: options.cli || false,
|
||||
transport: "stdio",
|
||||
};
|
||||
}
|
||||
}
|
||||
|
||||
// Otherwise use command line arguments
|
||||
const command = finalArgs[0] || "";
|
||||
const args = finalArgs.slice(1);
|
||||
|
||||
// Map "http" shorthand to "streamable-http"
|
||||
let transport = options.transport;
|
||||
if (transport === "http") {
|
||||
transport = "streamable-http";
|
||||
}
|
||||
|
||||
return {
|
||||
command,
|
||||
args,
|
||||
envArgs: options.e || {},
|
||||
cli: options.cli || false,
|
||||
transport: transport as "stdio" | "sse" | "streamable-http" | undefined,
|
||||
serverUrl: options.serverUrl,
|
||||
};
|
||||
}
|
||||
|
||||
|
|
@ -275,7 +331,7 @@ async function main(): Promise<void> {
|
|||
const args = parseArgs();
|
||||
|
||||
if (args.cli) {
|
||||
runCli(args);
|
||||
await runCli(args);
|
||||
} else {
|
||||
await runWebClient(args);
|
||||
}
|
||||
|
|
|
|||
|
|
@ -18,6 +18,12 @@ export async function connect(
|
|||
): Promise<void> {
|
||||
try {
|
||||
await client.connect(transport);
|
||||
|
||||
if (client.getServerCapabilities()?.logging) {
|
||||
// default logging level is undefined in the spec, but the user of the
|
||||
// inspector most likely wants debug.
|
||||
await client.setLoggingLevel("debug");
|
||||
}
|
||||
} catch (error) {
|
||||
throw new Error(
|
||||
`Failed to connect to MCP server: ${error instanceof Error ? error.message : String(error)}`,
|
||||
|
|
|
|||
|
|
@ -29,9 +29,13 @@ type Args = {
|
|||
logLevel?: LogLevel;
|
||||
toolName?: string;
|
||||
toolArg?: Record<string, string>;
|
||||
transport?: "sse" | "stdio" | "http";
|
||||
};
|
||||
|
||||
function createTransportOptions(target: string[]): TransportOptions {
|
||||
function createTransportOptions(
|
||||
target: string[],
|
||||
transport?: "sse" | "stdio" | "http",
|
||||
): TransportOptions {
|
||||
if (target.length === 0) {
|
||||
throw new Error(
|
||||
"Target is required. Specify a URL or a command to execute.",
|
||||
|
|
@ -50,8 +54,30 @@ function createTransportOptions(target: string[]): TransportOptions {
|
|||
throw new Error("Arguments cannot be passed to a URL-based MCP server.");
|
||||
}
|
||||
|
||||
let transportType: "sse" | "stdio" | "http";
|
||||
if (transport) {
|
||||
if (!isUrl && transport !== "stdio") {
|
||||
throw new Error("Only stdio transport can be used with local commands.");
|
||||
}
|
||||
if (isUrl && transport === "stdio") {
|
||||
throw new Error("stdio transport cannot be used with URLs.");
|
||||
}
|
||||
transportType = transport;
|
||||
} else if (isUrl) {
|
||||
const url = new URL(command);
|
||||
if (url.pathname.endsWith("/mcp")) {
|
||||
transportType = "http";
|
||||
} else if (url.pathname.endsWith("/sse")) {
|
||||
transportType = "sse";
|
||||
} else {
|
||||
transportType = "sse";
|
||||
}
|
||||
} else {
|
||||
transportType = "stdio";
|
||||
}
|
||||
|
||||
return {
|
||||
transportType: isUrl ? "sse" : "stdio",
|
||||
transportType,
|
||||
command: isUrl ? undefined : command,
|
||||
args: isUrl ? undefined : commandArgs,
|
||||
url: isUrl ? command : undefined,
|
||||
|
|
@ -59,7 +85,7 @@ function createTransportOptions(target: string[]): TransportOptions {
|
|||
}
|
||||
|
||||
async function callMethod(args: Args): Promise<void> {
|
||||
const transportOptions = createTransportOptions(args.target);
|
||||
const transportOptions = createTransportOptions(args.target, args.transport);
|
||||
const transport = createTransport(transportOptions);
|
||||
const client = new Client({
|
||||
name: "inspector-cli",
|
||||
|
|
@ -214,6 +240,22 @@ function parseArgs(): Args {
|
|||
|
||||
return value as LogLevel;
|
||||
},
|
||||
)
|
||||
//
|
||||
// Transport options
|
||||
//
|
||||
.option(
|
||||
"--transport <type>",
|
||||
"Transport type (sse, http, or stdio). Auto-detected from URL: /mcp → http, /sse → sse, commands → stdio",
|
||||
(value: string) => {
|
||||
const validTransports = ["sse", "http", "stdio"];
|
||||
if (!validTransports.includes(value)) {
|
||||
throw new Error(
|
||||
`Invalid transport type: ${value}. Valid types are: ${validTransports.join(", ")}`,
|
||||
);
|
||||
}
|
||||
return value as "sse" | "http" | "stdio";
|
||||
},
|
||||
);
|
||||
|
||||
// Parse only the arguments before --
|
||||
|
|
@ -245,6 +287,8 @@ async function main(): Promise<void> {
|
|||
try {
|
||||
const args = parseArgs();
|
||||
await callMethod(args);
|
||||
// Explicitly exit to ensure process terminates in CI
|
||||
process.exit(0);
|
||||
} catch (error) {
|
||||
handleError(error);
|
||||
}
|
||||
|
|
|
|||
|
|
@ -3,23 +3,17 @@ import {
|
|||
getDefaultEnvironment,
|
||||
StdioClientTransport,
|
||||
} from "@modelcontextprotocol/sdk/client/stdio.js";
|
||||
import { StreamableHTTPClientTransport } from "@modelcontextprotocol/sdk/client/streamableHttp.js";
|
||||
import type { Transport } from "@modelcontextprotocol/sdk/shared/transport.js";
|
||||
import { findActualExecutable } from "spawn-rx";
|
||||
|
||||
export type TransportOptions = {
|
||||
transportType: "sse" | "stdio";
|
||||
transportType: "sse" | "stdio" | "http";
|
||||
command?: string;
|
||||
args?: string[];
|
||||
url?: string;
|
||||
};
|
||||
|
||||
function createSSETransport(options: TransportOptions): Transport {
|
||||
const baseUrl = new URL(options.url ?? "");
|
||||
const sseUrl = new URL("/sse", baseUrl);
|
||||
|
||||
return new SSEClientTransport(sseUrl);
|
||||
}
|
||||
|
||||
function createStdioTransport(options: TransportOptions): Transport {
|
||||
let args: string[] = [];
|
||||
|
||||
|
|
@ -63,8 +57,18 @@ export function createTransport(options: TransportOptions): Transport {
|
|||
return createStdioTransport(options);
|
||||
}
|
||||
|
||||
// If not STDIO, then it must be either SSE or HTTP.
|
||||
if (!options.url) {
|
||||
throw new Error("URL must be provided for SSE or HTTP transport types.");
|
||||
}
|
||||
const url = new URL(options.url);
|
||||
|
||||
if (transportType === "sse") {
|
||||
return createSSETransport(options);
|
||||
return new SSEClientTransport(url);
|
||||
}
|
||||
|
||||
if (transportType === "http") {
|
||||
return new StreamableHTTPClientTransport(url);
|
||||
}
|
||||
|
||||
throw new Error(`Unsupported transport type: ${transportType}`);
|
||||
|
|
|
|||
Loading…
Reference in a new issue