Merge branch 'main' into reverse-env-order-for-cli-stdio
This commit is contained in:
commit
44b4417951
83 changed files with 10137 additions and 1426 deletions
35
.dockerignore
Normal file
35
.dockerignore
Normal file
|
|
@ -0,0 +1,35 @@
|
|||
# Version control
|
||||
.git
|
||||
.gitignore
|
||||
|
||||
# Node.js
|
||||
node_modules
|
||||
npm-debug.log
|
||||
|
||||
# Build artifacts
|
||||
client/dist
|
||||
client/build
|
||||
server/dist
|
||||
server/build
|
||||
|
||||
# Environment variables
|
||||
.env
|
||||
.env.local
|
||||
.env.development
|
||||
.env.test
|
||||
.env.production
|
||||
|
||||
# Editor files
|
||||
.vscode
|
||||
.idea
|
||||
|
||||
# Logs
|
||||
logs
|
||||
*.log
|
||||
|
||||
# Testing
|
||||
coverage
|
||||
|
||||
# Docker
|
||||
Dockerfile
|
||||
.dockerignore
|
||||
0
.git-blame-ignore-revs
Normal file
0
.git-blame-ignore-revs
Normal file
64
.github/workflows/claude.yml
vendored
Normal file
64
.github/workflows/claude.yml
vendored
Normal file
|
|
@ -0,0 +1,64 @@
|
|||
name: Claude Code
|
||||
|
||||
on:
|
||||
issue_comment:
|
||||
types: [created]
|
||||
pull_request_review_comment:
|
||||
types: [created]
|
||||
issues:
|
||||
types: [opened, assigned]
|
||||
pull_request_review:
|
||||
types: [submitted]
|
||||
|
||||
jobs:
|
||||
claude:
|
||||
if: |
|
||||
(
|
||||
(github.event_name == 'issue_comment' && contains(github.event.comment.body, '@claude')) ||
|
||||
(github.event_name == 'pull_request_review_comment' && contains(github.event.comment.body, '@claude')) ||
|
||||
(github.event_name == 'pull_request_review' && contains(github.event.review.body, '@claude')) ||
|
||||
(github.event_name == 'issues' && (contains(github.event.issue.body, '@claude') || contains(github.event.issue.title, '@claude')))
|
||||
) &&
|
||||
(
|
||||
github.actor == 'ihrpr' ||
|
||||
github.actor == 'olaservo'
|
||||
)
|
||||
runs-on: ubuntu-latest
|
||||
permissions:
|
||||
contents: read
|
||||
pull-requests: read
|
||||
issues: read
|
||||
id-token: write
|
||||
steps:
|
||||
- name: Checkout repository
|
||||
uses: actions/checkout@v4
|
||||
with:
|
||||
fetch-depth: 1
|
||||
|
||||
- name: Run Claude Code
|
||||
id: claude
|
||||
uses: anthropics/claude-code-action@beta
|
||||
with:
|
||||
anthropic_api_key: ${{ secrets.ANTHROPIC_API_KEY }}
|
||||
|
||||
# Optional: Specify model (defaults to Claude Sonnet 4, uncomment for Claude Opus 4)
|
||||
# model: "claude-opus-4-20250514"
|
||||
|
||||
# Optional: Customize the trigger phrase (default: @claude)
|
||||
# trigger_phrase: "/claude"
|
||||
|
||||
# Optional: Trigger when specific user is assigned to an issue
|
||||
# assignee_trigger: "claude-bot"
|
||||
|
||||
# Optional: Allow Claude to run specific commands
|
||||
# allowed_tools: "Bash(npm install),Bash(npm run build),Bash(npm run test:*),Bash(npm run lint:*)"
|
||||
|
||||
# Optional: Add custom instructions for Claude to customize its behavior for your project
|
||||
# custom_instructions: |
|
||||
# Follow our coding standards
|
||||
# Ensure all new code has tests
|
||||
# Use TypeScript for new files
|
||||
|
||||
# Optional: Custom environment variables for Claude
|
||||
# claude_env: |
|
||||
# NODE_ENV: test
|
||||
41
.github/workflows/cli_tests.yml
vendored
Normal file
41
.github/workflows/cli_tests.yml
vendored
Normal file
|
|
@ -0,0 +1,41 @@
|
|||
name: CLI Tests
|
||||
|
||||
on:
|
||||
push:
|
||||
paths:
|
||||
- "cli/**"
|
||||
pull_request:
|
||||
paths:
|
||||
- "cli/**"
|
||||
|
||||
jobs:
|
||||
test:
|
||||
runs-on: ubuntu-latest
|
||||
defaults:
|
||||
run:
|
||||
working-directory: ./cli
|
||||
steps:
|
||||
- uses: actions/checkout@v4
|
||||
|
||||
- name: Set up Node.js
|
||||
uses: actions/setup-node@v4
|
||||
with:
|
||||
node-version-file: package.json
|
||||
cache: npm
|
||||
|
||||
- name: Install dependencies
|
||||
run: |
|
||||
cd ..
|
||||
npm ci --ignore-scripts
|
||||
|
||||
- name: Build CLI
|
||||
run: npm run build
|
||||
|
||||
- name: Explicitly pre-install test dependencies
|
||||
run: npx -y @modelcontextprotocol/server-everything --help || true
|
||||
|
||||
- name: Run tests
|
||||
run: npm test
|
||||
env:
|
||||
NPM_CONFIG_YES: true
|
||||
CI: true
|
||||
78
.github/workflows/e2e_tests.yml
vendored
Normal file
78
.github/workflows/e2e_tests.yml
vendored
Normal file
|
|
@ -0,0 +1,78 @@
|
|||
name: Playwright Tests
|
||||
|
||||
on:
|
||||
push:
|
||||
branches: [main]
|
||||
pull_request:
|
||||
branches: [main]
|
||||
|
||||
jobs:
|
||||
test:
|
||||
# Installing Playright dependencies can take quite awhile, and also depends on GitHub CI load.
|
||||
timeout-minutes: 15
|
||||
runs-on: ubuntu-latest
|
||||
|
||||
steps:
|
||||
- name: Install dependencies
|
||||
run: |
|
||||
sudo apt-get update
|
||||
sudo apt-get install -y libwoff1
|
||||
|
||||
- uses: actions/checkout@v4
|
||||
|
||||
- uses: actions/setup-node@v4
|
||||
id: setup_node
|
||||
with:
|
||||
node-version-file: package.json
|
||||
cache: npm
|
||||
|
||||
# Cache Playwright browsers
|
||||
- name: Cache Playwright browsers
|
||||
id: cache-playwright
|
||||
uses: actions/cache@v4
|
||||
with:
|
||||
path: ~/.cache/ms-playwright # The default Playwright cache path
|
||||
key: ${{ runner.os }}-playwright-${{ hashFiles('package-lock.json') }} # Cache key based on OS and package-lock.json
|
||||
restore-keys: |
|
||||
${{ runner.os }}-playwright-
|
||||
|
||||
- name: Install dependencies
|
||||
run: npm ci
|
||||
|
||||
- name: Install Playwright dependencies
|
||||
run: npx playwright install-deps
|
||||
|
||||
- name: Install Playwright and browsers unless cached
|
||||
run: npx playwright install --with-deps
|
||||
if: steps.cache-playwright.outputs.cache-hit != 'true'
|
||||
|
||||
- name: Run Playwright tests
|
||||
id: playwright-tests
|
||||
run: npm run test:e2e
|
||||
|
||||
- name: Upload Playwright Report and Screenshots
|
||||
uses: actions/upload-artifact@v4
|
||||
if: steps.playwright-tests.conclusion != 'skipped'
|
||||
with:
|
||||
name: playwright-report
|
||||
path: |
|
||||
client/playwright-report/
|
||||
client/test-results/
|
||||
client/results.json
|
||||
retention-days: 2
|
||||
|
||||
- name: Publish Playwright Test Summary
|
||||
uses: daun/playwright-report-summary@v3
|
||||
if: steps.playwright-tests.conclusion != 'skipped'
|
||||
with:
|
||||
create-comment: ${{ github.event.pull_request.head.repo.full_name == github.repository }}
|
||||
report-file: client/results.json
|
||||
comment-title: "🎭 Playwright E2E Test Results"
|
||||
job-summary: true
|
||||
icon-style: "emojis"
|
||||
custom-info: |
|
||||
**Test Environment:** Ubuntu Latest, Node.js ${{ steps.setup_node.outputs.node-version }}
|
||||
**Browsers:** Chromium, Firefox
|
||||
|
||||
📊 [View Detailed HTML Report](https://github.com/${{ github.repository }}/actions/runs/${{ github.run_id }}) (download artifacts)
|
||||
test-command: "npm run test:e2e"
|
||||
56
.github/workflows/main.yml
vendored
56
.github/workflows/main.yml
vendored
|
|
@ -19,13 +19,16 @@ jobs:
|
|||
|
||||
- uses: actions/setup-node@v4
|
||||
with:
|
||||
node-version: 18
|
||||
node-version-file: package.json
|
||||
cache: npm
|
||||
|
||||
# Working around https://github.com/npm/cli/issues/4828
|
||||
# - run: npm ci
|
||||
- run: npm install --no-package-lock
|
||||
|
||||
- name: Check version consistency
|
||||
run: npm run check-version
|
||||
|
||||
- name: Check linting
|
||||
working-directory: ./client
|
||||
run: npm run lint
|
||||
|
|
@ -50,7 +53,7 @@ jobs:
|
|||
- uses: actions/checkout@v4
|
||||
- uses: actions/setup-node@v4
|
||||
with:
|
||||
node-version: 18
|
||||
node-version-file: package.json
|
||||
cache: npm
|
||||
registry-url: "https://registry.npmjs.org"
|
||||
|
||||
|
|
@ -62,3 +65,52 @@ jobs:
|
|||
- run: npm run publish-all
|
||||
env:
|
||||
NODE_AUTH_TOKEN: ${{ secrets.NPM_TOKEN }}
|
||||
|
||||
publish-github-container-registry:
|
||||
runs-on: ubuntu-latest
|
||||
if: github.event_name == 'release'
|
||||
environment: release
|
||||
needs: build
|
||||
permissions:
|
||||
contents: read
|
||||
packages: write
|
||||
attestations: write
|
||||
id-token: write
|
||||
steps:
|
||||
- uses: actions/checkout@v4
|
||||
|
||||
- name: Log in to the Container registry
|
||||
uses: docker/login-action@v3
|
||||
with:
|
||||
registry: ghcr.io
|
||||
username: ${{ github.actor }}
|
||||
password: ${{ secrets.GITHUB_TOKEN }}
|
||||
|
||||
- name: Extract metadata (tags, labels) for Docker
|
||||
id: meta
|
||||
uses: docker/metadata-action@v5
|
||||
with:
|
||||
images: ghcr.io/${{ github.repository }}
|
||||
|
||||
- name: Set up QEMU
|
||||
uses: docker/setup-qemu-action@v3
|
||||
|
||||
- name: Set up Docker Buildx
|
||||
uses: docker/setup-buildx-action@v3
|
||||
|
||||
- name: Build and push Docker image
|
||||
id: push
|
||||
uses: docker/build-push-action@v6
|
||||
with:
|
||||
context: .
|
||||
push: true
|
||||
platforms: linux/amd64,linux/arm64
|
||||
tags: ${{ steps.meta.outputs.tags }}
|
||||
labels: ${{ steps.meta.outputs.labels }}
|
||||
|
||||
- name: Generate artifact attestation
|
||||
uses: actions/attest-build-provenance@v2
|
||||
with:
|
||||
subject-name: ghcr.io/${{ github.repository }}
|
||||
subject-digest: ${{ steps.push.outputs.digest }}
|
||||
push-to-registry: true
|
||||
|
|
|
|||
6
.gitignore
vendored
6
.gitignore
vendored
|
|
@ -9,3 +9,9 @@ client/tsconfig.app.tsbuildinfo
|
|||
client/tsconfig.node.tsbuildinfo
|
||||
cli/build
|
||||
test-output
|
||||
# symlinked by `npm run link:sdk`:
|
||||
sdk
|
||||
client/playwright-report/
|
||||
client/results.json
|
||||
client/test-results/
|
||||
mcp.json
|
||||
|
|
|
|||
1
.node-version
Normal file
1
.node-version
Normal file
|
|
@ -0,0 +1 @@
|
|||
22.x.x
|
||||
|
|
@ -2,3 +2,4 @@ packages
|
|||
server/build
|
||||
CODE_OF_CONDUCT.md
|
||||
SECURITY.md
|
||||
mcp.json
|
||||
|
|
|
|||
|
|
@ -30,4 +30,4 @@ 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
|
||||
- `cli/`: Command-line interface for testing and invoking MCP server methods directly
|
||||
|
|
|
|||
|
|
@ -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://127.0.0.1:6274 to interact with the inspector
|
||||
4. Use the web UI at http://localhost: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. You can run `npm run prettier-check` and `npm run prettier-fix` as applicable.
|
||||
3. Test changes locally by running `npm test`
|
||||
3. Test changes locally by running `npm test` and `npm run test:e2e`
|
||||
4. Update documentation as needed
|
||||
5. Use clear commit messages explaining your changes
|
||||
6. Verify all changes work as expected
|
||||
|
|
|
|||
52
Dockerfile
Normal file
52
Dockerfile
Normal file
|
|
@ -0,0 +1,52 @@
|
|||
# Build stage
|
||||
FROM node:24-slim AS builder
|
||||
|
||||
# Set working directory
|
||||
WORKDIR /app
|
||||
|
||||
# Copy package files for installation
|
||||
COPY package*.json ./
|
||||
COPY .npmrc ./
|
||||
COPY client/package*.json ./client/
|
||||
COPY server/package*.json ./server/
|
||||
COPY cli/package*.json ./cli/
|
||||
|
||||
# Install dependencies
|
||||
RUN npm ci --ignore-scripts
|
||||
|
||||
# Copy source files
|
||||
COPY . .
|
||||
|
||||
# Build the application
|
||||
RUN npm run build
|
||||
|
||||
# Production stage
|
||||
FROM node:24-slim
|
||||
|
||||
WORKDIR /app
|
||||
|
||||
# Copy package files for production
|
||||
COPY package*.json ./
|
||||
COPY .npmrc ./
|
||||
COPY client/package*.json ./client/
|
||||
COPY server/package*.json ./server/
|
||||
COPY cli/package*.json ./cli/
|
||||
|
||||
# Install only production dependencies
|
||||
RUN npm ci --omit=dev --ignore-scripts
|
||||
|
||||
# Copy built files from builder stage
|
||||
COPY --from=builder /app/client/dist ./client/dist
|
||||
COPY --from=builder /app/client/bin ./client/bin
|
||||
COPY --from=builder /app/server/build ./server/build
|
||||
COPY --from=builder /app/cli/build ./cli/build
|
||||
|
||||
# Set default port values as environment variables
|
||||
ENV CLIENT_PORT=6274
|
||||
ENV SERVER_PORT=6277
|
||||
|
||||
# Document which ports the application uses internally
|
||||
EXPOSE ${CLIENT_PORT} ${SERVER_PORT}
|
||||
|
||||
# Use ENTRYPOINT with CMD for arguments
|
||||
ENTRYPOINT ["npm", "start"]
|
||||
169
README.md
169
README.md
|
|
@ -4,12 +4,31 @@ The MCP inspector is a developer tool for testing and debugging MCP servers.
|
|||
|
||||

|
||||
|
||||
## Architecture Overview
|
||||
|
||||
The MCP Inspector consists of two main components that work together:
|
||||
|
||||
- **MCP Inspector Client (MCPI)**: A React-based web UI that provides an interactive interface for testing and debugging MCP servers
|
||||
- **MCP Proxy (MCPP)**: A Node.js server that acts as a protocol bridge, connecting the web UI to MCP servers via various transport methods (stdio, SSE, streamable-http)
|
||||
|
||||
Note that the proxy is not a network proxy for intercepting traffic. Instead, it functions as both an MCP client (connecting to your MCP server) and an HTTP server (serving the web UI), enabling browser-based interaction with MCP servers that use different transport protocols.
|
||||
|
||||
## Running the Inspector
|
||||
|
||||
### Requirements
|
||||
|
||||
- Node.js: ^22.7.5
|
||||
|
||||
### Quick Start (UI mode)
|
||||
|
||||
To get up and running right away with the UI, just execute the following:
|
||||
|
||||
```bash
|
||||
npx @modelcontextprotocol/inspector
|
||||
```
|
||||
|
||||
The server will start up and the UI will be accessible at `http://localhost:6274`.
|
||||
|
||||
### 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`:
|
||||
|
|
@ -118,17 +137,70 @@ The inspector supports bearer token authentication for SSE connections. Enter yo
|
|||
|
||||
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.
|
||||
|
||||
#### Authentication
|
||||
|
||||
The MCP Inspector proxy server requires authentication by default. When starting the server, a random session token is generated and printed to the console:
|
||||
|
||||
```
|
||||
🔑 Session token: 3a1c267fad21f7150b7d624c160b7f09b0b8c4f623c7107bbf13378f051538d4
|
||||
|
||||
🔗 Open inspector with token pre-filled:
|
||||
http://localhost:6274/?MCP_PROXY_AUTH_TOKEN=3a1c267fad21f7150b7d624c160b7f09b0b8c4f623c7107bbf13378f051538d4
|
||||
```
|
||||
|
||||
This token must be included as a Bearer token in the Authorization header for all requests to the server. The inspector will automatically open your browser with the token pre-filled in the URL.
|
||||
|
||||
**Automatic browser opening** - The inspector now automatically opens your browser with the token pre-filled in the URL when authentication is enabled.
|
||||
|
||||
**Alternative: Manual configuration** - If you already have the inspector open:
|
||||
|
||||
1. Click the "Configuration" button in the sidebar
|
||||
2. Find "Proxy Session Token" and enter the token displayed in the proxy console
|
||||
3. Click "Save" to apply the configuration
|
||||
|
||||
The token will be saved in your browser's local storage for future use.
|
||||
|
||||
If you need to disable authentication (NOT RECOMMENDED), you can set the `DANGEROUSLY_OMIT_AUTH` environment variable:
|
||||
|
||||
```bash
|
||||
DANGEROUSLY_OMIT_AUTH=true npm start
|
||||
```
|
||||
|
||||
You can also set the token via the `MCP_PROXY_AUTH_TOKEN` environment variable when starting the server:
|
||||
|
||||
```bash
|
||||
MCP_PROXY_AUTH_TOKEN=$(openssl rand -hex 32) npm start
|
||||
```
|
||||
|
||||
#### Local-only Binding
|
||||
|
||||
By default, both the MCP Inspector proxy server and client bind only to `localhost` to prevent network access. This ensures they are not accessible from other devices on the network. If you need to bind to all interfaces for development purposes, you can override this with the `HOST` environment variable:
|
||||
|
||||
```bash
|
||||
HOST=0.0.0.0 npm start
|
||||
```
|
||||
|
||||
**Warning:** Only bind to all interfaces in trusted network environments, as this exposes the proxy server's ability to execute local processes and both services to network access.
|
||||
|
||||
#### DNS Rebinding Protection
|
||||
|
||||
To prevent DNS rebinding attacks, the MCP Inspector validates the `Origin` header on incoming requests. By default, only requests from the client origin are allowed (respects `CLIENT_PORT` if set, defaulting to port 6274). You can configure additional allowed origins by setting the `ALLOWED_ORIGINS` environment variable (comma-separated list):
|
||||
|
||||
```bash
|
||||
ALLOWED_ORIGINS=http://localhost:6274,http://localhost:8000 npm start
|
||||
```
|
||||
|
||||
### 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 |
|
||||
| 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 (works with authentication enabled). 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.
|
||||
|
||||
|
|
@ -162,6 +234,78 @@ Example server configuration file:
|
|||
}
|
||||
```
|
||||
|
||||
#### Transport Types in Config Files
|
||||
|
||||
The inspector automatically detects the transport type from your config file. You can specify different transport types:
|
||||
|
||||
**STDIO (default):**
|
||||
|
||||
```json
|
||||
{
|
||||
"mcpServers": {
|
||||
"my-stdio-server": {
|
||||
"type": "stdio",
|
||||
"command": "npx",
|
||||
"args": ["@modelcontextprotocol/server-everything"]
|
||||
}
|
||||
}
|
||||
}
|
||||
```
|
||||
|
||||
**SSE (Server-Sent Events):**
|
||||
|
||||
```json
|
||||
{
|
||||
"mcpServers": {
|
||||
"my-sse-server": {
|
||||
"type": "sse",
|
||||
"url": "http://localhost:3000/sse"
|
||||
}
|
||||
}
|
||||
}
|
||||
```
|
||||
|
||||
**Streamable HTTP:**
|
||||
|
||||
```json
|
||||
{
|
||||
"mcpServers": {
|
||||
"my-http-server": {
|
||||
"type": "streamable-http",
|
||||
"url": "http://localhost:3000/mcp"
|
||||
}
|
||||
}
|
||||
}
|
||||
```
|
||||
|
||||
#### Default Server Selection
|
||||
|
||||
You can launch the inspector without specifying a server name if your config has:
|
||||
|
||||
1. **A single server** - automatically selected:
|
||||
|
||||
```bash
|
||||
# Automatically uses "my-server" if it's the only one
|
||||
npx @modelcontextprotocol/inspector --config mcp.json
|
||||
```
|
||||
|
||||
2. **A server named "default-server"** - automatically selected:
|
||||
|
||||
```json
|
||||
{
|
||||
"mcpServers": {
|
||||
"default-server": {
|
||||
"command": "npx",
|
||||
"args": ["@modelcontextprotocol/server-everything"]
|
||||
},
|
||||
"other-server": {
|
||||
"command": "node",
|
||||
"args": ["other.js"]
|
||||
}
|
||||
}
|
||||
}
|
||||
```
|
||||
|
||||
> **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:
|
||||
|
|
@ -188,6 +332,12 @@ Development mode:
|
|||
|
||||
```bash
|
||||
npm run dev
|
||||
|
||||
# To co-develop with the typescript-sdk package (assuming it's cloned in ../typescript-sdk; set MCP_SDK otherwise):
|
||||
npm run dev:sdk "cd sdk && npm run examples:simple-server:w"
|
||||
# then open http://localhost:3000/mcp as SHTTP in the inspector.
|
||||
# To go back to the deployed SDK version:
|
||||
# npm run unlink:sdk && npm i
|
||||
```
|
||||
|
||||
> **Note for Windows users:**
|
||||
|
|
@ -233,9 +383,12 @@ npx @modelcontextprotocol/inspector --cli node build/index.js --method resources
|
|||
# List available prompts
|
||||
npx @modelcontextprotocol/inspector --cli node build/index.js --method prompts/list
|
||||
|
||||
# Connect to a remote MCP server
|
||||
# Connect to a remote MCP server (default is SSE transport)
|
||||
npx @modelcontextprotocol/inspector --cli https://my-mcp-server.example.com
|
||||
|
||||
# Connect to a remote MCP server (with Streamable HTTP transport)
|
||||
npx @modelcontextprotocol/inspector --cli https://my-mcp-server.example.com --transport http --method tools/list
|
||||
|
||||
# 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
|
||||
|
||||
|
|
|
|||
|
|
@ -1,6 +1,6 @@
|
|||
{
|
||||
"name": "@modelcontextprotocol/inspector-cli",
|
||||
"version": "0.12.0",
|
||||
"version": "0.16.4",
|
||||
"description": "CLI for the Model Context Protocol inspector",
|
||||
"license": "MIT",
|
||||
"author": "Anthropic, PBC (https://anthropic.com)",
|
||||
|
|
@ -21,7 +21,7 @@
|
|||
},
|
||||
"devDependencies": {},
|
||||
"dependencies": {
|
||||
"@modelcontextprotocol/sdk": "^1.11.0",
|
||||
"@modelcontextprotocol/sdk": "^1.17.2",
|
||||
"commander": "^13.1.0",
|
||||
"spawn-rx": "^5.1.2"
|
||||
}
|
||||
|
|
|
|||
|
|
@ -12,7 +12,7 @@ const colors = {
|
|||
|
||||
import fs from "fs";
|
||||
import path from "path";
|
||||
import { execSync, spawn } from "child_process";
|
||||
import { spawn } from "child_process";
|
||||
import os from "os";
|
||||
import { fileURLToPath } from "url";
|
||||
|
||||
|
|
@ -44,7 +44,14 @@ 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`);
|
||||
console.log(`${colors.BLUE}- Logging options (--log-level)${colors.NC}`);
|
||||
console.log(
|
||||
`${colors.BLUE}- Transport types (--transport http/sse/stdio)${colors.NC}`,
|
||||
);
|
||||
console.log(
|
||||
`${colors.BLUE}- Transport inference from URL suffixes (/mcp, /sse)${colors.NC}`,
|
||||
);
|
||||
console.log(`\n`);
|
||||
|
||||
// Get directory paths
|
||||
const SCRIPTS_DIR = __dirname;
|
||||
|
|
@ -62,9 +69,11 @@ if (!fs.existsSync(OUTPUT_DIR)) {
|
|||
}
|
||||
|
||||
// Create a temporary directory for test files
|
||||
const TEMP_DIR = fs.mkdirSync(path.join(os.tmpdir(), "mcp-inspector-tests"), {
|
||||
recursive: true,
|
||||
});
|
||||
const TEMP_DIR = path.join(os.tmpdir(), "mcp-inspector-tests");
|
||||
fs.mkdirSync(TEMP_DIR, { recursive: true });
|
||||
|
||||
// Track servers for cleanup
|
||||
let runningServers = [];
|
||||
|
||||
process.on("exit", () => {
|
||||
try {
|
||||
|
|
@ -74,6 +83,21 @@ process.on("exit", () => {
|
|||
`${colors.RED}Failed to remove temp directory: ${err.message}${colors.NC}`,
|
||||
);
|
||||
}
|
||||
|
||||
runningServers.forEach((server) => {
|
||||
try {
|
||||
process.kill(-server.pid);
|
||||
} catch (e) {}
|
||||
});
|
||||
});
|
||||
|
||||
process.on("SIGINT", () => {
|
||||
runningServers.forEach((server) => {
|
||||
try {
|
||||
process.kill(-server.pid);
|
||||
} catch (e) {}
|
||||
});
|
||||
process.exit(1);
|
||||
});
|
||||
|
||||
// Use the existing sample config file
|
||||
|
|
@ -96,6 +120,85 @@ try {
|
|||
const invalidConfigPath = path.join(TEMP_DIR, "invalid-config.json");
|
||||
fs.writeFileSync(invalidConfigPath, '{\n "mcpServers": {\n "invalid": {');
|
||||
|
||||
// Create config files with different transport types for testing
|
||||
const sseConfigPath = path.join(TEMP_DIR, "sse-config.json");
|
||||
fs.writeFileSync(
|
||||
sseConfigPath,
|
||||
JSON.stringify(
|
||||
{
|
||||
mcpServers: {
|
||||
"test-sse": {
|
||||
type: "sse",
|
||||
url: "http://localhost:3000/sse",
|
||||
note: "Test SSE server",
|
||||
},
|
||||
},
|
||||
},
|
||||
null,
|
||||
2,
|
||||
),
|
||||
);
|
||||
|
||||
const httpConfigPath = path.join(TEMP_DIR, "http-config.json");
|
||||
fs.writeFileSync(
|
||||
httpConfigPath,
|
||||
JSON.stringify(
|
||||
{
|
||||
mcpServers: {
|
||||
"test-http": {
|
||||
type: "streamable-http",
|
||||
url: "http://localhost:3000/mcp",
|
||||
note: "Test HTTP server",
|
||||
},
|
||||
},
|
||||
},
|
||||
null,
|
||||
2,
|
||||
),
|
||||
);
|
||||
|
||||
const stdioConfigPath = path.join(TEMP_DIR, "stdio-config.json");
|
||||
fs.writeFileSync(
|
||||
stdioConfigPath,
|
||||
JSON.stringify(
|
||||
{
|
||||
mcpServers: {
|
||||
"test-stdio": {
|
||||
type: "stdio",
|
||||
command: "npx",
|
||||
args: ["@modelcontextprotocol/server-everything"],
|
||||
env: {
|
||||
TEST_ENV: "test-value",
|
||||
},
|
||||
},
|
||||
},
|
||||
},
|
||||
null,
|
||||
2,
|
||||
),
|
||||
);
|
||||
|
||||
// Config without type field (backward compatibility)
|
||||
const legacyConfigPath = path.join(TEMP_DIR, "legacy-config.json");
|
||||
fs.writeFileSync(
|
||||
legacyConfigPath,
|
||||
JSON.stringify(
|
||||
{
|
||||
mcpServers: {
|
||||
"test-legacy": {
|
||||
command: "npx",
|
||||
args: ["@modelcontextprotocol/server-everything"],
|
||||
env: {
|
||||
LEGACY_ENV: "legacy-value",
|
||||
},
|
||||
},
|
||||
},
|
||||
},
|
||||
null,
|
||||
2,
|
||||
),
|
||||
);
|
||||
|
||||
// Function to run a basic test
|
||||
async function runBasicTest(testName, ...args) {
|
||||
const outputFile = path.join(
|
||||
|
|
@ -121,6 +224,11 @@ async function runBasicTest(testName, ...args) {
|
|||
stdio: ["ignore", "pipe", "pipe"],
|
||||
});
|
||||
|
||||
const timeout = setTimeout(() => {
|
||||
console.log(`${colors.YELLOW}Test timed out: ${testName}${colors.NC}`);
|
||||
child.kill();
|
||||
}, 10000);
|
||||
|
||||
// Pipe stdout and stderr to the output file
|
||||
child.stdout.pipe(outputStream);
|
||||
child.stderr.pipe(outputStream);
|
||||
|
|
@ -135,6 +243,7 @@ async function runBasicTest(testName, ...args) {
|
|||
});
|
||||
|
||||
child.on("close", (code) => {
|
||||
clearTimeout(timeout);
|
||||
outputStream.end();
|
||||
|
||||
if (code === 0) {
|
||||
|
|
@ -201,6 +310,13 @@ async function runErrorTest(testName, ...args) {
|
|||
stdio: ["ignore", "pipe", "pipe"],
|
||||
});
|
||||
|
||||
const timeout = setTimeout(() => {
|
||||
console.log(
|
||||
`${colors.YELLOW}Error test timed out: ${testName}${colors.NC}`,
|
||||
);
|
||||
child.kill();
|
||||
}, 10000);
|
||||
|
||||
// Pipe stdout and stderr to the output file
|
||||
child.stdout.pipe(outputStream);
|
||||
child.stderr.pipe(outputStream);
|
||||
|
|
@ -215,6 +331,7 @@ async function runErrorTest(testName, ...args) {
|
|||
});
|
||||
|
||||
child.on("close", (code) => {
|
||||
clearTimeout(timeout);
|
||||
outputStream.end();
|
||||
|
||||
// For error tests, we expect a non-zero exit code
|
||||
|
|
@ -611,6 +728,253 @@ async function runTests() {
|
|||
"debug",
|
||||
);
|
||||
|
||||
console.log(
|
||||
`\n${colors.YELLOW}=== Running Config Transport Type Tests ===${colors.NC}`,
|
||||
);
|
||||
|
||||
// Test 25: Config with stdio transport type
|
||||
await runBasicTest(
|
||||
"config_stdio_type",
|
||||
"--config",
|
||||
stdioConfigPath,
|
||||
"--server",
|
||||
"test-stdio",
|
||||
"--cli",
|
||||
"--method",
|
||||
"tools/list",
|
||||
);
|
||||
|
||||
// Test 26: Config with SSE transport type (CLI mode) - expects connection error
|
||||
await runErrorTest(
|
||||
"config_sse_type_cli",
|
||||
"--config",
|
||||
sseConfigPath,
|
||||
"--server",
|
||||
"test-sse",
|
||||
"--cli",
|
||||
"--method",
|
||||
"tools/list",
|
||||
);
|
||||
|
||||
// Test 27: Config with streamable-http transport type (CLI mode) - expects connection error
|
||||
await runErrorTest(
|
||||
"config_http_type_cli",
|
||||
"--config",
|
||||
httpConfigPath,
|
||||
"--server",
|
||||
"test-http",
|
||||
"--cli",
|
||||
"--method",
|
||||
"tools/list",
|
||||
);
|
||||
|
||||
// Test 28: Legacy config without type field (backward compatibility)
|
||||
await runBasicTest(
|
||||
"config_legacy_no_type",
|
||||
"--config",
|
||||
legacyConfigPath,
|
||||
"--server",
|
||||
"test-legacy",
|
||||
"--cli",
|
||||
"--method",
|
||||
"tools/list",
|
||||
);
|
||||
|
||||
console.log(
|
||||
`\n${colors.YELLOW}=== Running Default Server Tests ===${colors.NC}`,
|
||||
);
|
||||
|
||||
// Create config with single server for auto-selection
|
||||
const singleServerConfigPath = path.join(
|
||||
TEMP_DIR,
|
||||
"single-server-config.json",
|
||||
);
|
||||
fs.writeFileSync(
|
||||
singleServerConfigPath,
|
||||
JSON.stringify(
|
||||
{
|
||||
mcpServers: {
|
||||
"only-server": {
|
||||
command: "npx",
|
||||
args: ["@modelcontextprotocol/server-everything"],
|
||||
},
|
||||
},
|
||||
},
|
||||
null,
|
||||
2,
|
||||
),
|
||||
);
|
||||
|
||||
// Create config with default-server
|
||||
const defaultServerConfigPath = path.join(
|
||||
TEMP_DIR,
|
||||
"default-server-config.json",
|
||||
);
|
||||
fs.writeFileSync(
|
||||
defaultServerConfigPath,
|
||||
JSON.stringify(
|
||||
{
|
||||
mcpServers: {
|
||||
"default-server": {
|
||||
command: "npx",
|
||||
args: ["@modelcontextprotocol/server-everything"],
|
||||
},
|
||||
"other-server": {
|
||||
command: "node",
|
||||
args: ["other.js"],
|
||||
},
|
||||
},
|
||||
},
|
||||
null,
|
||||
2,
|
||||
),
|
||||
);
|
||||
|
||||
// Create config with multiple servers (no default)
|
||||
const multiServerConfigPath = path.join(TEMP_DIR, "multi-server-config.json");
|
||||
fs.writeFileSync(
|
||||
multiServerConfigPath,
|
||||
JSON.stringify(
|
||||
{
|
||||
mcpServers: {
|
||||
server1: {
|
||||
command: "npx",
|
||||
args: ["@modelcontextprotocol/server-everything"],
|
||||
},
|
||||
server2: {
|
||||
command: "node",
|
||||
args: ["other.js"],
|
||||
},
|
||||
},
|
||||
},
|
||||
null,
|
||||
2,
|
||||
),
|
||||
);
|
||||
|
||||
// Test 29: Config with single server auto-selection
|
||||
await runBasicTest(
|
||||
"single_server_auto_select",
|
||||
"--config",
|
||||
singleServerConfigPath,
|
||||
"--cli",
|
||||
"--method",
|
||||
"tools/list",
|
||||
);
|
||||
|
||||
// Test 30: Config with default-server should now require explicit selection (multiple servers)
|
||||
await runErrorTest(
|
||||
"default_server_requires_explicit_selection",
|
||||
"--config",
|
||||
defaultServerConfigPath,
|
||||
"--cli",
|
||||
"--method",
|
||||
"tools/list",
|
||||
);
|
||||
|
||||
// Test 31: Config with multiple servers and no default (should fail)
|
||||
await runErrorTest(
|
||||
"multi_server_no_default",
|
||||
"--config",
|
||||
multiServerConfigPath,
|
||||
"--cli",
|
||||
"--method",
|
||||
"tools/list",
|
||||
);
|
||||
|
||||
console.log(
|
||||
`\n${colors.YELLOW}=== Running HTTP Transport Tests ===${colors.NC}`,
|
||||
);
|
||||
|
||||
console.log(
|
||||
`${colors.BLUE}Starting server-everything in streamableHttp mode.${colors.NC}`,
|
||||
);
|
||||
const httpServer = spawn(
|
||||
"npx",
|
||||
["@modelcontextprotocol/server-everything", "streamableHttp"],
|
||||
{
|
||||
detached: true,
|
||||
stdio: "ignore",
|
||||
},
|
||||
);
|
||||
runningServers.push(httpServer);
|
||||
|
||||
await new Promise((resolve) => setTimeout(resolve, 3000));
|
||||
|
||||
// Test 32: HTTP transport inferred from URL ending with /mcp
|
||||
await runBasicTest(
|
||||
"http_transport_inferred",
|
||||
"http://127.0.0.1:3001/mcp",
|
||||
"--cli",
|
||||
"--method",
|
||||
"tools/list",
|
||||
);
|
||||
|
||||
// Test 33: HTTP transport with explicit --transport http flag
|
||||
await runBasicTest(
|
||||
"http_transport_with_explicit_flag",
|
||||
"http://127.0.0.1:3001/mcp",
|
||||
"--transport",
|
||||
"http",
|
||||
"--cli",
|
||||
"--method",
|
||||
"tools/list",
|
||||
);
|
||||
|
||||
// Test 34: HTTP transport with suffix and --transport http flag
|
||||
await runBasicTest(
|
||||
"http_transport_with_explicit_flag_and_suffix",
|
||||
"http://127.0.0.1:3001/mcp",
|
||||
"--transport",
|
||||
"http",
|
||||
"--cli",
|
||||
"--method",
|
||||
"tools/list",
|
||||
);
|
||||
|
||||
// Test 35: SSE transport given to HTTP server (should fail)
|
||||
await runErrorTest(
|
||||
"sse_transport_given_to_http_server",
|
||||
"http://127.0.0.1:3001",
|
||||
"--transport",
|
||||
"sse",
|
||||
"--cli",
|
||||
"--method",
|
||||
"tools/list",
|
||||
);
|
||||
|
||||
// Test 36: HTTP transport without URL (should fail)
|
||||
await runErrorTest(
|
||||
"http_transport_without_url",
|
||||
"--transport",
|
||||
"http",
|
||||
"--cli",
|
||||
"--method",
|
||||
"tools/list",
|
||||
);
|
||||
|
||||
// Test 37: SSE transport without URL (should fail)
|
||||
await runErrorTest(
|
||||
"sse_transport_without_url",
|
||||
"--transport",
|
||||
"sse",
|
||||
"--cli",
|
||||
"--method",
|
||||
"tools/list",
|
||||
);
|
||||
|
||||
// Kill HTTP server
|
||||
try {
|
||||
process.kill(-httpServer.pid);
|
||||
console.log(
|
||||
`${colors.BLUE}HTTP server killed, waiting for port to be released...${colors.NC}`,
|
||||
);
|
||||
} catch (e) {
|
||||
console.log(
|
||||
`${colors.RED}Error killing HTTP server: ${e.message}${colors.NC}`,
|
||||
);
|
||||
}
|
||||
|
||||
// Print test summary
|
||||
console.log(`\n${colors.YELLOW}=== Test Summary ===${colors.NC}`);
|
||||
console.log(`${colors.GREEN}Passed: ${PASSED_TESTS}${colors.NC}`);
|
||||
|
|
|
|||
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}`);
|
||||
|
|
|
|||
|
|
@ -1,5 +1,6 @@
|
|||
#!/usr/bin/env node
|
||||
|
||||
import open from "open";
|
||||
import { join, dirname } from "path";
|
||||
import { fileURLToPath } from "url";
|
||||
import handler from "serve-handler";
|
||||
|
|
@ -39,19 +40,23 @@ const server = http.createServer((request, response) => {
|
|||
return handler(request, response, handlerOptions);
|
||||
});
|
||||
|
||||
const port = process.env.PORT || 6274;
|
||||
const port = parseInt(process.env.CLIENT_PORT || "6274", 10);
|
||||
const host = process.env.HOST || "localhost";
|
||||
server.on("listening", () => {
|
||||
console.log(
|
||||
`🔍 MCP Inspector is up and running at http://127.0.0.1:${port} 🚀`,
|
||||
);
|
||||
const url = process.env.INSPECTOR_URL || `http://${host}:${port}`;
|
||||
console.log(`\n🚀 MCP Inspector is up and running at:\n ${url}\n`);
|
||||
if (process.env.MCP_AUTO_OPEN_ENABLED !== "false") {
|
||||
console.log(`🌐 Opening browser...`);
|
||||
open(url);
|
||||
}
|
||||
});
|
||||
server.on("error", (err) => {
|
||||
if (err.message.includes(`EADDRINUSE`)) {
|
||||
console.error(
|
||||
`❌ MCP Inspector PORT IS IN USE at http://127.0.0.1:${port} ❌ `,
|
||||
`❌ MCP Inspector PORT IS IN USE at http://${host}:${port} ❌ `,
|
||||
);
|
||||
} else {
|
||||
throw err;
|
||||
}
|
||||
});
|
||||
server.listen(port);
|
||||
server.listen(port, host);
|
||||
|
|
|
|||
Some files were not shown because too many files have changed in this diff Show more
Loading…
Reference in a new issue