Merge branch 'main' into main
This commit is contained in:
commit
9eb5e7b8c2
30 changed files with 1321 additions and 306 deletions
76
.github/workflows/e2e_tests.yml
vendored
Normal file
76
.github/workflows/e2e_tests.yml
vendored
Normal file
|
|
@ -0,0 +1,76 @@
|
||||||
|
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
|
||||||
|
with:
|
||||||
|
node-version: 18
|
||||||
|
|
||||||
|
# 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 18
|
||||||
|
**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"
|
||||||
4
.gitignore
vendored
4
.gitignore
vendored
|
|
@ -9,3 +9,7 @@ client/tsconfig.app.tsbuildinfo
|
||||||
client/tsconfig.node.tsbuildinfo
|
client/tsconfig.node.tsbuildinfo
|
||||||
cli/build
|
cli/build
|
||||||
test-output
|
test-output
|
||||||
|
client/playwright-report/
|
||||||
|
client/results.json
|
||||||
|
client/test-results/
|
||||||
|
|
||||||
|
|
|
||||||
|
|
@ -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
|
1. Fork the repository and clone it locally
|
||||||
2. Install dependencies with `npm install`
|
2. Install dependencies with `npm install`
|
||||||
3. Run `npm run dev` to start both client and server in development mode
|
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
|
## Development Process & Pull Requests
|
||||||
|
|
||||||
1. Create a new branch for your changes
|
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.
|
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
|
4. Update documentation as needed
|
||||||
5. Use clear commit messages explaining your changes
|
5. Use clear commit messages explaining your changes
|
||||||
6. Verify all changes work as expected
|
6. Verify all changes work as expected
|
||||||
|
|
|
||||||
11
README.md
11
README.md
|
|
@ -168,20 +168,20 @@ DANGEROUSLY_OMIT_AUTH=true npm start
|
||||||
|
|
||||||
#### Local-only Binding
|
#### Local-only Binding
|
||||||
|
|
||||||
By default, the MCP Inspector proxy server binds only to `127.0.0.1` (localhost) to prevent network access. This ensures the server is 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:
|
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
|
```bash
|
||||||
HOST=0.0.0.0 npm start
|
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.
|
**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
|
#### 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):
|
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
|
```bash
|
||||||
ALLOWED_ORIGINS=http://localhost:6274,http://127.0.0.1:6274,http://localhost:8000 npm start
|
ALLOWED_ORIGINS=http://localhost:6274,http://localhost:8000 npm start
|
||||||
```
|
```
|
||||||
|
|
||||||
### Configuration
|
### Configuration
|
||||||
|
|
@ -299,9 +299,12 @@ npx @modelcontextprotocol/inspector --cli node build/index.js --method resources
|
||||||
# List available prompts
|
# List available prompts
|
||||||
npx @modelcontextprotocol/inspector --cli node build/index.js --method prompts/list
|
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
|
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
|
||||||
|
|
||||||
# Call a tool on a remote server
|
# 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
|
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",
|
"name": "@modelcontextprotocol/inspector-cli",
|
||||||
"version": "0.14.3",
|
"version": "0.15.0",
|
||||||
"description": "CLI for the Model Context Protocol inspector",
|
"description": "CLI for the Model Context Protocol inspector",
|
||||||
"license": "MIT",
|
"license": "MIT",
|
||||||
"author": "Anthropic, PBC (https://anthropic.com)",
|
"author": "Anthropic, PBC (https://anthropic.com)",
|
||||||
|
|
@ -21,7 +21,7 @@
|
||||||
},
|
},
|
||||||
"devDependencies": {},
|
"devDependencies": {},
|
||||||
"dependencies": {
|
"dependencies": {
|
||||||
"@modelcontextprotocol/sdk": "^1.13.0",
|
"@modelcontextprotocol/sdk": "^1.13.1",
|
||||||
"commander": "^13.1.0",
|
"commander": "^13.1.0",
|
||||||
"spawn-rx": "^5.1.2"
|
"spawn-rx": "^5.1.2"
|
||||||
}
|
}
|
||||||
|
|
|
||||||
|
|
@ -44,7 +44,14 @@ console.log(`${colors.BLUE}- Resource-related options (--uri)${colors.NC}`);
|
||||||
console.log(
|
console.log(
|
||||||
`${colors.BLUE}- Prompt-related options (--prompt-name, --prompt-args)${colors.NC}`,
|
`${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
|
// Get directory paths
|
||||||
const SCRIPTS_DIR = __dirname;
|
const SCRIPTS_DIR = __dirname;
|
||||||
|
|
@ -62,9 +69,11 @@ if (!fs.existsSync(OUTPUT_DIR)) {
|
||||||
}
|
}
|
||||||
|
|
||||||
// Create a temporary directory for test files
|
// Create a temporary directory for test files
|
||||||
const TEMP_DIR = fs.mkdirSync(path.join(os.tmpdir(), "mcp-inspector-tests"), {
|
const TEMP_DIR = path.join(os.tmpdir(), "mcp-inspector-tests");
|
||||||
recursive: true,
|
fs.mkdirSync(TEMP_DIR, { recursive: true });
|
||||||
});
|
|
||||||
|
// Track servers for cleanup
|
||||||
|
let runningServers = [];
|
||||||
|
|
||||||
process.on("exit", () => {
|
process.on("exit", () => {
|
||||||
try {
|
try {
|
||||||
|
|
@ -74,6 +83,21 @@ process.on("exit", () => {
|
||||||
`${colors.RED}Failed to remove temp directory: ${err.message}${colors.NC}`,
|
`${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
|
// Use the existing sample config file
|
||||||
|
|
@ -121,6 +145,11 @@ async function runBasicTest(testName, ...args) {
|
||||||
stdio: ["ignore", "pipe", "pipe"],
|
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
|
// Pipe stdout and stderr to the output file
|
||||||
child.stdout.pipe(outputStream);
|
child.stdout.pipe(outputStream);
|
||||||
child.stderr.pipe(outputStream);
|
child.stderr.pipe(outputStream);
|
||||||
|
|
@ -135,6 +164,7 @@ async function runBasicTest(testName, ...args) {
|
||||||
});
|
});
|
||||||
|
|
||||||
child.on("close", (code) => {
|
child.on("close", (code) => {
|
||||||
|
clearTimeout(timeout);
|
||||||
outputStream.end();
|
outputStream.end();
|
||||||
|
|
||||||
if (code === 0) {
|
if (code === 0) {
|
||||||
|
|
@ -201,6 +231,13 @@ async function runErrorTest(testName, ...args) {
|
||||||
stdio: ["ignore", "pipe", "pipe"],
|
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
|
// Pipe stdout and stderr to the output file
|
||||||
child.stdout.pipe(outputStream);
|
child.stdout.pipe(outputStream);
|
||||||
child.stderr.pipe(outputStream);
|
child.stderr.pipe(outputStream);
|
||||||
|
|
@ -215,6 +252,7 @@ async function runErrorTest(testName, ...args) {
|
||||||
});
|
});
|
||||||
|
|
||||||
child.on("close", (code) => {
|
child.on("close", (code) => {
|
||||||
|
clearTimeout(timeout);
|
||||||
outputStream.end();
|
outputStream.end();
|
||||||
|
|
||||||
// For error tests, we expect a non-zero exit code
|
// For error tests, we expect a non-zero exit code
|
||||||
|
|
@ -611,6 +649,79 @@ async function runTests() {
|
||||||
"debug",
|
"debug",
|
||||||
);
|
);
|
||||||
|
|
||||||
|
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 25: 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 26: HTTP transport with explicit --transport http flag
|
||||||
|
await runBasicTest(
|
||||||
|
"http_transport_with_explicit_flag",
|
||||||
|
"http://127.0.0.1:3001",
|
||||||
|
"--transport",
|
||||||
|
"http",
|
||||||
|
"--cli",
|
||||||
|
"--method",
|
||||||
|
"tools/list",
|
||||||
|
);
|
||||||
|
|
||||||
|
// Test 27: 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 28: 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",
|
||||||
|
);
|
||||||
|
|
||||||
|
// 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
|
// Print test summary
|
||||||
console.log(`\n${colors.YELLOW}=== Test Summary ===${colors.NC}`);
|
console.log(`\n${colors.YELLOW}=== Test Summary ===${colors.NC}`);
|
||||||
console.log(`${colors.GREEN}Passed: ${PASSED_TESTS}${colors.NC}`);
|
console.log(`${colors.GREEN}Passed: ${PASSED_TESTS}${colors.NC}`);
|
||||||
|
|
|
||||||
|
|
@ -29,9 +29,13 @@ type Args = {
|
||||||
logLevel?: LogLevel;
|
logLevel?: LogLevel;
|
||||||
toolName?: string;
|
toolName?: string;
|
||||||
toolArg?: Record<string, 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) {
|
if (target.length === 0) {
|
||||||
throw new Error(
|
throw new Error(
|
||||||
"Target is required. Specify a URL or a command to execute.",
|
"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.");
|
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 {
|
return {
|
||||||
transportType: isUrl ? "sse" : "stdio",
|
transportType,
|
||||||
command: isUrl ? undefined : command,
|
command: isUrl ? undefined : command,
|
||||||
args: isUrl ? undefined : commandArgs,
|
args: isUrl ? undefined : commandArgs,
|
||||||
url: isUrl ? command : undefined,
|
url: isUrl ? command : undefined,
|
||||||
|
|
@ -59,7 +85,7 @@ function createTransportOptions(target: string[]): TransportOptions {
|
||||||
}
|
}
|
||||||
|
|
||||||
async function callMethod(args: Args): Promise<void> {
|
async function callMethod(args: Args): Promise<void> {
|
||||||
const transportOptions = createTransportOptions(args.target);
|
const transportOptions = createTransportOptions(args.target, args.transport);
|
||||||
const transport = createTransport(transportOptions);
|
const transport = createTransport(transportOptions);
|
||||||
const client = new Client({
|
const client = new Client({
|
||||||
name: "inspector-cli",
|
name: "inspector-cli",
|
||||||
|
|
@ -214,6 +240,22 @@ function parseArgs(): Args {
|
||||||
|
|
||||||
return value as LogLevel;
|
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 --
|
// Parse only the arguments before --
|
||||||
|
|
|
||||||
|
|
@ -3,11 +3,12 @@ import {
|
||||||
getDefaultEnvironment,
|
getDefaultEnvironment,
|
||||||
StdioClientTransport,
|
StdioClientTransport,
|
||||||
} from "@modelcontextprotocol/sdk/client/stdio.js";
|
} from "@modelcontextprotocol/sdk/client/stdio.js";
|
||||||
|
import { StreamableHTTPClientTransport } from "@modelcontextprotocol/sdk/client/streamableHttp.js";
|
||||||
import type { Transport } from "@modelcontextprotocol/sdk/shared/transport.js";
|
import type { Transport } from "@modelcontextprotocol/sdk/shared/transport.js";
|
||||||
import { findActualExecutable } from "spawn-rx";
|
import { findActualExecutable } from "spawn-rx";
|
||||||
|
|
||||||
export type TransportOptions = {
|
export type TransportOptions = {
|
||||||
transportType: "sse" | "stdio";
|
transportType: "sse" | "stdio" | "http";
|
||||||
command?: string;
|
command?: string;
|
||||||
args?: string[];
|
args?: string[];
|
||||||
url?: string;
|
url?: string;
|
||||||
|
|
@ -15,11 +16,22 @@ export type TransportOptions = {
|
||||||
|
|
||||||
function createSSETransport(options: TransportOptions): Transport {
|
function createSSETransport(options: TransportOptions): Transport {
|
||||||
const baseUrl = new URL(options.url ?? "");
|
const baseUrl = new URL(options.url ?? "");
|
||||||
const sseUrl = new URL("/sse", baseUrl);
|
const sseUrl = baseUrl.pathname.endsWith("/sse")
|
||||||
|
? baseUrl
|
||||||
|
: new URL("/sse", baseUrl);
|
||||||
|
|
||||||
return new SSEClientTransport(sseUrl);
|
return new SSEClientTransport(sseUrl);
|
||||||
}
|
}
|
||||||
|
|
||||||
|
function createHTTPTransport(options: TransportOptions): Transport {
|
||||||
|
const baseUrl = new URL(options.url ?? "");
|
||||||
|
const mcpUrl = baseUrl.pathname.endsWith("/mcp")
|
||||||
|
? baseUrl
|
||||||
|
: new URL("/mcp", baseUrl);
|
||||||
|
|
||||||
|
return new StreamableHTTPClientTransport(mcpUrl);
|
||||||
|
}
|
||||||
|
|
||||||
function createStdioTransport(options: TransportOptions): Transport {
|
function createStdioTransport(options: TransportOptions): Transport {
|
||||||
let args: string[] = [];
|
let args: string[] = [];
|
||||||
|
|
||||||
|
|
@ -67,6 +79,10 @@ export function createTransport(options: TransportOptions): Transport {
|
||||||
return createSSETransport(options);
|
return createSSETransport(options);
|
||||||
}
|
}
|
||||||
|
|
||||||
|
if (transportType === "http") {
|
||||||
|
return createHTTPTransport(options);
|
||||||
|
}
|
||||||
|
|
||||||
throw new Error(`Unsupported transport type: ${transportType}`);
|
throw new Error(`Unsupported transport type: ${transportType}`);
|
||||||
} catch (error) {
|
} catch (error) {
|
||||||
throw new Error(
|
throw new Error(
|
||||||
|
|
|
||||||
|
|
@ -1,5 +1,6 @@
|
||||||
#!/usr/bin/env node
|
#!/usr/bin/env node
|
||||||
|
|
||||||
|
import open from "open";
|
||||||
import { join, dirname } from "path";
|
import { join, dirname } from "path";
|
||||||
import { fileURLToPath } from "url";
|
import { fileURLToPath } from "url";
|
||||||
import handler from "serve-handler";
|
import handler from "serve-handler";
|
||||||
|
|
@ -39,19 +40,23 @@ const server = http.createServer((request, response) => {
|
||||||
return handler(request, response, handlerOptions);
|
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", () => {
|
server.on("listening", () => {
|
||||||
console.log(
|
const url = process.env.INSPECTOR_URL || `http://${host}:${port}`;
|
||||||
`🔍 MCP Inspector is up and running at http://127.0.0.1:${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) => {
|
server.on("error", (err) => {
|
||||||
if (err.message.includes(`EADDRINUSE`)) {
|
if (err.message.includes(`EADDRINUSE`)) {
|
||||||
console.error(
|
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 {
|
} else {
|
||||||
throw err;
|
throw err;
|
||||||
}
|
}
|
||||||
});
|
});
|
||||||
server.listen(port);
|
server.listen(port, host);
|
||||||
|
|
|
||||||
|
|
@ -7,11 +7,26 @@ import { fileURLToPath } from "url";
|
||||||
import { randomBytes } from "crypto";
|
import { randomBytes } from "crypto";
|
||||||
|
|
||||||
const __dirname = dirname(fileURLToPath(import.meta.url));
|
const __dirname = dirname(fileURLToPath(import.meta.url));
|
||||||
|
const DEFAULT_MCP_PROXY_LISTEN_PORT = "6277";
|
||||||
|
|
||||||
function delay(ms) {
|
function delay(ms) {
|
||||||
return new Promise((resolve) => setTimeout(resolve, ms, true));
|
return new Promise((resolve) => setTimeout(resolve, ms, true));
|
||||||
}
|
}
|
||||||
|
|
||||||
|
function getClientUrl(port, authDisabled, sessionToken, serverPort) {
|
||||||
|
const host = process.env.HOST || "localhost";
|
||||||
|
const baseUrl = `http://${host}:${port}`;
|
||||||
|
|
||||||
|
const params = new URLSearchParams();
|
||||||
|
if (serverPort && serverPort !== DEFAULT_MCP_PROXY_LISTEN_PORT) {
|
||||||
|
params.set("MCP_PROXY_PORT", serverPort);
|
||||||
|
}
|
||||||
|
if (!authDisabled) {
|
||||||
|
params.set("MCP_PROXY_AUTH_TOKEN", sessionToken);
|
||||||
|
}
|
||||||
|
return params.size > 0 ? `${baseUrl}/?${params.toString()}` : baseUrl;
|
||||||
|
}
|
||||||
|
|
||||||
async function startDevServer(serverOptions) {
|
async function startDevServer(serverOptions) {
|
||||||
const { SERVER_PORT, CLIENT_PORT, sessionToken, envVars, abort } =
|
const { SERVER_PORT, CLIENT_PORT, sessionToken, envVars, abort } =
|
||||||
serverOptions;
|
serverOptions;
|
||||||
|
|
@ -23,8 +38,8 @@ async function startDevServer(serverOptions) {
|
||||||
cwd: resolve(__dirname, "../..", "server"),
|
cwd: resolve(__dirname, "../..", "server"),
|
||||||
env: {
|
env: {
|
||||||
...process.env,
|
...process.env,
|
||||||
PORT: SERVER_PORT,
|
SERVER_PORT,
|
||||||
CLIENT_PORT: CLIENT_PORT,
|
CLIENT_PORT,
|
||||||
MCP_PROXY_TOKEN: sessionToken,
|
MCP_PROXY_TOKEN: sessionToken,
|
||||||
MCP_ENV_VARS: JSON.stringify(envVars),
|
MCP_ENV_VARS: JSON.stringify(envVars),
|
||||||
},
|
},
|
||||||
|
|
@ -82,8 +97,8 @@ async function startProdServer(serverOptions) {
|
||||||
{
|
{
|
||||||
env: {
|
env: {
|
||||||
...process.env,
|
...process.env,
|
||||||
PORT: SERVER_PORT,
|
SERVER_PORT,
|
||||||
CLIENT_PORT: CLIENT_PORT,
|
CLIENT_PORT,
|
||||||
MCP_PROXY_TOKEN: sessionToken,
|
MCP_PROXY_TOKEN: sessionToken,
|
||||||
MCP_ENV_VARS: JSON.stringify(envVars),
|
MCP_ENV_VARS: JSON.stringify(envVars),
|
||||||
},
|
},
|
||||||
|
|
@ -99,30 +114,40 @@ async function startProdServer(serverOptions) {
|
||||||
}
|
}
|
||||||
|
|
||||||
async function startDevClient(clientOptions) {
|
async function startDevClient(clientOptions) {
|
||||||
const { CLIENT_PORT, authDisabled, sessionToken, abort, cancelled } =
|
const {
|
||||||
clientOptions;
|
CLIENT_PORT,
|
||||||
|
SERVER_PORT,
|
||||||
|
authDisabled,
|
||||||
|
sessionToken,
|
||||||
|
abort,
|
||||||
|
cancelled,
|
||||||
|
} = clientOptions;
|
||||||
const clientCommand = "npx";
|
const clientCommand = "npx";
|
||||||
const clientArgs = ["vite", "--port", CLIENT_PORT];
|
const host = process.env.HOST || "localhost";
|
||||||
|
const clientArgs = ["vite", "--port", CLIENT_PORT, "--host", host];
|
||||||
|
|
||||||
const client = spawn(clientCommand, clientArgs, {
|
const client = spawn(clientCommand, clientArgs, {
|
||||||
cwd: resolve(__dirname, ".."),
|
cwd: resolve(__dirname, ".."),
|
||||||
env: { ...process.env, PORT: CLIENT_PORT },
|
env: { ...process.env, CLIENT_PORT },
|
||||||
signal: abort.signal,
|
signal: abort.signal,
|
||||||
echoOutput: true,
|
echoOutput: true,
|
||||||
});
|
});
|
||||||
|
|
||||||
// Auto-open browser after vite starts
|
const url = getClientUrl(
|
||||||
if (process.env.MCP_AUTO_OPEN_ENABLED !== "false") {
|
CLIENT_PORT,
|
||||||
const url = authDisabled
|
authDisabled,
|
||||||
? `http://127.0.0.1:${CLIENT_PORT}`
|
sessionToken,
|
||||||
: `http://127.0.0.1:${CLIENT_PORT}/?MCP_PROXY_AUTH_TOKEN=${sessionToken}`;
|
SERVER_PORT,
|
||||||
|
);
|
||||||
|
|
||||||
// Give vite time to start before opening browser
|
// Give vite time to start before opening or logging the URL
|
||||||
setTimeout(() => {
|
setTimeout(() => {
|
||||||
|
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);
|
open(url);
|
||||||
console.log(`\n🔗 Opening browser at: ${url}\n`);
|
}
|
||||||
}, 3000);
|
}, 3000);
|
||||||
}
|
|
||||||
|
|
||||||
await new Promise((resolve) => {
|
await new Promise((resolve) => {
|
||||||
client.subscribe({
|
client.subscribe({
|
||||||
|
|
@ -139,7 +164,14 @@ async function startDevClient(clientOptions) {
|
||||||
}
|
}
|
||||||
|
|
||||||
async function startProdClient(clientOptions) {
|
async function startProdClient(clientOptions) {
|
||||||
const { CLIENT_PORT, authDisabled, sessionToken, abort } = clientOptions;
|
const {
|
||||||
|
CLIENT_PORT,
|
||||||
|
SERVER_PORT,
|
||||||
|
authDisabled,
|
||||||
|
sessionToken,
|
||||||
|
abort,
|
||||||
|
cancelled,
|
||||||
|
} = clientOptions;
|
||||||
const inspectorClientPath = resolve(
|
const inspectorClientPath = resolve(
|
||||||
__dirname,
|
__dirname,
|
||||||
"../..",
|
"../..",
|
||||||
|
|
@ -148,16 +180,19 @@ async function startProdClient(clientOptions) {
|
||||||
"client.js",
|
"client.js",
|
||||||
);
|
);
|
||||||
|
|
||||||
// Auto-open browser with token
|
const url = getClientUrl(
|
||||||
if (process.env.MCP_AUTO_OPEN_ENABLED !== "false") {
|
CLIENT_PORT,
|
||||||
const url = authDisabled
|
authDisabled,
|
||||||
? `http://127.0.0.1:${CLIENT_PORT}`
|
sessionToken,
|
||||||
: `http://127.0.0.1:${CLIENT_PORT}/?MCP_PROXY_AUTH_TOKEN=${sessionToken}`;
|
SERVER_PORT,
|
||||||
open(url);
|
);
|
||||||
}
|
|
||||||
|
|
||||||
await spawnPromise("node", [inspectorClientPath], {
|
await spawnPromise("node", [inspectorClientPath], {
|
||||||
env: { ...process.env, PORT: CLIENT_PORT },
|
env: {
|
||||||
|
...process.env,
|
||||||
|
CLIENT_PORT,
|
||||||
|
INSPECTOR_URL: url,
|
||||||
|
},
|
||||||
signal: abort.signal,
|
signal: abort.signal,
|
||||||
echoOutput: true,
|
echoOutput: true,
|
||||||
});
|
});
|
||||||
|
|
@ -204,7 +239,7 @@ async function main() {
|
||||||
}
|
}
|
||||||
|
|
||||||
const CLIENT_PORT = process.env.CLIENT_PORT ?? "6274";
|
const CLIENT_PORT = process.env.CLIENT_PORT ?? "6274";
|
||||||
const SERVER_PORT = process.env.SERVER_PORT ?? "6277";
|
const SERVER_PORT = process.env.SERVER_PORT ?? DEFAULT_MCP_PROXY_LISTEN_PORT;
|
||||||
|
|
||||||
console.log(
|
console.log(
|
||||||
isDev
|
isDev
|
||||||
|
|
@ -249,6 +284,7 @@ async function main() {
|
||||||
try {
|
try {
|
||||||
const clientOptions = {
|
const clientOptions = {
|
||||||
CLIENT_PORT,
|
CLIENT_PORT,
|
||||||
|
SERVER_PORT,
|
||||||
authDisabled,
|
authDisabled,
|
||||||
sessionToken,
|
sessionToken,
|
||||||
abort,
|
abort,
|
||||||
|
|
|
||||||
18
client/e2e/global-teardown.js
Normal file
18
client/e2e/global-teardown.js
Normal file
|
|
@ -0,0 +1,18 @@
|
||||||
|
import { rimraf } from "rimraf";
|
||||||
|
|
||||||
|
async function globalTeardown() {
|
||||||
|
if (!process.env.CI) {
|
||||||
|
console.log("Cleaning up test-results directory...");
|
||||||
|
// Add a small delay to ensure all Playwright files are written
|
||||||
|
await new Promise((resolve) => setTimeout(resolve, 100));
|
||||||
|
await rimraf("./e2e/test-results");
|
||||||
|
console.log("Test-results directory cleaned up.");
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
export default globalTeardown;
|
||||||
|
|
||||||
|
// Call the function when this script is run directly
|
||||||
|
if (import.meta.url === `file://${process.argv[1]}`) {
|
||||||
|
globalTeardown().catch(console.error);
|
||||||
|
}
|
||||||
113
client/e2e/transport-type-dropdown.spec.ts
Normal file
113
client/e2e/transport-type-dropdown.spec.ts
Normal file
|
|
@ -0,0 +1,113 @@
|
||||||
|
import { test, expect } from "@playwright/test";
|
||||||
|
|
||||||
|
// Adjust the URL if your dev server runs on a different port
|
||||||
|
const APP_URL = "http://localhost:6274/";
|
||||||
|
|
||||||
|
test.describe("Transport Type Dropdown", () => {
|
||||||
|
test("should have options for STDIO, SSE, and Streamable HTTP", async ({
|
||||||
|
page,
|
||||||
|
}) => {
|
||||||
|
await page.goto(APP_URL);
|
||||||
|
|
||||||
|
// Wait for the Transport Type dropdown to be visible
|
||||||
|
const selectTrigger = page.getByLabel("Transport Type");
|
||||||
|
await expect(selectTrigger).toBeVisible();
|
||||||
|
|
||||||
|
// Open the dropdown
|
||||||
|
await selectTrigger.click();
|
||||||
|
|
||||||
|
// Check for the three options
|
||||||
|
await expect(page.getByRole("option", { name: "STDIO" })).toBeVisible();
|
||||||
|
await expect(page.getByRole("option", { name: "SSE" })).toBeVisible();
|
||||||
|
await expect(
|
||||||
|
page.getByRole("option", { name: "Streamable HTTP" }),
|
||||||
|
).toBeVisible();
|
||||||
|
});
|
||||||
|
|
||||||
|
test("should show Command and Arguments fields and hide URL field when Transport Type is STDIO", async ({
|
||||||
|
page,
|
||||||
|
}) => {
|
||||||
|
await page.goto(APP_URL);
|
||||||
|
|
||||||
|
// Wait for the Transport Type dropdown to be visible
|
||||||
|
const selectTrigger = page.getByLabel("Transport Type");
|
||||||
|
await expect(selectTrigger).toBeVisible();
|
||||||
|
|
||||||
|
// Open the dropdown and select STDIO
|
||||||
|
await selectTrigger.click();
|
||||||
|
await page.getByRole("option", { name: "STDIO" }).click();
|
||||||
|
|
||||||
|
// Wait for the form to update
|
||||||
|
await page.waitForTimeout(100);
|
||||||
|
|
||||||
|
// Check that Command and Arguments fields are visible
|
||||||
|
await expect(page.locator("#command-input")).toBeVisible();
|
||||||
|
await expect(page.locator("#arguments-input")).toBeVisible();
|
||||||
|
|
||||||
|
// Check that URL field is not visible
|
||||||
|
await expect(page.locator("#sse-url-input")).not.toBeVisible();
|
||||||
|
|
||||||
|
// Also verify the labels are present
|
||||||
|
await expect(page.getByText("Command")).toBeVisible();
|
||||||
|
await expect(page.getByText("Arguments")).toBeVisible();
|
||||||
|
await expect(page.getByText("URL")).not.toBeVisible();
|
||||||
|
});
|
||||||
|
|
||||||
|
test("should show URL field and hide Command and Arguments fields when Transport Type is SSE", async ({
|
||||||
|
page,
|
||||||
|
}) => {
|
||||||
|
await page.goto(APP_URL);
|
||||||
|
|
||||||
|
// Wait for the Transport Type dropdown to be visible
|
||||||
|
const selectTrigger = page.getByLabel("Transport Type");
|
||||||
|
await expect(selectTrigger).toBeVisible();
|
||||||
|
|
||||||
|
// Open the dropdown and select SSE
|
||||||
|
await selectTrigger.click();
|
||||||
|
await page.getByRole("option", { name: "SSE" }).click();
|
||||||
|
|
||||||
|
// Wait for the form to update
|
||||||
|
await page.waitForTimeout(100);
|
||||||
|
|
||||||
|
// Check that URL field is visible
|
||||||
|
await expect(page.locator("#sse-url-input")).toBeVisible();
|
||||||
|
|
||||||
|
// Check that Command and Arguments fields are not visible
|
||||||
|
await expect(page.locator("#command-input")).not.toBeVisible();
|
||||||
|
await expect(page.locator("#arguments-input")).not.toBeVisible();
|
||||||
|
|
||||||
|
// Also verify the labels are present/absent
|
||||||
|
await expect(page.getByText("URL")).toBeVisible();
|
||||||
|
await expect(page.getByText("Command")).not.toBeVisible();
|
||||||
|
await expect(page.getByText("Arguments")).not.toBeVisible();
|
||||||
|
});
|
||||||
|
|
||||||
|
test("should show URL field and hide Command and Arguments fields when Transport Type is Streamable HTTP", async ({
|
||||||
|
page,
|
||||||
|
}) => {
|
||||||
|
await page.goto(APP_URL);
|
||||||
|
|
||||||
|
// Wait for the Transport Type dropdown to be visible
|
||||||
|
const selectTrigger = page.getByLabel("Transport Type");
|
||||||
|
await expect(selectTrigger).toBeVisible();
|
||||||
|
|
||||||
|
// Open the dropdown and select Streamable HTTP
|
||||||
|
await selectTrigger.click();
|
||||||
|
await page.getByRole("option", { name: "Streamable HTTP" }).click();
|
||||||
|
|
||||||
|
// Wait for the form to update
|
||||||
|
await page.waitForTimeout(100);
|
||||||
|
|
||||||
|
// Check that URL field is visible
|
||||||
|
await expect(page.locator("#sse-url-input")).toBeVisible();
|
||||||
|
|
||||||
|
// Check that Command and Arguments fields are not visible
|
||||||
|
await expect(page.locator("#command-input")).not.toBeVisible();
|
||||||
|
await expect(page.locator("#arguments-input")).not.toBeVisible();
|
||||||
|
|
||||||
|
// Also verify the labels are present/absent
|
||||||
|
await expect(page.getByText("URL")).toBeVisible();
|
||||||
|
await expect(page.getByText("Command")).not.toBeVisible();
|
||||||
|
await expect(page.getByText("Arguments")).not.toBeVisible();
|
||||||
|
});
|
||||||
|
});
|
||||||
|
|
@ -21,6 +21,7 @@ module.exports = {
|
||||||
"/node_modules/",
|
"/node_modules/",
|
||||||
"/dist/",
|
"/dist/",
|
||||||
"/bin/",
|
"/bin/",
|
||||||
|
"/e2e/",
|
||||||
"\\.config\\.(js|ts|cjs|mjs)$",
|
"\\.config\\.(js|ts|cjs|mjs)$",
|
||||||
],
|
],
|
||||||
// Exclude the same patterns from coverage reports
|
// Exclude the same patterns from coverage reports
|
||||||
|
|
@ -28,6 +29,7 @@ module.exports = {
|
||||||
"/node_modules/",
|
"/node_modules/",
|
||||||
"/dist/",
|
"/dist/",
|
||||||
"/bin/",
|
"/bin/",
|
||||||
|
"/e2e/",
|
||||||
"\\.config\\.(js|ts|cjs|mjs)$",
|
"\\.config\\.(js|ts|cjs|mjs)$",
|
||||||
],
|
],
|
||||||
};
|
};
|
||||||
|
|
|
||||||
|
|
@ -1,6 +1,6 @@
|
||||||
{
|
{
|
||||||
"name": "@modelcontextprotocol/inspector-client",
|
"name": "@modelcontextprotocol/inspector-client",
|
||||||
"version": "0.14.3",
|
"version": "0.15.0",
|
||||||
"description": "Client-side application for the Model Context Protocol inspector",
|
"description": "Client-side application for the Model Context Protocol inspector",
|
||||||
"license": "MIT",
|
"license": "MIT",
|
||||||
"author": "Anthropic, PBC (https://anthropic.com)",
|
"author": "Anthropic, PBC (https://anthropic.com)",
|
||||||
|
|
@ -20,10 +20,12 @@
|
||||||
"lint": "eslint .",
|
"lint": "eslint .",
|
||||||
"preview": "vite preview --port 6274",
|
"preview": "vite preview --port 6274",
|
||||||
"test": "jest --config jest.config.cjs",
|
"test": "jest --config jest.config.cjs",
|
||||||
"test:watch": "jest --config jest.config.cjs --watch"
|
"test:watch": "jest --config jest.config.cjs --watch",
|
||||||
|
"test:e2e": "playwright test e2e && npm run cleanup:e2e",
|
||||||
|
"cleanup:e2e": "node e2e/global-teardown.js"
|
||||||
},
|
},
|
||||||
"dependencies": {
|
"dependencies": {
|
||||||
"@modelcontextprotocol/sdk": "^1.13.0",
|
"@modelcontextprotocol/sdk": "^1.13.1",
|
||||||
"@radix-ui/react-checkbox": "^1.1.4",
|
"@radix-ui/react-checkbox": "^1.1.4",
|
||||||
"ajv": "^6.12.6",
|
"ajv": "^6.12.6",
|
||||||
"@radix-ui/react-dialog": "^1.1.3",
|
"@radix-ui/react-dialog": "^1.1.3",
|
||||||
|
|
@ -38,7 +40,7 @@
|
||||||
"class-variance-authority": "^0.7.0",
|
"class-variance-authority": "^0.7.0",
|
||||||
"clsx": "^2.1.1",
|
"clsx": "^2.1.1",
|
||||||
"cmdk": "^1.0.4",
|
"cmdk": "^1.0.4",
|
||||||
"lucide-react": "^0.447.0",
|
"lucide-react": "^0.523.0",
|
||||||
"pkce-challenge": "^4.1.0",
|
"pkce-challenge": "^4.1.0",
|
||||||
"prismjs": "^1.30.0",
|
"prismjs": "^1.30.0",
|
||||||
"react": "^18.3.1",
|
"react": "^18.3.1",
|
||||||
|
|
|
||||||
70
client/playwright.config.ts
Normal file
70
client/playwright.config.ts
Normal file
|
|
@ -0,0 +1,70 @@
|
||||||
|
import { defineConfig, devices } from "@playwright/test";
|
||||||
|
|
||||||
|
/**
|
||||||
|
* @see https://playwright.dev/docs/test-configuration
|
||||||
|
*/
|
||||||
|
export default defineConfig({
|
||||||
|
/* Run your local dev server before starting the tests */
|
||||||
|
webServer: {
|
||||||
|
cwd: "..",
|
||||||
|
command: "npm run dev",
|
||||||
|
url: "http://localhost:6274",
|
||||||
|
reuseExistingServer: !process.env.CI,
|
||||||
|
},
|
||||||
|
|
||||||
|
testDir: "./e2e",
|
||||||
|
outputDir: "./e2e/test-results",
|
||||||
|
/* Run tests in files in parallel */
|
||||||
|
fullyParallel: true,
|
||||||
|
/* Fail the build on CI if you accidentally left test.only in the source code. */
|
||||||
|
forbidOnly: !!process.env.CI,
|
||||||
|
/* Retry on CI only */
|
||||||
|
retries: process.env.CI ? 2 : 0,
|
||||||
|
/* Opt out of parallel tests on CI. */
|
||||||
|
workers: process.env.CI ? 1 : undefined,
|
||||||
|
/* Reporter to use. See https://playwright.dev/docs/test-reporters */
|
||||||
|
reporter: process.env.CI
|
||||||
|
? [
|
||||||
|
["html", { outputFolder: "playwright-report" }],
|
||||||
|
["json", { outputFile: "results.json" }],
|
||||||
|
["line"],
|
||||||
|
]
|
||||||
|
: [["line"]],
|
||||||
|
/* Shared settings for all the projects below. See https://playwright.dev/docs/api/class-testoptions. */
|
||||||
|
use: {
|
||||||
|
/* Base URL to use in actions like `await page.goto('/')`. */
|
||||||
|
baseURL: "http://localhost:6274",
|
||||||
|
|
||||||
|
/* Collect trace when retrying the failed test. See https://playwright.dev/docs/trace-viewer */
|
||||||
|
trace: "on-first-retry",
|
||||||
|
|
||||||
|
/* Take screenshots on failure */
|
||||||
|
screenshot: "only-on-failure",
|
||||||
|
|
||||||
|
/* Record video on failure */
|
||||||
|
video: "retain-on-failure",
|
||||||
|
},
|
||||||
|
|
||||||
|
/* Configure projects for major browsers */
|
||||||
|
projects: [
|
||||||
|
{
|
||||||
|
name: "chromium",
|
||||||
|
use: { ...devices["Desktop Chrome"] },
|
||||||
|
},
|
||||||
|
|
||||||
|
{
|
||||||
|
name: "firefox",
|
||||||
|
use: { ...devices["Desktop Firefox"] },
|
||||||
|
},
|
||||||
|
|
||||||
|
// Skip WebKit on macOS due to compatibility issues
|
||||||
|
...(process.platform !== "darwin"
|
||||||
|
? [
|
||||||
|
{
|
||||||
|
name: "webkit",
|
||||||
|
use: { ...devices["Desktop Safari"] },
|
||||||
|
},
|
||||||
|
]
|
||||||
|
: []),
|
||||||
|
],
|
||||||
|
});
|
||||||
|
|
@ -16,10 +16,39 @@ interface DynamicJsonFormProps {
|
||||||
const isSimpleObject = (schema: JsonSchemaType): boolean => {
|
const isSimpleObject = (schema: JsonSchemaType): boolean => {
|
||||||
const supportedTypes = ["string", "number", "integer", "boolean", "null"];
|
const supportedTypes = ["string", "number", "integer", "boolean", "null"];
|
||||||
if (supportedTypes.includes(schema.type)) return true;
|
if (supportedTypes.includes(schema.type)) return true;
|
||||||
if (schema.type !== "object") return false;
|
if (schema.type === "object") {
|
||||||
return Object.values(schema.properties ?? {}).every((prop) =>
|
return Object.values(schema.properties ?? {}).every((prop) =>
|
||||||
supportedTypes.includes(prop.type),
|
supportedTypes.includes(prop.type),
|
||||||
);
|
);
|
||||||
|
}
|
||||||
|
if (schema.type === "array") {
|
||||||
|
return !!schema.items && isSimpleObject(schema.items);
|
||||||
|
}
|
||||||
|
return false;
|
||||||
|
};
|
||||||
|
|
||||||
|
const getArrayItemDefault = (schema: JsonSchemaType): JsonValue => {
|
||||||
|
if ("default" in schema && schema.default !== undefined) {
|
||||||
|
return schema.default;
|
||||||
|
}
|
||||||
|
|
||||||
|
switch (schema.type) {
|
||||||
|
case "string":
|
||||||
|
return "";
|
||||||
|
case "number":
|
||||||
|
case "integer":
|
||||||
|
return 0;
|
||||||
|
case "boolean":
|
||||||
|
return false;
|
||||||
|
case "array":
|
||||||
|
return [];
|
||||||
|
case "object":
|
||||||
|
return {};
|
||||||
|
case "null":
|
||||||
|
return null;
|
||||||
|
default:
|
||||||
|
return null;
|
||||||
|
}
|
||||||
};
|
};
|
||||||
|
|
||||||
const DynamicJsonForm = ({
|
const DynamicJsonForm = ({
|
||||||
|
|
@ -113,6 +142,8 @@ const DynamicJsonForm = ({
|
||||||
currentValue: JsonValue,
|
currentValue: JsonValue,
|
||||||
path: string[] = [],
|
path: string[] = [],
|
||||||
depth: number = 0,
|
depth: number = 0,
|
||||||
|
parentSchema?: JsonSchemaType,
|
||||||
|
propertyName?: string,
|
||||||
) => {
|
) => {
|
||||||
if (
|
if (
|
||||||
depth >= maxDepth &&
|
depth >= maxDepth &&
|
||||||
|
|
@ -122,7 +153,8 @@ const DynamicJsonForm = ({
|
||||||
return (
|
return (
|
||||||
<JsonEditor
|
<JsonEditor
|
||||||
value={JSON.stringify(
|
value={JSON.stringify(
|
||||||
currentValue ?? generateDefaultValue(propSchema),
|
currentValue ??
|
||||||
|
generateDefaultValue(propSchema, propertyName, parentSchema),
|
||||||
null,
|
null,
|
||||||
2,
|
2,
|
||||||
)}
|
)}
|
||||||
|
|
@ -140,6 +172,10 @@ const DynamicJsonForm = ({
|
||||||
);
|
);
|
||||||
}
|
}
|
||||||
|
|
||||||
|
// Check if this property is required in the parent schema
|
||||||
|
const isRequired =
|
||||||
|
parentSchema?.required?.includes(propertyName || "") ?? false;
|
||||||
|
|
||||||
switch (propSchema.type) {
|
switch (propSchema.type) {
|
||||||
case "string":
|
case "string":
|
||||||
return (
|
return (
|
||||||
|
|
@ -148,16 +184,11 @@ const DynamicJsonForm = ({
|
||||||
value={(currentValue as string) ?? ""}
|
value={(currentValue as string) ?? ""}
|
||||||
onChange={(e) => {
|
onChange={(e) => {
|
||||||
const val = e.target.value;
|
const val = e.target.value;
|
||||||
// Allow clearing non-required fields by setting undefined
|
// Always allow setting string values, including empty strings
|
||||||
// This preserves the distinction between empty string and unset
|
handleFieldChange(path, val);
|
||||||
if (!val && !propSchema.required) {
|
|
||||||
handleFieldChange(path, undefined);
|
|
||||||
} else {
|
|
||||||
handleFieldChange(path, val);
|
|
||||||
}
|
|
||||||
}}
|
}}
|
||||||
placeholder={propSchema.description}
|
placeholder={propSchema.description}
|
||||||
required={propSchema.required}
|
required={isRequired}
|
||||||
/>
|
/>
|
||||||
);
|
);
|
||||||
case "number":
|
case "number":
|
||||||
|
|
@ -167,9 +198,7 @@ const DynamicJsonForm = ({
|
||||||
value={(currentValue as number)?.toString() ?? ""}
|
value={(currentValue as number)?.toString() ?? ""}
|
||||||
onChange={(e) => {
|
onChange={(e) => {
|
||||||
const val = e.target.value;
|
const val = e.target.value;
|
||||||
// Allow clearing non-required number fields
|
if (!val && !isRequired) {
|
||||||
// This preserves the distinction between 0 and unset
|
|
||||||
if (!val && !propSchema.required) {
|
|
||||||
handleFieldChange(path, undefined);
|
handleFieldChange(path, undefined);
|
||||||
} else {
|
} else {
|
||||||
const num = Number(val);
|
const num = Number(val);
|
||||||
|
|
@ -179,7 +208,7 @@ const DynamicJsonForm = ({
|
||||||
}
|
}
|
||||||
}}
|
}}
|
||||||
placeholder={propSchema.description}
|
placeholder={propSchema.description}
|
||||||
required={propSchema.required}
|
required={isRequired}
|
||||||
/>
|
/>
|
||||||
);
|
);
|
||||||
case "integer":
|
case "integer":
|
||||||
|
|
@ -190,9 +219,7 @@ const DynamicJsonForm = ({
|
||||||
value={(currentValue as number)?.toString() ?? ""}
|
value={(currentValue as number)?.toString() ?? ""}
|
||||||
onChange={(e) => {
|
onChange={(e) => {
|
||||||
const val = e.target.value;
|
const val = e.target.value;
|
||||||
// Allow clearing non-required integer fields
|
if (!val && !isRequired) {
|
||||||
// This preserves the distinction between 0 and unset
|
|
||||||
if (!val && !propSchema.required) {
|
|
||||||
handleFieldChange(path, undefined);
|
handleFieldChange(path, undefined);
|
||||||
} else {
|
} else {
|
||||||
const num = Number(val);
|
const num = Number(val);
|
||||||
|
|
@ -203,7 +230,7 @@ const DynamicJsonForm = ({
|
||||||
}
|
}
|
||||||
}}
|
}}
|
||||||
placeholder={propSchema.description}
|
placeholder={propSchema.description}
|
||||||
required={propSchema.required}
|
required={isRequired}
|
||||||
/>
|
/>
|
||||||
);
|
);
|
||||||
case "boolean":
|
case "boolean":
|
||||||
|
|
@ -213,9 +240,135 @@ const DynamicJsonForm = ({
|
||||||
checked={(currentValue as boolean) ?? false}
|
checked={(currentValue as boolean) ?? false}
|
||||||
onChange={(e) => handleFieldChange(path, e.target.checked)}
|
onChange={(e) => handleFieldChange(path, e.target.checked)}
|
||||||
className="w-4 h-4"
|
className="w-4 h-4"
|
||||||
required={propSchema.required}
|
required={isRequired}
|
||||||
/>
|
/>
|
||||||
);
|
);
|
||||||
|
case "object":
|
||||||
|
if (!propSchema.properties) {
|
||||||
|
return (
|
||||||
|
<JsonEditor
|
||||||
|
value={JSON.stringify(currentValue ?? {}, null, 2)}
|
||||||
|
onChange={(newValue) => {
|
||||||
|
try {
|
||||||
|
const parsed = JSON.parse(newValue);
|
||||||
|
handleFieldChange(path, parsed);
|
||||||
|
setJsonError(undefined);
|
||||||
|
} catch (err) {
|
||||||
|
setJsonError(
|
||||||
|
err instanceof Error ? err.message : "Invalid JSON",
|
||||||
|
);
|
||||||
|
}
|
||||||
|
}}
|
||||||
|
error={jsonError}
|
||||||
|
/>
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
|
return (
|
||||||
|
<div className="space-y-2 border rounded p-3">
|
||||||
|
{Object.entries(propSchema.properties).map(([key, subSchema]) => (
|
||||||
|
<div key={key}>
|
||||||
|
<label className="block text-sm font-medium mb-1">
|
||||||
|
{key}
|
||||||
|
{propSchema.required?.includes(key) && (
|
||||||
|
<span className="text-red-500 ml-1">*</span>
|
||||||
|
)}
|
||||||
|
</label>
|
||||||
|
{renderFormFields(
|
||||||
|
subSchema as JsonSchemaType,
|
||||||
|
(currentValue as Record<string, JsonValue>)?.[key],
|
||||||
|
[...path, key],
|
||||||
|
depth + 1,
|
||||||
|
propSchema,
|
||||||
|
key,
|
||||||
|
)}
|
||||||
|
</div>
|
||||||
|
))}
|
||||||
|
</div>
|
||||||
|
);
|
||||||
|
case "array": {
|
||||||
|
const arrayValue = Array.isArray(currentValue) ? currentValue : [];
|
||||||
|
if (!propSchema.items) return null;
|
||||||
|
|
||||||
|
// If the array items are simple, render as form fields, otherwise use JSON editor
|
||||||
|
if (isSimpleObject(propSchema.items)) {
|
||||||
|
return (
|
||||||
|
<div className="space-y-4">
|
||||||
|
{propSchema.description && (
|
||||||
|
<p className="text-sm text-gray-600">
|
||||||
|
{propSchema.description}
|
||||||
|
</p>
|
||||||
|
)}
|
||||||
|
|
||||||
|
{propSchema.items?.description && (
|
||||||
|
<p className="text-sm text-gray-500">
|
||||||
|
Items: {propSchema.items.description}
|
||||||
|
</p>
|
||||||
|
)}
|
||||||
|
|
||||||
|
<div className="space-y-2">
|
||||||
|
{arrayValue.map((item, index) => (
|
||||||
|
<div key={index} className="flex items-center gap-2">
|
||||||
|
{renderFormFields(
|
||||||
|
propSchema.items as JsonSchemaType,
|
||||||
|
item,
|
||||||
|
[...path, index.toString()],
|
||||||
|
depth + 1,
|
||||||
|
)}
|
||||||
|
<Button
|
||||||
|
variant="outline"
|
||||||
|
size="sm"
|
||||||
|
onClick={() => {
|
||||||
|
const newArray = [...arrayValue];
|
||||||
|
newArray.splice(index, 1);
|
||||||
|
handleFieldChange(path, newArray);
|
||||||
|
}}
|
||||||
|
>
|
||||||
|
Remove
|
||||||
|
</Button>
|
||||||
|
</div>
|
||||||
|
))}
|
||||||
|
<Button
|
||||||
|
variant="outline"
|
||||||
|
size="sm"
|
||||||
|
onClick={() => {
|
||||||
|
const defaultValue = getArrayItemDefault(
|
||||||
|
propSchema.items as JsonSchemaType,
|
||||||
|
);
|
||||||
|
handleFieldChange(path, [...arrayValue, defaultValue]);
|
||||||
|
}}
|
||||||
|
title={
|
||||||
|
propSchema.items?.description
|
||||||
|
? `Add new ${propSchema.items.description}`
|
||||||
|
: "Add new item"
|
||||||
|
}
|
||||||
|
>
|
||||||
|
Add Item
|
||||||
|
</Button>
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
|
// For complex arrays, fall back to JSON editor
|
||||||
|
return (
|
||||||
|
<JsonEditor
|
||||||
|
value={JSON.stringify(currentValue ?? [], null, 2)}
|
||||||
|
onChange={(newValue) => {
|
||||||
|
try {
|
||||||
|
const parsed = JSON.parse(newValue);
|
||||||
|
handleFieldChange(path, parsed);
|
||||||
|
setJsonError(undefined);
|
||||||
|
} catch (err) {
|
||||||
|
setJsonError(
|
||||||
|
err instanceof Error ? err.message : "Invalid JSON",
|
||||||
|
);
|
||||||
|
}
|
||||||
|
}}
|
||||||
|
error={jsonError}
|
||||||
|
/>
|
||||||
|
);
|
||||||
|
}
|
||||||
default:
|
default:
|
||||||
return null;
|
return null;
|
||||||
}
|
}
|
||||||
|
|
|
||||||
|
|
@ -156,7 +156,7 @@ export const OAuthFlowProgress = ({
|
||||||
{authState.resourceMetadataError && (
|
{authState.resourceMetadataError && (
|
||||||
<div className="mt-2 p-3 border border-blue-300 bg-blue-50 rounded-md">
|
<div className="mt-2 p-3 border border-blue-300 bg-blue-50 rounded-md">
|
||||||
<p className="text-sm font-medium text-blue-700">
|
<p className="text-sm font-medium text-blue-700">
|
||||||
ℹ️ No resource metadata available from{" "}
|
ℹ️ Problem with resource metadata from{" "}
|
||||||
<a
|
<a
|
||||||
href={
|
href={
|
||||||
new URL(
|
new URL(
|
||||||
|
|
|
||||||
|
|
@ -7,7 +7,7 @@ import { TabsContent } from "@/components/ui/tabs";
|
||||||
import { Textarea } from "@/components/ui/textarea";
|
import { Textarea } from "@/components/ui/textarea";
|
||||||
import DynamicJsonForm from "./DynamicJsonForm";
|
import DynamicJsonForm from "./DynamicJsonForm";
|
||||||
import type { JsonValue, JsonSchemaType } from "@/utils/jsonUtils";
|
import type { JsonValue, JsonSchemaType } from "@/utils/jsonUtils";
|
||||||
import { generateDefaultValue } from "@/utils/schemaUtils";
|
import { generateDefaultValue, isPropertyRequired } from "@/utils/schemaUtils";
|
||||||
import {
|
import {
|
||||||
CompatibilityCallToolResult,
|
CompatibilityCallToolResult,
|
||||||
ListToolsResult,
|
ListToolsResult,
|
||||||
|
|
@ -48,7 +48,11 @@ const ToolsTab = ({
|
||||||
selectedTool?.inputSchema.properties ?? [],
|
selectedTool?.inputSchema.properties ?? [],
|
||||||
).map(([key, value]) => [
|
).map(([key, value]) => [
|
||||||
key,
|
key,
|
||||||
generateDefaultValue(value as JsonSchemaType),
|
generateDefaultValue(
|
||||||
|
value as JsonSchemaType,
|
||||||
|
key,
|
||||||
|
selectedTool?.inputSchema as JsonSchemaType,
|
||||||
|
),
|
||||||
]);
|
]);
|
||||||
setParams(Object.fromEntries(params));
|
setParams(Object.fromEntries(params));
|
||||||
}, [selectedTool]);
|
}, [selectedTool]);
|
||||||
|
|
@ -92,6 +96,9 @@ const ToolsTab = ({
|
||||||
{Object.entries(selectedTool.inputSchema.properties ?? []).map(
|
{Object.entries(selectedTool.inputSchema.properties ?? []).map(
|
||||||
([key, value]) => {
|
([key, value]) => {
|
||||||
const prop = value as JsonSchemaType;
|
const prop = value as JsonSchemaType;
|
||||||
|
const inputSchema =
|
||||||
|
selectedTool.inputSchema as JsonSchemaType;
|
||||||
|
const required = isPropertyRequired(key, inputSchema);
|
||||||
return (
|
return (
|
||||||
<div key={key}>
|
<div key={key}>
|
||||||
<Label
|
<Label
|
||||||
|
|
@ -99,6 +106,9 @@ const ToolsTab = ({
|
||||||
className="block text-sm font-medium text-gray-700 dark:text-gray-300"
|
className="block text-sm font-medium text-gray-700 dark:text-gray-300"
|
||||||
>
|
>
|
||||||
{key}
|
{key}
|
||||||
|
{required && (
|
||||||
|
<span className="text-red-500 ml-1">*</span>
|
||||||
|
)}
|
||||||
</Label>
|
</Label>
|
||||||
{prop.type === "boolean" ? (
|
{prop.type === "boolean" ? (
|
||||||
<div className="flex items-center space-x-2 mt-2">
|
<div className="flex items-center space-x-2 mt-2">
|
||||||
|
|
|
||||||
|
|
@ -41,6 +41,7 @@ jest.mock("@modelcontextprotocol/sdk/client/auth.js", () => ({
|
||||||
startAuthorization: jest.fn(),
|
startAuthorization: jest.fn(),
|
||||||
exchangeAuthorization: jest.fn(),
|
exchangeAuthorization: jest.fn(),
|
||||||
discoverOAuthProtectedResourceMetadata: jest.fn(),
|
discoverOAuthProtectedResourceMetadata: jest.fn(),
|
||||||
|
selectResourceURL: jest.fn(),
|
||||||
}));
|
}));
|
||||||
|
|
||||||
// Import the functions to get their types
|
// Import the functions to get their types
|
||||||
|
|
@ -88,7 +89,7 @@ describe("AuthDebugger", () => {
|
||||||
const defaultAuthState = EMPTY_DEBUGGER_STATE;
|
const defaultAuthState = EMPTY_DEBUGGER_STATE;
|
||||||
|
|
||||||
const defaultProps = {
|
const defaultProps = {
|
||||||
serverUrl: "https://example.com",
|
serverUrl: "https://example.com/mcp",
|
||||||
onBack: jest.fn(),
|
onBack: jest.fn(),
|
||||||
authState: defaultAuthState,
|
authState: defaultAuthState,
|
||||||
updateAuthState: jest.fn(),
|
updateAuthState: jest.fn(),
|
||||||
|
|
@ -203,7 +204,7 @@ describe("AuthDebugger", () => {
|
||||||
|
|
||||||
// Should first discover and save OAuth metadata
|
// Should first discover and save OAuth metadata
|
||||||
expect(mockDiscoverOAuthMetadata).toHaveBeenCalledWith(
|
expect(mockDiscoverOAuthMetadata).toHaveBeenCalledWith(
|
||||||
new URL("https://example.com"),
|
new URL("https://example.com/"),
|
||||||
);
|
);
|
||||||
|
|
||||||
// Check that updateAuthState was called with the right info message
|
// Check that updateAuthState was called with the right info message
|
||||||
|
|
@ -320,6 +321,7 @@ describe("AuthDebugger", () => {
|
||||||
isInitiatingAuth: false,
|
isInitiatingAuth: false,
|
||||||
resourceMetadata: null,
|
resourceMetadata: null,
|
||||||
resourceMetadataError: null,
|
resourceMetadataError: null,
|
||||||
|
resource: null,
|
||||||
oauthTokens: null,
|
oauthTokens: null,
|
||||||
oauthStep: "metadata_discovery",
|
oauthStep: "metadata_discovery",
|
||||||
latestError: null,
|
latestError: null,
|
||||||
|
|
@ -361,7 +363,7 @@ describe("AuthDebugger", () => {
|
||||||
});
|
});
|
||||||
|
|
||||||
expect(mockDiscoverOAuthMetadata).toHaveBeenCalledWith(
|
expect(mockDiscoverOAuthMetadata).toHaveBeenCalledWith(
|
||||||
new URL("https://example.com"),
|
new URL("https://example.com/"),
|
||||||
);
|
);
|
||||||
});
|
});
|
||||||
|
|
||||||
|
|
@ -496,11 +498,11 @@ describe("AuthDebugger", () => {
|
||||||
it("should successfully fetch and display protected resource metadata", async () => {
|
it("should successfully fetch and display protected resource metadata", async () => {
|
||||||
const updateAuthState = jest.fn();
|
const updateAuthState = jest.fn();
|
||||||
const mockResourceMetadata = {
|
const mockResourceMetadata = {
|
||||||
resource: "https://example.com/api",
|
resource: "https://example.com/mcp",
|
||||||
authorization_servers: ["https://custom-auth.example.com"],
|
authorization_servers: ["https://custom-auth.example.com"],
|
||||||
bearer_methods_supported: ["header", "body"],
|
bearer_methods_supported: ["header", "body"],
|
||||||
resource_documentation: "https://example.com/api/docs",
|
resource_documentation: "https://example.com/mcp/docs",
|
||||||
resource_policy_uri: "https://example.com/api/policy",
|
resource_policy_uri: "https://example.com/mcp/policy",
|
||||||
};
|
};
|
||||||
|
|
||||||
// Mock successful metadata discovery
|
// Mock successful metadata discovery
|
||||||
|
|
@ -538,7 +540,7 @@ describe("AuthDebugger", () => {
|
||||||
// Wait for the metadata to be fetched
|
// Wait for the metadata to be fetched
|
||||||
await waitFor(() => {
|
await waitFor(() => {
|
||||||
expect(mockDiscoverOAuthProtectedResourceMetadata).toHaveBeenCalledWith(
|
expect(mockDiscoverOAuthProtectedResourceMetadata).toHaveBeenCalledWith(
|
||||||
"https://example.com",
|
"https://example.com/mcp",
|
||||||
);
|
);
|
||||||
});
|
});
|
||||||
|
|
||||||
|
|
@ -584,7 +586,7 @@ describe("AuthDebugger", () => {
|
||||||
// Wait for the metadata fetch to fail
|
// Wait for the metadata fetch to fail
|
||||||
await waitFor(() => {
|
await waitFor(() => {
|
||||||
expect(mockDiscoverOAuthProtectedResourceMetadata).toHaveBeenCalledWith(
|
expect(mockDiscoverOAuthProtectedResourceMetadata).toHaveBeenCalledWith(
|
||||||
"https://example.com",
|
"https://example.com/mcp",
|
||||||
);
|
);
|
||||||
});
|
});
|
||||||
|
|
||||||
|
|
@ -594,7 +596,7 @@ describe("AuthDebugger", () => {
|
||||||
expect.objectContaining({
|
expect.objectContaining({
|
||||||
resourceMetadataError: mockError,
|
resourceMetadataError: mockError,
|
||||||
// Should use the original server URL as fallback
|
// Should use the original server URL as fallback
|
||||||
authServerUrl: new URL("https://example.com"),
|
authServerUrl: new URL("https://example.com/"),
|
||||||
oauthStep: "client_registration",
|
oauthStep: "client_registration",
|
||||||
}),
|
}),
|
||||||
);
|
);
|
||||||
|
|
@ -602,7 +604,7 @@ describe("AuthDebugger", () => {
|
||||||
|
|
||||||
// Verify that regular OAuth metadata discovery was still called
|
// Verify that regular OAuth metadata discovery was still called
|
||||||
expect(mockDiscoverOAuthMetadata).toHaveBeenCalledWith(
|
expect(mockDiscoverOAuthMetadata).toHaveBeenCalledWith(
|
||||||
new URL("https://example.com"),
|
new URL("https://example.com/"),
|
||||||
);
|
);
|
||||||
});
|
});
|
||||||
});
|
});
|
||||||
|
|
|
||||||
256
client/src/components/__tests__/DynamicJsonForm.array.test.tsx
Normal file
256
client/src/components/__tests__/DynamicJsonForm.array.test.tsx
Normal file
|
|
@ -0,0 +1,256 @@
|
||||||
|
import { render, screen, fireEvent } from "@testing-library/react";
|
||||||
|
import { describe, it, expect, jest } from "@jest/globals";
|
||||||
|
import DynamicJsonForm from "../DynamicJsonForm";
|
||||||
|
import type { JsonSchemaType } from "@/utils/jsonUtils";
|
||||||
|
|
||||||
|
describe("DynamicJsonForm Array Fields", () => {
|
||||||
|
const renderSimpleArrayForm = (props = {}) => {
|
||||||
|
const defaultProps = {
|
||||||
|
schema: {
|
||||||
|
type: "array" as const,
|
||||||
|
description: "Test array field",
|
||||||
|
items: {
|
||||||
|
type: "string" as const,
|
||||||
|
description: "Array item",
|
||||||
|
},
|
||||||
|
} satisfies JsonSchemaType,
|
||||||
|
value: [],
|
||||||
|
onChange: jest.fn(),
|
||||||
|
};
|
||||||
|
return render(<DynamicJsonForm {...defaultProps} {...props} />);
|
||||||
|
};
|
||||||
|
|
||||||
|
const renderComplexArrayForm = (props = {}) => {
|
||||||
|
const defaultProps = {
|
||||||
|
schema: {
|
||||||
|
type: "array" as const,
|
||||||
|
description: "Test complex array field",
|
||||||
|
items: {
|
||||||
|
type: "object" as const,
|
||||||
|
properties: {
|
||||||
|
nested: { type: "object" as const },
|
||||||
|
},
|
||||||
|
},
|
||||||
|
} satisfies JsonSchemaType,
|
||||||
|
value: [],
|
||||||
|
onChange: jest.fn(),
|
||||||
|
};
|
||||||
|
return render(<DynamicJsonForm {...defaultProps} {...props} />);
|
||||||
|
};
|
||||||
|
|
||||||
|
describe("Simple Array Rendering", () => {
|
||||||
|
it("should render form fields for simple array items", () => {
|
||||||
|
renderSimpleArrayForm({ value: ["item1", "item2"] });
|
||||||
|
|
||||||
|
// Should show array description
|
||||||
|
expect(screen.getByText("Test array field")).toBeDefined();
|
||||||
|
expect(screen.getByText("Items: Array item")).toBeDefined();
|
||||||
|
|
||||||
|
// Should show input fields for each item
|
||||||
|
const inputs = screen.getAllByRole("textbox");
|
||||||
|
expect(inputs).toHaveLength(2);
|
||||||
|
expect(inputs[0]).toHaveProperty("value", "item1");
|
||||||
|
expect(inputs[1]).toHaveProperty("value", "item2");
|
||||||
|
|
||||||
|
// Should show remove buttons
|
||||||
|
const removeButtons = screen.getAllByText("Remove");
|
||||||
|
expect(removeButtons).toHaveLength(2);
|
||||||
|
|
||||||
|
// Should show add button
|
||||||
|
expect(screen.getByText("Add Item")).toBeDefined();
|
||||||
|
});
|
||||||
|
|
||||||
|
it("should add new items when Add Item button is clicked", () => {
|
||||||
|
const onChange = jest.fn();
|
||||||
|
renderSimpleArrayForm({ value: ["item1"], onChange });
|
||||||
|
|
||||||
|
const addButton = screen.getByText("Add Item");
|
||||||
|
fireEvent.click(addButton);
|
||||||
|
|
||||||
|
expect(onChange).toHaveBeenCalledWith(["item1", ""]);
|
||||||
|
});
|
||||||
|
|
||||||
|
it("should remove items when Remove button is clicked", () => {
|
||||||
|
const onChange = jest.fn();
|
||||||
|
renderSimpleArrayForm({ value: ["item1", "item2"], onChange });
|
||||||
|
|
||||||
|
const removeButtons = screen.getAllByText("Remove");
|
||||||
|
fireEvent.click(removeButtons[0]);
|
||||||
|
|
||||||
|
expect(onChange).toHaveBeenCalledWith(["item2"]);
|
||||||
|
});
|
||||||
|
|
||||||
|
it("should update item values when input changes", () => {
|
||||||
|
const onChange = jest.fn();
|
||||||
|
renderSimpleArrayForm({ value: ["item1"], onChange });
|
||||||
|
|
||||||
|
const input = screen.getByRole("textbox");
|
||||||
|
fireEvent.change(input, { target: { value: "updated item" } });
|
||||||
|
|
||||||
|
expect(onChange).toHaveBeenCalledWith(["updated item"]);
|
||||||
|
});
|
||||||
|
|
||||||
|
it("should handle empty arrays", () => {
|
||||||
|
renderSimpleArrayForm({ value: [] });
|
||||||
|
|
||||||
|
// Should show description and add button but no items
|
||||||
|
expect(screen.getByText("Test array field")).toBeDefined();
|
||||||
|
expect(screen.getByText("Add Item")).toBeDefined();
|
||||||
|
expect(screen.queryByText("Remove")).toBeNull();
|
||||||
|
});
|
||||||
|
});
|
||||||
|
|
||||||
|
describe("Complex Array Fallback", () => {
|
||||||
|
it("should render JSON editor for complex arrays", () => {
|
||||||
|
renderComplexArrayForm();
|
||||||
|
|
||||||
|
// Should render as JSON editor (textarea)
|
||||||
|
const textarea = screen.getByRole("textbox");
|
||||||
|
expect(textarea).toHaveProperty("type", "textarea");
|
||||||
|
|
||||||
|
// Should not show form-specific array controls
|
||||||
|
expect(screen.queryByText("Add Item")).toBeNull();
|
||||||
|
expect(screen.queryByText("Remove")).toBeNull();
|
||||||
|
});
|
||||||
|
});
|
||||||
|
|
||||||
|
describe("Array Type Detection", () => {
|
||||||
|
it("should detect string arrays as simple", () => {
|
||||||
|
const schema = {
|
||||||
|
type: "array" as const,
|
||||||
|
items: { type: "string" as const },
|
||||||
|
};
|
||||||
|
renderSimpleArrayForm({ schema, value: ["test"] });
|
||||||
|
|
||||||
|
// Should render form fields, not JSON editor
|
||||||
|
expect(screen.getByRole("textbox")).not.toHaveProperty(
|
||||||
|
"type",
|
||||||
|
"textarea",
|
||||||
|
);
|
||||||
|
});
|
||||||
|
|
||||||
|
it("should detect number arrays as simple", () => {
|
||||||
|
const schema = {
|
||||||
|
type: "array" as const,
|
||||||
|
items: { type: "number" as const },
|
||||||
|
};
|
||||||
|
renderSimpleArrayForm({ schema, value: [1, 2] });
|
||||||
|
|
||||||
|
// Should render form fields (number inputs)
|
||||||
|
const inputs = screen.getAllByRole("spinbutton");
|
||||||
|
expect(inputs).toHaveLength(2);
|
||||||
|
});
|
||||||
|
|
||||||
|
it("should detect boolean arrays as simple", () => {
|
||||||
|
const schema = {
|
||||||
|
type: "array" as const,
|
||||||
|
items: { type: "boolean" as const },
|
||||||
|
};
|
||||||
|
renderSimpleArrayForm({ schema, value: [true, false] });
|
||||||
|
|
||||||
|
// Should render form fields (checkboxes)
|
||||||
|
const checkboxes = screen.getAllByRole("checkbox");
|
||||||
|
expect(checkboxes).toHaveLength(2);
|
||||||
|
});
|
||||||
|
|
||||||
|
it("should detect simple object arrays as simple", () => {
|
||||||
|
const schema = {
|
||||||
|
type: "array" as const,
|
||||||
|
items: {
|
||||||
|
type: "object" as const,
|
||||||
|
properties: {
|
||||||
|
name: { type: "string" as const },
|
||||||
|
age: { type: "number" as const },
|
||||||
|
},
|
||||||
|
},
|
||||||
|
};
|
||||||
|
renderSimpleArrayForm({ schema, value: [{ name: "John", age: 30 }] });
|
||||||
|
|
||||||
|
// Should render form fields for simple objects
|
||||||
|
expect(screen.getByText("Add Item")).toBeDefined();
|
||||||
|
expect(screen.getByText("Remove")).toBeDefined();
|
||||||
|
});
|
||||||
|
});
|
||||||
|
|
||||||
|
describe("Array with Different Item Types", () => {
|
||||||
|
it("should handle integer array items", () => {
|
||||||
|
const schema = {
|
||||||
|
type: "array" as const,
|
||||||
|
items: { type: "integer" as const },
|
||||||
|
};
|
||||||
|
const onChange = jest.fn();
|
||||||
|
renderSimpleArrayForm({ schema, value: [1, 2], onChange });
|
||||||
|
|
||||||
|
const inputs = screen.getAllByRole("spinbutton");
|
||||||
|
expect(inputs).toHaveLength(2);
|
||||||
|
expect(inputs[0]).toHaveProperty("value", "1");
|
||||||
|
expect(inputs[1]).toHaveProperty("value", "2");
|
||||||
|
|
||||||
|
// Test adding new integer item
|
||||||
|
const addButton = screen.getByText("Add Item");
|
||||||
|
fireEvent.click(addButton);
|
||||||
|
expect(onChange).toHaveBeenCalledWith([1, 2, 0]);
|
||||||
|
});
|
||||||
|
|
||||||
|
it("should handle boolean array items", () => {
|
||||||
|
const schema = {
|
||||||
|
type: "array" as const,
|
||||||
|
items: { type: "boolean" as const },
|
||||||
|
};
|
||||||
|
const onChange = jest.fn();
|
||||||
|
renderSimpleArrayForm({ schema, value: [true, false], onChange });
|
||||||
|
|
||||||
|
const checkboxes = screen.getAllByRole("checkbox");
|
||||||
|
expect(checkboxes).toHaveLength(2);
|
||||||
|
expect(checkboxes[0]).toHaveProperty("checked", true);
|
||||||
|
expect(checkboxes[1]).toHaveProperty("checked", false);
|
||||||
|
|
||||||
|
// Test adding new boolean item
|
||||||
|
const addButton = screen.getByText("Add Item");
|
||||||
|
fireEvent.click(addButton);
|
||||||
|
expect(onChange).toHaveBeenCalledWith([true, false, false]);
|
||||||
|
});
|
||||||
|
});
|
||||||
|
|
||||||
|
describe("Array Item Descriptions", () => {
|
||||||
|
it("should show item description when available", () => {
|
||||||
|
const schema = {
|
||||||
|
type: "array" as const,
|
||||||
|
description: "List of names",
|
||||||
|
items: {
|
||||||
|
type: "string" as const,
|
||||||
|
description: "Person name",
|
||||||
|
},
|
||||||
|
};
|
||||||
|
renderSimpleArrayForm({ schema });
|
||||||
|
|
||||||
|
expect(screen.getByText("List of names")).toBeDefined();
|
||||||
|
expect(screen.getByText("Items: Person name")).toBeDefined();
|
||||||
|
});
|
||||||
|
|
||||||
|
it("should use item description in add button title", () => {
|
||||||
|
const schema = {
|
||||||
|
type: "array" as const,
|
||||||
|
items: {
|
||||||
|
type: "string" as const,
|
||||||
|
description: "Email address",
|
||||||
|
},
|
||||||
|
};
|
||||||
|
renderSimpleArrayForm({ schema });
|
||||||
|
|
||||||
|
const addButton = screen.getByText("Add Item");
|
||||||
|
expect(addButton).toHaveProperty("title", "Add new Email address");
|
||||||
|
});
|
||||||
|
|
||||||
|
it("should use default title when no item description", () => {
|
||||||
|
const schema = {
|
||||||
|
type: "array" as const,
|
||||||
|
items: { type: "string" as const },
|
||||||
|
};
|
||||||
|
renderSimpleArrayForm({ schema });
|
||||||
|
|
||||||
|
const addButton = screen.getByText("Add Item");
|
||||||
|
expect(addButton).toHaveProperty("title", "Add new item");
|
||||||
|
});
|
||||||
|
});
|
||||||
|
});
|
||||||
Some files were not shown because too many files have changed in this diff Show more
Loading…
Reference in a new issue