Merge remote-tracking branch 'upstream/main'
This commit is contained in:
commit
4c22605d3c
96 changed files with 17785 additions and 4211 deletions
12
.github/workflows/main.yml
vendored
12
.github/workflows/main.yml
vendored
|
|
@ -14,6 +14,9 @@ jobs:
|
|||
steps:
|
||||
- uses: actions/checkout@v4
|
||||
|
||||
- name: Check formatting
|
||||
run: npx prettier --check .
|
||||
|
||||
- uses: actions/setup-node@v4
|
||||
with:
|
||||
node-version: 18
|
||||
|
|
@ -22,6 +25,15 @@ jobs:
|
|||
# Working around https://github.com/npm/cli/issues/4828
|
||||
# - run: npm ci
|
||||
- run: npm install --no-package-lock
|
||||
|
||||
- name: Check linting
|
||||
working-directory: ./client
|
||||
run: npm run lint
|
||||
|
||||
- name: Run client tests
|
||||
working-directory: ./client
|
||||
run: npm test
|
||||
|
||||
- run: npm run build
|
||||
|
||||
publish:
|
||||
|
|
|
|||
7
.gitignore
vendored
7
.gitignore
vendored
|
|
@ -1,6 +1,11 @@
|
|||
.DS_Store
|
||||
node_modules
|
||||
.vscode
|
||||
.idea
|
||||
node_modules/
|
||||
*-workspace/
|
||||
server/build
|
||||
client/dist
|
||||
client/tsconfig.app.tsbuildinfo
|
||||
client/tsconfig.node.tsbuildinfo
|
||||
cli/build
|
||||
test-output
|
||||
|
|
|
|||
|
|
@ -1,2 +1,4 @@
|
|||
packages
|
||||
server/build
|
||||
CODE_OF_CONDUCT.md
|
||||
SECURITY.md
|
||||
|
|
|
|||
33
CLAUDE.md
Normal file
33
CLAUDE.md
Normal file
|
|
@ -0,0 +1,33 @@
|
|||
# MCP Inspector Development Guide
|
||||
|
||||
## Build Commands
|
||||
|
||||
- Build all: `npm run build`
|
||||
- Build client: `npm run build-client`
|
||||
- Build server: `npm run build-server`
|
||||
- Development mode: `npm run dev` (use `npm run dev:windows` on Windows)
|
||||
- Format code: `npm run prettier-fix`
|
||||
- Client lint: `cd client && npm run lint`
|
||||
|
||||
## Code Style Guidelines
|
||||
|
||||
- Use TypeScript with proper type annotations
|
||||
- Follow React functional component patterns with hooks
|
||||
- Use ES modules (import/export) not CommonJS
|
||||
- Use Prettier for formatting (auto-formatted on commit)
|
||||
- Follow existing naming conventions:
|
||||
- camelCase for variables and functions
|
||||
- PascalCase for component names and types
|
||||
- kebab-case for file names
|
||||
- Use async/await for asynchronous operations
|
||||
- Implement proper error handling with try/catch blocks
|
||||
- Use Tailwind CSS for styling in the client
|
||||
- Keep components small and focused on a single responsibility
|
||||
|
||||
## Project Organization
|
||||
|
||||
The project is organized as a monorepo with workspaces:
|
||||
|
||||
- `client/`: React frontend with Vite, TypeScript and Tailwind
|
||||
- `server/`: Express backend with TypeScript
|
||||
- `bin/`: CLI scripts
|
||||
|
|
@ -7,13 +7,13 @@ Thanks for your interest in contributing! This guide explains how to get involve
|
|||
1. Fork the repository and clone it locally
|
||||
2. Install dependencies with `npm install`
|
||||
3. Run `npm run dev` to start both client and server in development mode
|
||||
4. Use the web UI at http://localhost:5173 to interact with the inspector
|
||||
4. Use the web UI at http://127.0.0.1:6274 to interact with the inspector
|
||||
|
||||
## Development Process & Pull Requests
|
||||
|
||||
1. Create a new branch for your changes
|
||||
2. Make your changes following existing code style and conventions
|
||||
3. Test changes locally
|
||||
2. Make your changes following existing code style and conventions. You can run `npm run prettier-check` and `npm run prettier-fix` as applicable.
|
||||
3. Test changes locally by running `npm test`
|
||||
4. Update documentation as needed
|
||||
5. Use clear commit messages explaining your changes
|
||||
6. Verify all changes work as expected
|
||||
|
|
|
|||
232
README.md
232
README.md
|
|
@ -2,31 +2,183 @@
|
|||
|
||||
The MCP inspector is a developer tool for testing and debugging MCP servers.
|
||||
|
||||

|
||||

|
||||
|
||||
## Running the Inspector
|
||||
|
||||
### Requirements
|
||||
|
||||
- Node.js: ^22.7.5
|
||||
|
||||
### From an MCP server repository
|
||||
|
||||
To inspect an MCP server implementation, there's no need to clone this repo. Instead, use `npx`. For example, if your server is built at `build/index.js`:
|
||||
|
||||
```bash
|
||||
npx @modelcontextprotocol/inspector build/index.js
|
||||
npx @modelcontextprotocol/inspector node build/index.js
|
||||
```
|
||||
|
||||
You can also pass arguments along which will get passed as arguments to your MCP server:
|
||||
|
||||
```
|
||||
npx @modelcontextprotocol/inspector build/index.js arg1 arg2 ...
|
||||
```
|
||||
|
||||
The inspector runs both a client UI (default port 5173) and an MCP proxy server (default port 3000). Open the client UI in your browser to use the inspector. You can customize the ports if needed:
|
||||
You can pass both arguments and environment variables to your MCP server. Arguments are passed directly to your server, while environment variables can be set using the `-e` flag:
|
||||
|
||||
```bash
|
||||
CLIENT_PORT=8080 SERVER_PORT=9000 npx @modelcontextprotocol/inspector build/index.js
|
||||
# Pass arguments only
|
||||
npx @modelcontextprotocol/inspector node build/index.js arg1 arg2
|
||||
|
||||
# Pass environment variables only
|
||||
npx @modelcontextprotocol/inspector -e key=value -e key2=$VALUE2 node build/index.js
|
||||
|
||||
# Pass both environment variables and arguments
|
||||
npx @modelcontextprotocol/inspector -e key=value -e key2=$VALUE2 node build/index.js arg1 arg2
|
||||
|
||||
# Use -- to separate inspector flags from server arguments
|
||||
npx @modelcontextprotocol/inspector -e key=$VALUE -- node build/index.js -e server-flag
|
||||
```
|
||||
|
||||
For more details on ways to use the inspector, see the [Inspector section of the MCP docs site](https://modelcontextprotocol.io/docs/tools/inspector).
|
||||
The inspector runs both an MCP Inspector (MCPI) client UI (default port 6274) and an MCP Proxy (MCPP) server (default port 6277). Open the MCPI client UI in your browser to use the inspector. (These ports are derived from the T9 dialpad mapping of MCPI and MCPP respectively, as a mnemonic). You can customize the ports if needed:
|
||||
|
||||
```bash
|
||||
CLIENT_PORT=8080 SERVER_PORT=9000 npx @modelcontextprotocol/inspector node build/index.js
|
||||
```
|
||||
|
||||
For more details on ways to use the inspector, see the [Inspector section of the MCP docs site](https://modelcontextprotocol.io/docs/tools/inspector). For help with debugging, see the [Debugging guide](https://modelcontextprotocol.io/docs/tools/debugging).
|
||||
|
||||
### Servers File Export
|
||||
|
||||
The MCP Inspector provides convenient buttons to export server launch configurations for use in clients such as Cursor, Claude Code, or the Inspector's CLI. The file is usually called `mcp.json`.
|
||||
|
||||
- **Server Entry** - Copies a single server configuration entry to your clipboard. This can be added to your `mcp.json` file inside the `mcpServers` object with your preferred server name.
|
||||
|
||||
**STDIO transport example:**
|
||||
|
||||
```json
|
||||
{
|
||||
"command": "node",
|
||||
"args": ["build/index.js", "--debug"],
|
||||
"env": {
|
||||
"API_KEY": "your-api-key",
|
||||
"DEBUG": "true"
|
||||
}
|
||||
}
|
||||
```
|
||||
|
||||
**SSE transport example:**
|
||||
|
||||
```json
|
||||
{
|
||||
"type": "sse",
|
||||
"url": "http://localhost:3000/events",
|
||||
"note": "For SSE connections, add this URL directly in Client"
|
||||
}
|
||||
```
|
||||
|
||||
- **Servers File** - Copies a complete MCP configuration file structure to your clipboard, with your current server configuration added as `default-server`. This can be saved directly as `mcp.json`.
|
||||
|
||||
**STDIO transport example:**
|
||||
|
||||
```json
|
||||
{
|
||||
"mcpServers": {
|
||||
"default-server": {
|
||||
"command": "node",
|
||||
"args": ["build/index.js", "--debug"],
|
||||
"env": {
|
||||
"API_KEY": "your-api-key",
|
||||
"DEBUG": "true"
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
```
|
||||
|
||||
**SSE transport example:**
|
||||
|
||||
```json
|
||||
{
|
||||
"mcpServers": {
|
||||
"default-server": {
|
||||
"type": "sse",
|
||||
"url": "http://localhost:3000/events",
|
||||
"note": "For SSE connections, add this URL directly in Client"
|
||||
}
|
||||
}
|
||||
}
|
||||
```
|
||||
|
||||
These buttons appear in the Inspector UI after you've configured your server settings, making it easy to save and reuse your configurations.
|
||||
|
||||
For SSE transport connections, the Inspector provides similar functionality for both buttons. The "Server Entry" button copies the SSE URL configuration that can be added to your existing configuration file, while the "Servers File" button creates a complete configuration file containing the SSE URL for direct use in clients.
|
||||
|
||||
You can paste the Server Entry into your existing `mcp.json` file under your chosen server name, or use the complete Servers File payload to create a new configuration file.
|
||||
|
||||
### Authentication
|
||||
|
||||
The inspector supports bearer token authentication for SSE connections. Enter your token in the UI when connecting to an MCP server, and it will be sent in the Authorization header. You can override the header name using the input field in the sidebar.
|
||||
|
||||
### Security Considerations
|
||||
|
||||
The MCP Inspector includes a proxy server that can run and communicate with local MCP processes. The proxy server should not be exposed to untrusted networks as it has permissions to spawn local processes and can connect to any specified MCP server.
|
||||
|
||||
### Configuration
|
||||
|
||||
The MCP Inspector supports the following configuration settings. To change them, click on the `Configuration` button in the MCP Inspector UI:
|
||||
|
||||
| Setting | Description | Default |
|
||||
| --------------------------------------- | ------------------------------------------------------------------------------------------------------------- | ------- |
|
||||
| `MCP_SERVER_REQUEST_TIMEOUT` | Timeout for requests to the MCP server (ms) | 10000 |
|
||||
| `MCP_REQUEST_TIMEOUT_RESET_ON_PROGRESS` | Reset timeout on progress notifications | true |
|
||||
| `MCP_REQUEST_MAX_TOTAL_TIMEOUT` | Maximum total timeout for requests sent to the MCP server (ms) (Use with progress notifications) | 60000 |
|
||||
| `MCP_PROXY_FULL_ADDRESS` | Set this if you are running the MCP Inspector Proxy on a non-default address. Example: http://10.1.1.22:5577 | "" |
|
||||
| `MCP_AUTO_OPEN_ENABLED` | Enable automatic browser opening when inspector starts. Only as environment var, not configurable in browser. | true |
|
||||
|
||||
These settings can be adjusted in real-time through the UI and will persist across sessions.
|
||||
|
||||
The inspector also supports configuration files to store settings for different MCP servers. This is useful when working with multiple servers or complex configurations:
|
||||
|
||||
```bash
|
||||
npx @modelcontextprotocol/inspector --config path/to/config.json --server everything
|
||||
```
|
||||
|
||||
Example server configuration file:
|
||||
|
||||
```json
|
||||
{
|
||||
"mcpServers": {
|
||||
"everything": {
|
||||
"command": "npx",
|
||||
"args": ["@modelcontextprotocol/server-everything"],
|
||||
"env": {
|
||||
"hello": "Hello MCP!"
|
||||
}
|
||||
},
|
||||
"my-server": {
|
||||
"command": "node",
|
||||
"args": ["build/index.js", "arg1", "arg2"],
|
||||
"env": {
|
||||
"key": "value",
|
||||
"key2": "value2"
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
```
|
||||
|
||||
> **Tip:** You can easily generate this configuration format using the **Server Entry** and **Servers File** buttons in the Inspector UI, as described in the Servers File Export section above.
|
||||
|
||||
You can also set the initial `transport` type, `serverUrl`, `serverCommand`, and `serverArgs` via query params, for example:
|
||||
|
||||
```
|
||||
http://localhost:6274/?transport=sse&serverUrl=http://localhost:8787/sse
|
||||
http://localhost:6274/?transport=streamable-http&serverUrl=http://localhost:8787/mcp
|
||||
http://localhost:6274/?transport=stdio&serverCommand=npx&serverArgs=arg1%20arg2
|
||||
```
|
||||
|
||||
You can also set initial config settings via query params, for example:
|
||||
|
||||
```
|
||||
http://localhost:6274/?MCP_SERVER_REQUEST_TIMEOUT=10000&MCP_REQUEST_TIMEOUT_RESET_ON_PROGRESS=false&MCP_PROXY_FULL_ADDRESS=http://10.1.1.22:5577
|
||||
```
|
||||
|
||||
Note that if both the query param and the corresponding localStorage item are set, the query param will take precedence.
|
||||
|
||||
### From this repository
|
||||
|
||||
|
|
@ -38,6 +190,13 @@ Development mode:
|
|||
npm run dev
|
||||
```
|
||||
|
||||
> **Note for Windows users:**
|
||||
> On Windows, use the following command instead:
|
||||
>
|
||||
> ```bash
|
||||
> npm run dev:windows
|
||||
> ```
|
||||
|
||||
Production mode:
|
||||
|
||||
```bash
|
||||
|
|
@ -45,6 +204,57 @@ npm run build
|
|||
npm start
|
||||
```
|
||||
|
||||
### CLI Mode
|
||||
|
||||
CLI mode enables programmatic interaction with MCP servers from the command line, ideal for scripting, automation, and integration with coding assistants. This creates an efficient feedback loop for MCP server development.
|
||||
|
||||
```bash
|
||||
npx @modelcontextprotocol/inspector --cli node build/index.js
|
||||
```
|
||||
|
||||
The CLI mode supports most operations across tools, resources, and prompts. A few examples:
|
||||
|
||||
```bash
|
||||
# Basic usage
|
||||
npx @modelcontextprotocol/inspector --cli node build/index.js
|
||||
|
||||
# With config file
|
||||
npx @modelcontextprotocol/inspector --cli --config path/to/config.json --server myserver
|
||||
|
||||
# List available tools
|
||||
npx @modelcontextprotocol/inspector --cli node build/index.js --method tools/list
|
||||
|
||||
# Call a specific tool
|
||||
npx @modelcontextprotocol/inspector --cli node build/index.js --method tools/call --tool-name mytool --tool-arg key=value --tool-arg another=value2
|
||||
|
||||
# List available resources
|
||||
npx @modelcontextprotocol/inspector --cli node build/index.js --method resources/list
|
||||
|
||||
# List available prompts
|
||||
npx @modelcontextprotocol/inspector --cli node build/index.js --method prompts/list
|
||||
|
||||
# Connect to a remote MCP server
|
||||
npx @modelcontextprotocol/inspector --cli https://my-mcp-server.example.com
|
||||
|
||||
# Call a tool on a remote server
|
||||
npx @modelcontextprotocol/inspector --cli https://my-mcp-server.example.com --method tools/call --tool-name remotetool --tool-arg param=value
|
||||
|
||||
# List resources from a remote server
|
||||
npx @modelcontextprotocol/inspector --cli https://my-mcp-server.example.com --method resources/list
|
||||
```
|
||||
|
||||
### UI Mode vs CLI Mode: When to Use Each
|
||||
|
||||
| Use Case | UI Mode | CLI Mode |
|
||||
| ------------------------ | ------------------------------------------------------------------------- | ---------------------------------------------------------------------------------------------------------------------------------------------------- |
|
||||
| **Server Development** | Visual interface for interactive testing and debugging during development | Scriptable commands for quick testing and continuous integration; creates feedback loops with AI coding assistants like Cursor for rapid development |
|
||||
| **Resource Exploration** | Interactive browser with hierarchical navigation and JSON visualization | Programmatic listing and reading for automation and scripting |
|
||||
| **Tool Testing** | Form-based parameter input with real-time response visualization | Command-line tool execution with JSON output for scripting |
|
||||
| **Prompt Engineering** | Interactive sampling with streaming responses and visual comparison | Batch processing of prompts with machine-readable output |
|
||||
| **Debugging** | Request history, visualized errors, and real-time notifications | Direct JSON output for log analysis and integration with other tools |
|
||||
| **Automation** | N/A | Ideal for CI/CD pipelines, batch processing, and integration with coding assistants |
|
||||
| **Learning MCP** | Rich visual interface helps new users understand server capabilities | Simplified commands for focused learning of specific endpoints |
|
||||
|
||||
## License
|
||||
|
||||
This project is licensed under the MIT License—see the [LICENSE](LICENSE) file for details.
|
||||
|
|
|
|||
88
bin/cli.js
88
bin/cli.js
|
|
@ -1,88 +0,0 @@
|
|||
#!/usr/bin/env node
|
||||
|
||||
import { resolve, dirname } from "path";
|
||||
import { spawnPromise } from "spawn-rx";
|
||||
import { fileURLToPath } from "url";
|
||||
|
||||
const __dirname = dirname(fileURLToPath(import.meta.url));
|
||||
|
||||
function delay(ms) {
|
||||
return new Promise((resolve) => setTimeout(resolve, ms));
|
||||
}
|
||||
|
||||
async function main() {
|
||||
// Get command line arguments
|
||||
const [, , command, ...mcpServerArgs] = process.argv;
|
||||
|
||||
const inspectorServerPath = resolve(
|
||||
__dirname,
|
||||
"..",
|
||||
"server",
|
||||
"build",
|
||||
"index.js",
|
||||
);
|
||||
|
||||
// Path to the client entry point
|
||||
const inspectorClientPath = resolve(
|
||||
__dirname,
|
||||
"..",
|
||||
"client",
|
||||
"bin",
|
||||
"cli.js",
|
||||
);
|
||||
|
||||
const CLIENT_PORT = process.env.CLIENT_PORT ?? "5173";
|
||||
const SERVER_PORT = process.env.SERVER_PORT ?? "3000";
|
||||
|
||||
console.log("Starting MCP inspector...");
|
||||
|
||||
const abort = new AbortController();
|
||||
|
||||
let cancelled = false;
|
||||
process.on("SIGINT", () => {
|
||||
cancelled = true;
|
||||
abort.abort();
|
||||
});
|
||||
|
||||
const server = spawnPromise(
|
||||
"node",
|
||||
[
|
||||
inspectorServerPath,
|
||||
...(command ? [`--env`, command] : []),
|
||||
...(mcpServerArgs ? [`--args=${mcpServerArgs.join(" ")}`] : []),
|
||||
],
|
||||
{
|
||||
env: { ...process.env, PORT: SERVER_PORT },
|
||||
signal: abort.signal,
|
||||
echoOutput: true,
|
||||
},
|
||||
);
|
||||
|
||||
const client = spawnPromise("node", [inspectorClientPath], {
|
||||
env: { ...process.env, PORT: CLIENT_PORT },
|
||||
signal: abort.signal,
|
||||
echoOutput: true,
|
||||
});
|
||||
|
||||
// Make sure our server/client didn't immediately fail
|
||||
await Promise.any([server, client, delay(2 * 1000)]);
|
||||
const portParam = SERVER_PORT === "3000" ? "" : `?proxyPort=${SERVER_PORT}`;
|
||||
console.log(
|
||||
`\n🔍 MCP Inspector is up and running at http://localhost:${CLIENT_PORT}${portParam} 🚀`,
|
||||
);
|
||||
|
||||
try {
|
||||
await Promise.any([server, client]);
|
||||
} catch (e) {
|
||||
if (!cancelled || process.env.DEBUG) throw e;
|
||||
}
|
||||
|
||||
return 0;
|
||||
}
|
||||
|
||||
main()
|
||||
.then((_) => process.exit(0))
|
||||
.catch((e) => {
|
||||
console.error(e);
|
||||
process.exit(1);
|
||||
});
|
||||
28
cli/package.json
Normal file
28
cli/package.json
Normal file
|
|
@ -0,0 +1,28 @@
|
|||
{
|
||||
"name": "@modelcontextprotocol/inspector-cli",
|
||||
"version": "0.13.0",
|
||||
"description": "CLI for the Model Context Protocol inspector",
|
||||
"license": "MIT",
|
||||
"author": "Anthropic, PBC (https://anthropic.com)",
|
||||
"homepage": "https://modelcontextprotocol.io",
|
||||
"bugs": "https://github.com/modelcontextprotocol/inspector/issues",
|
||||
"main": "build/cli.js",
|
||||
"type": "module",
|
||||
"bin": {
|
||||
"mcp-inspector-cli": "build/cli.js"
|
||||
},
|
||||
"files": [
|
||||
"build"
|
||||
],
|
||||
"scripts": {
|
||||
"build": "tsc",
|
||||
"postbuild": "node scripts/make-executable.js",
|
||||
"test": "node scripts/cli-tests.js"
|
||||
},
|
||||
"devDependencies": {},
|
||||
"dependencies": {
|
||||
"@modelcontextprotocol/sdk": "^1.11.5",
|
||||
"commander": "^13.1.0",
|
||||
"spawn-rx": "^5.1.2"
|
||||
}
|
||||
}
|
||||
633
cli/scripts/cli-tests.js
Executable file
633
cli/scripts/cli-tests.js
Executable file
|
|
@ -0,0 +1,633 @@
|
|||
#!/usr/bin/env node
|
||||
|
||||
// Colors for output
|
||||
const colors = {
|
||||
GREEN: "\x1b[32m",
|
||||
YELLOW: "\x1b[33m",
|
||||
RED: "\x1b[31m",
|
||||
BLUE: "\x1b[34m",
|
||||
ORANGE: "\x1b[33m",
|
||||
NC: "\x1b[0m", // No Color
|
||||
};
|
||||
|
||||
import fs from "fs";
|
||||
import path from "path";
|
||||
import { execSync, spawn } from "child_process";
|
||||
import os from "os";
|
||||
import { fileURLToPath } from "url";
|
||||
|
||||
// Get directory paths with ESM compatibility
|
||||
const __filename = fileURLToPath(import.meta.url);
|
||||
const __dirname = path.dirname(__filename);
|
||||
|
||||
// Track test results
|
||||
let PASSED_TESTS = 0;
|
||||
let FAILED_TESTS = 0;
|
||||
let SKIPPED_TESTS = 0;
|
||||
let TOTAL_TESTS = 0;
|
||||
|
||||
console.log(
|
||||
`${colors.YELLOW}=== MCP Inspector CLI Test Script ===${colors.NC}`,
|
||||
);
|
||||
console.log(
|
||||
`${colors.BLUE}This script tests the MCP Inspector CLI's ability to handle various command line options:${colors.NC}`,
|
||||
);
|
||||
console.log(`${colors.BLUE}- Basic CLI mode${colors.NC}`);
|
||||
console.log(`${colors.BLUE}- Environment variables (-e)${colors.NC}`);
|
||||
console.log(`${colors.BLUE}- Config file (--config)${colors.NC}`);
|
||||
console.log(`${colors.BLUE}- Server selection (--server)${colors.NC}`);
|
||||
console.log(`${colors.BLUE}- Method selection (--method)${colors.NC}`);
|
||||
console.log(
|
||||
`${colors.BLUE}- Tool-related options (--tool-name, --tool-arg)${colors.NC}`,
|
||||
);
|
||||
console.log(`${colors.BLUE}- Resource-related options (--uri)${colors.NC}`);
|
||||
console.log(
|
||||
`${colors.BLUE}- Prompt-related options (--prompt-name, --prompt-args)${colors.NC}`,
|
||||
);
|
||||
console.log(`${colors.BLUE}- Logging options (--log-level)${colors.NC}\n`);
|
||||
|
||||
// Get directory paths
|
||||
const SCRIPTS_DIR = __dirname;
|
||||
const PROJECT_ROOT = path.join(SCRIPTS_DIR, "../../");
|
||||
const BUILD_DIR = path.resolve(SCRIPTS_DIR, "../build");
|
||||
|
||||
// Define the test server command using npx
|
||||
const TEST_CMD = "npx";
|
||||
const TEST_ARGS = ["@modelcontextprotocol/server-everything"];
|
||||
|
||||
// Create output directory for test results
|
||||
const OUTPUT_DIR = path.join(SCRIPTS_DIR, "test-output");
|
||||
if (!fs.existsSync(OUTPUT_DIR)) {
|
||||
fs.mkdirSync(OUTPUT_DIR, { recursive: true });
|
||||
}
|
||||
|
||||
// Create a temporary directory for test files
|
||||
const TEMP_DIR = fs.mkdirSync(path.join(os.tmpdir(), "mcp-inspector-tests"), {
|
||||
recursive: true,
|
||||
});
|
||||
|
||||
process.on("exit", () => {
|
||||
try {
|
||||
fs.rmSync(TEMP_DIR, { recursive: true, force: true });
|
||||
} catch (err) {
|
||||
console.error(
|
||||
`${colors.RED}Failed to remove temp directory: ${err.message}${colors.NC}`,
|
||||
);
|
||||
}
|
||||
});
|
||||
|
||||
// Use the existing sample config file
|
||||
console.log(
|
||||
`${colors.BLUE}Using existing sample config file: ${PROJECT_ROOT}/sample-config.json${colors.NC}`,
|
||||
);
|
||||
try {
|
||||
const sampleConfig = fs.readFileSync(
|
||||
path.join(PROJECT_ROOT, "sample-config.json"),
|
||||
"utf8",
|
||||
);
|
||||
console.log(sampleConfig);
|
||||
} catch (error) {
|
||||
console.error(
|
||||
`${colors.RED}Error reading sample config: ${error.message}${colors.NC}`,
|
||||
);
|
||||
}
|
||||
|
||||
// Create an invalid config file for testing
|
||||
const invalidConfigPath = path.join(TEMP_DIR, "invalid-config.json");
|
||||
fs.writeFileSync(invalidConfigPath, '{\n "mcpServers": {\n "invalid": {');
|
||||
|
||||
// Function to run a basic test
|
||||
async function runBasicTest(testName, ...args) {
|
||||
const outputFile = path.join(
|
||||
OUTPUT_DIR,
|
||||
`${testName.replace(/\//g, "_")}.log`,
|
||||
);
|
||||
|
||||
console.log(`\n${colors.YELLOW}Testing: ${testName}${colors.NC}`);
|
||||
TOTAL_TESTS++;
|
||||
|
||||
// Run the command and capture output
|
||||
console.log(
|
||||
`${colors.BLUE}Command: node ${BUILD_DIR}/cli.js ${args.join(" ")}${colors.NC}`,
|
||||
);
|
||||
|
||||
try {
|
||||
// Create a write stream for the output file
|
||||
const outputStream = fs.createWriteStream(outputFile);
|
||||
|
||||
// Spawn the process
|
||||
return new Promise((resolve) => {
|
||||
const child = spawn("node", [path.join(BUILD_DIR, "cli.js"), ...args], {
|
||||
stdio: ["ignore", "pipe", "pipe"],
|
||||
});
|
||||
|
||||
// Pipe stdout and stderr to the output file
|
||||
child.stdout.pipe(outputStream);
|
||||
child.stderr.pipe(outputStream);
|
||||
|
||||
// Also capture output for display
|
||||
let output = "";
|
||||
child.stdout.on("data", (data) => {
|
||||
output += data.toString();
|
||||
});
|
||||
child.stderr.on("data", (data) => {
|
||||
output += data.toString();
|
||||
});
|
||||
|
||||
child.on("close", (code) => {
|
||||
outputStream.end();
|
||||
|
||||
if (code === 0) {
|
||||
console.log(`${colors.GREEN}✓ Test passed: ${testName}${colors.NC}`);
|
||||
console.log(`${colors.BLUE}First few lines of output:${colors.NC}`);
|
||||
const firstFewLines = output
|
||||
.split("\n")
|
||||
.slice(0, 5)
|
||||
.map((line) => ` ${line}`)
|
||||
.join("\n");
|
||||
console.log(firstFewLines);
|
||||
PASSED_TESTS++;
|
||||
resolve(true);
|
||||
} else {
|
||||
console.log(`${colors.RED}✗ Test failed: ${testName}${colors.NC}`);
|
||||
console.log(`${colors.RED}Error output:${colors.NC}`);
|
||||
console.log(
|
||||
output
|
||||
.split("\n")
|
||||
.map((line) => ` ${line}`)
|
||||
.join("\n"),
|
||||
);
|
||||
FAILED_TESTS++;
|
||||
|
||||
// Stop after any error is encountered
|
||||
console.log(
|
||||
`${colors.YELLOW}Stopping tests due to error. Please validate and fix before continuing.${colors.NC}`,
|
||||
);
|
||||
process.exit(1);
|
||||
}
|
||||
});
|
||||
});
|
||||
} catch (error) {
|
||||
console.error(
|
||||
`${colors.RED}Error running test: ${error.message}${colors.NC}`,
|
||||
);
|
||||
FAILED_TESTS++;
|
||||
process.exit(1);
|
||||
}
|
||||
}
|
||||
|
||||
// Function to run an error test (expected to fail)
|
||||
async function runErrorTest(testName, ...args) {
|
||||
const outputFile = path.join(
|
||||
OUTPUT_DIR,
|
||||
`${testName.replace(/\//g, "_")}.log`,
|
||||
);
|
||||
|
||||
console.log(`\n${colors.YELLOW}Testing error case: ${testName}${colors.NC}`);
|
||||
TOTAL_TESTS++;
|
||||
|
||||
// Run the command and capture output
|
||||
console.log(
|
||||
`${colors.BLUE}Command: node ${BUILD_DIR}/cli.js ${args.join(" ")}${colors.NC}`,
|
||||
);
|
||||
|
||||
try {
|
||||
// Create a write stream for the output file
|
||||
const outputStream = fs.createWriteStream(outputFile);
|
||||
|
||||
// Spawn the process
|
||||
return new Promise((resolve) => {
|
||||
const child = spawn("node", [path.join(BUILD_DIR, "cli.js"), ...args], {
|
||||
stdio: ["ignore", "pipe", "pipe"],
|
||||
});
|
||||
|
||||
// Pipe stdout and stderr to the output file
|
||||
child.stdout.pipe(outputStream);
|
||||
child.stderr.pipe(outputStream);
|
||||
|
||||
// Also capture output for display
|
||||
let output = "";
|
||||
child.stdout.on("data", (data) => {
|
||||
output += data.toString();
|
||||
});
|
||||
child.stderr.on("data", (data) => {
|
||||
output += data.toString();
|
||||
});
|
||||
|
||||
child.on("close", (code) => {
|
||||
outputStream.end();
|
||||
|
||||
// For error tests, we expect a non-zero exit code
|
||||
if (code !== 0) {
|
||||
console.log(
|
||||
`${colors.GREEN}✓ Error test passed: ${testName}${colors.NC}`,
|
||||
);
|
||||
console.log(`${colors.BLUE}Error output (expected):${colors.NC}`);
|
||||
const firstFewLines = output
|
||||
.split("\n")
|
||||
.slice(0, 5)
|
||||
.map((line) => ` ${line}`)
|
||||
.join("\n");
|
||||
console.log(firstFewLines);
|
||||
PASSED_TESTS++;
|
||||
resolve(true);
|
||||
} else {
|
||||
console.log(
|
||||
`${colors.RED}✗ Error test failed: ${testName} (expected error but got success)${colors.NC}`,
|
||||
);
|
||||
console.log(`${colors.RED}Output:${colors.NC}`);
|
||||
console.log(
|
||||
output
|
||||
.split("\n")
|
||||
.map((line) => ` ${line}`)
|
||||
.join("\n"),
|
||||
);
|
||||
FAILED_TESTS++;
|
||||
|
||||
// Stop after any error is encountered
|
||||
console.log(
|
||||
`${colors.YELLOW}Stopping tests due to error. Please validate and fix before continuing.${colors.NC}`,
|
||||
);
|
||||
process.exit(1);
|
||||
}
|
||||
});
|
||||
});
|
||||
} catch (error) {
|
||||
console.error(
|
||||
`${colors.RED}Error running test: ${error.message}${colors.NC}`,
|
||||
);
|
||||
FAILED_TESTS++;
|
||||
process.exit(1);
|
||||
}
|
||||
}
|
||||
|
||||
// Run all tests
|
||||
async function runTests() {
|
||||
console.log(
|
||||
`\n${colors.YELLOW}=== Running Basic CLI Mode Tests ===${colors.NC}`,
|
||||
);
|
||||
|
||||
// Test 1: Basic CLI mode with method
|
||||
await runBasicTest(
|
||||
"basic_cli_mode",
|
||||
TEST_CMD,
|
||||
...TEST_ARGS,
|
||||
"--cli",
|
||||
"--method",
|
||||
"tools/list",
|
||||
);
|
||||
|
||||
// Test 2: CLI mode with non-existent method (should fail)
|
||||
await runErrorTest(
|
||||
"nonexistent_method",
|
||||
TEST_CMD,
|
||||
...TEST_ARGS,
|
||||
"--cli",
|
||||
"--method",
|
||||
"nonexistent/method",
|
||||
);
|
||||
|
||||
// Test 3: CLI mode without method (should fail)
|
||||
await runErrorTest("missing_method", TEST_CMD, ...TEST_ARGS, "--cli");
|
||||
|
||||
console.log(
|
||||
`\n${colors.YELLOW}=== Running Environment Variable Tests ===${colors.NC}`,
|
||||
);
|
||||
|
||||
// Test 4: CLI mode with environment variables
|
||||
await runBasicTest(
|
||||
"env_variables",
|
||||
TEST_CMD,
|
||||
...TEST_ARGS,
|
||||
"-e",
|
||||
"KEY1=value1",
|
||||
"-e",
|
||||
"KEY2=value2",
|
||||
"--cli",
|
||||
"--method",
|
||||
"tools/list",
|
||||
);
|
||||
|
||||
// Test 5: CLI mode with invalid environment variable format (should fail)
|
||||
await runErrorTest(
|
||||
"invalid_env_format",
|
||||
TEST_CMD,
|
||||
...TEST_ARGS,
|
||||
"-e",
|
||||
"INVALID_FORMAT",
|
||||
"--cli",
|
||||
"--method",
|
||||
"tools/list",
|
||||
);
|
||||
|
||||
// Test 5b: CLI mode with environment variable containing equals sign in value
|
||||
await runBasicTest(
|
||||
"env_variable_with_equals",
|
||||
TEST_CMD,
|
||||
...TEST_ARGS,
|
||||
"-e",
|
||||
"API_KEY=abc123=xyz789==",
|
||||
"--cli",
|
||||
"--method",
|
||||
"tools/list",
|
||||
);
|
||||
|
||||
// Test 5c: CLI mode with environment variable containing base64-encoded value
|
||||
await runBasicTest(
|
||||
"env_variable_with_base64",
|
||||
TEST_CMD,
|
||||
...TEST_ARGS,
|
||||
"-e",
|
||||
"JWT_TOKEN=eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJzdWIiOiIxMjM0NTY3ODkwIn0=",
|
||||
"--cli",
|
||||
"--method",
|
||||
"tools/list",
|
||||
);
|
||||
|
||||
console.log(
|
||||
`\n${colors.YELLOW}=== Running Config File Tests ===${colors.NC}`,
|
||||
);
|
||||
|
||||
// Test 6: Using config file with CLI mode
|
||||
await runBasicTest(
|
||||
"config_file",
|
||||
"--config",
|
||||
path.join(PROJECT_ROOT, "sample-config.json"),
|
||||
"--server",
|
||||
"everything",
|
||||
"--cli",
|
||||
"--method",
|
||||
"tools/list",
|
||||
);
|
||||
|
||||
// Test 7: Using config file without server name (should fail)
|
||||
await runErrorTest(
|
||||
"config_without_server",
|
||||
"--config",
|
||||
path.join(PROJECT_ROOT, "sample-config.json"),
|
||||
"--cli",
|
||||
"--method",
|
||||
"tools/list",
|
||||
);
|
||||
|
||||
// Test 8: Using server name without config file (should fail)
|
||||
await runErrorTest(
|
||||
"server_without_config",
|
||||
"--server",
|
||||
"everything",
|
||||
"--cli",
|
||||
"--method",
|
||||
"tools/list",
|
||||
);
|
||||
|
||||
// Test 9: Using non-existent config file (should fail)
|
||||
await runErrorTest(
|
||||
"nonexistent_config",
|
||||
"--config",
|
||||
"./nonexistent-config.json",
|
||||
"--server",
|
||||
"everything",
|
||||
"--cli",
|
||||
"--method",
|
||||
"tools/list",
|
||||
);
|
||||
|
||||
// Test 10: Using invalid config file format (should fail)
|
||||
await runErrorTest(
|
||||
"invalid_config",
|
||||
"--config",
|
||||
invalidConfigPath,
|
||||
"--server",
|
||||
"everything",
|
||||
"--cli",
|
||||
"--method",
|
||||
"tools/list",
|
||||
);
|
||||
|
||||
// Test 11: Using config file with non-existent server (should fail)
|
||||
await runErrorTest(
|
||||
"nonexistent_server",
|
||||
"--config",
|
||||
path.join(PROJECT_ROOT, "sample-config.json"),
|
||||
"--server",
|
||||
"nonexistent",
|
||||
"--cli",
|
||||
"--method",
|
||||
"tools/list",
|
||||
);
|
||||
|
||||
console.log(
|
||||
`\n${colors.YELLOW}=== Running Tool-Related Tests ===${colors.NC}`,
|
||||
);
|
||||
|
||||
// Test 12: CLI mode with tool call
|
||||
await runBasicTest(
|
||||
"tool_call",
|
||||
TEST_CMD,
|
||||
...TEST_ARGS,
|
||||
"--cli",
|
||||
"--method",
|
||||
"tools/call",
|
||||
"--tool-name",
|
||||
"echo",
|
||||
"--tool-arg",
|
||||
"message=Hello",
|
||||
);
|
||||
|
||||
// Test 13: CLI mode with tool call but missing tool name (should fail)
|
||||
await runErrorTest(
|
||||
"missing_tool_name",
|
||||
TEST_CMD,
|
||||
...TEST_ARGS,
|
||||
"--cli",
|
||||
"--method",
|
||||
"tools/call",
|
||||
"--tool-arg",
|
||||
"message=Hello",
|
||||
);
|
||||
|
||||
// Test 14: CLI mode with tool call but invalid tool args format (should fail)
|
||||
await runErrorTest(
|
||||
"invalid_tool_args",
|
||||
TEST_CMD,
|
||||
...TEST_ARGS,
|
||||
"--cli",
|
||||
"--method",
|
||||
"tools/call",
|
||||
"--tool-name",
|
||||
"echo",
|
||||
"--tool-arg",
|
||||
"invalid_format",
|
||||
);
|
||||
|
||||
// Test 15: CLI mode with multiple tool args
|
||||
await runBasicTest(
|
||||
"multiple_tool_args",
|
||||
TEST_CMD,
|
||||
...TEST_ARGS,
|
||||
"--cli",
|
||||
"--method",
|
||||
"tools/call",
|
||||
"--tool-name",
|
||||
"add",
|
||||
"--tool-arg",
|
||||
"a=1",
|
||||
"b=2",
|
||||
);
|
||||
|
||||
console.log(
|
||||
`\n${colors.YELLOW}=== Running Resource-Related Tests ===${colors.NC}`,
|
||||
);
|
||||
|
||||
// Test 16: CLI mode with resource read
|
||||
await runBasicTest(
|
||||
"resource_read",
|
||||
TEST_CMD,
|
||||
...TEST_ARGS,
|
||||
"--cli",
|
||||
"--method",
|
||||
"resources/read",
|
||||
"--uri",
|
||||
"test://static/resource/1",
|
||||
);
|
||||
|
||||
// Test 17: CLI mode with resource read but missing URI (should fail)
|
||||
await runErrorTest(
|
||||
"missing_uri",
|
||||
TEST_CMD,
|
||||
...TEST_ARGS,
|
||||
"--cli",
|
||||
"--method",
|
||||
"resources/read",
|
||||
);
|
||||
|
||||
console.log(
|
||||
`\n${colors.YELLOW}=== Running Prompt-Related Tests ===${colors.NC}`,
|
||||
);
|
||||
|
||||
// Test 18: CLI mode with prompt get
|
||||
await runBasicTest(
|
||||
"prompt_get",
|
||||
TEST_CMD,
|
||||
...TEST_ARGS,
|
||||
"--cli",
|
||||
"--method",
|
||||
"prompts/get",
|
||||
"--prompt-name",
|
||||
"simple_prompt",
|
||||
);
|
||||
|
||||
// Test 19: CLI mode with prompt get and args
|
||||
await runBasicTest(
|
||||
"prompt_get_with_args",
|
||||
TEST_CMD,
|
||||
...TEST_ARGS,
|
||||
"--cli",
|
||||
"--method",
|
||||
"prompts/get",
|
||||
"--prompt-name",
|
||||
"complex_prompt",
|
||||
"--prompt-args",
|
||||
"temperature=0.7",
|
||||
"style=concise",
|
||||
);
|
||||
|
||||
// Test 20: CLI mode with prompt get but missing prompt name (should fail)
|
||||
await runErrorTest(
|
||||
"missing_prompt_name",
|
||||
TEST_CMD,
|
||||
...TEST_ARGS,
|
||||
"--cli",
|
||||
"--method",
|
||||
"prompts/get",
|
||||
);
|
||||
|
||||
console.log(`\n${colors.YELLOW}=== Running Logging Tests ===${colors.NC}`);
|
||||
|
||||
// Test 21: CLI mode with log level
|
||||
await runBasicTest(
|
||||
"log_level",
|
||||
TEST_CMD,
|
||||
...TEST_ARGS,
|
||||
"--cli",
|
||||
"--method",
|
||||
"logging/setLevel",
|
||||
"--log-level",
|
||||
"debug",
|
||||
);
|
||||
|
||||
// Test 22: CLI mode with invalid log level (should fail)
|
||||
await runErrorTest(
|
||||
"invalid_log_level",
|
||||
TEST_CMD,
|
||||
...TEST_ARGS,
|
||||
"--cli",
|
||||
"--method",
|
||||
"logging/setLevel",
|
||||
"--log-level",
|
||||
"invalid",
|
||||
);
|
||||
|
||||
console.log(
|
||||
`\n${colors.YELLOW}=== Running Combined Option Tests ===${colors.NC}`,
|
||||
);
|
||||
|
||||
// Note about the combined options issue
|
||||
console.log(
|
||||
`${colors.BLUE}Testing combined options with environment variables and config file.${colors.NC}`,
|
||||
);
|
||||
|
||||
// Test 23: CLI mode with config file, environment variables, and tool call
|
||||
await runBasicTest(
|
||||
"combined_options",
|
||||
"--config",
|
||||
path.join(PROJECT_ROOT, "sample-config.json"),
|
||||
"--server",
|
||||
"everything",
|
||||
"-e",
|
||||
"CLI_ENV_VAR=cli_value",
|
||||
"--cli",
|
||||
"--method",
|
||||
"tools/list",
|
||||
);
|
||||
|
||||
// Test 24: CLI mode with all possible options (that make sense together)
|
||||
await runBasicTest(
|
||||
"all_options",
|
||||
"--config",
|
||||
path.join(PROJECT_ROOT, "sample-config.json"),
|
||||
"--server",
|
||||
"everything",
|
||||
"-e",
|
||||
"CLI_ENV_VAR=cli_value",
|
||||
"--cli",
|
||||
"--method",
|
||||
"tools/call",
|
||||
"--tool-name",
|
||||
"echo",
|
||||
"--tool-arg",
|
||||
"message=Hello",
|
||||
"--log-level",
|
||||
"debug",
|
||||
);
|
||||
|
||||
// Print test summary
|
||||
console.log(`\n${colors.YELLOW}=== Test Summary ===${colors.NC}`);
|
||||
console.log(`${colors.GREEN}Passed: ${PASSED_TESTS}${colors.NC}`);
|
||||
console.log(`${colors.RED}Failed: ${FAILED_TESTS}${colors.NC}`);
|
||||
console.log(`${colors.ORANGE}Skipped: ${SKIPPED_TESTS}${colors.NC}`);
|
||||
console.log(`Total: ${TOTAL_TESTS}`);
|
||||
console.log(
|
||||
`${colors.BLUE}Detailed logs saved to: ${OUTPUT_DIR}${colors.NC}`,
|
||||
);
|
||||
|
||||
console.log(`\n${colors.GREEN}All tests completed!${colors.NC}`);
|
||||
}
|
||||
|
||||
// Run all tests
|
||||
runTests().catch((error) => {
|
||||
console.error(
|
||||
`${colors.RED}Tests failed with error: ${error.message}${colors.NC}`,
|
||||
);
|
||||
process.exit(1);
|
||||
});
|
||||
29
cli/scripts/make-executable.js
Executable file
29
cli/scripts/make-executable.js
Executable file
|
|
@ -0,0 +1,29 @@
|
|||
/**
|
||||
* Cross-platform script to make a file executable
|
||||
*/
|
||||
import { promises as fs } from "fs";
|
||||
import { platform } from "os";
|
||||
import { execSync } from "child_process";
|
||||
import path from "path";
|
||||
|
||||
const TARGET_FILE = path.resolve("build/cli.js");
|
||||
|
||||
async function makeExecutable() {
|
||||
try {
|
||||
// On Unix-like systems (Linux, macOS), use chmod
|
||||
if (platform() !== "win32") {
|
||||
execSync(`chmod +x "${TARGET_FILE}"`);
|
||||
console.log("Made file executable with chmod");
|
||||
} else {
|
||||
// On Windows, no need to make files "executable" in the Unix sense
|
||||
// Just ensure the file exists
|
||||
await fs.access(TARGET_FILE);
|
||||
console.log("File exists and is accessible on Windows");
|
||||
}
|
||||
} catch (error) {
|
||||
console.error("Error making file executable:", error);
|
||||
process.exit(1);
|
||||
}
|
||||
}
|
||||
|
||||
makeExecutable();
|
||||
287
cli/src/cli.ts
Normal file
287
cli/src/cli.ts
Normal file
|
|
@ -0,0 +1,287 @@
|
|||
#!/usr/bin/env node
|
||||
|
||||
import { Command } from "commander";
|
||||
import fs from "node:fs";
|
||||
import path from "node:path";
|
||||
import { dirname, resolve } from "path";
|
||||
import { spawnPromise } from "spawn-rx";
|
||||
import { fileURLToPath } from "url";
|
||||
|
||||
const __dirname = dirname(fileURLToPath(import.meta.url));
|
||||
|
||||
type Args = {
|
||||
command: string;
|
||||
args: string[];
|
||||
envArgs: Record<string, string>;
|
||||
cli: boolean;
|
||||
};
|
||||
|
||||
type CliOptions = {
|
||||
e?: Record<string, string>;
|
||||
config?: string;
|
||||
server?: string;
|
||||
cli?: boolean;
|
||||
};
|
||||
|
||||
type ServerConfig = {
|
||||
command: string;
|
||||
args?: string[];
|
||||
env?: Record<string, string>;
|
||||
};
|
||||
|
||||
function handleError(error: unknown): never {
|
||||
let message: string;
|
||||
|
||||
if (error instanceof Error) {
|
||||
message = error.message;
|
||||
} else if (typeof error === "string") {
|
||||
message = error;
|
||||
} else {
|
||||
message = "Unknown error";
|
||||
}
|
||||
|
||||
console.error(message);
|
||||
|
||||
process.exit(1);
|
||||
}
|
||||
|
||||
function delay(ms: number): Promise<void> {
|
||||
return new Promise((resolve) => setTimeout(resolve, ms, true));
|
||||
}
|
||||
|
||||
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",
|
||||
);
|
||||
|
||||
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", () => {
|
||||
cancelled = true;
|
||||
abort.abort();
|
||||
});
|
||||
|
||||
let server: ReturnType<typeof spawnPromise>;
|
||||
let serverOk: unknown;
|
||||
|
||||
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;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
async function runCli(args: Args): Promise<void> {
|
||||
const projectRoot = resolve(__dirname, "..");
|
||||
const cliPath = resolve(projectRoot, "build", "index.js");
|
||||
|
||||
const abort = new AbortController();
|
||||
|
||||
let cancelled = false;
|
||||
|
||||
process.on("SIGINT", () => {
|
||||
cancelled = true;
|
||||
abort.abort();
|
||||
});
|
||||
|
||||
try {
|
||||
await spawnPromise("node", [cliPath, args.command, ...args.args], {
|
||||
env: { ...process.env, ...args.envArgs },
|
||||
signal: abort.signal,
|
||||
echoOutput: true,
|
||||
});
|
||||
} catch (e) {
|
||||
if (!cancelled || process.env.DEBUG) {
|
||||
throw e;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
function loadConfigFile(configPath: string, serverName: string): ServerConfig {
|
||||
try {
|
||||
const resolvedConfigPath = path.isAbsolute(configPath)
|
||||
? configPath
|
||||
: path.resolve(process.cwd(), configPath);
|
||||
|
||||
if (!fs.existsSync(resolvedConfigPath)) {
|
||||
throw new Error(`Config file not found: ${resolvedConfigPath}`);
|
||||
}
|
||||
|
||||
const configContent = fs.readFileSync(resolvedConfigPath, "utf8");
|
||||
const parsedConfig = JSON.parse(configContent);
|
||||
|
||||
if (!parsedConfig.mcpServers || !parsedConfig.mcpServers[serverName]) {
|
||||
const availableServers = Object.keys(parsedConfig.mcpServers || {}).join(
|
||||
", ",
|
||||
);
|
||||
throw new Error(
|
||||
`Server '${serverName}' not found in config file. Available servers: ${availableServers}`,
|
||||
);
|
||||
}
|
||||
|
||||
const serverConfig = parsedConfig.mcpServers[serverName];
|
||||
|
||||
return serverConfig;
|
||||
} catch (err: unknown) {
|
||||
if (err instanceof SyntaxError) {
|
||||
throw new Error(`Invalid JSON in config file: ${err.message}`);
|
||||
}
|
||||
|
||||
throw err;
|
||||
}
|
||||
}
|
||||
|
||||
function parseKeyValuePair(
|
||||
value: string,
|
||||
previous: Record<string, string> = {},
|
||||
): Record<string, string> {
|
||||
const parts = value.split("=");
|
||||
const key = parts[0];
|
||||
const val = parts.slice(1).join("=");
|
||||
|
||||
if (val === undefined || val === "") {
|
||||
throw new Error(
|
||||
`Invalid parameter format: ${value}. Use key=value format.`,
|
||||
);
|
||||
}
|
||||
|
||||
return { ...previous, [key as string]: val };
|
||||
}
|
||||
|
||||
function parseArgs(): Args {
|
||||
const program = new Command();
|
||||
|
||||
const argSeparatorIndex = process.argv.indexOf("--");
|
||||
let preArgs = process.argv;
|
||||
let postArgs: string[] = [];
|
||||
|
||||
if (argSeparatorIndex !== -1) {
|
||||
preArgs = process.argv.slice(0, argSeparatorIndex);
|
||||
postArgs = process.argv.slice(argSeparatorIndex + 1);
|
||||
}
|
||||
|
||||
program
|
||||
.name("inspector-bin")
|
||||
.allowExcessArguments()
|
||||
.allowUnknownOption()
|
||||
.option(
|
||||
"-e <env>",
|
||||
"environment variables in KEY=VALUE format",
|
||||
parseKeyValuePair,
|
||||
{},
|
||||
)
|
||||
.option("--config <path>", "config file path")
|
||||
.option("--server <n>", "server name from config file")
|
||||
.option("--cli", "enable CLI mode");
|
||||
|
||||
// Parse only the arguments before --
|
||||
program.parse(preArgs);
|
||||
|
||||
const options = program.opts() as CliOptions;
|
||||
const remainingArgs = program.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.",
|
||||
);
|
||||
}
|
||||
|
||||
// If config file is specified, load and use the options from the file. We must merge the args
|
||||
// from the command line and the file together, or we will miss the method options (--method,
|
||||
// etc.)
|
||||
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,
|
||||
};
|
||||
}
|
||||
|
||||
// Otherwise use command line arguments
|
||||
const command = finalArgs[0] || "";
|
||||
const args = finalArgs.slice(1);
|
||||
|
||||
return {
|
||||
command,
|
||||
args,
|
||||
envArgs: options.e || {},
|
||||
cli: options.cli || false,
|
||||
};
|
||||
}
|
||||
|
||||
async function main(): Promise<void> {
|
||||
process.on("uncaughtException", (error) => {
|
||||
handleError(error);
|
||||
});
|
||||
|
||||
try {
|
||||
const args = parseArgs();
|
||||
|
||||
if (args.cli) {
|
||||
runCli(args);
|
||||
} else {
|
||||
await runWebClient(args);
|
||||
}
|
||||
} catch (error) {
|
||||
handleError(error);
|
||||
}
|
||||
}
|
||||
|
||||
main();
|
||||
51
cli/src/client/connection.ts
Normal file
51
cli/src/client/connection.ts
Normal file
|
|
@ -0,0 +1,51 @@
|
|||
import { Client } from "@modelcontextprotocol/sdk/client/index.js";
|
||||
import type { Transport } from "@modelcontextprotocol/sdk/shared/transport.js";
|
||||
import { McpResponse } from "./types.js";
|
||||
|
||||
export const validLogLevels = [
|
||||
"trace",
|
||||
"debug",
|
||||
"info",
|
||||
"warn",
|
||||
"error",
|
||||
] as const;
|
||||
|
||||
export type LogLevel = (typeof validLogLevels)[number];
|
||||
|
||||
export async function connect(
|
||||
client: Client,
|
||||
transport: Transport,
|
||||
): Promise<void> {
|
||||
try {
|
||||
await client.connect(transport);
|
||||
} catch (error) {
|
||||
throw new Error(
|
||||
`Failed to connect to MCP server: ${error instanceof Error ? error.message : String(error)}`,
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
export async function disconnect(transport: Transport): Promise<void> {
|
||||
try {
|
||||
await transport.close();
|
||||
} catch (error) {
|
||||
throw new Error(
|
||||
`Failed to disconnect from MCP server: ${error instanceof Error ? error.message : String(error)}`,
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
// Set logging level
|
||||
export async function setLoggingLevel(
|
||||
client: Client,
|
||||
level: LogLevel,
|
||||
): Promise<McpResponse> {
|
||||
try {
|
||||
const response = await client.setLoggingLevel(level as any);
|
||||
return response;
|
||||
} catch (error) {
|
||||
throw new Error(
|
||||
`Failed to set logging level: ${error instanceof Error ? error.message : String(error)}`,
|
||||
);
|
||||
}
|
||||
}
|
||||
6
cli/src/client/index.ts
Normal file
6
cli/src/client/index.ts
Normal file
|
|
@ -0,0 +1,6 @@
|
|||
// Re-export everything from the client modules
|
||||
export * from "./connection.js";
|
||||
export * from "./prompts.js";
|
||||
export * from "./resources.js";
|
||||
export * from "./tools.js";
|
||||
export * from "./types.js";
|
||||
34
cli/src/client/prompts.ts
Normal file
34
cli/src/client/prompts.ts
Normal file
|
|
@ -0,0 +1,34 @@
|
|||
import { Client } from "@modelcontextprotocol/sdk/client/index.js";
|
||||
import { McpResponse } from "./types.js";
|
||||
|
||||
// List available prompts
|
||||
export async function listPrompts(client: Client): Promise<McpResponse> {
|
||||
try {
|
||||
const response = await client.listPrompts();
|
||||
return response;
|
||||
} catch (error) {
|
||||
throw new Error(
|
||||
`Failed to list prompts: ${error instanceof Error ? error.message : String(error)}`,
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
// Get a prompt
|
||||
export async function getPrompt(
|
||||
client: Client,
|
||||
name: string,
|
||||
args?: Record<string, string>,
|
||||
): Promise<McpResponse> {
|
||||
try {
|
||||
const response = await client.getPrompt({
|
||||
name,
|
||||
arguments: args || {},
|
||||
});
|
||||
|
||||
return response;
|
||||
} catch (error) {
|
||||
throw new Error(
|
||||
`Failed to get prompt: ${error instanceof Error ? error.message : String(error)}`,
|
||||
);
|
||||
}
|
||||
}
|
||||
43
cli/src/client/resources.ts
Normal file
43
cli/src/client/resources.ts
Normal file
|
|
@ -0,0 +1,43 @@
|
|||
import { Client } from "@modelcontextprotocol/sdk/client/index.js";
|
||||
import { McpResponse } from "./types.js";
|
||||
|
||||
// List available resources
|
||||
export async function listResources(client: Client): Promise<McpResponse> {
|
||||
try {
|
||||
const response = await client.listResources();
|
||||
return response;
|
||||
} catch (error) {
|
||||
throw new Error(
|
||||
`Failed to list resources: ${error instanceof Error ? error.message : String(error)}`,
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
// Read a resource
|
||||
export async function readResource(
|
||||
client: Client,
|
||||
uri: string,
|
||||
): Promise<McpResponse> {
|
||||
try {
|
||||
const response = await client.readResource({ uri });
|
||||
return response;
|
||||
} catch (error) {
|
||||
throw new Error(
|
||||
`Failed to read resource ${uri}: ${error instanceof Error ? error.message : String(error)}`,
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
// List resource templates
|
||||
export async function listResourceTemplates(
|
||||
client: Client,
|
||||
): Promise<McpResponse> {
|
||||
try {
|
||||
const response = await client.listResourceTemplates();
|
||||
return response;
|
||||
} catch (error) {
|
||||
throw new Error(
|
||||
`Failed to list resource templates: ${error instanceof Error ? error.message : String(error)}`,
|
||||
);
|
||||
}
|
||||
}
|
||||
95
cli/src/client/tools.ts
Normal file
95
cli/src/client/tools.ts
Normal file
|
|
@ -0,0 +1,95 @@
|
|||
import { Client } from "@modelcontextprotocol/sdk/client/index.js";
|
||||
import { Tool } from "@modelcontextprotocol/sdk/types.js";
|
||||
import { McpResponse } from "./types.js";
|
||||
|
||||
type JsonSchemaType = {
|
||||
type: "string" | "number" | "integer" | "boolean" | "array" | "object";
|
||||
description?: string;
|
||||
properties?: Record<string, JsonSchemaType>;
|
||||
items?: JsonSchemaType;
|
||||
};
|
||||
|
||||
export async function listTools(client: Client): Promise<McpResponse> {
|
||||
try {
|
||||
const response = await client.listTools();
|
||||
return response;
|
||||
} catch (error) {
|
||||
throw new Error(
|
||||
`Failed to list tools: ${error instanceof Error ? error.message : String(error)}`,
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
function convertParameterValue(value: string, schema: JsonSchemaType): unknown {
|
||||
if (!value) {
|
||||
return value;
|
||||
}
|
||||
|
||||
if (schema.type === "number" || schema.type === "integer") {
|
||||
return Number(value);
|
||||
}
|
||||
|
||||
if (schema.type === "boolean") {
|
||||
return value.toLowerCase() === "true";
|
||||
}
|
||||
|
||||
if (schema.type === "object" || schema.type === "array") {
|
||||
try {
|
||||
return JSON.parse(value);
|
||||
} catch (error) {
|
||||
return value;
|
||||
}
|
||||
}
|
||||
|
||||
return value;
|
||||
}
|
||||
|
||||
function convertParameters(
|
||||
tool: Tool,
|
||||
params: Record<string, string>,
|
||||
): Record<string, unknown> {
|
||||
const result: Record<string, unknown> = {};
|
||||
const properties = tool.inputSchema.properties || {};
|
||||
|
||||
for (const [key, value] of Object.entries(params)) {
|
||||
const paramSchema = properties[key] as JsonSchemaType | undefined;
|
||||
|
||||
if (paramSchema) {
|
||||
result[key] = convertParameterValue(value, paramSchema);
|
||||
} else {
|
||||
// If no schema is found for this parameter, keep it as string
|
||||
result[key] = value;
|
||||
}
|
||||
}
|
||||
|
||||
return result;
|
||||
}
|
||||
|
||||
export async function callTool(
|
||||
client: Client,
|
||||
name: string,
|
||||
args: Record<string, string>,
|
||||
): Promise<McpResponse> {
|
||||
try {
|
||||
const toolsResponse = await listTools(client);
|
||||
const tools = toolsResponse.tools as Tool[];
|
||||
const tool = tools.find((t) => t.name === name);
|
||||
|
||||
let convertedArgs: Record<string, unknown> = args;
|
||||
|
||||
if (tool) {
|
||||
// Convert parameters based on the tool's schema
|
||||
convertedArgs = convertParameters(tool, args);
|
||||
}
|
||||
|
||||
const response = await client.callTool({
|
||||
name: name,
|
||||
arguments: convertedArgs,
|
||||
});
|
||||
return response;
|
||||
} catch (error) {
|
||||
throw new Error(
|
||||
`Failed to call tool ${name}: ${error instanceof Error ? error.message : String(error)}`,
|
||||
);
|
||||
}
|
||||
}
|
||||
1
cli/src/client/types.ts
Normal file
1
cli/src/client/types.ts
Normal file
|
|
@ -0,0 +1 @@
|
|||
export type McpResponse = Record<string, unknown>;
|
||||
20
cli/src/error-handler.ts
Normal file
20
cli/src/error-handler.ts
Normal file
|
|
@ -0,0 +1,20 @@
|
|||
function formatError(error: unknown): string {
|
||||
let message: string;
|
||||
|
||||
if (error instanceof Error) {
|
||||
message = error.message;
|
||||
} else if (typeof error === "string") {
|
||||
message = error;
|
||||
} else {
|
||||
message = "Unknown error";
|
||||
}
|
||||
|
||||
return message;
|
||||
}
|
||||
|
||||
export function handleError(error: unknown): never {
|
||||
const errorMessage = formatError(error);
|
||||
console.error(errorMessage);
|
||||
|
||||
process.exit(1);
|
||||
}
|
||||
253
cli/src/index.ts
Normal file
253
cli/src/index.ts
Normal file
|
|
@ -0,0 +1,253 @@
|
|||
#!/usr/bin/env node
|
||||
|
||||
import { Client } from "@modelcontextprotocol/sdk/client/index.js";
|
||||
import { Command } from "commander";
|
||||
import {
|
||||
callTool,
|
||||
connect,
|
||||
disconnect,
|
||||
getPrompt,
|
||||
listPrompts,
|
||||
listResources,
|
||||
listResourceTemplates,
|
||||
listTools,
|
||||
LogLevel,
|
||||
McpResponse,
|
||||
readResource,
|
||||
setLoggingLevel,
|
||||
validLogLevels,
|
||||
} from "./client/index.js";
|
||||
import { handleError } from "./error-handler.js";
|
||||
import { createTransport, TransportOptions } from "./transport.js";
|
||||
|
||||
type Args = {
|
||||
target: string[];
|
||||
method?: string;
|
||||
promptName?: string;
|
||||
promptArgs?: Record<string, string>;
|
||||
uri?: string;
|
||||
logLevel?: LogLevel;
|
||||
toolName?: string;
|
||||
toolArg?: Record<string, string>;
|
||||
};
|
||||
|
||||
function createTransportOptions(target: string[]): TransportOptions {
|
||||
if (target.length === 0) {
|
||||
throw new Error(
|
||||
"Target is required. Specify a URL or a command to execute.",
|
||||
);
|
||||
}
|
||||
|
||||
const [command, ...commandArgs] = target;
|
||||
|
||||
if (!command) {
|
||||
throw new Error("Command is required.");
|
||||
}
|
||||
|
||||
const isUrl = command.startsWith("http://") || command.startsWith("https://");
|
||||
|
||||
if (isUrl && commandArgs.length > 0) {
|
||||
throw new Error("Arguments cannot be passed to a URL-based MCP server.");
|
||||
}
|
||||
|
||||
return {
|
||||
transportType: isUrl ? "sse" : "stdio",
|
||||
command: isUrl ? undefined : command,
|
||||
args: isUrl ? undefined : commandArgs,
|
||||
url: isUrl ? command : undefined,
|
||||
};
|
||||
}
|
||||
|
||||
async function callMethod(args: Args): Promise<void> {
|
||||
const transportOptions = createTransportOptions(args.target);
|
||||
const transport = createTransport(transportOptions);
|
||||
const client = new Client({
|
||||
name: "inspector-cli",
|
||||
version: "0.5.1",
|
||||
});
|
||||
|
||||
try {
|
||||
await connect(client, transport);
|
||||
|
||||
let result: McpResponse;
|
||||
|
||||
// Tools methods
|
||||
if (args.method === "tools/list") {
|
||||
result = await listTools(client);
|
||||
} else if (args.method === "tools/call") {
|
||||
if (!args.toolName) {
|
||||
throw new Error(
|
||||
"Tool name is required for tools/call method. Use --tool-name to specify the tool name.",
|
||||
);
|
||||
}
|
||||
|
||||
result = await callTool(client, args.toolName, args.toolArg || {});
|
||||
}
|
||||
// Resources methods
|
||||
else if (args.method === "resources/list") {
|
||||
result = await listResources(client);
|
||||
} else if (args.method === "resources/read") {
|
||||
if (!args.uri) {
|
||||
throw new Error(
|
||||
"URI is required for resources/read method. Use --uri to specify the resource URI.",
|
||||
);
|
||||
}
|
||||
|
||||
result = await readResource(client, args.uri);
|
||||
} else if (args.method === "resources/templates/list") {
|
||||
result = await listResourceTemplates(client);
|
||||
}
|
||||
// Prompts methods
|
||||
else if (args.method === "prompts/list") {
|
||||
result = await listPrompts(client);
|
||||
} else if (args.method === "prompts/get") {
|
||||
if (!args.promptName) {
|
||||
throw new Error(
|
||||
"Prompt name is required for prompts/get method. Use --prompt-name to specify the prompt name.",
|
||||
);
|
||||
}
|
||||
|
||||
result = await getPrompt(client, args.promptName, args.promptArgs || {});
|
||||
}
|
||||
// Logging methods
|
||||
else if (args.method === "logging/setLevel") {
|
||||
if (!args.logLevel) {
|
||||
throw new Error(
|
||||
"Log level is required for logging/setLevel method. Use --log-level to specify the log level.",
|
||||
);
|
||||
}
|
||||
|
||||
result = await setLoggingLevel(client, args.logLevel);
|
||||
} else {
|
||||
throw new Error(
|
||||
`Unsupported method: ${args.method}. Supported methods include: tools/list, tools/call, resources/list, resources/read, resources/templates/list, prompts/list, prompts/get, logging/setLevel`,
|
||||
);
|
||||
}
|
||||
|
||||
console.log(JSON.stringify(result, null, 2));
|
||||
} finally {
|
||||
try {
|
||||
await disconnect(transport);
|
||||
} catch (disconnectError) {
|
||||
throw disconnectError;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
function parseKeyValuePair(
|
||||
value: string,
|
||||
previous: Record<string, string> = {},
|
||||
): Record<string, string> {
|
||||
const parts = value.split("=");
|
||||
const key = parts[0];
|
||||
const val = parts.slice(1).join("=");
|
||||
|
||||
if (val === undefined || val === "") {
|
||||
throw new Error(
|
||||
`Invalid parameter format: ${value}. Use key=value format.`,
|
||||
);
|
||||
}
|
||||
|
||||
return { ...previous, [key as string]: val };
|
||||
}
|
||||
|
||||
function parseArgs(): Args {
|
||||
const program = new Command();
|
||||
|
||||
// Find if there's a -- in the arguments and split them
|
||||
const argSeparatorIndex = process.argv.indexOf("--");
|
||||
let preArgs = process.argv;
|
||||
let postArgs: string[] = [];
|
||||
|
||||
if (argSeparatorIndex !== -1) {
|
||||
preArgs = process.argv.slice(0, argSeparatorIndex);
|
||||
postArgs = process.argv.slice(argSeparatorIndex + 1);
|
||||
}
|
||||
|
||||
program
|
||||
.name("inspector-cli")
|
||||
.allowUnknownOption()
|
||||
.argument("<target...>", "Command and arguments or URL of the MCP server")
|
||||
//
|
||||
// Method selection
|
||||
//
|
||||
.option("--method <method>", "Method to invoke")
|
||||
//
|
||||
// Tool-related options
|
||||
//
|
||||
.option("--tool-name <toolName>", "Tool name (for tools/call method)")
|
||||
.option(
|
||||
"--tool-arg <pairs...>",
|
||||
"Tool argument as key=value pair",
|
||||
parseKeyValuePair,
|
||||
{},
|
||||
)
|
||||
//
|
||||
// Resource-related options
|
||||
//
|
||||
.option("--uri <uri>", "URI of the resource (for resources/read method)")
|
||||
//
|
||||
// Prompt-related options
|
||||
//
|
||||
.option(
|
||||
"--prompt-name <promptName>",
|
||||
"Name of the prompt (for prompts/get method)",
|
||||
)
|
||||
.option(
|
||||
"--prompt-args <pairs...>",
|
||||
"Prompt arguments as key=value pairs",
|
||||
parseKeyValuePair,
|
||||
{},
|
||||
)
|
||||
//
|
||||
// Logging options
|
||||
//
|
||||
.option(
|
||||
"--log-level <level>",
|
||||
"Logging level (for logging/setLevel method)",
|
||||
(value: string) => {
|
||||
if (!validLogLevels.includes(value as any)) {
|
||||
throw new Error(
|
||||
`Invalid log level: ${value}. Valid levels are: ${validLogLevels.join(", ")}`,
|
||||
);
|
||||
}
|
||||
|
||||
return value as LogLevel;
|
||||
},
|
||||
);
|
||||
|
||||
// Parse only the arguments before --
|
||||
program.parse(preArgs);
|
||||
|
||||
const options = program.opts() as Omit<Args, "target">;
|
||||
let remainingArgs = program.args;
|
||||
|
||||
// Add back any arguments that came after --
|
||||
const finalArgs = [...remainingArgs, ...postArgs];
|
||||
|
||||
if (!options.method) {
|
||||
throw new Error(
|
||||
"Method is required. Use --method to specify the method to invoke.",
|
||||
);
|
||||
}
|
||||
|
||||
return {
|
||||
target: finalArgs,
|
||||
...options,
|
||||
};
|
||||
}
|
||||
|
||||
async function main(): Promise<void> {
|
||||
process.on("uncaughtException", (error) => {
|
||||
handleError(error);
|
||||
});
|
||||
|
||||
try {
|
||||
const args = parseArgs();
|
||||
await callMethod(args);
|
||||
} catch (error) {
|
||||
handleError(error);
|
||||
}
|
||||
}
|
||||
|
||||
main();
|
||||
76
cli/src/transport.ts
Normal file
76
cli/src/transport.ts
Normal file
|
|
@ -0,0 +1,76 @@
|
|||
import { SSEClientTransport } from "@modelcontextprotocol/sdk/client/sse.js";
|
||||
import {
|
||||
getDefaultEnvironment,
|
||||
StdioClientTransport,
|
||||
} from "@modelcontextprotocol/sdk/client/stdio.js";
|
||||
import type { Transport } from "@modelcontextprotocol/sdk/shared/transport.js";
|
||||
import { findActualExecutable } from "spawn-rx";
|
||||
|
||||
export type TransportOptions = {
|
||||
transportType: "sse" | "stdio";
|
||||
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[] = [];
|
||||
|
||||
if (options.args !== undefined) {
|
||||
args = options.args;
|
||||
}
|
||||
|
||||
const processEnv: Record<string, string> = {};
|
||||
|
||||
for (const [key, value] of Object.entries(process.env)) {
|
||||
if (value !== undefined) {
|
||||
processEnv[key] = value;
|
||||
}
|
||||
}
|
||||
|
||||
const defaultEnv = getDefaultEnvironment();
|
||||
|
||||
const env: Record<string, string> = {
|
||||
...processEnv,
|
||||
...defaultEnv,
|
||||
};
|
||||
|
||||
const { cmd: actualCommand, args: actualArgs } = findActualExecutable(
|
||||
options.command ?? "",
|
||||
args,
|
||||
);
|
||||
|
||||
return new StdioClientTransport({
|
||||
command: actualCommand,
|
||||
args: actualArgs,
|
||||
env,
|
||||
stderr: "pipe",
|
||||
});
|
||||
}
|
||||
|
||||
export function createTransport(options: TransportOptions): Transport {
|
||||
const { transportType } = options;
|
||||
|
||||
try {
|
||||
if (transportType === "stdio") {
|
||||
return createStdioTransport(options);
|
||||
}
|
||||
|
||||
if (transportType === "sse") {
|
||||
return createSSETransport(options);
|
||||
}
|
||||
|
||||
throw new Error(`Unsupported transport type: ${transportType}`);
|
||||
} catch (error) {
|
||||
throw new Error(
|
||||
`Failed to create transport: ${error instanceof Error ? error.message : String(error)}`,
|
||||
);
|
||||
}
|
||||
}
|
||||
Some files were not shown because too many files have changed in this diff Show more
Loading…
Reference in a new issue