diff --git a/.github/ISSUE_TEMPLATE/bug_report.md b/.github/ISSUE_TEMPLATE/bug_report.md new file mode 100644 index 000000000..9c51db890 --- /dev/null +++ b/.github/ISSUE_TEMPLATE/bug_report.md @@ -0,0 +1,40 @@ +--- +name: Bug report +about: Create a report to help us improve +title: "" +labels: "" +assignees: "" +--- + +**Inspector Version** + +- [e.g. 0.16.5) + +**Describe the bug** +A clear and concise description of what the bug is. + +**To Reproduce** +Steps to reproduce the behavior: + +1. Go to '...' +2. Click on '....' +3. Scroll down to '....' +4. See error + +**Expected behavior** +A clear and concise description of what you expected to happen. + +**Screenshots** +If applicable, add screenshots to help explain your problem. + +**Environment (please complete the following information):** + +- OS: [e.g. iOS] +- Browser [e.g. chrome, safari] + +**Additional context** +Add any other context about the problem here. + +**Version Consideration** + +Inspector V2 is under development to address architectural and UX improvements. During this time, V1 contributions should focus on **bug fixes and MCP spec compliance**. See [CONTRIBUTING.md](../../CONTRIBUTING.md) for more details. diff --git a/.github/pull_request_template.md b/.github/pull_request_template.md new file mode 100644 index 000000000..24a0ec922 --- /dev/null +++ b/.github/pull_request_template.md @@ -0,0 +1,57 @@ +## Summary + + + +> **Note:** Inspector V2 is under development to address architectural and UX improvements. During this time, V1 contributions should focus on **bug fixes and MCP spec compliance**. See [CONTRIBUTING.md](../CONTRIBUTING.md) for more details. + +## Type of Change + + + +- [ ] Bug fix (non-breaking change that fixes an issue) +- [ ] New feature (non-breaking change that adds functionality) +- [ ] Documentation update +- [ ] Refactoring (no functional changes) +- [ ] Test updates +- [ ] Build/CI improvements + +## Changes Made + + + +## Related Issues + + + +## Testing + + + +- [ ] Tested in UI mode +- [ ] Tested in CLI mode +- [ ] Tested with STDIO transport +- [ ] Tested with SSE transport +- [ ] Tested with Streamable HTTP transport +- [ ] Added/updated automated tests +- [ ] Manual testing performed + +### Test Results and/or Instructions + + + +Screenshots are encouraged to share your testing results for this change. + +## Checklist + +- [ ] Code follows the style guidelines (ran `npm run prettier-fix`) +- [ ] Self-review completed +- [ ] Code is commented where necessary +- [ ] Documentation updated (README, comments, etc.) + +## Breaking Changes + + + +## Additional Context + + diff --git a/.github/workflows/claude.yml b/.github/workflows/claude.yml index a4fd6c52a..23a66f869 100644 --- a/.github/workflows/claude.yml +++ b/.github/workflows/claude.yml @@ -18,10 +18,6 @@ jobs: (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: @@ -29,36 +25,61 @@ jobs: pull-requests: read issues: read id-token: write + actions: read steps: + - name: Get PR details + if: | + (github.event_name == 'issue_comment' && github.event.issue.pull_request) || + github.event_name == 'pull_request_review_comment' || + github.event_name == 'pull_request_review' + id: pr + uses: actions/github-script@v7 + with: + script: | + let prNumber; + if (context.eventName === 'issue_comment') { + prNumber = context.issue.number; + } else { + prNumber = context.payload.pull_request.number; + } + + const pr = await github.rest.pulls.get({ + owner: context.repo.owner, + repo: context.repo.repo, + pull_number: prNumber + }); + + core.setOutput('sha', pr.data.head.sha); + core.setOutput('repo', pr.data.head.repo.full_name); + + - name: Checkout PR branch + if: steps.pr.outcome == 'success' + uses: actions/checkout@v4 + with: + ref: ${{ steps.pr.outputs.sha }} + repository: ${{ steps.pr.outputs.repo }} + fetch-depth: 0 + - name: Checkout repository + if: steps.pr.outcome != 'success' uses: actions/checkout@v4 with: - fetch-depth: 1 + fetch-depth: 0 - name: Run Claude Code id: claude - uses: anthropics/claude-code-action@beta + uses: anthropics/claude-code-action@v1 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:*)" + # Allow Claude to read CI results on PRs + additional_permissions: | + actions: read - # 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 + # Trigger when assigned to an issue + assignee_trigger: "claude" - # Optional: Custom environment variables for Claude - # claude_env: | - # NODE_ENV: test + claude_args: | + --mcp-config .mcp.json + --allowedTools "Bash,mcp__mcp-docs" + --append-system-prompt "If posting a comment to GitHub, give a concise summary of the comment at the top and put all the details in a
block. When working on MCP-related code or reviewing MCP-related changes, use the mcp-docs MCP server to look up the latest protocol documentation. For schema details, reference https://github.com/modelcontextprotocol/modelcontextprotocol/tree/main/schema which contains versioned schemas in JSON (schema.json) and TypeScript (schema.ts) formats." diff --git a/.github/workflows/cli_tests.yml b/.github/workflows/cli_tests.yml index 8bd3bb8ec..ede7643e8 100644 --- a/.github/workflows/cli_tests.yml +++ b/.github/workflows/cli_tests.yml @@ -31,9 +31,6 @@ jobs: - 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: diff --git a/.github/workflows/e2e_tests.yml b/.github/workflows/e2e_tests.yml index 573672cc8..378905b44 100644 --- a/.github/workflows/e2e_tests.yml +++ b/.github/workflows/e2e_tests.yml @@ -8,7 +8,7 @@ on: jobs: test: - # Installing Playright dependencies can take quite awhile, and also depends on GitHub CI load. + # Installing Playwright dependencies can take quite awhile, and also depends on GitHub CI load. timeout-minutes: 15 runs-on: ubuntu-latest diff --git a/.gitignore b/.gitignore index 9a130493c..7d72999e2 100644 --- a/.gitignore +++ b/.gitignore @@ -10,8 +10,13 @@ client/tsconfig.node.tsbuildinfo cli/build test-output .env +tool-test-output +metadata-test-output # symlinked by `npm run link:sdk`: sdk client/playwright-report/ client/results.json client/test-results/ +client/e2e/test-results/ +mcp.json +.claude/settings.local.json diff --git a/.husky/pre-commit b/.husky/pre-commit new file mode 100644 index 000000000..0a3afdcb6 --- /dev/null +++ b/.husky/pre-commit @@ -0,0 +1,2 @@ +npx lint-staged +git update-index --again diff --git a/.mcp.json b/.mcp.json new file mode 100644 index 000000000..5f68642aa --- /dev/null +++ b/.mcp.json @@ -0,0 +1,8 @@ +{ + "mcpServers": { + "mcp-docs": { + "type": "http", + "url": "https://modelcontextprotocol.io/mcp" + } + } +} diff --git a/.prettierignore b/.prettierignore index c8824c9a4..167a7cb48 100644 --- a/.prettierignore +++ b/.prettierignore @@ -2,3 +2,5 @@ packages server/build CODE_OF_CONDUCT.md SECURITY.md +mcp.json +.claude/settings.local.json \ No newline at end of file diff --git a/AGENTS.md b/AGENTS.md new file mode 100644 index 000000000..27d28f72d --- /dev/null +++ b/AGENTS.md @@ -0,0 +1,35 @@ +# MCP Inspector Development Guide + +> **Note:** Inspector V2 is under development to address architectural and UX improvements. During this time, V1 contributions should focus on **bug fixes and MCP spec compliance**. See [CONTRIBUTING.md](CONTRIBUTING.md) for more details. + +## Build Commands + +- Build all: `npm run build` +- Build client: `npm run build-client` +- Build server: `npm run build-server` +- Development mode: `npm run dev` (use `npm run dev:windows` on Windows) +- Format code: `npm run prettier-fix` +- Client lint: `cd client && npm run lint` + +## Code Style Guidelines + +- Use TypeScript with proper type annotations +- Follow React functional component patterns with hooks +- Use ES modules (import/export) not CommonJS +- Use Prettier for formatting (auto-formatted on commit) +- Follow existing naming conventions: + - camelCase for variables and functions + - PascalCase for component names and types + - kebab-case for file names +- Use async/await for asynchronous operations +- Implement proper error handling with try/catch blocks +- Use Tailwind CSS for styling in the client +- Keep components small and focused on a single responsibility + +## Project Organization + +The project is organized as a monorepo with workspaces: + +- `client/`: React frontend with Vite, TypeScript and Tailwind +- `server/`: Express backend with TypeScript +- `cli/`: Command-line interface for testing and invoking MCP server methods directly diff --git a/CLAUDE.md b/CLAUDE.md index ec826b1fd..285e0f5b3 100644 --- a/CLAUDE.md +++ b/CLAUDE.md @@ -1,33 +1 @@ -# MCP Inspector Development Guide - -## Build Commands - -- Build all: `npm run build` -- Build client: `npm run build-client` -- Build server: `npm run build-server` -- Development mode: `npm run dev` (use `npm run dev:windows` on Windows) -- Format code: `npm run prettier-fix` -- Client lint: `cd client && npm run lint` - -## Code Style Guidelines - -- Use TypeScript with proper type annotations -- Follow React functional component patterns with hooks -- Use ES modules (import/export) not CommonJS -- Use Prettier for formatting (auto-formatted on commit) -- Follow existing naming conventions: - - camelCase for variables and functions - - PascalCase for component names and types - - kebab-case for file names -- Use async/await for asynchronous operations -- Implement proper error handling with try/catch blocks -- Use Tailwind CSS for styling in the client -- Keep components small and focused on a single responsibility - -## Project Organization - -The project is organized as a monorepo with workspaces: - -- `client/`: React frontend with Vite, TypeScript and Tailwind -- `server/`: Express backend with TypeScript -- `cli/`: Command-line interface for testing and invoking MCP server methods directly +@./AGENTS.md diff --git a/CONTRIBUTING.md b/CONTRIBUTING.md index 0129a9e32..daf1e2e0f 100644 --- a/CONTRIBUTING.md +++ b/CONTRIBUTING.md @@ -9,6 +9,16 @@ Thanks for your interest in contributing! This guide explains how to get involve 3. Run `npm run dev` to start both client and server in development mode 4. Use the web UI at http://localhost:6274 to interact with the inspector +## Inspector V2 Development + +We're actively developing **Inspector V2** to address architectural and UX improvements. We invite you to follow progress and participate in the Inspector V2 Working Group in [Discord](https://modelcontextprotocol.io/community/communication), [weekly meetings](https://meet.modelcontextprotocol.io/tag/inspector-v2-wg), and [GitHub Discussions](https://github.com/modelcontextprotocol/modelcontextprotocol/discussions/categories/meeting-notes-other) (where notes are posted after meetings). + +**Current version (V1) contribution scope:** + +- Bug fixes and MCP spec compliance are actively maintained +- Documentation updates are always appreciated +- Major changes will be directed to V2 development + ## Development Process & Pull Requests 1. Create a new branch for your changes @@ -30,7 +40,7 @@ If you find a security vulnerability, please refer to our [Security Policy](SECU ## Questions? -Feel free to [open an issue](https://github.com/modelcontextprotocol/mcp-inspector/issues) for questions or create a discussion for general topics. +Feel free to [open an issue](https://github.com/modelcontextprotocol/inspector/issues) for questions or join the MCP Contributor [Discord server](https://modelcontextprotocol.io/community/communication). Also, please see notes above on Inspector V2 Development. ## License diff --git a/Dockerfile b/Dockerfile index f36fb8bb7..d66091d16 100644 --- a/Dockerfile +++ b/Dockerfile @@ -1,5 +1,5 @@ # Build stage -FROM node:24-slim AS builder +FROM node:current-alpine3.22 AS builder # Set working directory WORKDIR /app @@ -49,4 +49,4 @@ ENV SERVER_PORT=6277 EXPOSE ${CLIENT_PORT} ${SERVER_PORT} # Use ENTRYPOINT with CMD for arguments -ENTRYPOINT ["npm", "start"] \ No newline at end of file +ENTRYPOINT ["npm", "start"] diff --git a/LICENSE b/LICENSE index 3d4843545..4a9398576 100644 --- a/LICENSE +++ b/LICENSE @@ -1,6 +1,193 @@ +The MCP project is undergoing a licensing transition from the MIT License to the Apache License, Version 2.0 ("Apache-2.0"). All new code and specification contributions to the project are licensed under Apache-2.0. Documentation contributions (excluding specifications) are licensed under CC-BY-4.0. + +Contributions for which relicensing consent has been obtained are licensed under Apache-2.0. Contributions made by authors who originally licensed their work under the MIT License and who have not yet granted explicit permission to relicense remain licensed under the MIT License. + +No rights beyond those granted by the applicable original license are conveyed for such contributions. + +--- + + Apache License + Version 2.0, January 2004 + http://www.apache.org/licenses/ + + TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION + + 1. Definitions. + + "License" shall mean the terms and conditions for use, reproduction, + and distribution as defined by Sections 1 through 9 of this document. + + "Licensor" shall mean the copyright owner or entity authorized by + the copyright owner that is granting the License. + + "Legal Entity" shall mean the union of the acting entity and all + other entities that control, are controlled by, or are under common + control with that entity. For the purposes of this definition, + "control" means (i) the power, direct or indirect, to cause the + direction or management of such entity, whether by contract or + otherwise, or (ii) ownership of fifty percent (50%) or more of the + outstanding shares, or (iii) beneficial ownership of such entity. + + "You" (or "Your") shall mean an individual or Legal Entity + exercising permissions granted by this License. + + "Source" form shall mean the preferred form for making modifications, + including but not limited to software source code, documentation + source, and configuration files. + + "Object" form shall mean any form resulting from mechanical + transformation or translation of a Source form, including but + not limited to compiled object code, generated documentation, + and conversions to other media types. + + "Work" shall mean the work of authorship, whether in Source or + Object form, made available under the License, as indicated by a + copyright notice that is included in or attached to the work + (an example is provided in the Appendix below). + + "Derivative Works" shall mean any work, whether in Source or Object + form, that is based on (or derived from) the Work and for which the + editorial revisions, annotations, elaborations, or other modifications + represent, as a whole, an original work of authorship. For the purposes + of this License, Derivative Works shall not include works that remain + separable from, or merely link (or bind by name) to the interfaces of, + the Work and Derivative Works thereof. + + "Contribution" shall mean any work of authorship, including + the original version of the Work and any modifications or additions + to that Work or Derivative Works thereof, that is intentionally + submitted to the Licensor for inclusion in the Work by the copyright + owner or by an individual or Legal Entity authorized to submit on behalf + of the copyright owner. For the purposes of this definition, "submitted" + means any form of electronic, verbal, or written communication sent + to the Licensor or its representatives, including but not limited to + communication on electronic mailing lists, source code control systems, + and issue tracking systems that are managed by, or on behalf of, the + Licensor for the purpose of discussing and improving the Work, but + excluding communication that is conspicuously marked or otherwise + designated in writing by the copyright owner as "Not a Contribution." + + "Contributor" shall mean Licensor and any individual or Legal Entity + on behalf of whom a Contribution has been received by Licensor and + subsequently incorporated within the Work. + + 2. Grant of Copyright License. Subject to the terms and conditions of + this License, each Contributor hereby grants to You a perpetual, + worldwide, non-exclusive, no-charge, royalty-free, irrevocable + copyright license to reproduce, prepare Derivative Works of, + publicly display, publicly perform, sublicense, and distribute the + Work and such Derivative Works in Source or Object form. + + 3. Grant of Patent License. Subject to the terms and conditions of + this License, each Contributor hereby grants to You a perpetual, + worldwide, non-exclusive, no-charge, royalty-free, irrevocable + (except as stated in this section) patent license to make, have made, + use, offer to sell, sell, import, and otherwise transfer the Work, + where such license applies only to those patent claims licensable + by such Contributor that are necessarily infringed by their + Contribution(s) alone or by combination of their Contribution(s) + with the Work to which such Contribution(s) was submitted. If You + institute patent litigation against any entity (including a + cross-claim or counterclaim in a lawsuit) alleging that the Work + or a Contribution incorporated within the Work constitutes direct + or contributory patent infringement, then any patent licenses + granted to You under this License for that Work shall terminate + as of the date such litigation is filed. + + 4. Redistribution. You may reproduce and distribute copies of the + Work or Derivative Works thereof in any medium, with or without + modifications, and in Source or Object form, provided that You + meet the following conditions: + + (a) You must give any other recipients of the Work or + Derivative Works a copy of this License; and + + (b) You must cause any modified files to carry prominent notices + stating that You changed the files; and + + (c) You must retain, in the Source form of any Derivative Works + that You distribute, all copyright, patent, trademark, and + attribution notices from the Source form of the Work, + excluding those notices that do not pertain to any part of + the Derivative Works; and + + (d) If the Work includes a "NOTICE" text file as part of its + distribution, then any Derivative Works that You distribute must + include a readable copy of the attribution notices contained + within such NOTICE file, excluding those notices that do not + pertain to any part of the Derivative Works, in at least one + of the following places: within a NOTICE text file distributed + as part of the Derivative Works; within the Source form or + documentation, if provided along with the Derivative Works; or, + within a display generated by the Derivative Works, if and + wherever such third-party notices normally appear. The contents + of the NOTICE file are for informational purposes only and + do not modify the License. You may add Your own attribution + notices within Derivative Works that You distribute, alongside + or as an addendum to the NOTICE text from the Work, provided + that such additional attribution notices cannot be construed + as modifying the License. + + You may add Your own copyright statement to Your modifications and + may provide additional or different license terms and conditions + for use, reproduction, or distribution of Your modifications, or + for any such Derivative Works as a whole, provided Your use, + reproduction, and distribution of the Work otherwise complies with + the conditions stated in this License. + + 5. Submission of Contributions. Unless You explicitly state otherwise, + any Contribution intentionally submitted for inclusion in the Work + by You to the Licensor shall be under the terms and conditions of + this License, without any additional terms or conditions. + Notwithstanding the above, nothing herein shall supersede or modify + the terms of any separate license agreement you may have executed + with Licensor regarding such Contributions. + + 6. Trademarks. This License does not grant permission to use the trade + names, trademarks, service marks, or product names of the Licensor, + except as required for reasonable and customary use in describing the + origin of the Work and reproducing the content of the NOTICE file. + + 7. Disclaimer of Warranty. Unless required by applicable law or + agreed to in writing, Licensor provides the Work (and each + Contributor provides its Contributions) on an "AS IS" BASIS, + WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or + implied, including, without limitation, any warranties or conditions + of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A + PARTICULAR PURPOSE. You are solely responsible for determining the + appropriateness of using or redistributing the Work and assume any + risks associated with Your exercise of permissions under this License. + + 8. Limitation of Liability. In no event and under no legal theory, + whether in tort (including negligence), contract, or otherwise, + unless required by applicable law (such as deliberate and grossly + negligent acts) or agreed to in writing, shall any Contributor be + liable to You for damages, including any direct, indirect, special, + incidental, or consequential damages of any character arising as a + result of this License or out of the use or inability to use the + Work (including but not limited to damages for loss of goodwill, + work stoppage, computer failure or malfunction, or any and all + other commercial damages or losses), even if such Contributor + has been advised of the possibility of such damages. + + 9. Accepting Warranty or Additional Liability. While redistributing + the Work or Derivative Works thereof, You may choose to offer, + and charge a fee for, acceptance of support, warranty, indemnity, + or other liability obligations and/or rights consistent with this + License. However, in accepting such obligations, You may act only + on Your own behalf and on Your sole responsibility, not on behalf + of any other Contributor, and only if You agree to indemnify, + defend, and hold each Contributor harmless for any liability + incurred by, or claims asserted against, such Contributor by reason + of your accepting any such warranty or additional liability. + + END OF TERMS AND CONDITIONS + +--- + MIT License -Copyright (c) 2024 Anthropic, PBC +Copyright (c) 2024-2025 Model Context Protocol a Series of LF Projects, LLC. Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal @@ -19,3 +206,11 @@ AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. + +--- + +Creative Commons Attribution 4.0 International (CC-BY-4.0) + +Documentation in this project (excluding specifications) is licensed under +CC-BY-4.0. See https://creativecommons.org/licenses/by/4.0/legalcode for +the full license text. diff --git a/README.md b/README.md index 6a671f1c4..36e9f3dee 100644 --- a/README.md +++ b/README.md @@ -29,6 +29,19 @@ npx @modelcontextprotocol/inspector The server will start up and the UI will be accessible at `http://localhost:6274`. +### Docker Container + +You can also start it in a Docker container with the following command: + +```bash +docker run --rm \ + -p 127.0.0.1:6274:6274 \ + -p 127.0.0.1:6277:6277 \ + -e HOST=0.0.0.0 \ + -e MCP_AUTO_OPEN_ENABLED=false \ + ghcr.io/modelcontextprotocol/inspector:latest +``` + ### 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`: @@ -90,6 +103,16 @@ The MCP Inspector provides convenient buttons to export server launch configurat } ``` + **Streamable HTTP transport example:** + + ```json + { + "type": "streamable-http", + "url": "http://localhost:3000/mcp", + "note": "For Streamable HTTP connections, add this URL directly in your MCP Client" + } + ``` + - **Servers File** - Copies a complete MCP configuration file structure to your clipboard, with your current server configuration added as `default-server`. This can be saved directly as `mcp.json`. **STDIO transport example:** @@ -123,9 +146,23 @@ The MCP Inspector provides convenient buttons to export server launch configurat } ``` + **Streamable HTTP transport example:** + + ```json + { + "mcpServers": { + "default-server": { + "type": "streamable-http", + "url": "http://localhost:3000/mcp", + "note": "For Streamable HTTP connections, add this URL directly in your MCP Client" + } + } + } + ``` + These buttons appear in the Inspector UI after you've configured your server settings, making it easy to save and reuse your configurations. -For SSE transport connections, the Inspector provides similar functionality for both buttons. The "Server Entry" button copies the SSE URL configuration that can be added to your existing configuration file, while the "Servers File" button creates a complete configuration file containing the SSE URL for direct use in clients. +For SSE and Streamable HTTP transport connections, the Inspector provides similar functionality for both buttons. The "Server Entry" button copies the configuration that can be added to your existing configuration file, while the "Servers File" button creates a complete configuration file containing the URL for direct use in clients. You can paste the Server Entry into your existing `mcp.json` file under your chosen server name, or use the complete Servers File payload to create a new configuration file. @@ -166,6 +203,16 @@ If you need to disable authentication (NOT RECOMMENDED), you can set the `DANGER DANGEROUSLY_OMIT_AUTH=true npm start ``` +--- + +**🚨 WARNING 🚨** + +Disabling authentication with `DANGEROUSLY_OMIT_AUTH` is incredibly dangerous! Disabling auth leaves your machine open to attack not just when exposed to the public internet, but also **via your web browser**. Meaning, visiting a malicious website OR viewing a malicious advertizement could allow an attacker to remotely compromise your computer. Do not disable this feature unless you truly understand the risks. + +Read more about the risks of this vulnerability on Oligo's blog: [Critical RCE Vulnerability in Anthropic MCP Inspector - CVE-2025-49596](https://www.oligo.security/blog/critical-rce-vulnerability-in-anthropic-mcp-inspector-cve-2025-49596) + +--- + You can also set the token via the `MCP_PROXY_AUTH_TOKEN` environment variable when starting the server: ```bash @@ -194,13 +241,15 @@ ALLOWED_ORIGINS=http://localhost:6274,http://localhost:8000 npm start 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 (works with authentication enabled). Only as environment var, not configurable in browser. | true | +| Setting | Description | Default | +| --------------------------------------- | --------------------------------------------------------------------------------------------------------------------------------------------------- | ------- | +| `MCP_SERVER_REQUEST_TIMEOUT` | Client-side timeout (ms) - Inspector will cancel the request if no response is received within this time. Note: servers may have their own timeouts | 300000 | +| `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 | + +**Note on Timeouts:** The timeout settings above control when the Inspector (as an MCP client) will cancel requests. These are independent of any server-side timeouts. For example, if a server tool has a 10-minute timeout but the Inspector's timeout is set to 30 seconds, the Inspector will cancel the request after 30 seconds. Conversely, if the Inspector's timeout is 10 minutes but the server times out after 30 seconds, you'll receive the server's timeout error. For tools that require user interaction (like elicitation) or long-running operations, ensure the Inspector's timeout is set appropriately. These settings can be adjusted in real-time through the UI and will persist across sessions. @@ -234,6 +283,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: @@ -247,7 +368,7 @@ http://localhost:6274/?transport=stdio&serverCommand=npx&serverArgs=arg1%20arg2 You can also set initial config settings via query params, for example: ``` -http://localhost:6274/?MCP_SERVER_REQUEST_TIMEOUT=10000&MCP_REQUEST_TIMEOUT_RESET_ON_PROGRESS=false&MCP_PROXY_FULL_ADDRESS=http://10.1.1.22:5577 +http://localhost:6274/?MCP_SERVER_REQUEST_TIMEOUT=60000&MCP_REQUEST_TIMEOUT_RESET_ON_PROGRESS=false&MCP_PROXY_FULL_ADDRESS=http://10.1.1.22:5577 ``` Note that if both the query param and the corresponding localStorage item are set, the query param will take precedence. @@ -305,6 +426,9 @@ npx @modelcontextprotocol/inspector --cli node build/index.js --method tools/lis # Call a specific tool npx @modelcontextprotocol/inspector --cli node build/index.js --method tools/call --tool-name mytool --tool-arg key=value --tool-arg another=value2 +# Call a tool with JSON arguments +npx @modelcontextprotocol/inspector --cli node build/index.js --method tools/call --tool-name mytool --tool-arg 'options={"format": "json", "max_tokens": 100}' + # List available resources npx @modelcontextprotocol/inspector --cli node build/index.js --method resources/list @@ -317,6 +441,9 @@ 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 +# Connect to a remote MCP server (with custom headers) +npx @modelcontextprotocol/inspector --cli https://my-mcp-server.example.com --transport http --method tools/list --header "X-API-Key: your-api-key" + # 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 @@ -336,6 +463,17 @@ npx @modelcontextprotocol/inspector --cli https://my-mcp-server.example.com --me | **Automation** | N/A | Ideal for CI/CD pipelines, batch processing, and integration with coding assistants | | **Learning MCP** | Rich visual interface helps new users understand server capabilities | Simplified commands for focused learning of specific endpoints | +## Tool Input Validation Guidelines + +When implementing or modifying tool input parameter handling in the Inspector: + +- **Omit optional fields with empty values** - When processing form inputs, omit empty strings or null values for optional parameters, UNLESS the field has an explicit default value in the schema that matches the current value +- **Preserve explicit default values** - If a field schema contains an explicit default (e.g., `default: null`), and the current value matches that default, include it in the request. This is a meaningful value the tool expects +- **Always include required fields** - Preserve required field values even when empty, allowing the MCP server to validate and return appropriate error messages +- **Defer deep validation to the server** - Implement basic field presence checking in the Inspector client, but rely on the MCP server for parameter validation according to its schema + +These guidelines maintain clean parameter passing and proper separation of concerns between the Inspector client and MCP servers. + ## License This project is licensed under the MIT License—see the [LICENSE](LICENSE) file for details. diff --git a/cli/__tests__/README.md b/cli/__tests__/README.md new file mode 100644 index 000000000..dd3f5ccca --- /dev/null +++ b/cli/__tests__/README.md @@ -0,0 +1,44 @@ +# CLI Tests + +## Running Tests + +```bash +# Run all tests +npm test + +# Run in watch mode (useful for test file changes; won't work on CLI source changes without rebuild) +npm run test:watch + +# Run specific test file +npm run test:cli # cli.test.ts +npm run test:cli-tools # tools.test.ts +npm run test:cli-headers # headers.test.ts +npm run test:cli-metadata # metadata.test.ts +``` + +## Test Files + +- `cli.test.ts` - Basic CLI functionality: CLI mode, environment variables, config files, resources, prompts, logging, transport types +- `tools.test.ts` - Tool-related tests: Tool discovery, JSON argument parsing, error handling, prompts +- `headers.test.ts` - Header parsing and validation +- `metadata.test.ts` - Metadata functionality: General metadata, tool-specific metadata, parsing, merging, validation + +## Helpers + +The `helpers/` directory contains shared utilities: + +- `cli-runner.ts` - Spawns CLI as subprocess and captures output +- `test-mcp-server.ts` - Standalone stdio MCP server script for stdio transport testing +- `instrumented-server.ts` - In-process MCP test server for HTTP/SSE transports with request recording +- `assertions.ts` - Custom assertion helpers for CLI output validation +- `fixtures.ts` - Test config file generators and temporary directory management + +## Notes + +- Tests run in parallel across files (Vitest default) +- Tests within a file run sequentially (we have isolated config files and ports, so we could get more aggressive if desired) +- Config files use `crypto.randomUUID()` for uniqueness in parallel execution +- HTTP/SSE servers use dynamic port allocation to avoid conflicts +- Coverage is not used because much of the code that we want to measure is run by a spawned process, so it can't be tracked by Vitest +- /sample-config.json is no longer used by tests - not clear if this file serves some other purpose so leaving it for now +- All tests now use built-in MCP test servers, there are no external dependencies on servers from a registry diff --git a/cli/__tests__/cli.test.ts b/cli/__tests__/cli.test.ts new file mode 100644 index 000000000..b263f618c --- /dev/null +++ b/cli/__tests__/cli.test.ts @@ -0,0 +1,871 @@ +import { describe, it, beforeAll, afterAll, expect } from "vitest"; +import { runCli } from "./helpers/cli-runner.js"; +import { + expectCliSuccess, + expectCliFailure, + expectValidJson, +} from "./helpers/assertions.js"; +import { + NO_SERVER_SENTINEL, + createSampleTestConfig, + createTestConfig, + createInvalidConfig, + deleteConfigFile, +} from "./helpers/fixtures.js"; +import { getTestMcpServerCommand } from "./helpers/test-server-stdio.js"; +import { createTestServerHttp } from "./helpers/test-server-http.js"; +import { + createEchoTool, + createTestServerInfo, +} from "./helpers/test-fixtures.js"; + +describe("CLI Tests", () => { + describe("Basic CLI Mode", () => { + it("should execute tools/list successfully", async () => { + const { command, args } = getTestMcpServerCommand(); + const result = await runCli([ + command, + ...args, + "--cli", + "--method", + "tools/list", + ]); + + expectCliSuccess(result); + const json = expectValidJson(result); + expect(json).toHaveProperty("tools"); + expect(Array.isArray(json.tools)).toBe(true); + + // Validate expected tools from test-mcp-server + const toolNames = json.tools.map((tool: any) => tool.name); + expect(toolNames).toContain("echo"); + expect(toolNames).toContain("get-sum"); + expect(toolNames).toContain("get-annotated-message"); + }); + + it("should fail with nonexistent method", async () => { + const result = await runCli([ + NO_SERVER_SENTINEL, + "--cli", + "--method", + "nonexistent/method", + ]); + + expectCliFailure(result); + }); + + it("should fail without method", async () => { + const result = await runCli([NO_SERVER_SENTINEL, "--cli"]); + + expectCliFailure(result); + }); + }); + + describe("Environment Variables", () => { + it("should accept environment variables", async () => { + const { command, args } = getTestMcpServerCommand(); + const result = await runCli([ + command, + ...args, + "-e", + "KEY1=value1", + "-e", + "KEY2=value2", + "--cli", + "--method", + "resources/read", + "--uri", + "test://env", + ]); + + expectCliSuccess(result); + const json = expectValidJson(result); + expect(json).toHaveProperty("contents"); + expect(Array.isArray(json.contents)).toBe(true); + expect(json.contents.length).toBeGreaterThan(0); + + // Parse the env vars from the resource + const envVars = JSON.parse(json.contents[0].text); + expect(envVars.KEY1).toBe("value1"); + expect(envVars.KEY2).toBe("value2"); + }); + + it("should reject invalid environment variable format", async () => { + const result = await runCli([ + NO_SERVER_SENTINEL, + "-e", + "INVALID_FORMAT", + "--cli", + "--method", + "tools/list", + ]); + + expectCliFailure(result); + }); + + it("should handle environment variable with equals sign in value", async () => { + const { command, args } = getTestMcpServerCommand(); + const result = await runCli([ + command, + ...args, + "-e", + "API_KEY=abc123=xyz789==", + "--cli", + "--method", + "resources/read", + "--uri", + "test://env", + ]); + + expectCliSuccess(result); + const json = expectValidJson(result); + const envVars = JSON.parse(json.contents[0].text); + expect(envVars.API_KEY).toBe("abc123=xyz789=="); + }); + + it("should handle environment variable with base64-encoded value", async () => { + const { command, args } = getTestMcpServerCommand(); + const result = await runCli([ + command, + ...args, + "-e", + "JWT_TOKEN=eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJzdWIiOiIxMjM0NTY3ODkwIn0=", + "--cli", + "--method", + "resources/read", + "--uri", + "test://env", + ]); + + expectCliSuccess(result); + const json = expectValidJson(result); + const envVars = JSON.parse(json.contents[0].text); + expect(envVars.JWT_TOKEN).toBe( + "eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJzdWIiOiIxMjM0NTY3ODkwIn0=", + ); + }); + }); + + describe("Config File", () => { + it("should use config file with CLI mode", async () => { + const configPath = createSampleTestConfig(); + try { + const result = await runCli([ + "--config", + configPath, + "--server", + "test-stdio", + "--cli", + "--method", + "tools/list", + ]); + + expectCliSuccess(result); + const json = expectValidJson(result); + expect(json).toHaveProperty("tools"); + expect(Array.isArray(json.tools)).toBe(true); + expect(json.tools.length).toBeGreaterThan(0); + } finally { + deleteConfigFile(configPath); + } + }); + + it("should fail when using config file without server name", async () => { + const configPath = createSampleTestConfig(); + try { + const result = await runCli([ + "--config", + configPath, + "--cli", + "--method", + "tools/list", + ]); + + expectCliFailure(result); + } finally { + deleteConfigFile(configPath); + } + }); + + it("should fail when using server name without config file", async () => { + const result = await runCli([ + "--server", + "test-stdio", + "--cli", + "--method", + "tools/list", + ]); + + expectCliFailure(result); + }); + + it("should fail with nonexistent config file", async () => { + const result = await runCli([ + "--config", + "./nonexistent-config.json", + "--server", + "test-stdio", + "--cli", + "--method", + "tools/list", + ]); + + expectCliFailure(result); + }); + + it("should fail with invalid config file format", async () => { + // Create invalid config temporarily + const invalidConfigPath = createInvalidConfig(); + try { + const result = await runCli([ + "--config", + invalidConfigPath, + "--server", + "test-stdio", + "--cli", + "--method", + "tools/list", + ]); + + expectCliFailure(result); + } finally { + deleteConfigFile(invalidConfigPath); + } + }); + + it("should fail with nonexistent server in config", async () => { + const configPath = createSampleTestConfig(); + try { + const result = await runCli([ + "--config", + configPath, + "--server", + "nonexistent", + "--cli", + "--method", + "tools/list", + ]); + + expectCliFailure(result); + } finally { + deleteConfigFile(configPath); + } + }); + }); + + describe("Resource Options", () => { + it("should read resource with URI", async () => { + const { command, args } = getTestMcpServerCommand(); + const result = await runCli([ + command, + ...args, + "--cli", + "--method", + "resources/read", + "--uri", + "demo://resource/static/document/architecture.md", + ]); + + expectCliSuccess(result); + const json = expectValidJson(result); + expect(json).toHaveProperty("contents"); + expect(Array.isArray(json.contents)).toBe(true); + expect(json.contents.length).toBeGreaterThan(0); + expect(json.contents[0]).toHaveProperty( + "uri", + "demo://resource/static/document/architecture.md", + ); + expect(json.contents[0]).toHaveProperty("mimeType", "text/markdown"); + expect(json.contents[0]).toHaveProperty("text"); + expect(json.contents[0].text).toContain("Architecture Documentation"); + }); + + it("should fail when reading resource without URI", async () => { + const { command, args } = getTestMcpServerCommand(); + const result = await runCli([ + command, + ...args, + "--cli", + "--method", + "resources/read", + ]); + + expectCliFailure(result); + }); + }); + + describe("Prompt Options", () => { + it("should get prompt by name", async () => { + const { command, args } = getTestMcpServerCommand(); + const result = await runCli([ + command, + ...args, + "--cli", + "--method", + "prompts/get", + "--prompt-name", + "simple-prompt", + ]); + + expectCliSuccess(result); + const json = expectValidJson(result); + expect(json).toHaveProperty("messages"); + expect(Array.isArray(json.messages)).toBe(true); + expect(json.messages.length).toBeGreaterThan(0); + expect(json.messages[0]).toHaveProperty("role", "user"); + expect(json.messages[0]).toHaveProperty("content"); + expect(json.messages[0].content).toHaveProperty("type", "text"); + expect(json.messages[0].content.text).toBe( + "This is a simple prompt for testing purposes.", + ); + }); + + it("should get prompt with arguments", async () => { + const { command, args } = getTestMcpServerCommand(); + const result = await runCli([ + command, + ...args, + "--cli", + "--method", + "prompts/get", + "--prompt-name", + "args-prompt", + "--prompt-args", + "city=New York", + "state=NY", + ]); + + expectCliSuccess(result); + const json = expectValidJson(result); + expect(json).toHaveProperty("messages"); + expect(Array.isArray(json.messages)).toBe(true); + expect(json.messages.length).toBeGreaterThan(0); + expect(json.messages[0]).toHaveProperty("role", "user"); + expect(json.messages[0]).toHaveProperty("content"); + expect(json.messages[0].content).toHaveProperty("type", "text"); + // Verify that the arguments were actually used in the response + expect(json.messages[0].content.text).toContain("city=New York"); + expect(json.messages[0].content.text).toContain("state=NY"); + }); + + it("should fail when getting prompt without name", async () => { + const { command, args } = getTestMcpServerCommand(); + const result = await runCli([ + command, + ...args, + "--cli", + "--method", + "prompts/get", + ]); + + expectCliFailure(result); + }); + }); + + describe("Logging Options", () => { + it("should set log level", async () => { + const server = createTestServerHttp({ + serverInfo: createTestServerInfo(), + logging: true, + }); + + try { + const port = await server.start("http"); + const serverUrl = `${server.getUrl()}/mcp`; + + const result = await runCli([ + serverUrl, + "--cli", + "--method", + "logging/setLevel", + "--log-level", + "debug", + "--transport", + "http", + ]); + + expectCliSuccess(result); + // Validate the response - logging/setLevel should return an empty result + const json = expectValidJson(result); + expect(json).toEqual({}); + + // Validate that the server actually received and recorded the log level + expect(server.getCurrentLogLevel()).toBe("debug"); + } finally { + await server.stop(); + } + }); + + it("should reject invalid log level", async () => { + const { command, args } = getTestMcpServerCommand(); + const result = await runCli([ + command, + ...args, + "--cli", + "--method", + "logging/setLevel", + "--log-level", + "invalid", + ]); + + expectCliFailure(result); + }); + }); + + describe("Combined Options", () => { + it("should handle config file with environment variables", async () => { + const configPath = createSampleTestConfig(); + try { + const result = await runCli([ + "--config", + configPath, + "--server", + "test-stdio", + "-e", + "CLI_ENV_VAR=cli_value", + "--cli", + "--method", + "resources/read", + "--uri", + "test://env", + ]); + + expectCliSuccess(result); + const json = expectValidJson(result); + expect(json).toHaveProperty("contents"); + expect(Array.isArray(json.contents)).toBe(true); + expect(json.contents.length).toBeGreaterThan(0); + + // Parse the env vars from the resource + const envVars = JSON.parse(json.contents[0].text); + expect(envVars).toHaveProperty("CLI_ENV_VAR"); + expect(envVars.CLI_ENV_VAR).toBe("cli_value"); + } finally { + deleteConfigFile(configPath); + } + }); + + it("should handle all options together", async () => { + const configPath = createSampleTestConfig(); + try { + const result = await runCli([ + "--config", + configPath, + "--server", + "test-stdio", + "-e", + "CLI_ENV_VAR=cli_value", + "--cli", + "--method", + "tools/call", + "--tool-name", + "echo", + "--tool-arg", + "message=Hello", + "--log-level", + "debug", + ]); + + expectCliSuccess(result); + const json = expectValidJson(result); + expect(json).toHaveProperty("content"); + expect(Array.isArray(json.content)).toBe(true); + expect(json.content.length).toBeGreaterThan(0); + expect(json.content[0]).toHaveProperty("type", "text"); + expect(json.content[0].text).toBe("Echo: Hello"); + } finally { + deleteConfigFile(configPath); + } + }); + }); + + describe("Config Transport Types", () => { + it("should work with stdio transport type", async () => { + const { command, args } = getTestMcpServerCommand(); + const configPath = createTestConfig({ + mcpServers: { + "test-stdio": { + type: "stdio", + command, + args, + env: { + TEST_ENV: "test-value", + }, + }, + }, + }); + try { + // First validate tools/list works + const toolsResult = await runCli([ + "--config", + configPath, + "--server", + "test-stdio", + "--cli", + "--method", + "tools/list", + ]); + + expectCliSuccess(toolsResult); + const toolsJson = expectValidJson(toolsResult); + expect(toolsJson).toHaveProperty("tools"); + expect(Array.isArray(toolsJson.tools)).toBe(true); + expect(toolsJson.tools.length).toBeGreaterThan(0); + + // Then validate env vars from config are passed to server + const envResult = await runCli([ + "--config", + configPath, + "--server", + "test-stdio", + "--cli", + "--method", + "resources/read", + "--uri", + "test://env", + ]); + + expectCliSuccess(envResult); + const envJson = expectValidJson(envResult); + const envVars = JSON.parse(envJson.contents[0].text); + expect(envVars).toHaveProperty("TEST_ENV"); + expect(envVars.TEST_ENV).toBe("test-value"); + } finally { + deleteConfigFile(configPath); + } + }); + + it("should fail with SSE transport type in CLI mode (connection error)", async () => { + const configPath = createTestConfig({ + mcpServers: { + "test-sse": { + type: "sse", + url: "http://localhost:3000/sse", + note: "Test SSE server", + }, + }, + }); + try { + const result = await runCli([ + "--config", + configPath, + "--server", + "test-sse", + "--cli", + "--method", + "tools/list", + ]); + + expectCliFailure(result); + } finally { + deleteConfigFile(configPath); + } + }); + + it("should fail with HTTP transport type in CLI mode (connection error)", async () => { + const configPath = createTestConfig({ + mcpServers: { + "test-http": { + type: "streamable-http", + url: "http://localhost:3001/mcp", + note: "Test HTTP server", + }, + }, + }); + try { + const result = await runCli([ + "--config", + configPath, + "--server", + "test-http", + "--cli", + "--method", + "tools/list", + ]); + + expectCliFailure(result); + } finally { + deleteConfigFile(configPath); + } + }); + + it("should work with legacy config without type field", async () => { + const { command, args } = getTestMcpServerCommand(); + const configPath = createTestConfig({ + mcpServers: { + "test-legacy": { + command, + args, + env: { + LEGACY_ENV: "legacy-value", + }, + }, + }, + }); + try { + // First validate tools/list works + const toolsResult = await runCli([ + "--config", + configPath, + "--server", + "test-legacy", + "--cli", + "--method", + "tools/list", + ]); + + expectCliSuccess(toolsResult); + const toolsJson = expectValidJson(toolsResult); + expect(toolsJson).toHaveProperty("tools"); + expect(Array.isArray(toolsJson.tools)).toBe(true); + expect(toolsJson.tools.length).toBeGreaterThan(0); + + // Then validate env vars from config are passed to server + const envResult = await runCli([ + "--config", + configPath, + "--server", + "test-legacy", + "--cli", + "--method", + "resources/read", + "--uri", + "test://env", + ]); + + expectCliSuccess(envResult); + const envJson = expectValidJson(envResult); + const envVars = JSON.parse(envJson.contents[0].text); + expect(envVars).toHaveProperty("LEGACY_ENV"); + expect(envVars.LEGACY_ENV).toBe("legacy-value"); + } finally { + deleteConfigFile(configPath); + } + }); + }); + + describe("Default Server Selection", () => { + it("should auto-select single server", async () => { + const { command, args } = getTestMcpServerCommand(); + const configPath = createTestConfig({ + mcpServers: { + "only-server": { + command, + args, + }, + }, + }); + try { + const result = await runCli([ + "--config", + configPath, + "--cli", + "--method", + "tools/list", + ]); + + expectCliSuccess(result); + const json = expectValidJson(result); + expect(json).toHaveProperty("tools"); + expect(Array.isArray(json.tools)).toBe(true); + expect(json.tools.length).toBeGreaterThan(0); + } finally { + deleteConfigFile(configPath); + } + }); + + it("should require explicit server selection even with default-server key (multiple servers)", async () => { + const { command, args } = getTestMcpServerCommand(); + const configPath = createTestConfig({ + mcpServers: { + "default-server": { + command, + args, + }, + "other-server": { + command: "node", + args: ["other.js"], + }, + }, + }); + try { + const result = await runCli([ + "--config", + configPath, + "--cli", + "--method", + "tools/list", + ]); + + expectCliFailure(result); + } finally { + deleteConfigFile(configPath); + } + }); + + it("should require explicit server selection with multiple servers", async () => { + const { command, args } = getTestMcpServerCommand(); + const configPath = createTestConfig({ + mcpServers: { + server1: { + command, + args, + }, + server2: { + command: "node", + args: ["other.js"], + }, + }, + }); + try { + const result = await runCli([ + "--config", + configPath, + "--cli", + "--method", + "tools/list", + ]); + + expectCliFailure(result); + } finally { + deleteConfigFile(configPath); + } + }); + }); + + describe("HTTP Transport", () => { + it("should infer HTTP transport from URL ending with /mcp", async () => { + const server = createTestServerHttp({ + serverInfo: createTestServerInfo(), + tools: [createEchoTool()], + }); + + try { + await server.start("http"); + const serverUrl = `${server.getUrl()}/mcp`; + + const result = await runCli([ + serverUrl, + "--cli", + "--method", + "tools/list", + ]); + + expectCliSuccess(result); + const json = expectValidJson(result); + expect(json).toHaveProperty("tools"); + expect(Array.isArray(json.tools)).toBe(true); + expect(json.tools.length).toBeGreaterThan(0); + } finally { + await server.stop(); + } + }); + + it("should work with explicit --transport http flag", async () => { + const server = createTestServerHttp({ + serverInfo: createTestServerInfo(), + tools: [createEchoTool()], + }); + + try { + await server.start("http"); + const serverUrl = `${server.getUrl()}/mcp`; + + const result = await runCli([ + serverUrl, + "--transport", + "http", + "--cli", + "--method", + "tools/list", + ]); + + expectCliSuccess(result); + const json = expectValidJson(result); + expect(json).toHaveProperty("tools"); + expect(Array.isArray(json.tools)).toBe(true); + expect(json.tools.length).toBeGreaterThan(0); + } finally { + await server.stop(); + } + }); + + it("should work with explicit transport flag and URL suffix", async () => { + const server = createTestServerHttp({ + serverInfo: createTestServerInfo(), + tools: [createEchoTool()], + }); + + try { + await server.start("http"); + const serverUrl = `${server.getUrl()}/mcp`; + + const result = await runCli([ + serverUrl, + "--transport", + "http", + "--cli", + "--method", + "tools/list", + ]); + + expectCliSuccess(result); + const json = expectValidJson(result); + expect(json).toHaveProperty("tools"); + expect(Array.isArray(json.tools)).toBe(true); + expect(json.tools.length).toBeGreaterThan(0); + } finally { + await server.stop(); + } + }); + + it("should fail when SSE transport is given to HTTP server", async () => { + const server = createTestServerHttp({ + serverInfo: createTestServerInfo(), + tools: [createEchoTool()], + }); + + try { + await server.start("http"); + const serverUrl = `${server.getUrl()}/mcp`; + + const result = await runCli([ + serverUrl, + "--transport", + "sse", + "--cli", + "--method", + "tools/list", + ]); + + expectCliFailure(result); + } finally { + await server.stop(); + } + }); + + it("should fail when HTTP transport is specified without URL", async () => { + const result = await runCli([ + "--transport", + "http", + "--cli", + "--method", + "tools/list", + ]); + + expectCliFailure(result); + }); + + it("should fail when SSE transport is specified without URL", async () => { + const result = await runCli([ + "--transport", + "sse", + "--cli", + "--method", + "tools/list", + ]); + + expectCliFailure(result); + }); + }); +}); diff --git a/cli/__tests__/headers.test.ts b/cli/__tests__/headers.test.ts new file mode 100644 index 000000000..6adf1effe --- /dev/null +++ b/cli/__tests__/headers.test.ts @@ -0,0 +1,210 @@ +import { describe, it, expect } from "vitest"; +import { runCli } from "./helpers/cli-runner.js"; +import { + expectCliFailure, + expectOutputContains, + expectCliSuccess, +} from "./helpers/assertions.js"; +import { createTestServerHttp } from "./helpers/test-server-http.js"; +import { + createEchoTool, + createTestServerInfo, +} from "./helpers/test-fixtures.js"; + +describe("Header Parsing and Validation", () => { + describe("Valid Headers", () => { + it("should parse valid single header and send it to server", async () => { + const server = createTestServerHttp({ + serverInfo: createTestServerInfo(), + tools: [createEchoTool()], + }); + + try { + const port = await server.start("http"); + const serverUrl = `${server.getUrl()}/mcp`; + + const result = await runCli([ + serverUrl, + "--cli", + "--method", + "tools/list", + "--transport", + "http", + "--header", + "Authorization: Bearer token123", + ]); + + expectCliSuccess(result); + + // Check that the server received the request with the correct headers + const recordedRequests = server.getRecordedRequests(); + expect(recordedRequests.length).toBeGreaterThan(0); + + // Find the tools/list request (should be the last one) + const toolsListRequest = recordedRequests[recordedRequests.length - 1]; + expect(toolsListRequest).toBeDefined(); + expect(toolsListRequest.method).toBe("tools/list"); + + // Express normalizes headers to lowercase + expect(toolsListRequest.headers).toHaveProperty("authorization"); + expect(toolsListRequest.headers?.authorization).toBe("Bearer token123"); + } finally { + await server.stop(); + } + }); + + it("should parse multiple headers", async () => { + const server = createTestServerHttp({ + serverInfo: createTestServerInfo(), + tools: [createEchoTool()], + }); + + try { + const port = await server.start("http"); + const serverUrl = `${server.getUrl()}/mcp`; + + const result = await runCli([ + serverUrl, + "--cli", + "--method", + "tools/list", + "--transport", + "http", + "--header", + "Authorization: Bearer token123", + "--header", + "X-API-Key: secret123", + ]); + + expectCliSuccess(result); + + const recordedRequests = server.getRecordedRequests(); + const toolsListRequest = recordedRequests[recordedRequests.length - 1]; + expect(toolsListRequest.method).toBe("tools/list"); + expect(toolsListRequest.headers?.authorization).toBe("Bearer token123"); + expect(toolsListRequest.headers?.["x-api-key"]).toBe("secret123"); + } finally { + await server.stop(); + } + }); + + it("should handle header with colons in value", async () => { + const server = createTestServerHttp({ + serverInfo: createTestServerInfo(), + tools: [createEchoTool()], + }); + + try { + const port = await server.start("http"); + const serverUrl = `${server.getUrl()}/mcp`; + + const result = await runCli([ + serverUrl, + "--cli", + "--method", + "tools/list", + "--transport", + "http", + "--header", + "X-Time: 2023:12:25:10:30:45", + ]); + + expectCliSuccess(result); + + const recordedRequests = server.getRecordedRequests(); + const toolsListRequest = recordedRequests[recordedRequests.length - 1]; + expect(toolsListRequest.method).toBe("tools/list"); + expect(toolsListRequest.headers?.["x-time"]).toBe( + "2023:12:25:10:30:45", + ); + } finally { + await server.stop(); + } + }); + + it("should handle whitespace in headers", async () => { + const server = createTestServerHttp({ + serverInfo: createTestServerInfo(), + tools: [createEchoTool()], + }); + + try { + const port = await server.start("http"); + const serverUrl = `${server.getUrl()}/mcp`; + + const result = await runCli([ + serverUrl, + "--cli", + "--method", + "tools/list", + "--transport", + "http", + "--header", + " X-Header : value with spaces ", + ]); + + expectCliSuccess(result); + + const recordedRequests = server.getRecordedRequests(); + const toolsListRequest = recordedRequests[recordedRequests.length - 1]; + expect(toolsListRequest.method).toBe("tools/list"); + // Header values should be trimmed by the CLI parser + expect(toolsListRequest.headers?.["x-header"]).toBe( + "value with spaces", + ); + } finally { + await server.stop(); + } + }); + }); + + describe("Invalid Header Formats", () => { + it("should reject header format without colon", async () => { + const result = await runCli([ + "https://example.com", + "--cli", + "--method", + "tools/list", + "--transport", + "http", + "--header", + "InvalidHeader", + ]); + + expectCliFailure(result); + expectOutputContains(result, "Invalid header format"); + }); + + it("should reject header format with empty name", async () => { + const result = await runCli([ + "https://example.com", + "--cli", + "--method", + "tools/list", + "--transport", + "http", + "--header", + ": value", + ]); + + expectCliFailure(result); + expectOutputContains(result, "Invalid header format"); + }); + + it("should reject header format with empty value", async () => { + const result = await runCli([ + "https://example.com", + "--cli", + "--method", + "tools/list", + "--transport", + "http", + "--header", + "Header:", + ]); + + expectCliFailure(result); + expectOutputContains(result, "Invalid header format"); + }); + }); +}); diff --git a/cli/__tests__/helpers/assertions.ts b/cli/__tests__/helpers/assertions.ts new file mode 100644 index 000000000..e3ed9d02b --- /dev/null +++ b/cli/__tests__/helpers/assertions.ts @@ -0,0 +1,52 @@ +import { expect } from "vitest"; +import type { CliResult } from "./cli-runner.js"; + +/** + * Assert that CLI command succeeded (exit code 0) + */ +export function expectCliSuccess(result: CliResult) { + expect(result.exitCode).toBe(0); +} + +/** + * Assert that CLI command failed (non-zero exit code) + */ +export function expectCliFailure(result: CliResult) { + expect(result.exitCode).not.toBe(0); +} + +/** + * Assert that output contains expected text + */ +export function expectOutputContains(result: CliResult, text: string) { + expect(result.output).toContain(text); +} + +/** + * Assert that output contains valid JSON + * Uses stdout (not stderr) since JSON is written to stdout and warnings go to stderr + */ +export function expectValidJson(result: CliResult) { + expect(() => JSON.parse(result.stdout)).not.toThrow(); + return JSON.parse(result.stdout); +} + +/** + * Assert that output contains JSON with error flag + */ +export function expectJsonError(result: CliResult) { + const json = expectValidJson(result); + expect(json.isError).toBe(true); + return json; +} + +/** + * Assert that output contains expected JSON structure + */ +export function expectJsonStructure(result: CliResult, expectedKeys: string[]) { + const json = expectValidJson(result); + expectedKeys.forEach((key) => { + expect(json).toHaveProperty(key); + }); + return json; +} diff --git a/cli/__tests__/helpers/cli-runner.ts b/cli/__tests__/helpers/cli-runner.ts new file mode 100644 index 000000000..073aa9ae4 --- /dev/null +++ b/cli/__tests__/helpers/cli-runner.ts @@ -0,0 +1,98 @@ +import { spawn } from "child_process"; +import { resolve } from "path"; +import { fileURLToPath } from "url"; +import { dirname } from "path"; + +const __dirname = dirname(fileURLToPath(import.meta.url)); +const CLI_PATH = resolve(__dirname, "../../build/cli.js"); + +export interface CliResult { + exitCode: number | null; + stdout: string; + stderr: string; + output: string; // Combined stdout + stderr +} + +export interface CliOptions { + timeout?: number; + cwd?: string; + env?: Record; + signal?: AbortSignal; +} + +/** + * Run the CLI with given arguments and capture output + */ +export async function runCli( + args: string[], + options: CliOptions = {}, +): Promise { + return new Promise((resolve, reject) => { + const child = spawn("node", [CLI_PATH, ...args], { + stdio: ["pipe", "pipe", "pipe"], + cwd: options.cwd, + env: { ...process.env, ...options.env }, + signal: options.signal, + // Kill child process tree on exit + detached: false, + }); + + let stdout = ""; + let stderr = ""; + let resolved = false; + + // Default timeout of 10 seconds (less than vitest's 15s) + const timeoutMs = options.timeout ?? 10000; + const timeout = setTimeout(() => { + if (!resolved) { + resolved = true; + // Kill the process and all its children + try { + if (process.platform === "win32") { + child.kill("SIGTERM"); + } else { + // On Unix, kill the process group + process.kill(-child.pid!, "SIGTERM"); + } + } catch (e) { + // Process might already be dead, try direct kill + try { + child.kill("SIGKILL"); + } catch (e2) { + // Process is definitely dead + } + } + reject(new Error(`CLI command timed out after ${timeoutMs}ms`)); + } + }, timeoutMs); + + child.stdout.on("data", (data) => { + stdout += data.toString(); + }); + + child.stderr.on("data", (data) => { + stderr += data.toString(); + }); + + child.on("close", (code) => { + if (!resolved) { + resolved = true; + clearTimeout(timeout); + resolve({ + exitCode: code, + stdout, + stderr, + output: stdout + stderr, + }); + } + }); + + child.on("error", (error) => { + if (!resolved) { + resolved = true; + clearTimeout(timeout); + reject(error); + } + }); + }); +} diff --git a/cli/__tests__/helpers/fixtures.ts b/cli/__tests__/helpers/fixtures.ts new file mode 100644 index 000000000..5914f485c --- /dev/null +++ b/cli/__tests__/helpers/fixtures.ts @@ -0,0 +1,89 @@ +import fs from "fs"; +import path from "path"; +import os from "os"; +import crypto from "crypto"; +import { getTestMcpServerCommand } from "./test-server-stdio.js"; + +/** + * Sentinel value for tests that don't need a real server + * (tests that expect failure before connecting) + */ +export const NO_SERVER_SENTINEL = "invalid-command-that-does-not-exist"; + +/** + * Create a sample test config with test-stdio and test-http servers + * Returns a temporary config file path that should be cleaned up with deleteConfigFile() + * @param httpUrl - Optional full URL (including /mcp path) for test-http server. + * If not provided, uses a placeholder URL. The test-http server exists + * to test server selection logic and may not actually be used. + */ +export function createSampleTestConfig(httpUrl?: string): string { + const { command, args } = getTestMcpServerCommand(); + return createTestConfig({ + mcpServers: { + "test-stdio": { + type: "stdio", + command, + args, + env: { + HELLO: "Hello MCP!", + }, + }, + "test-http": { + type: "streamable-http", + url: httpUrl || "http://localhost:3001/mcp", + }, + }, + }); +} + +/** + * Create a temporary directory for test files + * Uses crypto.randomUUID() to ensure uniqueness even when called in parallel + */ +function createTempDir(prefix: string = "mcp-inspector-test-"): string { + const uniqueId = crypto.randomUUID(); + const tempDir = path.join(os.tmpdir(), `${prefix}${uniqueId}`); + fs.mkdirSync(tempDir, { recursive: true }); + return tempDir; +} + +/** + * Clean up temporary directory + */ +function cleanupTempDir(dir: string) { + try { + fs.rmSync(dir, { recursive: true, force: true }); + } catch (err) { + // Ignore cleanup errors + } +} + +/** + * Create a test config file + */ +export function createTestConfig(config: { + mcpServers: Record; +}): string { + const tempDir = createTempDir("mcp-inspector-config-"); + const configPath = path.join(tempDir, "config.json"); + fs.writeFileSync(configPath, JSON.stringify(config, null, 2)); + return configPath; +} + +/** + * Create an invalid config file (malformed JSON) + */ +export function createInvalidConfig(): string { + const tempDir = createTempDir("mcp-inspector-config-"); + const configPath = path.join(tempDir, "invalid-config.json"); + fs.writeFileSync(configPath, '{\n "mcpServers": {\n "invalid": {'); + return configPath; +} + +/** + * Delete a config file and its containing directory + */ +export function deleteConfigFile(configPath: string): void { + cleanupTempDir(path.dirname(configPath)); +} diff --git a/cli/__tests__/helpers/test-fixtures.ts b/cli/__tests__/helpers/test-fixtures.ts new file mode 100644 index 000000000..d92d79ae0 --- /dev/null +++ b/cli/__tests__/helpers/test-fixtures.ts @@ -0,0 +1,267 @@ +/** + * Shared types and test fixtures for composable MCP test servers + */ + +import type { McpServer } from "@modelcontextprotocol/sdk/server/mcp.js"; +import type { Implementation } from "@modelcontextprotocol/sdk/types.js"; +import * as z from "zod/v4"; +import { ZodRawShapeCompat } from "@modelcontextprotocol/sdk/server/zod-compat.js"; + +type ToolInputSchema = ZodRawShapeCompat; + +export interface ToolDefinition { + name: string; + description: string; + inputSchema?: ToolInputSchema; + handler: (params: Record) => Promise; +} + +export interface ResourceDefinition { + uri: string; + name: string; + description?: string; + mimeType?: string; + text?: string; +} + +type PromptArgsSchema = ZodRawShapeCompat; + +export interface PromptDefinition { + name: string; + description?: string; + argsSchema?: PromptArgsSchema; +} + +// This allows us to compose tests servers using the metadata and features we want in a given scenario +export interface ServerConfig { + serverInfo: Implementation; // Server metadata (name, version, etc.) - required + tools?: ToolDefinition[]; // Tools to register (optional, empty array means no tools, but tools capability is still advertised) + resources?: ResourceDefinition[]; // Resources to register (optional, empty array means no resources, but resources capability is still advertised) + prompts?: PromptDefinition[]; // Prompts to register (optional, empty array means no prompts, but prompts capability is still advertised) + logging?: boolean; // Whether to advertise logging capability (default: false) +} + +/** + * Create an "echo" tool that echoes back the input message + */ +export function createEchoTool(): ToolDefinition { + return { + name: "echo", + description: "Echo back the input message", + inputSchema: { + message: z.string().describe("Message to echo back"), + }, + handler: async (params: Record) => { + return { message: `Echo: ${params.message as string}` }; + }, + }; +} + +/** + * Create an "add" tool that adds two numbers together + */ +export function createAddTool(): ToolDefinition { + return { + name: "add", + description: "Add two numbers together", + inputSchema: { + a: z.number().describe("First number"), + b: z.number().describe("Second number"), + }, + handler: async (params: Record) => { + const a = params.a as number; + const b = params.b as number; + return { result: a + b }; + }, + }; +} + +/** + * Create a "get-sum" tool that returns the sum of two numbers (alias for add) + */ +export function createGetSumTool(): ToolDefinition { + return { + name: "get-sum", + description: "Get the sum of two numbers", + inputSchema: { + a: z.number().describe("First number"), + b: z.number().describe("Second number"), + }, + handler: async (params: Record) => { + const a = params.a as number; + const b = params.b as number; + return { result: a + b }; + }, + }; +} + +/** + * Create a "get-annotated-message" tool that returns a message with optional image + */ +export function createGetAnnotatedMessageTool(): ToolDefinition { + return { + name: "get-annotated-message", + description: "Get an annotated message", + inputSchema: { + messageType: z + .enum(["success", "error", "warning", "info"]) + .describe("Type of message"), + includeImage: z + .boolean() + .optional() + .describe("Whether to include an image"), + }, + handler: async (params: Record) => { + const messageType = params.messageType as string; + const includeImage = params.includeImage as boolean | undefined; + const message = `This is a ${messageType} message`; + const content: Array< + | { type: "text"; text: string } + | { type: "image"; data: string; mimeType: string } + > = [ + { + type: "text", + text: message, + }, + ]; + + if (includeImage) { + content.push({ + type: "image", + data: "iVBORw0KGgoAAAANSUhEUgAAAAEAAAABCAYAAAAfFcSJAAAADUlEQVR42mNk+M9QDwADhgGAWjR9awAAAABJRU5ErkJggg==", // 1x1 transparent PNG + mimeType: "image/png", + }); + } + + return { content }; + }, + }; +} + +/** + * Create a "simple-prompt" prompt definition + */ +export function createSimplePrompt(): PromptDefinition { + return { + name: "simple-prompt", + description: "A simple prompt for testing", + }; +} + +/** + * Create an "args-prompt" prompt that accepts arguments + */ +export function createArgsPrompt(): PromptDefinition { + return { + name: "args-prompt", + description: "A prompt that accepts arguments for testing", + argsSchema: { + city: z.string().describe("City name"), + state: z.string().describe("State name"), + }, + }; +} + +/** + * Create an "architecture" resource definition + */ +export function createArchitectureResource(): ResourceDefinition { + return { + name: "architecture", + uri: "demo://resource/static/document/architecture.md", + description: "Architecture documentation", + mimeType: "text/markdown", + text: `# Architecture Documentation + +This is a test resource for the MCP test server. + +## Overview + +This resource is used for testing resource reading functionality in the CLI. + +## Sections + +- Introduction +- Design +- Implementation +- Testing + +## Notes + +This is a static resource provided by the test MCP server. +`, + }; +} + +/** + * Create a "test-cwd" resource that exposes the current working directory (generally useful when testing with the stdio test server) + */ +export function createTestCwdResource(): ResourceDefinition { + return { + name: "test-cwd", + uri: "test://cwd", + description: "Current working directory of the test server", + mimeType: "text/plain", + text: process.cwd(), + }; +} + +/** + * Create a "test-env" resource that exposes environment variables (generally useful when testing with the stdio test server) + */ +export function createTestEnvResource(): ResourceDefinition { + return { + name: "test-env", + uri: "test://env", + description: "Environment variables available to the test server", + mimeType: "application/json", + text: JSON.stringify(process.env, null, 2), + }; +} + +/** + * Create a "test-argv" resource that exposes command-line arguments (generally useful when testing with the stdio test server) + */ +export function createTestArgvResource(): ResourceDefinition { + return { + name: "test-argv", + uri: "test://argv", + description: "Command-line arguments the test server was started with", + mimeType: "application/json", + text: JSON.stringify(process.argv, null, 2), + }; +} + +/** + * Create minimal server info for test servers + */ +export function createTestServerInfo( + name: string = "test-server", + version: string = "1.0.0", +): Implementation { + return { + name, + version, + }; +} + +/** + * Get default server config with common test tools, prompts, and resources + */ +export function getDefaultServerConfig(): ServerConfig { + return { + serverInfo: createTestServerInfo("test-mcp-server", "1.0.0"), + tools: [ + createEchoTool(), + createGetSumTool(), + createGetAnnotatedMessageTool(), + ], + prompts: [createSimplePrompt(), createArgsPrompt()], + resources: [ + createArchitectureResource(), + createTestCwdResource(), + createTestEnvResource(), + createTestArgvResource(), + ], + }; +} diff --git a/cli/__tests__/helpers/test-server-http.ts b/cli/__tests__/helpers/test-server-http.ts new file mode 100644 index 000000000..4626ef516 --- /dev/null +++ b/cli/__tests__/helpers/test-server-http.ts @@ -0,0 +1,443 @@ +import { McpServer } from "@modelcontextprotocol/sdk/server/mcp.js"; +import { StreamableHTTPServerTransport } from "@modelcontextprotocol/sdk/server/streamableHttp.js"; +import { SSEServerTransport } from "@modelcontextprotocol/sdk/server/sse.js"; +import { SetLevelRequestSchema } from "@modelcontextprotocol/sdk/types.js"; +import type { Request, Response } from "express"; +import express from "express"; +import { createServer as createHttpServer, Server as HttpServer } from "http"; +import { createServer as createNetServer } from "net"; +import * as z from "zod/v4"; +import type { ServerConfig } from "./test-fixtures.js"; + +export interface RecordedRequest { + method: string; + params?: any; + headers?: Record; + metadata?: Record; + response: any; + timestamp: number; +} + +/** + * Find an available port starting from the given port + */ +async function findAvailablePort(startPort: number): Promise { + return new Promise((resolve, reject) => { + const server = createNetServer(); + server.listen(startPort, () => { + const port = (server.address() as { port: number })?.port; + server.close(() => resolve(port || startPort)); + }); + server.on("error", (err: NodeJS.ErrnoException) => { + if (err.code === "EADDRINUSE") { + // Try next port + findAvailablePort(startPort + 1) + .then(resolve) + .catch(reject); + } else { + reject(err); + } + }); + }); +} + +/** + * Extract headers from Express request + */ +function extractHeaders(req: Request): Record { + const headers: Record = {}; + for (const [key, value] of Object.entries(req.headers)) { + if (typeof value === "string") { + headers[key] = value; + } else if (Array.isArray(value) && value.length > 0) { + headers[key] = value[value.length - 1]; + } + } + return headers; +} + +// With this test server, your test can hold an instance and you can get the server's recorded message history at any time. +// +export class TestServerHttp { + private mcpServer: McpServer; + private config: ServerConfig; + private recordedRequests: RecordedRequest[] = []; + private httpServer?: HttpServer; + private transport?: StreamableHTTPServerTransport | SSEServerTransport; + private url?: string; + private currentRequestHeaders?: Record; + private currentLogLevel: string | null = null; + + constructor(config: ServerConfig) { + this.config = config; + const capabilities: { + tools?: {}; + resources?: {}; + prompts?: {}; + logging?: {}; + } = {}; + + // Only include capabilities for features that are present in config + if (config.tools !== undefined) { + capabilities.tools = {}; + } + if (config.resources !== undefined) { + capabilities.resources = {}; + } + if (config.prompts !== undefined) { + capabilities.prompts = {}; + } + if (config.logging === true) { + capabilities.logging = {}; + } + + this.mcpServer = new McpServer(config.serverInfo, { + capabilities, + }); + + this.setupHandlers(); + if (config.logging === true) { + this.setupLoggingHandler(); + } + } + + private setupHandlers() { + // Set up tools + if (this.config.tools && this.config.tools.length > 0) { + for (const tool of this.config.tools) { + this.mcpServer.registerTool( + tool.name, + { + description: tool.description, + inputSchema: tool.inputSchema, + }, + async (args) => { + const result = await tool.handler(args as Record); + return { + content: [{ type: "text", text: JSON.stringify(result) }], + }; + }, + ); + } + } + + // Set up resources + if (this.config.resources && this.config.resources.length > 0) { + for (const resource of this.config.resources) { + this.mcpServer.registerResource( + resource.name, + resource.uri, + { + description: resource.description, + mimeType: resource.mimeType, + }, + async () => { + return { + contents: [ + { + uri: resource.uri, + mimeType: resource.mimeType || "text/plain", + text: resource.text || "", + }, + ], + }; + }, + ); + } + } + + // Set up prompts + if (this.config.prompts && this.config.prompts.length > 0) { + for (const prompt of this.config.prompts) { + this.mcpServer.registerPrompt( + prompt.name, + { + description: prompt.description, + argsSchema: prompt.argsSchema, + }, + async (args) => { + // Return a simple prompt response + return { + messages: [ + { + role: "user", + content: { + type: "text", + text: `Prompt: ${prompt.name}${args ? ` with args: ${JSON.stringify(args)}` : ""}`, + }, + }, + ], + }; + }, + ); + } + } + } + + private setupLoggingHandler() { + // Intercept logging/setLevel requests to track the level + this.mcpServer.server.setRequestHandler( + SetLevelRequestSchema, + async (request) => { + this.currentLogLevel = request.params.level; + // Return empty result as per MCP spec + return {}; + }, + ); + } + + /** + * Start the server with the specified transport + */ + async start( + transport: "http" | "sse", + requestedPort?: number, + ): Promise { + const port = requestedPort + ? await findAvailablePort(requestedPort) + : await findAvailablePort(transport === "http" ? 3001 : 3000); + + this.url = `http://localhost:${port}`; + + if (transport === "http") { + return this.startHttp(port); + } else { + return this.startSse(port); + } + } + + private async startHttp(port: number): Promise { + const app = express(); + app.use(express.json()); + + // Create HTTP server + this.httpServer = createHttpServer(app); + + // Create StreamableHTTP transport + this.transport = new StreamableHTTPServerTransport({}); + + // Set up Express route to handle MCP requests + app.post("/mcp", async (req: Request, res: Response) => { + // Capture headers for this request + this.currentRequestHeaders = extractHeaders(req); + + try { + await (this.transport as StreamableHTTPServerTransport).handleRequest( + req, + res, + req.body, + ); + } catch (error) { + res.status(500).json({ + error: error instanceof Error ? error.message : String(error), + }); + } + }); + + // Intercept messages to record them + const originalOnMessage = this.transport.onmessage; + this.transport.onmessage = async (message) => { + const timestamp = Date.now(); + const method = + "method" in message && typeof message.method === "string" + ? message.method + : "unknown"; + const params = "params" in message ? message.params : undefined; + + try { + // Extract metadata from params if present + const metadata = + params && typeof params === "object" && "_meta" in params + ? ((params as any)._meta as Record) + : undefined; + + // Let the server handle the message + if (originalOnMessage) { + await originalOnMessage.call(this.transport, message); + } + + // Record successful request (response will be sent by transport) + // Note: We can't easily capture the response here, so we'll record + // that the request was processed + this.recordedRequests.push({ + method, + params, + headers: { ...this.currentRequestHeaders }, + metadata: metadata ? { ...metadata } : undefined, + response: { processed: true }, + timestamp, + }); + } catch (error) { + // Extract metadata from params if present + const metadata = + params && typeof params === "object" && "_meta" in params + ? ((params as any)._meta as Record) + : undefined; + + // Record error + this.recordedRequests.push({ + method, + params, + headers: { ...this.currentRequestHeaders }, + metadata: metadata ? { ...metadata } : undefined, + response: { + error: error instanceof Error ? error.message : String(error), + }, + timestamp, + }); + throw error; + } + }; + + // Connect transport to server + await this.mcpServer.connect(this.transport); + + // Start listening + return new Promise((resolve, reject) => { + this.httpServer!.listen(port, () => { + resolve(port); + }); + this.httpServer!.on("error", reject); + }); + } + + private async startSse(port: number): Promise { + const app = express(); + app.use(express.json()); + + // Create HTTP server + this.httpServer = createHttpServer(app); + + // For SSE, we need to set up an Express route that creates the transport per request + // This is a simplified version - SSE transport is created per connection + app.get("/mcp", async (req: Request, res: Response) => { + this.currentRequestHeaders = extractHeaders(req); + const sseTransport = new SSEServerTransport("/mcp", res); + + // Intercept messages + const originalOnMessage = sseTransport.onmessage; + sseTransport.onmessage = async (message) => { + const timestamp = Date.now(); + const method = + "method" in message && typeof message.method === "string" + ? message.method + : "unknown"; + const params = "params" in message ? message.params : undefined; + + try { + // Extract metadata from params if present + const metadata = + params && typeof params === "object" && "_meta" in params + ? ((params as any)._meta as Record) + : undefined; + + if (originalOnMessage) { + await originalOnMessage.call(sseTransport, message); + } + + this.recordedRequests.push({ + method, + params, + headers: { ...this.currentRequestHeaders }, + metadata: metadata ? { ...metadata } : undefined, + response: { processed: true }, + timestamp, + }); + } catch (error) { + // Extract metadata from params if present + const metadata = + params && typeof params === "object" && "_meta" in params + ? ((params as any)._meta as Record) + : undefined; + + this.recordedRequests.push({ + method, + params, + headers: { ...this.currentRequestHeaders }, + metadata: metadata ? { ...metadata } : undefined, + response: { + error: error instanceof Error ? error.message : String(error), + }, + timestamp, + }); + throw error; + } + }; + + await this.mcpServer.connect(sseTransport); + await sseTransport.start(); + }); + + // Note: SSE transport is created per request, so we don't store a single instance + this.transport = undefined; + + // Start listening + return new Promise((resolve, reject) => { + this.httpServer!.listen(port, () => { + resolve(port); + }); + this.httpServer!.on("error", reject); + }); + } + + /** + * Stop the server + */ + async stop(): Promise { + await this.mcpServer.close(); + + if (this.transport) { + await this.transport.close(); + this.transport = undefined; + } + + if (this.httpServer) { + return new Promise((resolve) => { + // Force close all connections + this.httpServer!.closeAllConnections?.(); + this.httpServer!.close(() => { + this.httpServer = undefined; + resolve(); + }); + }); + } + } + + /** + * Get all recorded requests + */ + getRecordedRequests(): RecordedRequest[] { + return [...this.recordedRequests]; + } + + /** + * Clear recorded requests + */ + clearRecordings(): void { + this.recordedRequests = []; + } + + /** + * Get the server URL + */ + getUrl(): string { + if (!this.url) { + throw new Error("Server not started"); + } + return this.url; + } + + /** + * Get the most recent log level that was set + */ + getCurrentLogLevel(): string | null { + return this.currentLogLevel; + } +} + +/** + * Create an HTTP/SSE MCP test server + */ +export function createTestServerHttp(config: ServerConfig): TestServerHttp { + return new TestServerHttp(config); +} diff --git a/cli/__tests__/helpers/test-server-stdio.ts b/cli/__tests__/helpers/test-server-stdio.ts new file mode 100644 index 000000000..7fe6a1c47 --- /dev/null +++ b/cli/__tests__/helpers/test-server-stdio.ts @@ -0,0 +1,241 @@ +#!/usr/bin/env node + +/** + * Test MCP server for stdio transport testing + * Can be used programmatically or run as a standalone executable + */ + +import { McpServer } from "@modelcontextprotocol/sdk/server/mcp.js"; +import { StdioServerTransport } from "@modelcontextprotocol/sdk/server/stdio.js"; +import * as z from "zod/v4"; +import path from "path"; +import { fileURLToPath } from "url"; +import { dirname } from "path"; +import type { + ServerConfig, + ToolDefinition, + PromptDefinition, + ResourceDefinition, +} from "./test-fixtures.js"; +import { getDefaultServerConfig } from "./test-fixtures.js"; + +const __dirname = dirname(fileURLToPath(import.meta.url)); + +export class TestServerStdio { + private mcpServer: McpServer; + private config: ServerConfig; + private transport?: StdioServerTransport; + + constructor(config: ServerConfig) { + this.config = config; + const capabilities: { + tools?: {}; + resources?: {}; + prompts?: {}; + logging?: {}; + } = {}; + + // Only include capabilities for features that are present in config + if (config.tools !== undefined) { + capabilities.tools = {}; + } + if (config.resources !== undefined) { + capabilities.resources = {}; + } + if (config.prompts !== undefined) { + capabilities.prompts = {}; + } + if (config.logging === true) { + capabilities.logging = {}; + } + + this.mcpServer = new McpServer(config.serverInfo, { + capabilities, + }); + + this.setupHandlers(); + } + + private setupHandlers() { + // Set up tools + if (this.config.tools && this.config.tools.length > 0) { + for (const tool of this.config.tools) { + this.mcpServer.registerTool( + tool.name, + { + description: tool.description, + inputSchema: tool.inputSchema, + }, + async (args) => { + const result = await tool.handler(args as Record); + // If handler returns content array directly (like get-annotated-message), use it + if (result && Array.isArray(result.content)) { + return { content: result.content }; + } + // If handler returns message (like echo), format it + if (result && typeof result.message === "string") { + return { + content: [ + { + type: "text", + text: result.message, + }, + ], + }; + } + // Otherwise, stringify the result + return { + content: [ + { + type: "text", + text: JSON.stringify(result), + }, + ], + }; + }, + ); + } + } + + // Set up resources + if (this.config.resources && this.config.resources.length > 0) { + for (const resource of this.config.resources) { + this.mcpServer.registerResource( + resource.name, + resource.uri, + { + description: resource.description, + mimeType: resource.mimeType, + }, + async () => { + // For dynamic resources, get fresh text + let text = resource.text; + if (resource.name === "test-cwd") { + text = process.cwd(); + } else if (resource.name === "test-env") { + text = JSON.stringify(process.env, null, 2); + } else if (resource.name === "test-argv") { + text = JSON.stringify(process.argv, null, 2); + } + + return { + contents: [ + { + uri: resource.uri, + mimeType: resource.mimeType || "text/plain", + text: text || "", + }, + ], + }; + }, + ); + } + } + + // Set up prompts + if (this.config.prompts && this.config.prompts.length > 0) { + for (const prompt of this.config.prompts) { + this.mcpServer.registerPrompt( + prompt.name, + { + description: prompt.description, + argsSchema: prompt.argsSchema, + }, + async (args) => { + if (prompt.name === "args-prompt" && args) { + const city = (args as any).city as string; + const state = (args as any).state as string; + return { + messages: [ + { + role: "user", + content: { + type: "text", + text: `This is a prompt with arguments: city=${city}, state=${state}`, + }, + }, + ], + }; + } else { + return { + messages: [ + { + role: "user", + content: { + type: "text", + text: "This is a simple prompt for testing purposes.", + }, + }, + ], + }; + } + }, + ); + } + } + } + + /** + * Start the server with stdio transport + */ + async start(): Promise { + this.transport = new StdioServerTransport(); + await this.mcpServer.connect(this.transport); + } + + /** + * Stop the server + */ + async stop(): Promise { + await this.mcpServer.close(); + if (this.transport) { + await this.transport.close(); + this.transport = undefined; + } + } +} + +/** + * Create a stdio MCP test server + */ +export function createTestServerStdio(config: ServerConfig): TestServerStdio { + return new TestServerStdio(config); +} + +/** + * Get the path to the test MCP server script + */ +export function getTestMcpServerPath(): string { + return path.resolve(__dirname, "test-server-stdio.ts"); +} + +/** + * Get the command and args to run the test MCP server + */ +export function getTestMcpServerCommand(): { command: string; args: string[] } { + return { + command: "tsx", + args: [getTestMcpServerPath()], + }; +} + +// If run as a standalone script, start with default config +// Check if this file is being executed directly (not imported) +const isMainModule = + import.meta.url.endsWith(process.argv[1]) || + process.argv[1]?.endsWith("test-server-stdio.ts") || + process.argv[1]?.endsWith("test-server-stdio.js"); + +if (isMainModule) { + const server = new TestServerStdio(getDefaultServerConfig()); + server + .start() + .then(() => { + // Server is now running and listening on stdio + // Keep the process alive + }) + .catch((error) => { + console.error("Failed to start test MCP server:", error); + process.exit(1); + }); +} diff --git a/cli/__tests__/metadata.test.ts b/cli/__tests__/metadata.test.ts new file mode 100644 index 000000000..93d5f8ca6 --- /dev/null +++ b/cli/__tests__/metadata.test.ts @@ -0,0 +1,933 @@ +import { describe, it, expect } from "vitest"; +import { runCli } from "./helpers/cli-runner.js"; +import { + expectCliSuccess, + expectCliFailure, + expectValidJson, +} from "./helpers/assertions.js"; +import { createTestServerHttp } from "./helpers/test-server-http.js"; +import { + createEchoTool, + createAddTool, + createTestServerInfo, +} from "./helpers/test-fixtures.js"; +import { NO_SERVER_SENTINEL } from "./helpers/fixtures.js"; + +describe("Metadata Tests", () => { + describe("General Metadata", () => { + it("should work with tools/list", async () => { + const server = createTestServerHttp({ + serverInfo: createTestServerInfo(), + tools: [createEchoTool()], + }); + + try { + await server.start("http"); + const serverUrl = `${server.getUrl()}/mcp`; + + const result = await runCli([ + serverUrl, + "--cli", + "--method", + "tools/list", + "--metadata", + "client=test-client", + "--transport", + "http", + ]); + + expectCliSuccess(result); + const json = expectValidJson(result); + expect(json).toHaveProperty("tools"); + + // Validate metadata was sent + const recordedRequests = server.getRecordedRequests(); + const toolsListRequest = recordedRequests.find( + (r) => r.method === "tools/list", + ); + expect(toolsListRequest).toBeDefined(); + expect(toolsListRequest?.metadata).toEqual({ client: "test-client" }); + } finally { + await server.stop(); + } + }); + + it("should work with resources/list", async () => { + const server = createTestServerHttp({ + serverInfo: createTestServerInfo(), + resources: [ + { + uri: "test://resource", + name: "test-resource", + text: "test content", + }, + ], + }); + + try { + await server.start("http"); + const serverUrl = `${server.getUrl()}/mcp`; + + const result = await runCli([ + serverUrl, + "--cli", + "--method", + "resources/list", + "--metadata", + "client=test-client", + "--transport", + "http", + ]); + + expectCliSuccess(result); + const json = expectValidJson(result); + expect(json).toHaveProperty("resources"); + + // Validate metadata was sent + const recordedRequests = server.getRecordedRequests(); + const resourcesListRequest = recordedRequests.find( + (r) => r.method === "resources/list", + ); + expect(resourcesListRequest).toBeDefined(); + expect(resourcesListRequest?.metadata).toEqual({ + client: "test-client", + }); + } finally { + await server.stop(); + } + }); + + it("should work with prompts/list", async () => { + const server = createTestServerHttp({ + serverInfo: createTestServerInfo(), + prompts: [ + { + name: "test-prompt", + description: "A test prompt", + }, + ], + }); + + try { + await server.start("http"); + const serverUrl = `${server.getUrl()}/mcp`; + + const result = await runCli([ + serverUrl, + "--cli", + "--method", + "prompts/list", + "--metadata", + "client=test-client", + "--transport", + "http", + ]); + + expectCliSuccess(result); + const json = expectValidJson(result); + expect(json).toHaveProperty("prompts"); + + // Validate metadata was sent + const recordedRequests = server.getRecordedRequests(); + const promptsListRequest = recordedRequests.find( + (r) => r.method === "prompts/list", + ); + expect(promptsListRequest).toBeDefined(); + expect(promptsListRequest?.metadata).toEqual({ + client: "test-client", + }); + } finally { + await server.stop(); + } + }); + + it("should work with resources/read", async () => { + const server = createTestServerHttp({ + serverInfo: createTestServerInfo(), + resources: [ + { + uri: "test://resource", + name: "test-resource", + text: "test content", + }, + ], + }); + + try { + await server.start("http"); + const serverUrl = `${server.getUrl()}/mcp`; + + const result = await runCli([ + serverUrl, + "--cli", + "--method", + "resources/read", + "--uri", + "test://resource", + "--metadata", + "client=test-client", + "--transport", + "http", + ]); + + expectCliSuccess(result); + const json = expectValidJson(result); + expect(json).toHaveProperty("contents"); + + // Validate metadata was sent + const recordedRequests = server.getRecordedRequests(); + const readRequest = recordedRequests.find( + (r) => r.method === "resources/read", + ); + expect(readRequest).toBeDefined(); + expect(readRequest?.metadata).toEqual({ client: "test-client" }); + } finally { + await server.stop(); + } + }); + + it("should work with prompts/get", async () => { + const server = createTestServerHttp({ + serverInfo: createTestServerInfo(), + prompts: [ + { + name: "test-prompt", + description: "A test prompt", + }, + ], + }); + + try { + await server.start("http"); + const serverUrl = `${server.getUrl()}/mcp`; + + const result = await runCli([ + serverUrl, + "--cli", + "--method", + "prompts/get", + "--prompt-name", + "test-prompt", + "--metadata", + "client=test-client", + "--transport", + "http", + ]); + + expectCliSuccess(result); + const json = expectValidJson(result); + expect(json).toHaveProperty("messages"); + + // Validate metadata was sent + const recordedRequests = server.getRecordedRequests(); + const getPromptRequest = recordedRequests.find( + (r) => r.method === "prompts/get", + ); + expect(getPromptRequest).toBeDefined(); + expect(getPromptRequest?.metadata).toEqual({ client: "test-client" }); + } finally { + await server.stop(); + } + }); + }); + + describe("Tool-Specific Metadata", () => { + it("should work with tools/call", async () => { + const server = createTestServerHttp({ + serverInfo: createTestServerInfo(), + tools: [createEchoTool()], + }); + + try { + await server.start("http"); + const serverUrl = `${server.getUrl()}/mcp`; + + const result = await runCli([ + serverUrl, + "--cli", + "--method", + "tools/call", + "--tool-name", + "echo", + "--tool-arg", + "message=hello world", + "--tool-metadata", + "client=test-client", + "--transport", + "http", + ]); + + expectCliSuccess(result); + const json = expectValidJson(result); + expect(json).toHaveProperty("content"); + + // Validate metadata was sent + const recordedRequests = server.getRecordedRequests(); + const toolCallRequest = recordedRequests.find( + (r) => r.method === "tools/call", + ); + expect(toolCallRequest).toBeDefined(); + expect(toolCallRequest?.metadata).toEqual({ client: "test-client" }); + } finally { + await server.stop(); + } + }); + + it("should work with complex tool", async () => { + const server = createTestServerHttp({ + serverInfo: createTestServerInfo(), + tools: [createAddTool()], + }); + + try { + await server.start("http"); + const serverUrl = `${server.getUrl()}/mcp`; + + const result = await runCli([ + serverUrl, + "--cli", + "--method", + "tools/call", + "--tool-name", + "add", + "--tool-arg", + "a=10", + "b=20", + "--tool-metadata", + "client=test-client", + "--transport", + "http", + ]); + + expectCliSuccess(result); + const json = expectValidJson(result); + expect(json).toHaveProperty("content"); + + // Validate metadata was sent + const recordedRequests = server.getRecordedRequests(); + const toolCallRequest = recordedRequests.find( + (r) => r.method === "tools/call", + ); + expect(toolCallRequest).toBeDefined(); + expect(toolCallRequest?.metadata).toEqual({ client: "test-client" }); + } finally { + await server.stop(); + } + }); + }); + + describe("Metadata Merging", () => { + it("should merge general and tool-specific metadata (tool-specific overrides)", async () => { + const server = createTestServerHttp({ + serverInfo: createTestServerInfo(), + tools: [createEchoTool()], + }); + + try { + await server.start("http"); + const serverUrl = `${server.getUrl()}/mcp`; + + const result = await runCli([ + serverUrl, + "--cli", + "--method", + "tools/call", + "--tool-name", + "echo", + "--tool-arg", + "message=hello world", + "--metadata", + "client=general-client", + "shared_key=shared_value", + "--tool-metadata", + "client=tool-specific-client", + "--transport", + "http", + ]); + + expectCliSuccess(result); + + // Validate metadata was merged correctly (tool-specific overrides general) + const recordedRequests = server.getRecordedRequests(); + const toolCallRequest = recordedRequests.find( + (r) => r.method === "tools/call", + ); + expect(toolCallRequest).toBeDefined(); + expect(toolCallRequest?.metadata).toEqual({ + client: "tool-specific-client", // Tool-specific overrides general + shared_key: "shared_value", // General metadata is preserved + }); + } finally { + await server.stop(); + } + }); + }); + + describe("Metadata Parsing", () => { + it("should handle numeric values", async () => { + const server = createTestServerHttp({ + serverInfo: createTestServerInfo(), + tools: [createEchoTool()], + }); + + try { + await server.start("http"); + const serverUrl = `${server.getUrl()}/mcp`; + + const result = await runCli([ + serverUrl, + "--cli", + "--method", + "tools/list", + "--metadata", + "integer_value=42", + "decimal_value=3.14159", + "negative_value=-10", + "--transport", + "http", + ]); + + expectCliSuccess(result); + + // Validate metadata values are sent as strings + const recordedRequests = server.getRecordedRequests(); + const toolsListRequest = recordedRequests.find( + (r) => r.method === "tools/list", + ); + expect(toolsListRequest).toBeDefined(); + expect(toolsListRequest?.metadata).toEqual({ + integer_value: "42", + decimal_value: "3.14159", + negative_value: "-10", + }); + } finally { + await server.stop(); + } + }); + + it("should handle JSON values", async () => { + const server = createTestServerHttp({ + serverInfo: createTestServerInfo(), + tools: [createEchoTool()], + }); + + try { + await server.start("http"); + const serverUrl = `${server.getUrl()}/mcp`; + + const result = await runCli([ + serverUrl, + "--cli", + "--method", + "tools/list", + "--metadata", + 'json_object="{\\"key\\":\\"value\\"}"', + 'json_array="[1,2,3]"', + 'json_string="\\"quoted\\""', + "--transport", + "http", + ]); + + expectCliSuccess(result); + + // Validate JSON values are sent as strings + const recordedRequests = server.getRecordedRequests(); + const toolsListRequest = recordedRequests.find( + (r) => r.method === "tools/list", + ); + expect(toolsListRequest).toBeDefined(); + expect(toolsListRequest?.metadata).toEqual({ + json_object: '{"key":"value"}', + json_array: "[1,2,3]", + json_string: '"quoted"', + }); + } finally { + await server.stop(); + } + }); + + it("should handle special characters", async () => { + const server = createTestServerHttp({ + serverInfo: createTestServerInfo(), + tools: [createEchoTool()], + }); + + try { + await server.start("http"); + const serverUrl = `${server.getUrl()}/mcp`; + + const result = await runCli([ + serverUrl, + "--cli", + "--method", + "tools/list", + "--metadata", + "unicode=🚀🎉✨", + "special_chars=!@#$%^&*()", + "spaces=hello world with spaces", + "--transport", + "http", + ]); + + expectCliSuccess(result); + + // Validate special characters are preserved + const recordedRequests = server.getRecordedRequests(); + const toolsListRequest = recordedRequests.find( + (r) => r.method === "tools/list", + ); + expect(toolsListRequest).toBeDefined(); + expect(toolsListRequest?.metadata).toEqual({ + unicode: "🚀🎉✨", + special_chars: "!@#$%^&*()", + spaces: "hello world with spaces", + }); + } finally { + await server.stop(); + } + }); + }); + + describe("Metadata Edge Cases", () => { + it("should handle single metadata entry", async () => { + const server = createTestServerHttp({ + serverInfo: createTestServerInfo(), + tools: [createEchoTool()], + }); + + try { + await server.start("http"); + const serverUrl = `${server.getUrl()}/mcp`; + + const result = await runCli([ + serverUrl, + "--cli", + "--method", + "tools/list", + "--metadata", + "single_key=single_value", + "--transport", + "http", + ]); + + expectCliSuccess(result); + + // Validate single metadata entry + const recordedRequests = server.getRecordedRequests(); + const toolsListRequest = recordedRequests.find( + (r) => r.method === "tools/list", + ); + expect(toolsListRequest).toBeDefined(); + expect(toolsListRequest?.metadata).toEqual({ + single_key: "single_value", + }); + } finally { + await server.stop(); + } + }); + + it("should handle many metadata entries", async () => { + const server = createTestServerHttp({ + serverInfo: createTestServerInfo(), + tools: [createEchoTool()], + }); + + try { + await server.start("http"); + const serverUrl = `${server.getUrl()}/mcp`; + + const result = await runCli([ + serverUrl, + "--cli", + "--method", + "tools/list", + "--metadata", + "key1=value1", + "key2=value2", + "key3=value3", + "key4=value4", + "key5=value5", + "--transport", + "http", + ]); + + expectCliSuccess(result); + + // Validate all metadata entries + const recordedRequests = server.getRecordedRequests(); + const toolsListRequest = recordedRequests.find( + (r) => r.method === "tools/list", + ); + expect(toolsListRequest).toBeDefined(); + expect(toolsListRequest?.metadata).toEqual({ + key1: "value1", + key2: "value2", + key3: "value3", + key4: "value4", + key5: "value5", + }); + } finally { + await server.stop(); + } + }); + }); + + describe("Metadata Error Cases", () => { + it("should fail with invalid metadata format (missing equals)", async () => { + const result = await runCli([ + NO_SERVER_SENTINEL, + "--cli", + "--method", + "tools/list", + "--metadata", + "invalid_format_no_equals", + ]); + + expectCliFailure(result); + }); + + it("should fail with invalid tool-metadata format (missing equals)", async () => { + const result = await runCli([ + NO_SERVER_SENTINEL, + "--cli", + "--method", + "tools/call", + "--tool-name", + "echo", + "--tool-arg", + "message=test", + "--tool-metadata", + "invalid_format_no_equals", + ]); + + expectCliFailure(result); + }); + }); + + describe("Metadata Impact", () => { + it("should handle tool-specific metadata precedence over general", async () => { + const server = createTestServerHttp({ + serverInfo: createTestServerInfo(), + tools: [createEchoTool()], + }); + + try { + await server.start("http"); + const serverUrl = `${server.getUrl()}/mcp`; + + const result = await runCli([ + serverUrl, + "--cli", + "--method", + "tools/call", + "--tool-name", + "echo", + "--tool-arg", + "message=precedence test", + "--metadata", + "client=general-client", + "--tool-metadata", + "client=tool-specific-client", + "--transport", + "http", + ]); + + expectCliSuccess(result); + + // Validate tool-specific metadata overrides general + const recordedRequests = server.getRecordedRequests(); + const toolCallRequest = recordedRequests.find( + (r) => r.method === "tools/call", + ); + expect(toolCallRequest).toBeDefined(); + expect(toolCallRequest?.metadata).toEqual({ + client: "tool-specific-client", + }); + } finally { + await server.stop(); + } + }); + + it("should work with resources methods", async () => { + const server = createTestServerHttp({ + serverInfo: createTestServerInfo(), + resources: [ + { + uri: "test://resource", + name: "test-resource", + text: "test content", + }, + ], + }); + + try { + await server.start("http"); + const serverUrl = `${server.getUrl()}/mcp`; + + const result = await runCli([ + serverUrl, + "--cli", + "--method", + "resources/list", + "--metadata", + "resource_client=test-resource-client", + "--transport", + "http", + ]); + + expectCliSuccess(result); + + // Validate metadata was sent + const recordedRequests = server.getRecordedRequests(); + const resourcesListRequest = recordedRequests.find( + (r) => r.method === "resources/list", + ); + expect(resourcesListRequest).toBeDefined(); + expect(resourcesListRequest?.metadata).toEqual({ + resource_client: "test-resource-client", + }); + } finally { + await server.stop(); + } + }); + + it("should work with prompts methods", async () => { + const server = createTestServerHttp({ + serverInfo: createTestServerInfo(), + prompts: [ + { + name: "test-prompt", + description: "A test prompt", + }, + ], + }); + + try { + await server.start("http"); + const serverUrl = `${server.getUrl()}/mcp`; + + const result = await runCli([ + serverUrl, + "--cli", + "--method", + "prompts/get", + "--prompt-name", + "test-prompt", + "--metadata", + "prompt_client=test-prompt-client", + "--transport", + "http", + ]); + + expectCliSuccess(result); + + // Validate metadata was sent + const recordedRequests = server.getRecordedRequests(); + const getPromptRequest = recordedRequests.find( + (r) => r.method === "prompts/get", + ); + expect(getPromptRequest).toBeDefined(); + expect(getPromptRequest?.metadata).toEqual({ + prompt_client: "test-prompt-client", + }); + } finally { + await server.stop(); + } + }); + }); + + describe("Metadata Validation", () => { + it("should handle special characters in keys", async () => { + const server = createTestServerHttp({ + serverInfo: createTestServerInfo(), + tools: [createEchoTool()], + }); + + try { + await server.start("http"); + const serverUrl = `${server.getUrl()}/mcp`; + + const result = await runCli([ + serverUrl, + "--cli", + "--method", + "tools/call", + "--tool-name", + "echo", + "--tool-arg", + "message=special keys test", + "--metadata", + "key-with-dashes=value1", + "key_with_underscores=value2", + "key.with.dots=value3", + "--transport", + "http", + ]); + + expectCliSuccess(result); + + // Validate special characters in keys are preserved + const recordedRequests = server.getRecordedRequests(); + const toolCallRequest = recordedRequests.find( + (r) => r.method === "tools/call", + ); + expect(toolCallRequest).toBeDefined(); + expect(toolCallRequest?.metadata).toEqual({ + "key-with-dashes": "value1", + key_with_underscores: "value2", + "key.with.dots": "value3", + }); + } finally { + await server.stop(); + } + }); + }); + + describe("Metadata Integration", () => { + it("should work with all MCP methods", async () => { + const server = createTestServerHttp({ + serverInfo: createTestServerInfo(), + tools: [createEchoTool()], + }); + + try { + await server.start("http"); + const serverUrl = `${server.getUrl()}/mcp`; + + const result = await runCli([ + serverUrl, + "--cli", + "--method", + "tools/list", + "--metadata", + "integration_test=true", + "test_phase=all_methods", + "--transport", + "http", + ]); + + expectCliSuccess(result); + + // Validate metadata was sent + const recordedRequests = server.getRecordedRequests(); + const toolsListRequest = recordedRequests.find( + (r) => r.method === "tools/list", + ); + expect(toolsListRequest).toBeDefined(); + expect(toolsListRequest?.metadata).toEqual({ + integration_test: "true", + test_phase: "all_methods", + }); + } finally { + await server.stop(); + } + }); + + it("should handle complex metadata scenario", async () => { + const server = createTestServerHttp({ + serverInfo: createTestServerInfo(), + tools: [createEchoTool()], + }); + + try { + await server.start("http"); + const serverUrl = `${server.getUrl()}/mcp`; + + const result = await runCli([ + serverUrl, + "--cli", + "--method", + "tools/call", + "--tool-name", + "echo", + "--tool-arg", + "message=complex test", + "--metadata", + "session_id=12345", + "user_id=67890", + "timestamp=2024-01-01T00:00:00Z", + "request_id=req-abc-123", + "--tool-metadata", + "tool_session=session-xyz-789", + "execution_context=test", + "priority=high", + "--transport", + "http", + ]); + + expectCliSuccess(result); + + // Validate complex metadata merging + const recordedRequests = server.getRecordedRequests(); + const toolCallRequest = recordedRequests.find( + (r) => r.method === "tools/call", + ); + expect(toolCallRequest).toBeDefined(); + expect(toolCallRequest?.metadata).toEqual({ + session_id: "12345", + user_id: "67890", + timestamp: "2024-01-01T00:00:00Z", + request_id: "req-abc-123", + tool_session: "session-xyz-789", + execution_context: "test", + priority: "high", + }); + } finally { + await server.stop(); + } + }); + + it("should handle metadata parsing validation", async () => { + const server = createTestServerHttp({ + serverInfo: createTestServerInfo(), + tools: [createEchoTool()], + }); + + try { + await server.start("http"); + const serverUrl = `${server.getUrl()}/mcp`; + + const result = await runCli([ + serverUrl, + "--cli", + "--method", + "tools/call", + "--tool-name", + "echo", + "--tool-arg", + "message=parsing validation test", + "--metadata", + "valid_key=valid_value", + "numeric_key=123", + "boolean_key=true", + 'json_key=\'{"test":"value"}\'', + "special_key=!@#$%^&*()", + "unicode_key=🚀🎉✨", + "--transport", + "http", + ]); + + expectCliSuccess(result); + + // Validate all value types are sent as strings + // Note: The CLI parses metadata values, so single-quoted JSON strings + // are preserved with their quotes + const recordedRequests = server.getRecordedRequests(); + const toolCallRequest = recordedRequests.find( + (r) => r.method === "tools/call", + ); + expect(toolCallRequest).toBeDefined(); + expect(toolCallRequest?.metadata).toEqual({ + valid_key: "valid_value", + numeric_key: "123", + boolean_key: "true", + json_key: '\'{"test":"value"}\'', // Single quotes are preserved + special_key: "!@#$%^&*()", + unicode_key: "🚀🎉✨", + }); + } finally { + await server.stop(); + } + }); + }); +}); diff --git a/cli/__tests__/tools.test.ts b/cli/__tests__/tools.test.ts new file mode 100644 index 000000000..e83b5ea0d --- /dev/null +++ b/cli/__tests__/tools.test.ts @@ -0,0 +1,523 @@ +import { describe, it, expect } from "vitest"; +import { runCli } from "./helpers/cli-runner.js"; +import { + expectCliSuccess, + expectCliFailure, + expectValidJson, + expectJsonError, +} from "./helpers/assertions.js"; +import { getTestMcpServerCommand } from "./helpers/test-server-stdio.js"; + +describe("Tool Tests", () => { + describe("Tool Discovery", () => { + it("should list available tools", async () => { + const { command, args } = getTestMcpServerCommand(); + const result = await runCli([ + command, + ...args, + "--cli", + "--method", + "tools/list", + ]); + + expectCliSuccess(result); + const json = expectValidJson(result); + expect(json).toHaveProperty("tools"); + expect(Array.isArray(json.tools)).toBe(true); + expect(json.tools.length).toBeGreaterThan(0); + // Validate that tools have required properties + expect(json.tools[0]).toHaveProperty("name"); + expect(json.tools[0]).toHaveProperty("description"); + // Validate expected tools from test-mcp-server + const toolNames = json.tools.map((tool: any) => tool.name); + expect(toolNames).toContain("echo"); + expect(toolNames).toContain("get-sum"); + expect(toolNames).toContain("get-annotated-message"); + }); + }); + + describe("JSON Argument Parsing", () => { + it("should handle string arguments (backward compatibility)", async () => { + const { command, args } = getTestMcpServerCommand(); + const result = await runCli([ + command, + ...args, + "--cli", + "--method", + "tools/call", + "--tool-name", + "echo", + "--tool-arg", + "message=hello world", + ]); + + expectCliSuccess(result); + const json = expectValidJson(result); + expect(json).toHaveProperty("content"); + expect(Array.isArray(json.content)).toBe(true); + expect(json.content.length).toBeGreaterThan(0); + expect(json.content[0]).toHaveProperty("type", "text"); + expect(json.content[0].text).toBe("Echo: hello world"); + }); + + it("should handle integer number arguments", async () => { + const { command, args } = getTestMcpServerCommand(); + const result = await runCli([ + command, + ...args, + "--cli", + "--method", + "tools/call", + "--tool-name", + "get-sum", + "--tool-arg", + "a=42", + "b=58", + ]); + + expectCliSuccess(result); + const json = expectValidJson(result); + expect(json).toHaveProperty("content"); + expect(Array.isArray(json.content)).toBe(true); + expect(json.content.length).toBeGreaterThan(0); + expect(json.content[0]).toHaveProperty("type", "text"); + // test-mcp-server returns JSON with {result: a+b} + const resultData = JSON.parse(json.content[0].text); + expect(resultData.result).toBe(100); + }); + + it("should handle decimal number arguments", async () => { + const { command, args } = getTestMcpServerCommand(); + const result = await runCli([ + command, + ...args, + "--cli", + "--method", + "tools/call", + "--tool-name", + "get-sum", + "--tool-arg", + "a=19.99", + "b=20.01", + ]); + + expectCliSuccess(result); + const json = expectValidJson(result); + expect(json).toHaveProperty("content"); + expect(Array.isArray(json.content)).toBe(true); + expect(json.content.length).toBeGreaterThan(0); + expect(json.content[0]).toHaveProperty("type", "text"); + // test-mcp-server returns JSON with {result: a+b} + const resultData = JSON.parse(json.content[0].text); + expect(resultData.result).toBeCloseTo(40.0, 2); + }); + + it("should handle boolean arguments - true", async () => { + const { command, args } = getTestMcpServerCommand(); + const result = await runCli([ + command, + ...args, + "--cli", + "--method", + "tools/call", + "--tool-name", + "get-annotated-message", + "--tool-arg", + "messageType=success", + "includeImage=true", + ]); + + expectCliSuccess(result); + const json = expectValidJson(result); + expect(json).toHaveProperty("content"); + expect(Array.isArray(json.content)).toBe(true); + // Should have both text and image content + expect(json.content.length).toBeGreaterThan(1); + const hasImage = json.content.some((item: any) => item.type === "image"); + expect(hasImage).toBe(true); + }); + + it("should handle boolean arguments - false", async () => { + const { command, args } = getTestMcpServerCommand(); + const result = await runCli([ + command, + ...args, + "--cli", + "--method", + "tools/call", + "--tool-name", + "get-annotated-message", + "--tool-arg", + "messageType=error", + "includeImage=false", + ]); + + expectCliSuccess(result); + const json = expectValidJson(result); + expect(json).toHaveProperty("content"); + expect(Array.isArray(json.content)).toBe(true); + // Should only have text content, no image + const hasImage = json.content.some((item: any) => item.type === "image"); + expect(hasImage).toBe(false); + // test-mcp-server returns "This is a {messageType} message" + expect(json.content[0].text.toLowerCase()).toContain("error"); + }); + + it("should handle null arguments", async () => { + const { command, args } = getTestMcpServerCommand(); + const result = await runCli([ + command, + ...args, + "--cli", + "--method", + "tools/call", + "--tool-name", + "echo", + "--tool-arg", + 'message="null"', + ]); + + expectCliSuccess(result); + const json = expectValidJson(result); + expect(json).toHaveProperty("content"); + expect(Array.isArray(json.content)).toBe(true); + expect(json.content[0]).toHaveProperty("type", "text"); + // The string "null" should be passed through + expect(json.content[0].text).toBe("Echo: null"); + }); + + it("should handle multiple arguments with mixed types", async () => { + const { command, args } = getTestMcpServerCommand(); + const result = await runCli([ + command, + ...args, + "--cli", + "--method", + "tools/call", + "--tool-name", + "get-sum", + "--tool-arg", + "a=42.5", + "b=57.5", + ]); + + expectCliSuccess(result); + const json = expectValidJson(result); + expect(json).toHaveProperty("content"); + expect(Array.isArray(json.content)).toBe(true); + expect(json.content.length).toBeGreaterThan(0); + expect(json.content[0]).toHaveProperty("type", "text"); + // test-mcp-server returns JSON with {result: a+b} + const resultData = JSON.parse(json.content[0].text); + expect(resultData.result).toBeCloseTo(100.0, 1); + }); + }); + + describe("JSON Parsing Edge Cases", () => { + it("should fall back to string for invalid JSON", async () => { + const { command, args } = getTestMcpServerCommand(); + const result = await runCli([ + command, + ...args, + "--cli", + "--method", + "tools/call", + "--tool-name", + "echo", + "--tool-arg", + "message={invalid json}", + ]); + + expectCliSuccess(result); + const json = expectValidJson(result); + expect(json).toHaveProperty("content"); + expect(Array.isArray(json.content)).toBe(true); + expect(json.content[0]).toHaveProperty("type", "text"); + // Should treat invalid JSON as a string + expect(json.content[0].text).toBe("Echo: {invalid json}"); + }); + + it("should handle empty string value", async () => { + const { command, args } = getTestMcpServerCommand(); + const result = await runCli([ + command, + ...args, + "--cli", + "--method", + "tools/call", + "--tool-name", + "echo", + "--tool-arg", + 'message=""', + ]); + + expectCliSuccess(result); + const json = expectValidJson(result); + expect(json).toHaveProperty("content"); + expect(Array.isArray(json.content)).toBe(true); + expect(json.content[0]).toHaveProperty("type", "text"); + // Empty string should be preserved + expect(json.content[0].text).toBe("Echo: "); + }); + + it("should handle special characters in strings", async () => { + const { command, args } = getTestMcpServerCommand(); + const result = await runCli([ + command, + ...args, + "--cli", + "--method", + "tools/call", + "--tool-name", + "echo", + "--tool-arg", + 'message="C:\\\\Users\\\\test"', + ]); + + expectCliSuccess(result); + const json = expectValidJson(result); + expect(json).toHaveProperty("content"); + expect(Array.isArray(json.content)).toBe(true); + expect(json.content[0]).toHaveProperty("type", "text"); + // Special characters should be preserved + expect(json.content[0].text).toContain("C:"); + expect(json.content[0].text).toContain("Users"); + expect(json.content[0].text).toContain("test"); + }); + + it("should handle unicode characters", async () => { + const { command, args } = getTestMcpServerCommand(); + const result = await runCli([ + command, + ...args, + "--cli", + "--method", + "tools/call", + "--tool-name", + "echo", + "--tool-arg", + 'message="🚀🎉✨"', + ]); + + expectCliSuccess(result); + const json = expectValidJson(result); + expect(json).toHaveProperty("content"); + expect(Array.isArray(json.content)).toBe(true); + expect(json.content[0]).toHaveProperty("type", "text"); + // Unicode characters should be preserved + expect(json.content[0].text).toContain("🚀"); + expect(json.content[0].text).toContain("🎉"); + expect(json.content[0].text).toContain("✨"); + }); + + it("should handle arguments with equals signs in values", async () => { + const { command, args } = getTestMcpServerCommand(); + const result = await runCli([ + command, + ...args, + "--cli", + "--method", + "tools/call", + "--tool-name", + "echo", + "--tool-arg", + "message=2+2=4", + ]); + + expectCliSuccess(result); + const json = expectValidJson(result); + expect(json).toHaveProperty("content"); + expect(Array.isArray(json.content)).toBe(true); + expect(json.content[0]).toHaveProperty("type", "text"); + // Equals signs in values should be preserved + expect(json.content[0].text).toBe("Echo: 2+2=4"); + }); + + it("should handle base64-like strings", async () => { + const { command, args } = getTestMcpServerCommand(); + const base64String = + "eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJzdWIiOiIxMjM0NTY3ODkwIn0="; + const result = await runCli([ + command, + ...args, + "--cli", + "--method", + "tools/call", + "--tool-name", + "echo", + "--tool-arg", + `message=${base64String}`, + ]); + + expectCliSuccess(result); + const json = expectValidJson(result); + expect(json).toHaveProperty("content"); + expect(Array.isArray(json.content)).toBe(true); + expect(json.content[0]).toHaveProperty("type", "text"); + // Base64-like strings should be preserved + expect(json.content[0].text).toBe(`Echo: ${base64String}`); + }); + }); + + describe("Tool Error Handling", () => { + it("should fail with nonexistent tool", async () => { + const { command, args } = getTestMcpServerCommand(); + const result = await runCli([ + command, + ...args, + "--cli", + "--method", + "tools/call", + "--tool-name", + "nonexistent_tool", + "--tool-arg", + "message=test", + ]); + + // CLI returns exit code 0 but includes isError: true in JSON + expectJsonError(result); + }); + + it("should fail when tool name is missing", async () => { + const { command, args } = getTestMcpServerCommand(); + const result = await runCli([ + command, + ...args, + "--cli", + "--method", + "tools/call", + "--tool-arg", + "message=test", + ]); + + expectCliFailure(result); + }); + + it("should fail with invalid tool argument format", async () => { + const { command, args } = getTestMcpServerCommand(); + const result = await runCli([ + command, + ...args, + "--cli", + "--method", + "tools/call", + "--tool-name", + "echo", + "--tool-arg", + "invalid_format_no_equals", + ]); + + expectCliFailure(result); + }); + }); + + describe("Prompt JSON Arguments", () => { + it("should handle prompt with JSON arguments", async () => { + const { command, args } = getTestMcpServerCommand(); + const result = await runCli([ + command, + ...args, + "--cli", + "--method", + "prompts/get", + "--prompt-name", + "args-prompt", + "--prompt-args", + "city=New York", + "state=NY", + ]); + + expectCliSuccess(result); + const json = expectValidJson(result); + expect(json).toHaveProperty("messages"); + expect(Array.isArray(json.messages)).toBe(true); + expect(json.messages.length).toBeGreaterThan(0); + expect(json.messages[0]).toHaveProperty("content"); + expect(json.messages[0].content).toHaveProperty("type", "text"); + // Validate that the arguments were actually used in the response + // test-mcp-server formats it as "This is a prompt with arguments: city={city}, state={state}" + expect(json.messages[0].content.text).toContain("city=New York"); + expect(json.messages[0].content.text).toContain("state=NY"); + }); + + it("should handle prompt with simple arguments", async () => { + // Note: simple-prompt doesn't accept arguments, but the CLI should still + // accept the command and the server should ignore the arguments + const { command, args } = getTestMcpServerCommand(); + const result = await runCli([ + command, + ...args, + "--cli", + "--method", + "prompts/get", + "--prompt-name", + "simple-prompt", + "--prompt-args", + "name=test", + "count=5", + ]); + + expectCliSuccess(result); + const json = expectValidJson(result); + expect(json).toHaveProperty("messages"); + expect(Array.isArray(json.messages)).toBe(true); + expect(json.messages.length).toBeGreaterThan(0); + expect(json.messages[0]).toHaveProperty("content"); + expect(json.messages[0].content).toHaveProperty("type", "text"); + // test-mcp-server's simple-prompt returns standard message (ignoring args) + expect(json.messages[0].content.text).toBe( + "This is a simple prompt for testing purposes.", + ); + }); + }); + + describe("Backward Compatibility", () => { + it("should support existing string-only usage", async () => { + const { command, args } = getTestMcpServerCommand(); + const result = await runCli([ + command, + ...args, + "--cli", + "--method", + "tools/call", + "--tool-name", + "echo", + "--tool-arg", + "message=hello", + ]); + + expectCliSuccess(result); + const json = expectValidJson(result); + expect(json).toHaveProperty("content"); + expect(Array.isArray(json.content)).toBe(true); + expect(json.content[0]).toHaveProperty("type", "text"); + expect(json.content[0].text).toBe("Echo: hello"); + }); + + it("should support multiple string arguments", async () => { + const { command, args } = getTestMcpServerCommand(); + const result = await runCli([ + command, + ...args, + "--cli", + "--method", + "tools/call", + "--tool-name", + "get-sum", + "--tool-arg", + "a=10", + "b=20", + ]); + + expectCliSuccess(result); + const json = expectValidJson(result); + expect(json).toHaveProperty("content"); + expect(Array.isArray(json.content)).toBe(true); + expect(json.content.length).toBeGreaterThan(0); + expect(json.content[0]).toHaveProperty("type", "text"); + // test-mcp-server returns JSON with {result: a+b} + const resultData = JSON.parse(json.content[0].text); + expect(resultData.result).toBe(30); + }); + }); +}); diff --git a/cli/package.json b/cli/package.json index bf3447339..ce521bee0 100644 --- a/cli/package.json +++ b/cli/package.json @@ -1,9 +1,9 @@ { "name": "@modelcontextprotocol/inspector-cli", - "version": "0.16.2", + "version": "0.19.0", "description": "CLI for the Model Context Protocol inspector", - "license": "MIT", - "author": "Anthropic, PBC (https://anthropic.com)", + "license": "SEE LICENSE IN LICENSE", + "author": "Model Context Protocol a Series of LF Projects, LLC.", "homepage": "https://modelcontextprotocol.io", "bugs": "https://github.com/modelcontextprotocol/inspector/issues", "main": "build/cli.js", @@ -17,12 +17,22 @@ "scripts": { "build": "tsc", "postbuild": "node scripts/make-executable.js", - "test": "node scripts/cli-tests.js" + "test": "vitest run", + "test:watch": "vitest", + "test:cli": "vitest run cli.test.ts", + "test:cli-tools": "vitest run tools.test.ts", + "test:cli-headers": "vitest run headers.test.ts", + "test:cli-metadata": "vitest run metadata.test.ts" + }, + "devDependencies": { + "@types/express": "^5.0.6", + "tsx": "^4.7.0", + "vitest": "^4.0.17" }, - "devDependencies": {}, "dependencies": { - "@modelcontextprotocol/sdk": "^1.17.0", + "@modelcontextprotocol/sdk": "^1.25.2", "commander": "^13.1.0", + "express": "^5.2.1", "spawn-rx": "^5.1.2" } } diff --git a/cli/scripts/cli-tests.js b/cli/scripts/cli-tests.js deleted file mode 100755 index 68ce3885c..000000000 --- a/cli/scripts/cli-tests.js +++ /dev/null @@ -1,764 +0,0 @@ -#!/usr/bin/env node - -// Colors for output -const colors = { - GREEN: "\x1b[32m", - YELLOW: "\x1b[33m", - RED: "\x1b[31m", - BLUE: "\x1b[34m", - ORANGE: "\x1b[33m", - NC: "\x1b[0m", // No Color -}; - -import fs from "fs"; -import path from "path"; -import { spawn } from "child_process"; -import os from "os"; -import { fileURLToPath } from "url"; - -// Get directory paths with ESM compatibility -const __filename = fileURLToPath(import.meta.url); -const __dirname = path.dirname(__filename); - -// Track test results -let PASSED_TESTS = 0; -let FAILED_TESTS = 0; -let SKIPPED_TESTS = 0; -let TOTAL_TESTS = 0; - -console.log( - `${colors.YELLOW}=== MCP Inspector CLI Test Script ===${colors.NC}`, -); -console.log( - `${colors.BLUE}This script tests the MCP Inspector CLI's ability to handle various command line options:${colors.NC}`, -); -console.log(`${colors.BLUE}- Basic CLI mode${colors.NC}`); -console.log(`${colors.BLUE}- Environment variables (-e)${colors.NC}`); -console.log(`${colors.BLUE}- Config file (--config)${colors.NC}`); -console.log(`${colors.BLUE}- Server selection (--server)${colors.NC}`); -console.log(`${colors.BLUE}- Method selection (--method)${colors.NC}`); -console.log( - `${colors.BLUE}- Tool-related options (--tool-name, --tool-arg)${colors.NC}`, -); -console.log(`${colors.BLUE}- Resource-related options (--uri)${colors.NC}`); -console.log( - `${colors.BLUE}- Prompt-related options (--prompt-name, --prompt-args)${colors.NC}`, -); -console.log(`${colors.BLUE}- Logging options (--log-level)${colors.NC}`); -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; -const PROJECT_ROOT = path.join(SCRIPTS_DIR, "../../"); -const BUILD_DIR = path.resolve(SCRIPTS_DIR, "../build"); - -// Define the test server command using npx -const TEST_CMD = "npx"; -const TEST_ARGS = ["@modelcontextprotocol/server-everything"]; - -// Create output directory for test results -const OUTPUT_DIR = path.join(SCRIPTS_DIR, "test-output"); -if (!fs.existsSync(OUTPUT_DIR)) { - fs.mkdirSync(OUTPUT_DIR, { recursive: true }); -} - -// Create a temporary directory for test files -const TEMP_DIR = path.join(os.tmpdir(), "mcp-inspector-tests"); -fs.mkdirSync(TEMP_DIR, { recursive: true }); - -// Track servers for cleanup -let runningServers = []; - -process.on("exit", () => { - try { - fs.rmSync(TEMP_DIR, { recursive: true, force: true }); - } catch (err) { - console.error( - `${colors.RED}Failed to remove temp directory: ${err.message}${colors.NC}`, - ); - } - - 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 -console.log( - `${colors.BLUE}Using existing sample config file: ${PROJECT_ROOT}/sample-config.json${colors.NC}`, -); -try { - const sampleConfig = fs.readFileSync( - path.join(PROJECT_ROOT, "sample-config.json"), - "utf8", - ); - console.log(sampleConfig); -} catch (error) { - console.error( - `${colors.RED}Error reading sample config: ${error.message}${colors.NC}`, - ); -} - -// Create an invalid config file for testing -const invalidConfigPath = path.join(TEMP_DIR, "invalid-config.json"); -fs.writeFileSync(invalidConfigPath, '{\n "mcpServers": {\n "invalid": {'); - -// Function to run a basic test -async function runBasicTest(testName, ...args) { - const outputFile = path.join( - OUTPUT_DIR, - `${testName.replace(/\//g, "_")}.log`, - ); - - console.log(`\n${colors.YELLOW}Testing: ${testName}${colors.NC}`); - TOTAL_TESTS++; - - // Run the command and capture output - console.log( - `${colors.BLUE}Command: node ${BUILD_DIR}/cli.js ${args.join(" ")}${colors.NC}`, - ); - - try { - // Create a write stream for the output file - const outputStream = fs.createWriteStream(outputFile); - - // Spawn the process - return new Promise((resolve) => { - const child = spawn("node", [path.join(BUILD_DIR, "cli.js"), ...args], { - stdio: ["ignore", "pipe", "pipe"], - }); - - 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); - - // Also capture output for display - let output = ""; - child.stdout.on("data", (data) => { - output += data.toString(); - }); - child.stderr.on("data", (data) => { - output += data.toString(); - }); - - child.on("close", (code) => { - clearTimeout(timeout); - outputStream.end(); - - if (code === 0) { - console.log(`${colors.GREEN}✓ Test passed: ${testName}${colors.NC}`); - console.log(`${colors.BLUE}First few lines of output:${colors.NC}`); - const firstFewLines = output - .split("\n") - .slice(0, 5) - .map((line) => ` ${line}`) - .join("\n"); - console.log(firstFewLines); - PASSED_TESTS++; - resolve(true); - } else { - console.log(`${colors.RED}✗ Test failed: ${testName}${colors.NC}`); - console.log(`${colors.RED}Error output:${colors.NC}`); - console.log( - output - .split("\n") - .map((line) => ` ${line}`) - .join("\n"), - ); - FAILED_TESTS++; - - // Stop after any error is encountered - console.log( - `${colors.YELLOW}Stopping tests due to error. Please validate and fix before continuing.${colors.NC}`, - ); - process.exit(1); - } - }); - }); - } catch (error) { - console.error( - `${colors.RED}Error running test: ${error.message}${colors.NC}`, - ); - FAILED_TESTS++; - process.exit(1); - } -} - -// Function to run an error test (expected to fail) -async function runErrorTest(testName, ...args) { - const outputFile = path.join( - OUTPUT_DIR, - `${testName.replace(/\//g, "_")}.log`, - ); - - console.log(`\n${colors.YELLOW}Testing error case: ${testName}${colors.NC}`); - TOTAL_TESTS++; - - // Run the command and capture output - console.log( - `${colors.BLUE}Command: node ${BUILD_DIR}/cli.js ${args.join(" ")}${colors.NC}`, - ); - - try { - // Create a write stream for the output file - const outputStream = fs.createWriteStream(outputFile); - - // Spawn the process - return new Promise((resolve) => { - const child = spawn("node", [path.join(BUILD_DIR, "cli.js"), ...args], { - stdio: ["ignore", "pipe", "pipe"], - }); - - 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); - - // Also capture output for display - let output = ""; - child.stdout.on("data", (data) => { - output += data.toString(); - }); - child.stderr.on("data", (data) => { - output += data.toString(); - }); - - child.on("close", (code) => { - clearTimeout(timeout); - outputStream.end(); - - // For error tests, we expect a non-zero exit code - if (code !== 0) { - console.log( - `${colors.GREEN}✓ Error test passed: ${testName}${colors.NC}`, - ); - console.log(`${colors.BLUE}Error output (expected):${colors.NC}`); - const firstFewLines = output - .split("\n") - .slice(0, 5) - .map((line) => ` ${line}`) - .join("\n"); - console.log(firstFewLines); - PASSED_TESTS++; - resolve(true); - } else { - console.log( - `${colors.RED}✗ Error test failed: ${testName} (expected error but got success)${colors.NC}`, - ); - console.log(`${colors.RED}Output:${colors.NC}`); - console.log( - output - .split("\n") - .map((line) => ` ${line}`) - .join("\n"), - ); - FAILED_TESTS++; - - // Stop after any error is encountered - console.log( - `${colors.YELLOW}Stopping tests due to error. Please validate and fix before continuing.${colors.NC}`, - ); - process.exit(1); - } - }); - }); - } catch (error) { - console.error( - `${colors.RED}Error running test: ${error.message}${colors.NC}`, - ); - FAILED_TESTS++; - process.exit(1); - } -} - -// Run all tests -async function runTests() { - console.log( - `\n${colors.YELLOW}=== Running Basic CLI Mode Tests ===${colors.NC}`, - ); - - // Test 1: Basic CLI mode with method - await runBasicTest( - "basic_cli_mode", - TEST_CMD, - ...TEST_ARGS, - "--cli", - "--method", - "tools/list", - ); - - // Test 2: CLI mode with non-existent method (should fail) - await runErrorTest( - "nonexistent_method", - TEST_CMD, - ...TEST_ARGS, - "--cli", - "--method", - "nonexistent/method", - ); - - // Test 3: CLI mode without method (should fail) - await runErrorTest("missing_method", TEST_CMD, ...TEST_ARGS, "--cli"); - - console.log( - `\n${colors.YELLOW}=== Running Environment Variable Tests ===${colors.NC}`, - ); - - // Test 4: CLI mode with environment variables - await runBasicTest( - "env_variables", - TEST_CMD, - ...TEST_ARGS, - "-e", - "KEY1=value1", - "-e", - "KEY2=value2", - "--cli", - "--method", - "tools/list", - ); - - // Test 5: CLI mode with invalid environment variable format (should fail) - await runErrorTest( - "invalid_env_format", - TEST_CMD, - ...TEST_ARGS, - "-e", - "INVALID_FORMAT", - "--cli", - "--method", - "tools/list", - ); - - // Test 5b: CLI mode with environment variable containing equals sign in value - await runBasicTest( - "env_variable_with_equals", - TEST_CMD, - ...TEST_ARGS, - "-e", - "API_KEY=abc123=xyz789==", - "--cli", - "--method", - "tools/list", - ); - - // Test 5c: CLI mode with environment variable containing base64-encoded value - await runBasicTest( - "env_variable_with_base64", - TEST_CMD, - ...TEST_ARGS, - "-e", - "JWT_TOKEN=eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJzdWIiOiIxMjM0NTY3ODkwIn0=", - "--cli", - "--method", - "tools/list", - ); - - console.log( - `\n${colors.YELLOW}=== Running Config File Tests ===${colors.NC}`, - ); - - // Test 6: Using config file with CLI mode - await runBasicTest( - "config_file", - "--config", - path.join(PROJECT_ROOT, "sample-config.json"), - "--server", - "everything", - "--cli", - "--method", - "tools/list", - ); - - // Test 7: Using config file without server name (should fail) - await runErrorTest( - "config_without_server", - "--config", - path.join(PROJECT_ROOT, "sample-config.json"), - "--cli", - "--method", - "tools/list", - ); - - // Test 8: Using server name without config file (should fail) - await runErrorTest( - "server_without_config", - "--server", - "everything", - "--cli", - "--method", - "tools/list", - ); - - // Test 9: Using non-existent config file (should fail) - await runErrorTest( - "nonexistent_config", - "--config", - "./nonexistent-config.json", - "--server", - "everything", - "--cli", - "--method", - "tools/list", - ); - - // Test 10: Using invalid config file format (should fail) - await runErrorTest( - "invalid_config", - "--config", - invalidConfigPath, - "--server", - "everything", - "--cli", - "--method", - "tools/list", - ); - - // Test 11: Using config file with non-existent server (should fail) - await runErrorTest( - "nonexistent_server", - "--config", - path.join(PROJECT_ROOT, "sample-config.json"), - "--server", - "nonexistent", - "--cli", - "--method", - "tools/list", - ); - - console.log( - `\n${colors.YELLOW}=== Running Tool-Related Tests ===${colors.NC}`, - ); - - // Test 12: CLI mode with tool call - await runBasicTest( - "tool_call", - TEST_CMD, - ...TEST_ARGS, - "--cli", - "--method", - "tools/call", - "--tool-name", - "echo", - "--tool-arg", - "message=Hello", - ); - - // Test 13: CLI mode with tool call but missing tool name (should fail) - await runErrorTest( - "missing_tool_name", - TEST_CMD, - ...TEST_ARGS, - "--cli", - "--method", - "tools/call", - "--tool-arg", - "message=Hello", - ); - - // Test 14: CLI mode with tool call but invalid tool args format (should fail) - await runErrorTest( - "invalid_tool_args", - TEST_CMD, - ...TEST_ARGS, - "--cli", - "--method", - "tools/call", - "--tool-name", - "echo", - "--tool-arg", - "invalid_format", - ); - - // Test 15: CLI mode with multiple tool args - await runBasicTest( - "multiple_tool_args", - TEST_CMD, - ...TEST_ARGS, - "--cli", - "--method", - "tools/call", - "--tool-name", - "add", - "--tool-arg", - "a=1", - "b=2", - ); - - console.log( - `\n${colors.YELLOW}=== Running Resource-Related Tests ===${colors.NC}`, - ); - - // Test 16: CLI mode with resource read - await runBasicTest( - "resource_read", - TEST_CMD, - ...TEST_ARGS, - "--cli", - "--method", - "resources/read", - "--uri", - "test://static/resource/1", - ); - - // Test 17: CLI mode with resource read but missing URI (should fail) - await runErrorTest( - "missing_uri", - TEST_CMD, - ...TEST_ARGS, - "--cli", - "--method", - "resources/read", - ); - - console.log( - `\n${colors.YELLOW}=== Running Prompt-Related Tests ===${colors.NC}`, - ); - - // Test 18: CLI mode with prompt get - await runBasicTest( - "prompt_get", - TEST_CMD, - ...TEST_ARGS, - "--cli", - "--method", - "prompts/get", - "--prompt-name", - "simple_prompt", - ); - - // Test 19: CLI mode with prompt get and args - await runBasicTest( - "prompt_get_with_args", - TEST_CMD, - ...TEST_ARGS, - "--cli", - "--method", - "prompts/get", - "--prompt-name", - "complex_prompt", - "--prompt-args", - "temperature=0.7", - "style=concise", - ); - - // Test 20: CLI mode with prompt get but missing prompt name (should fail) - await runErrorTest( - "missing_prompt_name", - TEST_CMD, - ...TEST_ARGS, - "--cli", - "--method", - "prompts/get", - ); - - console.log(`\n${colors.YELLOW}=== Running Logging Tests ===${colors.NC}`); - - // Test 21: CLI mode with log level - await runBasicTest( - "log_level", - TEST_CMD, - ...TEST_ARGS, - "--cli", - "--method", - "logging/setLevel", - "--log-level", - "debug", - ); - - // Test 22: CLI mode with invalid log level (should fail) - await runErrorTest( - "invalid_log_level", - TEST_CMD, - ...TEST_ARGS, - "--cli", - "--method", - "logging/setLevel", - "--log-level", - "invalid", - ); - - console.log( - `\n${colors.YELLOW}=== Running Combined Option Tests ===${colors.NC}`, - ); - - // Note about the combined options issue - console.log( - `${colors.BLUE}Testing combined options with environment variables and config file.${colors.NC}`, - ); - - // Test 23: CLI mode with config file, environment variables, and tool call - await runBasicTest( - "combined_options", - "--config", - path.join(PROJECT_ROOT, "sample-config.json"), - "--server", - "everything", - "-e", - "CLI_ENV_VAR=cli_value", - "--cli", - "--method", - "tools/list", - ); - - // Test 24: CLI mode with all possible options (that make sense together) - await runBasicTest( - "all_options", - "--config", - path.join(PROJECT_ROOT, "sample-config.json"), - "--server", - "everything", - "-e", - "CLI_ENV_VAR=cli_value", - "--cli", - "--method", - "tools/call", - "--tool-name", - "echo", - "--tool-arg", - "message=Hello", - "--log-level", - "debug", - ); - - 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/mcp", - "--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", - ); - - // Test 29: HTTP transport without URL (should fail) - await runErrorTest( - "http_transport_without_url", - "--transport", - "http", - "--cli", - "--method", - "tools/list", - ); - - // Test 30: 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}`); - console.log(`${colors.RED}Failed: ${FAILED_TESTS}${colors.NC}`); - console.log(`${colors.ORANGE}Skipped: ${SKIPPED_TESTS}${colors.NC}`); - console.log(`Total: ${TOTAL_TESTS}`); - console.log( - `${colors.BLUE}Detailed logs saved to: ${OUTPUT_DIR}${colors.NC}`, - ); - - console.log(`\n${colors.GREEN}All tests completed!${colors.NC}`); -} - -// Run all tests -runTests().catch((error) => { - console.error( - `${colors.RED}Tests failed with error: ${error.message}${colors.NC}`, - ); - process.exit(1); -}); diff --git a/cli/src/cli.ts b/cli/src/cli.ts index 5ff1f1110..f4187e02d 100644 --- a/cli/src/cli.ts +++ b/cli/src/cli.ts @@ -14,6 +14,9 @@ type Args = { args: string[]; envArgs: Record; cli: boolean; + transport?: "stdio" | "sse" | "streamable-http"; + serverUrl?: string; + headers?: Record; }; type CliOptions = { @@ -21,13 +24,23 @@ type CliOptions = { config?: string; server?: string; cli?: boolean; + transport?: string; + serverUrl?: string; + header?: Record; }; -type ServerConfig = { - command: string; - args?: string[]; - env?: Record; -}; +type ServerConfig = + | { + type: "stdio"; + command: string; + args?: string[]; + env?: Record; + } + | { + type: "sse" | "streamable-http"; + url: string; + note?: string; + }; function handleError(error: unknown): never { let message: string; @@ -74,6 +87,16 @@ async function runWebClient(args: Args): Promise { 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); @@ -83,6 +106,10 @@ async function runWebClient(args: Args): Promise { await spawnPromise("node", [inspectorClientPath, ...startArgs], { signal: abort.signal, echoOutput: true, + // pipe the stdout through here, prevents issues with buffering and + // dropping the end of console.out after 8192 chars due to node + // closing the stdout pipe before the output has finished flushing + stdio: "inherit", }); } catch (e) { if (!cancelled || process.env.DEBUG) throw e; @@ -103,10 +130,35 @@ async function runCli(args: Args): Promise { }); try { - await spawnPromise("node", [cliPath, args.command, ...args.args], { + // Build CLI arguments + const cliArgs = [cliPath]; + + // Add target URL/command first + cliArgs.push(args.command, ...args.args); + + // 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 headers if specified + if (args.headers) { + for (const [key, value] of Object.entries(args.headers)) { + cliArgs.push("--header", `${key}: ${value}`); + } + } + + await spawnPromise("node", cliArgs, { env: { ...process.env, ...args.envArgs }, signal: abort.signal, echoOutput: true, + // pipe the stdout through here, prevents issues with buffering and + // dropping the end of console.out after 8192 chars due to node + // closing the stdout pipe before the output has finished flushing + stdio: "inherit", }); } catch (e) { if (!cancelled || process.env.DEBUG) { @@ -166,6 +218,30 @@ function parseKeyValuePair( return { ...previous, [key as string]: val }; } +function parseHeaderPair( + value: string, + previous: Record = {}, +): Record { + const colonIndex = value.indexOf(":"); + + if (colonIndex === -1) { + throw new Error( + `Invalid header format: ${value}. Use "HeaderName: Value" format.`, + ); + } + + const key = value.slice(0, colonIndex).trim(); + const val = value.slice(colonIndex + 1).trim(); + + if (key === "" || val === "") { + throw new Error( + `Invalid header format: ${value}. Use "HeaderName: Value" format.`, + ); + } + + return { ...previous, [key]: val }; +} + function parseArgs(): Args { const program = new Command(); @@ -190,7 +266,15 @@ function parseArgs(): Args { ) .option("--config ", "config file path") .option("--server ", "server name from config file") - .option("--cli", "enable CLI mode"); + .option("--cli", "enable CLI mode") + .option("--transport ", "transport type (stdio, sse, http)") + .option("--server-url ", "server URL for SSE/HTTP transport") + .option( + "--header ", + 'HTTP headers as "HeaderName: Value" pairs (for HTTP/SSE transports)', + parseHeaderPair, + {}, + ); // Parse only the arguments before -- program.parse(preArgs); @@ -201,14 +285,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 @@ -217,23 +320,56 @@ 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", + headers: options.header, + }; + } 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, + headers: options.header, + }; + } 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", + headers: options.header, + }; + } } // 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, + headers: options.header, }; } diff --git a/cli/src/client/prompts.ts b/cli/src/client/prompts.ts index 0b237496d..e7a1cf2f2 100644 --- a/cli/src/client/prompts.ts +++ b/cli/src/client/prompts.ts @@ -1,10 +1,25 @@ import { Client } from "@modelcontextprotocol/sdk/client/index.js"; import { McpResponse } from "./types.js"; +// JSON value type matching the client utils +type JsonValue = + | string + | number + | boolean + | null + | undefined + | JsonValue[] + | { [key: string]: JsonValue }; + // List available prompts -export async function listPrompts(client: Client): Promise { +export async function listPrompts( + client: Client, + metadata?: Record, +): Promise { try { - const response = await client.listPrompts(); + const params = + metadata && Object.keys(metadata).length > 0 ? { _meta: metadata } : {}; + const response = await client.listPrompts(params); return response; } catch (error) { throw new Error( @@ -17,13 +32,34 @@ export async function listPrompts(client: Client): Promise { export async function getPrompt( client: Client, name: string, - args?: Record, + args?: Record, + metadata?: Record, ): Promise { try { - const response = await client.getPrompt({ + // Convert all arguments to strings for prompt arguments + const stringArgs: Record = {}; + if (args) { + for (const [key, value] of Object.entries(args)) { + if (typeof value === "string") { + stringArgs[key] = value; + } else if (value === null || value === undefined) { + stringArgs[key] = String(value); + } else { + stringArgs[key] = JSON.stringify(value); + } + } + } + + const params: any = { name, - arguments: args || {}, - }); + arguments: stringArgs, + }; + + if (metadata && Object.keys(metadata).length > 0) { + params._meta = metadata; + } + + const response = await client.getPrompt(params); return response; } catch (error) { diff --git a/cli/src/client/resources.ts b/cli/src/client/resources.ts index bf33d64d2..3e44820ca 100644 --- a/cli/src/client/resources.ts +++ b/cli/src/client/resources.ts @@ -2,9 +2,14 @@ import { Client } from "@modelcontextprotocol/sdk/client/index.js"; import { McpResponse } from "./types.js"; // List available resources -export async function listResources(client: Client): Promise { +export async function listResources( + client: Client, + metadata?: Record, +): Promise { try { - const response = await client.listResources(); + const params = + metadata && Object.keys(metadata).length > 0 ? { _meta: metadata } : {}; + const response = await client.listResources(params); return response; } catch (error) { throw new Error( @@ -17,9 +22,14 @@ export async function listResources(client: Client): Promise { export async function readResource( client: Client, uri: string, + metadata?: Record, ): Promise { try { - const response = await client.readResource({ uri }); + const params: any = { uri }; + if (metadata && Object.keys(metadata).length > 0) { + params._meta = metadata; + } + const response = await client.readResource(params); return response; } catch (error) { throw new Error( @@ -31,9 +41,12 @@ export async function readResource( // List resource templates export async function listResourceTemplates( client: Client, + metadata?: Record, ): Promise { try { - const response = await client.listResourceTemplates(); + const params = + metadata && Object.keys(metadata).length > 0 ? { _meta: metadata } : {}; + const response = await client.listResourceTemplates(params); return response; } catch (error) { throw new Error( diff --git a/cli/src/client/tools.ts b/cli/src/client/tools.ts index acdb48710..516814115 100644 --- a/cli/src/client/tools.ts +++ b/cli/src/client/tools.ts @@ -2,6 +2,16 @@ import { Client } from "@modelcontextprotocol/sdk/client/index.js"; import { Tool } from "@modelcontextprotocol/sdk/types.js"; import { McpResponse } from "./types.js"; +// JSON value type matching the client utils +type JsonValue = + | string + | number + | boolean + | null + | undefined + | JsonValue[] + | { [key: string]: JsonValue }; + type JsonSchemaType = { type: "string" | "number" | "integer" | "boolean" | "array" | "object"; description?: string; @@ -9,9 +19,14 @@ type JsonSchemaType = { items?: JsonSchemaType; }; -export async function listTools(client: Client): Promise { +export async function listTools( + client: Client, + metadata?: Record, +): Promise { try { - const response = await client.listTools(); + const params = + metadata && Object.keys(metadata).length > 0 ? { _meta: metadata } : {}; + const response = await client.listTools(params); return response; } catch (error) { throw new Error( @@ -20,7 +35,10 @@ export async function listTools(client: Client): Promise { } } -function convertParameterValue(value: string, schema: JsonSchemaType): unknown { +function convertParameterValue( + value: string, + schema: JsonSchemaType, +): JsonValue { if (!value) { return value; } @@ -35,7 +53,7 @@ function convertParameterValue(value: string, schema: JsonSchemaType): unknown { if (schema.type === "object" || schema.type === "array") { try { - return JSON.parse(value); + return JSON.parse(value) as JsonValue; } catch (error) { return value; } @@ -47,8 +65,8 @@ function convertParameterValue(value: string, schema: JsonSchemaType): unknown { function convertParameters( tool: Tool, params: Record, -): Record { - const result: Record = {}; +): Record { + const result: Record = {}; const properties = tool.inputSchema.properties || {}; for (const [key, value] of Object.entries(params)) { @@ -68,23 +86,50 @@ function convertParameters( export async function callTool( client: Client, name: string, - args: Record, + args: Record, + generalMetadata?: Record, + toolSpecificMetadata?: Record, ): Promise { try { - const toolsResponse = await listTools(client); + const toolsResponse = await listTools(client, generalMetadata); const tools = toolsResponse.tools as Tool[]; const tool = tools.find((t) => t.name === name); - let convertedArgs: Record = args; + let convertedArgs: Record = args; if (tool) { - // Convert parameters based on the tool's schema - convertedArgs = convertParameters(tool, args); + // Convert parameters based on the tool's schema, but only for string values + // since we now accept pre-parsed values from the CLI + const stringArgs: Record = {}; + for (const [key, value] of Object.entries(args)) { + if (typeof value === "string") { + stringArgs[key] = value; + } + } + + if (Object.keys(stringArgs).length > 0) { + const convertedStringArgs = convertParameters(tool, stringArgs); + convertedArgs = { ...args, ...convertedStringArgs }; + } + } + + // Merge general metadata with tool-specific metadata + // Tool-specific metadata takes precedence over general metadata + let mergedMetadata: Record | undefined; + if (generalMetadata || toolSpecificMetadata) { + mergedMetadata = { + ...(generalMetadata || {}), + ...(toolSpecificMetadata || {}), + }; } const response = await client.callTool({ name: name, arguments: convertedArgs, + _meta: + mergedMetadata && Object.keys(mergedMetadata).length > 0 + ? mergedMetadata + : undefined, }); return response; } catch (error) { diff --git a/cli/src/index.ts b/cli/src/index.ts index 2b0c4f53d..45a71a052 100644 --- a/cli/src/index.ts +++ b/cli/src/index.ts @@ -1,5 +1,6 @@ #!/usr/bin/env node +import * as fs from "fs"; import { Client } from "@modelcontextprotocol/sdk/client/index.js"; import { Command } from "commander"; import { @@ -19,22 +20,37 @@ import { } from "./client/index.js"; import { handleError } from "./error-handler.js"; import { createTransport, TransportOptions } from "./transport.js"; +import { awaitableLog } from "./utils/awaitable-log.js"; + +// JSON value type for CLI arguments +type JsonValue = + | string + | number + | boolean + | null + | undefined + | JsonValue[] + | { [key: string]: JsonValue }; type Args = { target: string[]; method?: string; promptName?: string; - promptArgs?: Record; + promptArgs?: Record; uri?: string; logLevel?: LogLevel; toolName?: string; - toolArg?: Record; + toolArg?: Record; + toolMeta?: Record; transport?: "sse" | "stdio" | "http"; + headers?: Record; + metadata?: Record; }; function createTransportOptions( target: string[], transport?: "sse" | "stdio" | "http", + headers?: Record, ): TransportOptions { if (target.length === 0) { throw new Error( @@ -81,16 +97,32 @@ function createTransportOptions( command: isUrl ? undefined : command, args: isUrl ? undefined : commandArgs, url: isUrl ? command : undefined, + headers, }; } async function callMethod(args: Args): Promise { - const transportOptions = createTransportOptions(args.target, args.transport); - const transport = createTransport(transportOptions); - const client = new Client({ - name: "inspector-cli", - version: "0.5.1", + // Read package.json to get name and version for client identity + const pathA = "../package.json"; // We're in package @modelcontextprotocol/inspector-cli + const pathB = "../../package.json"; // We're in package @modelcontextprotocol/inspector + let packageJson: { name: string; version: string }; + let packageJsonData = await import(fs.existsSync(pathA) ? pathA : pathB, { + with: { type: "json" }, }); + packageJson = packageJsonData.default; + + const transportOptions = createTransportOptions( + args.target, + args.transport, + args.headers, + ); + const transport = createTransport(transportOptions); + + const [, name = packageJson.name] = packageJson.name.split("/"); + const version = packageJson.version; + const clientIdentity = { name, version }; + + const client = new Client(clientIdentity); try { await connect(client, transport); @@ -99,7 +131,7 @@ async function callMethod(args: Args): Promise { // Tools methods if (args.method === "tools/list") { - result = await listTools(client); + result = await listTools(client, args.metadata); } else if (args.method === "tools/call") { if (!args.toolName) { throw new Error( @@ -107,11 +139,17 @@ async function callMethod(args: Args): Promise { ); } - result = await callTool(client, args.toolName, args.toolArg || {}); + result = await callTool( + client, + args.toolName, + args.toolArg || {}, + args.metadata, + args.toolMeta, + ); } // Resources methods else if (args.method === "resources/list") { - result = await listResources(client); + result = await listResources(client, args.metadata); } else if (args.method === "resources/read") { if (!args.uri) { throw new Error( @@ -119,13 +157,13 @@ async function callMethod(args: Args): Promise { ); } - result = await readResource(client, args.uri); + result = await readResource(client, args.uri, args.metadata); } else if (args.method === "resources/templates/list") { - result = await listResourceTemplates(client); + result = await listResourceTemplates(client, args.metadata); } // Prompts methods else if (args.method === "prompts/list") { - result = await listPrompts(client); + result = await listPrompts(client, args.metadata); } else if (args.method === "prompts/get") { if (!args.promptName) { throw new Error( @@ -133,7 +171,12 @@ async function callMethod(args: Args): Promise { ); } - result = await getPrompt(client, args.promptName, args.promptArgs || {}); + result = await getPrompt( + client, + args.promptName, + args.promptArgs || {}, + args.metadata, + ); } // Logging methods else if (args.method === "logging/setLevel") { @@ -150,7 +193,7 @@ async function callMethod(args: Args): Promise { ); } - console.log(JSON.stringify(result, null, 2)); + await awaitableLog(JSON.stringify(result, null, 2)); } finally { try { await disconnect(transport); @@ -162,8 +205,8 @@ async function callMethod(args: Args): Promise { function parseKeyValuePair( value: string, - previous: Record = {}, -): Record { + previous: Record = {}, +): Record { const parts = value.split("="); const key = parts[0]; const val = parts.slice(1).join("="); @@ -174,7 +217,40 @@ function parseKeyValuePair( ); } - return { ...previous, [key as string]: val }; + // Try to parse as JSON first + let parsedValue: JsonValue; + try { + parsedValue = JSON.parse(val) as JsonValue; + } catch { + // If JSON parsing fails, keep as string + parsedValue = val; + } + + return { ...previous, [key as string]: parsedValue }; +} + +function parseHeaderPair( + value: string, + previous: Record = {}, +): Record { + const colonIndex = value.indexOf(":"); + + if (colonIndex === -1) { + throw new Error( + `Invalid header format: ${value}. Use "HeaderName: Value" format.`, + ); + } + + const key = value.slice(0, colonIndex).trim(); + const val = value.slice(colonIndex + 1).trim(); + + if (key === "" || val === "") { + throw new Error( + `Invalid header format: ${value}. Use "HeaderName: Value" format.`, + ); + } + + return { ...previous, [key]: val }; } function parseArgs(): Args { @@ -256,12 +332,41 @@ function parseArgs(): Args { } return value as "sse" | "http" | "stdio"; }, + ) + // + // HTTP headers + // + .option( + "--header ", + 'HTTP headers as "HeaderName: Value" pairs (for HTTP/SSE transports)', + parseHeaderPair, + {}, + ) + // + // Metadata options + // + .option( + "--metadata ", + "General metadata as key=value pairs (applied to all methods)", + parseKeyValuePair, + {}, + ) + .option( + "--tool-metadata ", + "Tool-specific metadata as key=value pairs (for tools/call method only)", + parseKeyValuePair, + {}, ); // Parse only the arguments before -- program.parse(preArgs); - const options = program.opts() as Omit; + const options = program.opts() as Omit & { + header?: Record; + metadata?: Record; + toolMetadata?: Record; + }; + let remainingArgs = program.args; // Add back any arguments that came after -- @@ -276,6 +381,23 @@ function parseArgs(): Args { return { target: finalArgs, ...options, + headers: options.header, // commander.js uses 'header' field, map to 'headers' + metadata: options.metadata + ? Object.fromEntries( + Object.entries(options.metadata).map(([key, value]) => [ + key, + String(value), + ]), + ) + : undefined, + toolMeta: options.toolMetadata + ? Object.fromEntries( + Object.entries(options.toolMetadata).map(([key, value]) => [ + key, + String(value), + ]), + ) + : undefined, }; } @@ -287,6 +409,7 @@ async function main(): Promise { try { const args = parseArgs(); await callMethod(args); + // Explicitly exit to ensure process terminates in CI process.exit(0); } catch (error) { diff --git a/cli/src/transport.ts b/cli/src/transport.ts index b6276356d..84af393b9 100644 --- a/cli/src/transport.ts +++ b/cli/src/transport.ts @@ -12,6 +12,7 @@ export type TransportOptions = { command?: string; args?: string[]; url?: string; + headers?: Record; }; function createStdioTransport(options: TransportOptions): Transport { @@ -32,8 +33,8 @@ function createStdioTransport(options: TransportOptions): Transport { const defaultEnv = getDefaultEnvironment(); const env: Record = { - ...processEnv, ...defaultEnv, + ...processEnv, }; const { cmd: actualCommand, args: actualArgs } = findActualExecutable( @@ -64,11 +65,25 @@ export function createTransport(options: TransportOptions): Transport { const url = new URL(options.url); if (transportType === "sse") { - return new SSEClientTransport(url); + const transportOptions = options.headers + ? { + requestInit: { + headers: options.headers, + }, + } + : undefined; + return new SSEClientTransport(url, transportOptions); } if (transportType === "http") { - return new StreamableHTTPClientTransport(url); + const transportOptions = options.headers + ? { + requestInit: { + headers: options.headers, + }, + } + : undefined; + return new StreamableHTTPClientTransport(url, transportOptions); } throw new Error(`Unsupported transport type: ${transportType}`); diff --git a/cli/src/utils/awaitable-log.ts b/cli/src/utils/awaitable-log.ts new file mode 100644 index 000000000..144f01123 --- /dev/null +++ b/cli/src/utils/awaitable-log.ts @@ -0,0 +1,7 @@ +export function awaitableLog(logValue: string): Promise { + return new Promise((resolve) => { + process.stdout.write(logValue, () => { + resolve(); + }); + }); +} diff --git a/cli/vitest.config.ts b/cli/vitest.config.ts new file mode 100644 index 000000000..9984fb11a --- /dev/null +++ b/cli/vitest.config.ts @@ -0,0 +1,10 @@ +import { defineConfig } from "vitest/config"; + +export default defineConfig({ + test: { + globals: true, + environment: "node", + include: ["**/__tests__/**/*.test.ts"], + testTimeout: 15000, // 15 seconds - CLI tests spawn subprocesses that need time + }, +}); diff --git a/client/bin/start.js b/client/bin/start.js index e0496cde0..f67301de4 100755 --- a/client/bin/start.js +++ b/client/bin/start.js @@ -28,8 +28,15 @@ function getClientUrl(port, authDisabled, sessionToken, serverPort) { } async function startDevServer(serverOptions) { - const { SERVER_PORT, CLIENT_PORT, sessionToken, envVars, abort } = - serverOptions; + const { + SERVER_PORT, + CLIENT_PORT, + sessionToken, + envVars, + abort, + transport, + serverUrl, + } = serverOptions; const serverCommand = "npx"; const serverArgs = ["tsx", "watch", "--clear-screen=false", "src/index.ts"]; const isWindows = process.platform === "win32"; @@ -42,6 +49,8 @@ async function startDevServer(serverOptions) { CLIENT_PORT, MCP_PROXY_AUTH_TOKEN: sessionToken, MCP_ENV_VARS: JSON.stringify(envVars), + ...(transport ? { MCP_TRANSPORT: transport } : {}), + ...(serverUrl ? { MCP_SERVER_URL: serverUrl } : {}), }, signal: abort.signal, echoOutput: true, @@ -78,6 +87,8 @@ async function startProdServer(serverOptions) { abort, command, mcpServerArgs, + transport, + serverUrl, } = serverOptions; const inspectorServerPath = resolve( __dirname, @@ -95,6 +106,8 @@ async function startProdServer(serverOptions) { ...(mcpServerArgs && mcpServerArgs.length > 0 ? [`--args=${mcpServerArgs.join(" ")}`] : []), + ...(transport ? [`--transport=${transport}`] : []), + ...(serverUrl ? [`--server-url=${serverUrl}`] : []), ], { env: { @@ -208,6 +221,8 @@ async function main() { let command = null; let parsingFlags = true; let isDev = false; + let transport = null; + let serverUrl = null; for (let i = 0; i < args.length; i++) { const arg = args[i]; @@ -222,6 +237,16 @@ async function main() { continue; } + if (parsingFlags && arg === "--transport" && i + 1 < args.length) { + transport = args[++i]; + continue; + } + + if (parsingFlags && arg === "--server-url" && i + 1 < args.length) { + serverUrl = args[++i]; + continue; + } + if (parsingFlags && arg === "-e" && i + 1 < args.length) { const envVar = args[++i]; const equalsIndex = envVar.indexOf("="); @@ -273,6 +298,8 @@ async function main() { abort, command, mcpServerArgs, + transport, + serverUrl, }; const result = isDev diff --git a/client/e2e/cli-arguments.spec.ts b/client/e2e/cli-arguments.spec.ts new file mode 100644 index 000000000..a4dcdcce2 --- /dev/null +++ b/client/e2e/cli-arguments.spec.ts @@ -0,0 +1,65 @@ +import { test, expect } from "@playwright/test"; + +// These tests verify that CLI arguments correctly set URL parameters +// The CLI should parse config files and pass transport/serverUrl as URL params +test.describe("CLI Arguments @cli", () => { + test("should pass transport parameter from command line", async ({ + page, + }) => { + // Simulate: npx . --transport sse --server-url http://localhost:3000/sse + await page.goto( + "http://localhost:6274/?transport=sse&serverUrl=http://localhost:3000/sse", + ); + + // Wait for the Transport Type dropdown to be visible + const selectTrigger = page.getByLabel("Transport Type"); + await expect(selectTrigger).toBeVisible(); + + // Verify transport dropdown shows SSE + await expect(selectTrigger).toContainText("SSE"); + + // Verify URL field is visible and populated + const urlInput = page.locator("#sse-url-input"); + await expect(urlInput).toBeVisible(); + await expect(urlInput).toHaveValue("http://localhost:3000/sse"); + }); + + test("should pass transport parameter for streamable-http", async ({ + page, + }) => { + // Simulate config with streamable-http transport + await page.goto( + "http://localhost:6274/?transport=streamable-http&serverUrl=http://localhost:3000/mcp", + ); + + // Wait for the Transport Type dropdown to be visible + const selectTrigger = page.getByLabel("Transport Type"); + await expect(selectTrigger).toBeVisible(); + + // Verify transport dropdown shows Streamable HTTP + await expect(selectTrigger).toContainText("Streamable HTTP"); + + // Verify URL field is visible and populated + const urlInput = page.locator("#sse-url-input"); + await expect(urlInput).toBeVisible(); + await expect(urlInput).toHaveValue("http://localhost:3000/mcp"); + }); + + test("should not pass transport parameter for stdio config", async ({ + page, + }) => { + // Simulate stdio config (no transport param needed) + await page.goto("http://localhost:6274/"); + + // Wait for the Transport Type dropdown to be visible + const selectTrigger = page.getByLabel("Transport Type"); + await expect(selectTrigger).toBeVisible(); + + // Verify transport dropdown defaults to STDIO + await expect(selectTrigger).toContainText("STDIO"); + + // Verify command/args fields are visible + await expect(page.locator("#command-input")).toBeVisible(); + await expect(page.locator("#arguments-input")).toBeVisible(); + }); +}); diff --git a/client/package.json b/client/package.json index cbb7d8b67..1feec2122 100644 --- a/client/package.json +++ b/client/package.json @@ -1,9 +1,9 @@ { "name": "@modelcontextprotocol/inspector-client", - "version": "0.16.2", + "version": "0.19.0", "description": "Client-side application for the Model Context Protocol inspector", - "license": "MIT", - "author": "Anthropic, PBC (https://anthropic.com)", + "license": "SEE LICENSE IN LICENSE", + "author": "Model Context Protocol a Series of LF Projects, LLC.", "homepage": "https://modelcontextprotocol.io", "bugs": "https://github.com/modelcontextprotocol/inspector/issues", "type": "module", @@ -25,7 +25,7 @@ "cleanup:e2e": "node e2e/global-teardown.js" }, "dependencies": { - "@modelcontextprotocol/sdk": "^1.17.0", + "@modelcontextprotocol/sdk": "^1.25.2", "@radix-ui/react-checkbox": "^1.1.4", "@radix-ui/react-dialog": "^1.1.3", "@radix-ui/react-icons": "^1.3.0", @@ -33,6 +33,7 @@ "@radix-ui/react-popover": "^1.1.3", "@radix-ui/react-select": "^2.1.2", "@radix-ui/react-slot": "^1.1.0", + "@radix-ui/react-switch": "^1.2.6", "@radix-ui/react-tabs": "^1.1.1", "@radix-ui/react-toast": "^1.2.6", "@radix-ui/react-tooltip": "^1.1.8", @@ -48,7 +49,6 @@ "react-simple-code-editor": "^0.14.1", "serve-handler": "^6.1.6", "tailwind-merge": "^2.5.3", - "tailwindcss-animate": "^1.0.7", "zod": "^3.25.76" }, "devDependencies": { @@ -61,7 +61,7 @@ "@types/react": "^18.3.23", "@types/react-dom": "^18.3.0", "@types/serve-handler": "^6.1.4", - "@vitejs/plugin-react": "^4.7.0", + "@vitejs/plugin-react": "^5.0.4", "autoprefixer": "^10.4.20", "co": "^4.6.0", "eslint": "^9.11.1", @@ -70,11 +70,13 @@ "globals": "^15.9.0", "jest": "^29.7.0", "jest-environment-jsdom": "^29.7.0", + "jest-fixed-jsdom": "^0.0.9", "postcss": "^8.5.6", "tailwindcss": "^3.4.13", + "tailwindcss-animate": "^1.0.7", "ts-jest": "^29.4.0", "typescript": "^5.5.3", "typescript-eslint": "^8.38.0", - "vite": "^6.3.5" + "vite": "^7.1.11" } } diff --git a/client/src/App.tsx b/client/src/App.tsx index cb2affc9b..cc49d25c3 100644 --- a/client/src/App.tsx +++ b/client/src/App.tsx @@ -16,12 +16,25 @@ import { ServerNotification, Tool, LoggingLevel, + Task, + GetTaskResultSchema, } from "@modelcontextprotocol/sdk/types.js"; import { OAuthTokensSchema } from "@modelcontextprotocol/sdk/shared/auth.js"; +import type { + AnySchema, + SchemaOutput, +} from "@modelcontextprotocol/sdk/server/zod-compat.js"; import { SESSION_KEYS, getServerSpecificKey } from "./lib/constants"; +import { + hasValidMetaName, + hasValidMetaPrefix, + isReservedMetaKey, +} from "@/utils/metaUtils"; import { AuthDebuggerState, EMPTY_DEBUGGER_STATE } from "./lib/auth-types"; import { OAuthStateMachine } from "./lib/oauth-state-machine"; import { cacheToolOutputSchemas } from "./utils/schemaUtils"; +import { cleanParams } from "./utils/paramUtils"; +import type { JsonSchemaType } from "./utils/jsonUtils"; import React, { Suspense, useCallback, @@ -34,7 +47,6 @@ import { useDraggablePane, useDraggableSidebar, } from "./lib/hooks/useDraggablePane"; -import { StdErrNotification } from "./lib/notificationTypes"; import { Tabs, TabsContent, TabsList, TabsTrigger } from "@/components/ui/tabs"; import { Button } from "@/components/ui/button"; @@ -45,7 +57,9 @@ import { Hammer, Hash, Key, + ListTodo, MessageSquare, + Settings, } from "lucide-react"; import { z } from "zod"; @@ -60,6 +74,7 @@ import RootsTab from "./components/RootsTab"; import SamplingTab, { PendingRequest } from "./components/SamplingTab"; import Sidebar from "./components/Sidebar"; import ToolsTab from "./components/ToolsTab"; +import TasksTab from "./components/TasksTab"; import { InspectorConfig } from "./lib/configurationTypes"; import ChatTab from "./components/ChatTab"; import { cn } from "@/lib/utils"; @@ -72,14 +87,38 @@ import { getInitialArgs, initializeInspectorConfig, saveInspectorConfig, + getMCPTaskTtl, } from "./utils/configUtils"; import ElicitationTab, { PendingElicitationRequest, ElicitationResponse, } from "./components/ElicitationTab"; +import { + CustomHeaders, + migrateFromLegacyAuth, +} from "./lib/types/customHeaders"; +import MetadataTab from "./components/MetadataTab"; const CONFIG_LOCAL_STORAGE_KEY = "inspectorConfig_v1"; +const filterReservedMetadata = ( + metadata: Record, +): Record => { + return Object.entries(metadata).reduce>( + (acc, [key, value]) => { + if ( + !isReservedMetaKey(key) && + hasValidMetaPrefix(key) && + hasValidMetaName(key) + ) { + acc[key] = value; + } + return acc; + }, + {}, + ); +}; + const App = () => { const [resources, setResources] = useState([]); const [resourceTemplates, setResourceTemplates] = useState< @@ -92,12 +131,14 @@ const App = () => { const [prompts, setPrompts] = useState([]); const [promptContent, setPromptContent] = useState(""); const [tools, setTools] = useState([]); + const [tasks, setTasks] = useState([]); const [toolResult, setToolResult] = useState(null); const [errors, setErrors] = useState>({ resources: null, prompts: null, tools: null, + tasks: null, }); const [command, setCommand] = useState(getInitialCommand); const [args, setArgs] = useState(getInitialArgs); @@ -106,11 +147,16 @@ const App = () => { const [transportType, setTransportType] = useState< "stdio" | "sse" | "streamable-http" >(getInitialTransportType); + const [connectionType, setConnectionType] = useState<"direct" | "proxy">( + () => { + return ( + (localStorage.getItem("lastConnectionType") as "direct" | "proxy") || + "proxy" + ); + }, + ); const [logLevel, setLogLevel] = useState("debug"); const [notifications, setNotifications] = useState([]); - const [stdErrNotifications, setStdErrNotifications] = useState< - StdErrNotification[] - >([]); const [roots, setRoots] = useState([]); const [env, setEnv] = useState>({}); @@ -133,6 +179,43 @@ const App = () => { return localStorage.getItem("lastOauthScope") || ""; }); + const [oauthClientSecret, setOauthClientSecret] = useState(() => { + return localStorage.getItem("lastOauthClientSecret") || ""; + }); + + // Custom headers state with migration from legacy auth + const [customHeaders, setCustomHeaders] = useState(() => { + const savedHeaders = localStorage.getItem("lastCustomHeaders"); + if (savedHeaders) { + try { + return JSON.parse(savedHeaders); + } catch (error) { + console.warn( + `Failed to parse custom headers: "${savedHeaders}", will try legacy migration`, + error, + ); + // Fall back to migration if JSON parsing fails + } + } + + // Migrate from legacy auth if available + const legacyToken = localStorage.getItem("lastBearerToken") || ""; + const legacyHeaderName = localStorage.getItem("lastHeaderName") || ""; + + if (legacyToken) { + return migrateFromLegacyAuth(legacyToken, legacyHeaderName); + } + + // Default to empty array + return [ + { + name: "Authorization", + value: "Bearer ", + enabled: false, + }, + ]; + }); + const [pendingSampleRequests, setPendingSampleRequests] = useState< Array< PendingRequest & { @@ -154,9 +237,31 @@ const App = () => { const [authState, setAuthState] = useState(EMPTY_DEBUGGER_STATE); + // Metadata state - persisted in localStorage + const [metadata, setMetadata] = useState>(() => { + const savedMetadata = localStorage.getItem("lastMetadata"); + if (savedMetadata) { + try { + const parsed = JSON.parse(savedMetadata); + if (parsed && typeof parsed === "object") { + return filterReservedMetadata(parsed); + } + } catch (error) { + console.warn("Failed to parse saved metadata:", error); + } + } + return {}; + }); + const updateAuthState = (updates: Partial) => { setAuthState((prev) => ({ ...prev, ...updates })); }; + + const handleMetadataChange = (newMetadata: Record) => { + const sanitizedMetadata = filterReservedMetadata(newMetadata); + setMetadata(sanitizedMetadata); + localStorage.setItem("lastMetadata", JSON.stringify(sanitizedMetadata)); + }; const nextRequestId = useRef(0); const rootsRef = useRef([]); @@ -169,6 +274,8 @@ const App = () => { const [selectedPrompt, setSelectedPrompt] = useState(null); const [selectedTool, setSelectedTool] = useState(null); + const [selectedTask, setSelectedTask] = useState(null); + const [isPollingTask, setIsPollingTask] = useState(false); const [nextResourceCursor, setNextResourceCursor] = useState< string | undefined >(); @@ -179,6 +286,7 @@ const App = () => { string | undefined >(); const [nextToolCursor, setNextToolCursor] = useState(); + const [nextTaskCursor, setNextTaskCursor] = useState(); const progressTokenRef = useRef(0); const [activeTab, setActiveTab] = useState(() => { @@ -194,6 +302,32 @@ const App = () => { currentTabRef.current = activeTab; }, [activeTab]); + const navigateToOriginatingTab = (originatingTab?: string) => { + if (!originatingTab) return; + + const validTabs = [ + ...(serverCapabilities?.resources ? ["resources"] : []), + ...(serverCapabilities?.prompts ? ["prompts"] : []), + ...(serverCapabilities?.tools ? ["tools"] : []), + ...(serverCapabilities?.tasks ? ["tasks"] : []), + "ping", + "sampling", + "elicitations", + "roots", + "auth", + ]; + + if (!validTabs.includes(originatingTab)) return; + + setActiveTab(originatingTab); + window.location.hash = originatingTab; + + setTimeout(() => { + setActiveTab(originatingTab); + window.location.hash = originatingTab; + }, 100); + }; + const { height: historyPaneHeight, handleDragStart } = useDraggablePane(300); const { width: sidebarWidth, @@ -201,16 +335,21 @@ const App = () => { handleDragStart: handleSidebarDragStart, } = useDraggableSidebar(320); - // @ts-expect-error - this is used to set the initial tab - // eslint-disable-next-line @typescript-eslint/no-unused-vars - const [currentTab, setCurrentTab] = useState("resources"); + const selectedTaskRef = useRef(null); + useEffect(() => { + selectedTaskRef.current = selectedTask; + }, [selectedTask]); const { connectionStatus, serverCapabilities, + serverImplementation, mcpClient, requestHistory, + clearRequestHistory, makeRequest, + cancelTask: cancelMcpTask, + listTasks: listMcpTasks, sendNotification, handleCompletion, completionsSupported, @@ -222,25 +361,49 @@ const App = () => { args, sseUrl, env, - bearerToken, - headerName, + customHeaders, oauthClientId, + oauthClientSecret, oauthScope, config, + connectionType, onNotification: (notification) => { setNotifications((prev) => [...prev, notification as ServerNotification]); - }, - onStdErrNotification: (notification) => { - setStdErrNotifications((prev) => [ - ...prev, - notification as StdErrNotification, - ]); + + if (notification.method === "notifications/tasks/list_changed") { + void listTasks(); + } + + if (notification.method === "notifications/tasks/status") { + const task = notification.params as unknown as Task; + setTasks((prev) => { + const exists = prev.some((t) => t.taskId === task.taskId); + if (exists) { + return prev.map((t) => (t.taskId === task.taskId ? task : t)); + } else { + return [task, ...prev]; + } + }); + if (selectedTaskRef.current?.taskId === task.taskId) { + setSelectedTask(task); + } + } }, onPendingRequest: (request, resolve, reject) => { + const currentTab = lastToolCallOriginTabRef.current; setPendingSampleRequests((prev) => [ ...prev, - { id: nextRequestId.current++, request, resolve, reject }, + { + id: nextRequestId.current++, + request, + originatingTab: currentTab, + resolve, + reject, + }, ]); + + setActiveTab("sampling"); + window.location.hash = "sampling"; }, onElicitationRequest: (request, resolve) => { const currentTab = lastToolCallOriginTabRef.current; @@ -267,6 +430,7 @@ const App = () => { }, getRoots: () => rootsRef.current, defaultLoggingLevel: logLevel, + metadata, }); useEffect(() => { @@ -277,6 +441,7 @@ const App = () => { ...(serverCapabilities?.resources ? ["resources"] : []), ...(serverCapabilities?.prompts ? ["prompts"] : []), ...(serverCapabilities?.tools ? ["tools"] : []), + ...(serverCapabilities?.tasks ? ["tasks"] : []), "ping", "sampling", "elicitations", @@ -293,7 +458,9 @@ const App = () => { ? "prompts" : serverCapabilities?.tools ? "tools" - : "ping"; + : serverCapabilities?.tasks + ? "tasks" + : "ping"; setActiveTab(defaultTab); window.location.hash = defaultTab; @@ -301,6 +468,13 @@ const App = () => { } }, [serverCapabilities]); + useEffect(() => { + if (mcpClient && activeTab === "tasks") { + void listTasks(); + } + // eslint-disable-next-line react-hooks/exhaustive-deps + }, [mcpClient, activeTab]); + useEffect(() => { localStorage.setItem("lastCommand", command); }, [command]); @@ -318,13 +492,42 @@ const App = () => { }, [transportType]); useEffect(() => { - localStorage.setItem("lastBearerToken", bearerToken); + localStorage.setItem("lastConnectionType", connectionType); + }, [connectionType]); + + useEffect(() => { + if (bearerToken) { + localStorage.setItem("lastBearerToken", bearerToken); + } else { + localStorage.removeItem("lastBearerToken"); + } }, [bearerToken]); useEffect(() => { - localStorage.setItem("lastHeaderName", headerName); + if (headerName) { + localStorage.setItem("lastHeaderName", headerName); + } else { + localStorage.removeItem("lastHeaderName"); + } }, [headerName]); + useEffect(() => { + localStorage.setItem("lastCustomHeaders", JSON.stringify(customHeaders)); + }, [customHeaders]); + + // Auto-migrate from legacy auth when custom headers are empty but legacy auth exists + useEffect(() => { + if (customHeaders.length === 0 && (bearerToken || headerName)) { + const migratedHeaders = migrateFromLegacyAuth(bearerToken, headerName); + if (migratedHeaders.length > 0) { + setCustomHeaders(migratedHeaders); + // Clear legacy auth after migration + setBearerToken(""); + setHeaderName(""); + } + } + }, [bearerToken, headerName, customHeaders, setCustomHeaders]); + useEffect(() => { localStorage.setItem("lastOauthClientId", oauthClientId); }, [oauthClientId]); @@ -333,6 +536,10 @@ const App = () => { localStorage.setItem("lastOauthScope", oauthScope); }, [oauthScope]); + useEffect(() => { + localStorage.setItem("lastOauthClientSecret", oauthClientSecret); + }, [oauthClientSecret]); + useEffect(() => { saveInspectorConfig(CONFIG_LOCAL_STORAGE_KEY, config); }, [config]); @@ -461,6 +668,14 @@ const App = () => { if (data.defaultArgs) { setArgs(data.defaultArgs); } + if (data.defaultTransport) { + setTransportType( + data.defaultTransport as "stdio" | "sse" | "streamable-http", + ); + } + if (data.defaultServerUrl) { + setSseUrl(data.defaultServerUrl); + } }) .catch((error) => console.error("Error fetching default environment:", error), @@ -479,7 +694,9 @@ const App = () => { ? "prompts" : serverCapabilities?.tools ? "tools" - : "ping"; + : serverCapabilities?.tasks + ? "tasks" + : "ping"; window.location.hash = defaultTab; } else if (!mcpClient && window.location.hash) { // Clear hash when disconnected - completely remove the fragment @@ -507,6 +724,9 @@ const App = () => { setPendingSampleRequests((prev) => { const request = prev.find((r) => r.id === id); request?.resolve(result); + + navigateToOriginatingTab(request?.originatingTab); + return prev.filter((r) => r.id !== id); }); }; @@ -515,6 +735,9 @@ const App = () => { setPendingSampleRequests((prev) => { const request = prev.find((r) => r.id === id); request?.reject(new Error("Sampling request rejected")); + + navigateToOriginatingTab(request?.originatingTab); + return prev.filter((r) => r.id !== id); }); }; @@ -535,6 +758,7 @@ const App = () => { ...(serverCapabilities?.resources ? ["resources"] : []), ...(serverCapabilities?.prompts ? ["prompts"] : []), ...(serverCapabilities?.tools ? ["tools"] : []), + ...(serverCapabilities?.tasks ? ["tasks"] : []), "ping", "sampling", "elicitations", @@ -561,11 +785,11 @@ const App = () => { setErrors((prev) => ({ ...prev, [tabKey]: null })); }; - const sendMCPRequest = async ( + const sendMCPRequest = async ( request: ClientRequest, schema: T, tabKey?: keyof typeof errors, - ) => { + ): Promise> => { try { const response = await makeRequest(request, schema); if (tabKey !== undefined) { @@ -706,29 +930,203 @@ const App = () => { cacheToolOutputSchemas(response.tools); }; - const callTool = async (name: string, params: Record) => { + const callTool = async ( + name: string, + params: Record, + toolMetadata?: Record, + runAsTask?: boolean, + ): Promise => { lastToolCallOriginTabRef.current = currentTabRef.current; try { - const response = await sendMCPRequest( - { - method: "tools/call" as const, - params: { - name, - arguments: params, - _meta: { - progressToken: progressTokenRef.current++, - }, - }, + // Find the tool schema to clean parameters properly + const tool = tools.find((t) => t.name === name); + const cleanedParams = tool?.inputSchema + ? cleanParams(params, tool.inputSchema as JsonSchemaType) + : params; + + // Merge general metadata with tool-specific metadata + // Tool-specific metadata takes precedence over general metadata + const mergedMetadata = { + ...metadata, // General metadata + progressToken: progressTokenRef.current++, + ...toolMetadata, // Tool-specific metadata + }; + + const request: ClientRequest = { + method: "tools/call" as const, + params: { + name, + arguments: cleanedParams, + _meta: mergedMetadata, }, + }; + + if (runAsTask) { + request.params = { + ...request.params, + task: { + ttl: getMCPTaskTtl(config), + }, + }; + } + + const response = await sendMCPRequest( + request, CompatibilityCallToolResultSchema, "tools", ); - setToolResult(response); - return response; + // Check if this was a task-augmented request that returned a task reference + // The server returns { task: { taskId, status, ... } } when a task is created + const isTaskResult = ( + res: unknown, + ): res is { + task: { taskId: string; status: string; pollInterval: number }; + } => + !!res && + typeof res === "object" && + "task" in res && + !!res.task && + typeof res.task === "object" && + "taskId" in res.task; + + if (runAsTask && isTaskResult(response)) { + const taskId = response.task.taskId; + const pollInterval = response.task.pollInterval; + // Set polling state BEFORE setting tool result for proper UI update + setIsPollingTask(true); + // Safely extract any _meta from the original response (if present) + const initialResponseMeta = + response && + typeof response === "object" && + "_meta" in (response as Record) + ? ((response as { _meta?: Record })._meta ?? {}) + : undefined; + setToolResult({ + content: [ + { + type: "text", + text: `Task created: ${taskId}. Polling for status...`, + }, + ], + _meta: { + ...(initialResponseMeta || {}), + "io.modelcontextprotocol/related-task": { taskId }, + }, + } as CompatibilityCallToolResult); + + // Polling loop + let taskCompleted = false; + while (!taskCompleted) { + try { + // Wait for 1 second before polling + await new Promise((resolve) => setTimeout(resolve, pollInterval)); + + const taskStatus = await sendMCPRequest( + { + method: "tasks/get", + params: { taskId }, + }, + GetTaskResultSchema, + ); + + if ( + taskStatus.status === "completed" || + taskStatus.status === "failed" || + taskStatus.status === "cancelled" + ) { + taskCompleted = true; + console.log( + `Polling complete for task ${taskId}: ${taskStatus.status}`, + ); + + if (taskStatus.status === "completed") { + console.log(`Fetching result for task ${taskId}`); + const result = await sendMCPRequest( + { + method: "tasks/result", + params: { taskId }, + }, + CompatibilityCallToolResultSchema, + ); + console.log(`Result received for task ${taskId}:`, result); + setToolResult(result as CompatibilityCallToolResult); + setIsPollingTask(false); + + // Refresh tasks list to show completed state + void listTasks(); + return result as CompatibilityCallToolResult; + } else { + const failedResult: CompatibilityCallToolResult = { + content: [ + { + type: "text", + text: `Task ${taskStatus.status}: ${taskStatus.statusMessage || "No additional information"}`, + }, + ], + isError: true, + }; + setToolResult(failedResult); + setIsPollingTask(false); + // Refresh tasks list to show failed/cancelled state + void listTasks(); + return failedResult; + } + } else { + // Update status message while polling + // Safely extract any _meta from the original response (if present) + const pollingResponseMeta = + response && + typeof response === "object" && + "_meta" in (response as Record) + ? ((response as { _meta?: Record })._meta ?? + {}) + : undefined; + setToolResult({ + content: [ + { + type: "text", + text: `Task status: ${taskStatus.status}${taskStatus.statusMessage ? ` - ${taskStatus.statusMessage}` : ""}. Polling...`, + }, + ], + _meta: { + ...(pollingResponseMeta || {}), + "io.modelcontextprotocol/related-task": { taskId }, + }, + } as CompatibilityCallToolResult); + // Refresh tasks list to show progress + void listTasks(); + } + } catch (pollingError) { + console.error("Error polling task status:", pollingError); + const errorResult: CompatibilityCallToolResult = { + content: [ + { + type: "text", + text: `Error polling task status: ${pollingError instanceof Error ? pollingError.message : String(pollingError)}`, + }, + ], + isError: true, + }; + setToolResult(errorResult); + setIsPollingTask(false); + // Clear any validation errors since tool execution completed + setErrors((prev) => ({ ...prev, tools: null })); + return errorResult; + } + } + // This should not be reached due to returns above, but TypeScript needs it + setIsPollingTask(false); + return response as CompatibilityCallToolResult; + } else { + setToolResult(response as CompatibilityCallToolResult); + // Clear any validation errors since tool execution completed + setErrors((prev) => ({ ...prev, tools: null })); + return response as CompatibilityCallToolResult; + } } catch (e) { - const toolResult: CompatibilityCallToolResult = { + const errorToolResult: CompatibilityCallToolResult = { content: [ { type: "text", @@ -737,8 +1135,41 @@ const App = () => { ], isError: true, }; - setToolResult(toolResult); - return toolResult; + setToolResult(errorToolResult); + // Clear validation errors - tool execution errors are shown in ToolResults + setErrors((prev) => ({ ...prev, tools: null })); + return errorToolResult; + } + }; + + const listTasks = useCallback(async () => { + try { + const response = await listMcpTasks(nextTaskCursor); + setTasks(response.tasks); + setNextTaskCursor(response.nextCursor); + // Inline error clear to avoid extra dependency on clearError + setErrors((prev) => ({ ...prev, tasks: null })); + } catch (e) { + setErrors((prev) => ({ + ...prev, + tasks: (e as Error).message ?? String(e), + })); + } + }, [listMcpTasks, nextTaskCursor]); + + const cancelTask = async (taskId: string) => { + try { + const response = await cancelMcpTask(taskId); + setTasks((prev) => prev.map((t) => (t.taskId === taskId ? response : t))); + if (selectedTask?.taskId === taskId) { + setSelectedTask(response); + } + clearError("tasks"); + } catch (e) { + setErrors((prev) => ({ + ...prev, + tasks: (e as Error).message ?? String(e), + })); } }; @@ -746,6 +1177,10 @@ const App = () => { await sendNotification({ method: "notifications/roots/list_changed" }); }; + const handleClearNotifications = () => { + setNotifications([]); + }; + const sendLogLevelRequest = async (level: LoggingLevel) => { await sendMCPRequest( { @@ -757,10 +1192,6 @@ const App = () => { setLogLevel(level); }; - const clearStdErrNotifications = () => { - setStdErrNotifications([]); - }; - const AuthDebuggerWrapper = () => ( { setEnv={setEnv} config={config} setConfig={setConfig} - bearerToken={bearerToken} - setBearerToken={setBearerToken} - headerName={headerName} - setHeaderName={setHeaderName} + customHeaders={customHeaders} + setCustomHeaders={setCustomHeaders} oauthClientId={oauthClientId} setOauthClientId={setOauthClientId} + oauthClientSecret={oauthClientSecret} + setOauthClientSecret={setOauthClientSecret} oauthScope={oauthScope} setOauthScope={setOauthScope} onConnect={connectMcpServer} onDisconnect={disconnectMcpServer} - stdErrNotifications={stdErrNotifications} logLevel={logLevel} sendLogLevelRequest={sendLogLevelRequest} loggingSupported={!!serverCapabilities?.logging || false} - clearStdErrNotifications={clearStdErrNotifications} + connectionType={connectionType} + setConnectionType={setConnectionType} + serverImplementation={serverImplementation} />
{ Tools + + + Tasks + Ping @@ -918,6 +1357,10 @@ const App = () => { Chat + + + Metadata +
@@ -1028,10 +1471,15 @@ const App = () => { setNextToolCursor(undefined); cacheToolOutputSchemas([]); }} - callTool={async (name, params) => { + callTool={async ( + name: string, + params: Record, + metadata?: Record, + runAsTask?: boolean, + ) => { clearError("tools"); setToolResult(null); - await callTool(name, params); + await callTool(name, params, metadata, runAsTask); }} selectedTool={selectedTool} setSelectedTool={(tool) => { @@ -1040,6 +1488,7 @@ const App = () => { setToolResult(null); }} toolResult={toolResult} + isPollingTask={isPollingTask} nextCursor={nextToolCursor} error={errors.tools} resourceContent={resourceContentMap} @@ -1048,6 +1497,25 @@ const App = () => { readResource(uri); }} /> + { + clearError("tasks"); + listTasks(); + }} + clearTasks={() => { + setTasks([]); + setNextTaskCursor(undefined); + }} + cancelTask={cancelTask} + selectedTask={selectedTask} + setSelectedTask={(task) => { + clearError("tasks"); + setSelectedTask(task); + }} + error={errors.tasks} + nextCursor={nextTaskCursor} + /> { @@ -1080,6 +1548,10 @@ const App = () => { callTool={callTool} listTools={listTools} /> + )}
@@ -1115,7 +1587,7 @@ const App = () => {
{
diff --git a/client/src/__tests__/App.config.test.tsx b/client/src/__tests__/App.config.test.tsx index b2e03d362..7458c2055 100644 --- a/client/src/__tests__/App.config.test.tsx +++ b/client/src/__tests__/App.config.test.tsx @@ -49,6 +49,7 @@ jest.mock("../lib/hooks/useConnection", () => ({ serverCapabilities: null, mcpClient: null, requestHistory: [], + clearRequestHistory: jest.fn(), makeRequest: jest.fn(), sendNotification: jest.fn(), handleCompletion: jest.fn(), diff --git a/client/src/__tests__/App.routing.test.tsx b/client/src/__tests__/App.routing.test.tsx index dbd463f95..4713bef9a 100644 --- a/client/src/__tests__/App.routing.test.tsx +++ b/client/src/__tests__/App.routing.test.tsx @@ -42,12 +42,14 @@ const disconnectedConnectionState = { serverCapabilities: null, mcpClient: null, requestHistory: [], + clearRequestHistory: jest.fn(), makeRequest: jest.fn(), sendNotification: jest.fn(), handleCompletion: jest.fn(), completionsSupported: false, connect: jest.fn(), disconnect: jest.fn(), + serverImplementation: null, }; // Connected state for tests that need an active connection diff --git a/client/src/__tests__/App.samplingNavigation.test.tsx b/client/src/__tests__/App.samplingNavigation.test.tsx new file mode 100644 index 000000000..70a42a92f --- /dev/null +++ b/client/src/__tests__/App.samplingNavigation.test.tsx @@ -0,0 +1,239 @@ +import { + act, + fireEvent, + render, + screen, + waitFor, +} from "@testing-library/react"; +import App from "../App"; +import { useConnection } from "../lib/hooks/useConnection"; +import type { Client } from "@modelcontextprotocol/sdk/client/index.js"; +import type { + CreateMessageRequest, + CreateMessageResult, +} from "@modelcontextprotocol/sdk/types.js"; + +type OnPendingRequestHandler = ( + request: CreateMessageRequest, + resolve: (result: CreateMessageResult) => void, + reject: (error: Error) => void, +) => void; + +type SamplingRequestMockProps = { + request: { id: number }; + onApprove: (id: number, result: CreateMessageResult) => void; + onReject: (id: number) => void; +}; + +type UseConnectionReturn = ReturnType; + +// Mock auth dependencies first +jest.mock("@modelcontextprotocol/sdk/client/auth.js", () => ({ + auth: jest.fn(), +})); + +jest.mock("../lib/oauth-state-machine", () => ({ + OAuthStateMachine: jest.fn(), +})); + +jest.mock("../lib/auth", () => ({ + InspectorOAuthClientProvider: jest.fn().mockImplementation(() => ({ + tokens: jest.fn().mockResolvedValue(null), + clear: jest.fn(), + })), + DebugInspectorOAuthClientProvider: jest.fn(), +})); + +jest.mock("../utils/configUtils", () => ({ + ...jest.requireActual("../utils/configUtils"), + getMCPProxyAddress: jest.fn(() => "http://localhost:6277"), + getMCPProxyAuthToken: jest.fn(() => ({ + token: "", + header: "X-MCP-Proxy-Auth", + })), + getInitialTransportType: jest.fn(() => "stdio"), + getInitialSseUrl: jest.fn(() => "http://localhost:3001/sse"), + getInitialCommand: jest.fn(() => "mcp-server-everything"), + getInitialArgs: jest.fn(() => ""), + initializeInspectorConfig: jest.fn(() => ({})), + saveInspectorConfig: jest.fn(), +})); + +jest.mock("../lib/hooks/useDraggablePane", () => ({ + useDraggablePane: () => ({ + height: 300, + handleDragStart: jest.fn(), + }), + useDraggableSidebar: () => ({ + width: 320, + isDragging: false, + handleDragStart: jest.fn(), + }), +})); + +jest.mock("../components/Sidebar", () => ({ + __esModule: true, + default: () =>
Sidebar
, +})); + +jest.mock("../lib/hooks/useToast", () => ({ + useToast: () => ({ toast: jest.fn() }), +})); + +// Keep the test focused on navigation; avoid DynamicJsonForm/schema complexity. +jest.mock("../components/SamplingRequest", () => ({ + __esModule: true, + default: ({ request, onApprove, onReject }: SamplingRequestMockProps) => ( +
+
sampling-request-{request.id}
+ + +
+ ), +})); + +// Mock fetch +global.fetch = jest.fn().mockResolvedValue({ json: () => Promise.resolve({}) }); + +jest.mock("../lib/hooks/useConnection", () => ({ + useConnection: jest.fn(), +})); + +describe("App - Sampling auto-navigation", () => { + const mockUseConnection = jest.mocked(useConnection); + + const baseConnectionState = { + connectionStatus: "connected" as const, + serverCapabilities: { tools: { listChanged: true, subscribe: true } }, + mcpClient: { + request: jest.fn(), + notification: jest.fn(), + close: jest.fn(), + } as unknown as Client, + requestHistory: [], + clearRequestHistory: jest.fn(), + makeRequest: jest.fn(), + sendNotification: jest.fn(), + handleCompletion: jest.fn(), + completionsSupported: false, + connect: jest.fn(), + disconnect: jest.fn(), + serverImplementation: null, + cancelTask: jest.fn(), + listTasks: jest.fn(), + }; + + beforeEach(() => { + jest.restoreAllMocks(); + window.location.hash = "#tools"; + }); + + test("switches to #sampling when a sampling request arrives and switches back to #tools after approve", async () => { + let capturedOnPendingRequest: OnPendingRequestHandler | undefined; + + mockUseConnection.mockImplementation((options) => { + capturedOnPendingRequest = ( + options as { onPendingRequest?: OnPendingRequestHandler } + ).onPendingRequest; + return baseConnectionState as unknown as UseConnectionReturn; + }); + + render(); + + // Ensure we start on tools. + await waitFor(() => { + expect(window.location.hash).toBe("#tools"); + }); + + const resolve = jest.fn(); + const reject = jest.fn(); + + act(() => { + if (!capturedOnPendingRequest) { + throw new Error("Expected onPendingRequest to be provided"); + } + + capturedOnPendingRequest( + { + method: "sampling/createMessage", + params: { messages: [], maxTokens: 1 }, + }, + resolve, + reject, + ); + }); + + await waitFor(() => { + expect(window.location.hash).toBe("#sampling"); + expect(screen.getByTestId("sampling-request")).toBeTruthy(); + }); + + fireEvent.click(screen.getByText("Approve")); + + await waitFor(() => { + expect(resolve).toHaveBeenCalled(); + expect(window.location.hash).toBe("#tools"); + }); + }); + + test("switches back to #tools after reject", async () => { + let capturedOnPendingRequest: OnPendingRequestHandler | undefined; + + mockUseConnection.mockImplementation((options) => { + capturedOnPendingRequest = ( + options as { onPendingRequest?: OnPendingRequestHandler } + ).onPendingRequest; + return baseConnectionState as unknown as UseConnectionReturn; + }); + + render(); + + await waitFor(() => { + expect(window.location.hash).toBe("#tools"); + }); + + const resolve = jest.fn(); + const reject = jest.fn(); + + act(() => { + if (!capturedOnPendingRequest) { + throw new Error("Expected onPendingRequest to be provided"); + } + + capturedOnPendingRequest( + { + method: "sampling/createMessage", + params: { messages: [], maxTokens: 1 }, + }, + resolve, + reject, + ); + }); + + await waitFor(() => { + expect(window.location.hash).toBe("#sampling"); + expect(screen.getByTestId("sampling-request")).toBeTruthy(); + }); + + fireEvent.click(screen.getByRole("button", { name: /Reject/i })); + + await waitFor(() => { + expect(reject).toHaveBeenCalled(); + expect(window.location.hash).toBe("#tools"); + }); + }); +}); diff --git a/client/src/components/AuthDebugger.tsx b/client/src/components/AuthDebugger.tsx index ec09963ec..6252c1161 100644 --- a/client/src/components/AuthDebugger.tsx +++ b/client/src/components/AuthDebugger.tsx @@ -6,6 +6,7 @@ import { AuthDebuggerState, EMPTY_DEBUGGER_STATE } from "../lib/auth-types"; import { OAuthFlowProgress } from "./OAuthFlowProgress"; import { OAuthStateMachine } from "../lib/oauth-state-machine"; import { SESSION_KEYS } from "../lib/constants"; +import { validateRedirectUrl } from "@/utils/urlValidation"; export interface AuthDebuggerProps { serverUrl: string; @@ -163,13 +164,30 @@ const AuthDebugger = ({ currentState.oauthStep === "authorization_code" && currentState.authorizationUrl ) { + // Validate the URL before redirecting + try { + validateRedirectUrl(currentState.authorizationUrl); + } catch (error) { + updateAuthState({ + ...currentState, + isInitiatingAuth: false, + latestError: + error instanceof Error ? error : new Error(String(error)), + statusMessage: { + type: "error", + message: `Invalid authorization URL: ${error instanceof Error ? error.message : String(error)}`, + }, + }); + return; + } + // Store the current auth state before redirecting sessionStorage.setItem( SESSION_KEYS.AUTH_DEBUGGER_STATE, JSON.stringify(currentState), ); // Open the authorization URL automatically - window.location.href = currentState.authorizationUrl; + window.location.href = currentState.authorizationUrl.toString(); break; } } diff --git a/client/src/components/CustomHeaders.tsx b/client/src/components/CustomHeaders.tsx new file mode 100644 index 000000000..463f7333b --- /dev/null +++ b/client/src/components/CustomHeaders.tsx @@ -0,0 +1,241 @@ +import { useState } from "react"; +import { Button } from "@/components/ui/button"; +import { Input } from "@/components/ui/input"; +import { Textarea } from "@/components/ui/textarea"; +import { Switch } from "@/components/ui/switch"; +import { Plus, Trash2, Eye, EyeOff } from "lucide-react"; +import { + CustomHeaders as CustomHeadersType, + CustomHeader, + createEmptyHeader, +} from "@/lib/types/customHeaders"; + +interface CustomHeadersProps { + headers: CustomHeadersType; + onChange: (headers: CustomHeadersType) => void; + className?: string; +} + +const CustomHeaders = ({ + headers, + onChange, + className, +}: CustomHeadersProps) => { + const [isJsonMode, setIsJsonMode] = useState(false); + const [jsonValue, setJsonValue] = useState(""); + const [jsonError, setJsonError] = useState(null); + const [visibleValues, setVisibleValues] = useState>(new Set()); + + const updateHeader = ( + index: number, + field: keyof CustomHeader, + value: string | boolean, + ) => { + const newHeaders = [...headers]; + newHeaders[index] = { ...newHeaders[index], [field]: value }; + onChange(newHeaders); + }; + + const addHeader = () => { + onChange([...headers, createEmptyHeader()]); + }; + + const removeHeader = (index: number) => { + const newHeaders = headers.filter((_, i) => i !== index); + onChange(newHeaders); + }; + + const toggleValueVisibility = (index: number) => { + const newVisible = new Set(visibleValues); + if (newVisible.has(index)) { + newVisible.delete(index); + } else { + newVisible.add(index); + } + setVisibleValues(newVisible); + }; + + const switchToJsonMode = () => { + const jsonObject: Record = {}; + headers.forEach((header) => { + if (header.enabled && header.name.trim() && header.value.trim()) { + jsonObject[header.name.trim()] = header.value.trim(); + } + }); + setJsonValue(JSON.stringify(jsonObject, null, 2)); + setJsonError(null); + setIsJsonMode(true); + }; + + const switchToFormMode = () => { + try { + const parsed = JSON.parse(jsonValue); + if ( + typeof parsed !== "object" || + parsed === null || + Array.isArray(parsed) + ) { + setJsonError("JSON must be an object with string key-value pairs"); + return; + } + + const newHeaders: CustomHeadersType = Object.entries(parsed).map( + ([name, value]) => ({ + name, + value: String(value), + enabled: true, + }), + ); + + onChange(newHeaders); + setJsonError(null); + setIsJsonMode(false); + } catch { + setJsonError("Invalid JSON format"); + } + }; + + const handleJsonChange = (value: string) => { + setJsonValue(value); + setJsonError(null); + }; + + if (isJsonMode) { + return ( +
+
+

+ Custom Headers (JSON) +

+ +
+
+