Compare commits

..

748 Commits

Author SHA1 Message Date
Cliff Hall
4fc742b01d Revert "Bump version to 0.11.0" 2025-04-30 12:38:15 -04:00
Cliff Hall
fa458702ab Merge pull request #350 from cliffhall/bump-to-0.11.0
Bump version to 0.11.0
2025-04-30 10:26:43 -04:00
Cliff Hall
173a45a200 Merge branch 'main' into bump-to-0.11.0 2025-04-30 10:22:25 -04:00
Ola Hungerford
745991b8ef Merge pull request #357 from OpenLinkSoftware/main
When argument to a tool is not specified it should not be default and send via MCP request as a NULL value.
2025-04-29 20:28:34 -07:00
Mitko Iliev
42b0a77505 Merge branch 'modelcontextprotocol:main' into main 2025-04-29 12:51:22 +03:00
cliffhall
b3fc199d25 Bump release to 0.11.0
* In main.yml
  - reversed a change from last release that did an explicit build, because the prepare script was no longer in package.json
* In package.json
  - replaced prepare script, which will cause automatic build after npm install
  - set version to 0.11.0
  - set versions of inspector-cli, inspector-client, and inspector-server to  ^0.11.0
* In package.lock.json
  - updated versions of inspector, inspector-cli, inspector-client, and inspector-server to  ^0.11.0
* In cli/package.json
  - set version to 0.11.0
  - set versions of sdk to 1.10.2
* In client/package.json
  - set version to 0.11.0
  - set versions of sdk to 1.10.2
* In server/package.json
  - set version to 0.11.0
  - set versions of sdk to 1.10.2
2025-04-25 11:49:39 -04:00
Cliff Hall
cdab12a8e5 Merge pull request #339 from cliffhall/fix-streamable-endpoint
Fix support for streamable-http connections
2025-04-25 11:26:46 -04:00
Cliff Hall
966f95b5af Merge branch 'main' into fix-streamable-endpoint 2025-04-24 16:53:26 -04:00
Cliff Hall
2e4a52250a Merge pull request #246 from nathanArseneau/sampling-form
Create sampling response form
2025-04-24 14:34:55 -04:00
Cliff Hall
102fce5570 Merge branch 'main' into sampling-form 2025-04-24 14:20:17 -04:00
Cliff Hall
d1bff49deb Merge pull request #338 from Kavyapriya-1804/fix-reset-prompt-results
fix - Reset Prompt results
2025-04-24 12:49:35 -04:00
cliffhall
5d0c3c48f6 Prettier 2025-04-24 12:01:02 -04:00
cliffhall
7b9cd1e74d In server/index.ts
- Add last-event-id to STREAMABLE_HTTP_HEADERS_PASSTHROUGH.
2025-04-24 11:39:48 -04:00
cliffhall
bf1026b6ec Fix failing unit tests
* This PR caused the Sidebar.test.ts file tests to fail because TransformStream is not found.
* TransformStream exists in the Node version I'm testing with (20), but it still isn't found by Jest
* Turns out it is a problem with Jest, and the workaround is the simple package jest-fixed-jsdom, which subclasses JSDOMEnvironment testing environment, placing this and several other dependencies in its global object.

* In package.json
  - add jest-fixed-jsdom as a devDependency

* In jest.config.cjs
  - change testEnvironment to jest-fixed-jsdom
2025-04-23 17:52:17 -04:00
Cliff Hall
498e49e2d8 Merge pull request #1 from shivdeepak/fix-streamable-endpoint
fix cors issue with accessing mcp-session-id header
2025-04-23 16:53:59 -04:00
Mitko Iliev
1dd99d651e Merge branch 'modelcontextprotocol:main' into main 2025-04-23 21:56:13 +03:00
Shiv Deepak Muddada
1ec4e3b556 fix cors issue with accessing mcp-session-id header 2025-04-23 01:43:49 -07:00
Nathan Arseneau
29b465fe45 Merge branch 'main' into sampling-form 2025-04-22 22:07:37 -04:00
cliffhall
6e4dcd6120 WIP: Attempting to proxy streamable-http connections. Inspector still works fine with STDIO and SSE servers.
* In index.ts,
  - refactor transport webAppTransports to be a map with the session id as key and transport as value.

* Implement /mcp GET and POST endpoints using StreamableHTTPServerTransport and doing the new session in the POST (opposite from SSE) handler.

* In package.json
  - update the SDK to 1.10.2

* In useConnection.ts
  - import StreamableHTTPClientTransport
    - NOTE: while we NEED to do this, it causes useConnection.test.ts to fail with " ReferenceError: TransformStream is not defined"
  - in connect method
    - instantiate the appropriate transport
2025-04-22 18:25:47 -04:00
cliffhall
3a2e248527 Prettier 2025-04-21 11:40:01 -04:00
cliffhall
e5f6524eb6 Fix support for streamable-http connections.
* In server/index.js
  - add get/post handlers for /mcp
  - amend console log on SSE connect, with deprecation message
  - add /stdio GET handler and refactored /sse GET handler to not also do stdio. Each transport has its own handler now
  - add appropriate headers to streamable-http request

* In /client/src/lib/hooks/useConnection.ts
  - in connect function
    - create server url properly based on new transport type.
2025-04-21 11:34:55 -04:00
KavyapriyaJG
c843ac6e49 fix - Reset Prompt results on selection 2025-04-21 10:00:40 +05:30
Cliff Hall
6ab7ac3e1a Merge pull request #294 from shivdeepak/main
add support for Streamable HTTP server
2025-04-19 12:21:20 -04:00
Mitko Iliev
fa6fc62ecb Fixed: if not given cannnot be null default, tests 2025-04-19 00:47:14 +03:00
Mitko Iliev
b9c58252a1 Fixed: if not given cannnot be null default 2025-04-19 00:05:56 +03:00
Shiv Deepak Muddada
8213402185 attach auth headers to the streamable http request 2025-04-17 21:34:17 -07:00
Shiv Deepak Muddada
36178632fc Merge branch 'main' into main 2025-04-17 21:33:53 -07:00
David Soria Parra
bbe4924c88 bump 2025-04-18 00:08:56 +01:00
David Soria Parra
d90940ab8f 0.10.2 2025-04-17 23:59:43 +01:00
David Soria Parra
8ed2651ffd run build in ci 2025-04-17 23:55:50 +01:00
David Soria Parra
0f33c87ed4 Merge pull request #327 from cliffhall/bump-to-0.10.1
Bump inspector to 0.10.1
2025-04-17 23:39:17 +01:00
cliffhall
2720d68417 Bump inspector, cli, client, server to 0.10.1 2025-04-17 18:11:41 -04:00
Cliff Hall
b3971259d2 Merge branch 'main' into main 2025-04-17 16:40:48 -04:00
Cliff Hall
15fb99b644 Merge pull request #324 from cliffhall/bump-to-0.10.0
Bump to 0.10.0
2025-04-17 16:04:52 -04:00
cliffhall
958c9a36f1 Bump typescript-sdk version to 1.10.0 throughout 2025-04-17 15:42:56 -04:00
cliffhall
92bf9abb40 Bump version to 0.10.0 in
* cli/package.json
* client/package.json
* server/package.json
* package.json
  - also bump npm dependencies for cli, client, and server to 0.10.0
* package-lock.json
2025-04-17 14:21:22 -04:00
cliffhall
bb7834543b Revert "Bump version to 0.10.0 in"
This reverts commit d7dff30cdb.
2025-04-17 14:15:43 -04:00
cliffhall
d7dff30cdb Bump version to 0.10.0 in
* cli/package.json
* client/package.json
* server/package.json
* package.json
  - also bump npm dependencies for cli, client, and server to 0.10.0
* package-lock.json
2025-04-17 14:08:39 -04:00
Cliff Hall
214e5e4c25 Merge pull request #318 from lcamhoa/update-readme
Update README requirement node js version
2025-04-17 10:56:29 -04:00
Cliff Hall
d45d8c9125 Merge branch 'main' into update-readme 2025-04-17 10:53:47 -04:00
Cliff Hall
7cad9a018c Merge pull request #280 from max-stytch/max/disconnect
fix: Disconnecting should clear oauth state
2025-04-17 10:43:37 -04:00
Cliff Hall
7c8f2926a0 Merge branch 'main' into max/disconnect 2025-04-17 10:37:41 -04:00
Cliff Hall
3aa8753f7c Merge pull request #279 from max-stytch/max/improved-oauth-callback
feat: QoL improvements for OAuth Callback
2025-04-17 10:34:02 -04:00
Hoa Lam
eba153847e Merge branch 'main' into update-readme 2025-04-17 08:36:43 +07:00
Maxwell Gerber
1345a50011 lint 2025-04-16 16:25:51 -07:00
Maxwell Gerber
15960f5aa4 refactor: Use new serverspecifickey API 2025-04-16 16:24:49 -07:00
Maxwell Gerber
0dc6df57d6 Merge remote-tracking branch 'theirs/main' into max/disconnect 2025-04-16 16:10:35 -07:00
Maxwell Gerber
c8e9a772e4 Merge remote-tracking branch 'theirs/main' into max/improved-oauth-callback 2025-04-16 16:08:11 -07:00
Cliff Hall
cd28370f2c Merge pull request #284 from max-stytch/max/default-tool-json
fix: When tool type cannot be determined, use DynamicJsonForm
2025-04-16 17:12:32 -04:00
Cliff Hall
4adf4b1e51 Merge pull request #312 from modelcontextprotocol/dependabot/npm_and_yarn/npm_and_yarn-d43cab3199
Bump vite from 5.4.17 to 5.4.18 in the npm_and_yarn group across 1 directory
2025-04-16 16:50:20 -04:00
Cliff Hall
880cb4a1de Merge pull request #322 from Kavyapriya-1804/feat-display-section-cleared-on-clear-button-hit
feat - Display section reset on clear button hit
2025-04-16 15:56:00 -04:00
Cliff Hall
78cd701dc9 Merge pull request #317 from geelen/fix-auth-server-specific-storage
Fix: Store auth tokens with server-specific keys
2025-04-16 15:38:50 -04:00
Cliff Hall
e31ee74842 Merge branch 'main' into fix-auth-server-specific-storage 2025-04-16 15:36:31 -04:00
KavyapriyaJG
9996be166f Fix - added null type to prompt for reset 2025-04-17 00:27:12 +05:30
KavyapriyaJG
0b1c00baab Ft - Display section reset on clear button hit 2025-04-17 00:04:58 +05:30
dependabot[bot]
8b0daef4ce Bump vite in the npm_and_yarn group across 1 directory
Bumps the npm_and_yarn group with 1 update in the / directory: [vite](https://github.com/vitejs/vite/tree/HEAD/packages/vite).


Updates `vite` from 5.4.17 to 5.4.18
- [Release notes](https://github.com/vitejs/vite/releases)
- [Changelog](https://github.com/vitejs/vite/blob/v5.4.18/packages/vite/CHANGELOG.md)
- [Commits](https://github.com/vitejs/vite/commits/v5.4.18/packages/vite)

---
updated-dependencies:
- dependency-name: vite
  dependency-version: 5.4.18
  dependency-type: direct:development
  dependency-group: npm_and_yarn
...

Signed-off-by: dependabot[bot] <support@github.com>
2025-04-16 17:07:23 +00:00
Cliff Hall
49dddfb12b Merge pull request #316 from cliffhall/fix-cli-build
Refactor project after addition of CLI
2025-04-16 13:05:53 -04:00
Cliff Hall
e878538d05 Merge branch 'main' into fix-cli-build 2025-04-16 12:31:55 -04:00
cliffhall
8901beb73e Upgrade server's express version to "^5.1.0" 2025-04-16 11:45:39 -04:00
Cliff Hall
c65b5f8132 Merge branch 'main' into sampling-form 2025-04-16 10:25:41 -04:00
Ola Hungerford
befa209935 Merge pull request #320 from kavinkumar807/fix-sidebar-console-warning
fix: add key prop to fix console warning in sidebar
2025-04-16 06:46:27 -07:00
Ola Hungerford
8e8a5bb866 Merge pull request #303 from ZhengkaiWang/fix_readme_missing_character
fix:README.md to add missing node command
2025-04-16 06:44:18 -07:00
cliffhall
33309f351c In client/package.json, add port arg to dev script 2025-04-16 09:38:37 -04:00
ZK
d9100c8ed4 Merge branch 'main' into fix_readme_missing_character 2025-04-16 15:10:07 +08:00
kavinkumarbaskar
e4b4039e90 prettier check 2025-04-16 12:06:54 +05:30
kavinkumarbaskar
e798504867 fixed console warning
- added key in select item to fix the console warning
2025-04-16 12:02:35 +05:30
Nathan Arseneau
6b57f7ce11 feat: test ci linter 2025-04-15 22:05:48 -04:00
Nathan Arseneau
a4e6daae15 Merge branch 'main' into sampling-form 2025-04-15 21:55:31 -04:00
Hoa Lam
61614052e5 Merge branch 'main' into update-readme 2025-04-16 08:54:50 +07:00
Nathan Arseneau
5696c19df9 Merge branch 'main' into sampling-form 2025-04-15 21:54:04 -04:00
Hoa Lam
fa7eba23b7 Update README requirement node js version 2025-04-16 08:48:04 +07:00
Glen Maddern
df0b526a41 fix: store auth tokens with server-specific keys
Changes client information and access tokens to use server-specific keys in sessionStorage. This fixes issues where changing the server URL would try to use tokens from a different server.
2025-04-16 10:14:08 +10:00
cliffhall
0229aed948 Fix bin path (remove ./) 2025-04-15 18:21:04 -04:00
cliffhall
a16a94537a Remove build before tests. Have to figure out how to automate the cli tests. they weren't in this file anyway, so another task 2025-04-15 18:11:51 -04:00
cliffhall
9854409ece Build before test 2025-04-15 18:10:22 -04:00
cliffhall
b19c78bc0a Remove cli tests from build (build has to happen first for those tests) 2025-04-15 18:08:31 -04:00
cliffhall
6a99feaf33 Refactor project components
* Remove bin folder, leaving cli, server, and client
* This fixes #315
* In .gitignore,
  - add .idea
  - remove bin/build
* Remove bin and bin/cli.js
* Remove bin/scripts/copy-cli.js
* Refactor/move bin/scripts to cli/scripts
* Refactor/move bin/src/index.ts to cli/src/cli.ts
* Refactor/renamed client/bin/cli.js to client/bin/client.js
* In .github/workflows/main.yml,
  - add run of cli tests
* In cli/pacakge.json
  - change main and bin/mcp-inspector-cli properties to build/cli.js
* In client/package.json,
  - change bin/mcp-inspector-client properties to build/start.js
* In pacakge.json
  - change bin/mcp-inspector property to ./cli/build/cli.js
  - removed bin and cli/bin from files list
  - removed @modelcontextprotocol/inspector-bin dependency
  - rearranged and corrected scripts
2025-04-15 17:59:26 -04:00
Cliff Hall
f7272d8d8c Merge pull request #177 from nbarraud/cli-and-config-file-support
Add CLI and config file support
2025-04-15 13:57:25 -04:00
Nicolas Barraud
fd7dbba7a8 Merge branch 'main' into cli-and-config-file-support 2025-04-15 12:06:09 -04:00
Cliff Hall
5fa76a7e02 Merge pull request #270 from leoshimo/leo/269-show-initialize-request-in-history
feat: Show initialize request/response in History panel (#269)
2025-04-15 11:27:39 -04:00
Nicolas Barraud
fe02efd017 Merge branch 'main' into cli-and-config-file-support 2025-04-14 22:28:49 -04:00
ZK
24418bc2cd Merge branch 'main' into fix_readme_missing_character 2025-04-15 09:57:52 +08:00
leoshimo
22eb81350a feat: Show initialize request/response in History panel (#269)
- Add logging for initialize request and response in useConnection.connect
- Include server capabilities, version, and instructions in history
2025-04-14 17:33:58 -07:00
Cliff Hall
0b37722ad1 Merge pull request #272 from idosal/set-header
Enable Authentication header name configuration
2025-04-14 18:52:34 -04:00
Nicolas Barraud
485e703043 Merge branch 'main' into cli-and-config-file-support 2025-04-14 18:51:33 -04:00
Cliff Hall
6420605d30 Merge branch 'main' into set-header 2025-04-14 18:23:55 -04:00
Cliff Hall
25cc0f69fd Merge pull request #300 from kavinkumar807/fix-tool-error-is-not-highlighted-for-sample-llm-tool-call-rejection
fix: missing condition for lengthy strings
2025-04-14 17:53:07 -04:00
Cliff Hall
f1d5824a25 Merge branch 'main' into fix-tool-error-is-not-highlighted-for-sample-llm-tool-call-rejection 2025-04-14 17:50:35 -04:00
Cliff Hall
d332352968 Merge pull request #286 from Cloudkkk/main
feat: 🎸 Add clear button for error notifications
2025-04-14 17:06:03 -04:00
Cliff Hall
d0622d3eb5 Merge branch 'main' into main 2025-04-14 17:00:34 -04:00
Cliff Hall
33aad8a271 Merge branch 'main' into max/default-tool-json 2025-04-14 16:15:27 -04:00
kavinkumarbaskar
352f5af7f8 Merge branch 'main' into fix-tool-error-is-not-highlighted-for-sample-llm-tool-call-rejection 2025-04-14 23:09:33 +05:30
Nicolas Barraud
3784816374 Merge branch 'main' into cli-and-config-file-support 2025-04-14 13:36:03 -04:00
Nicolas Barraud
de233c9b30 Conflict resolution 2025-04-14 13:34:49 -04:00
Nicolas Barraud
dcef9dd068 Merge branch 'cli-and-config-file-support' of https://github.com/nbarraud/inspector into cli-and-config-file-support 2025-04-14 13:30:16 -04:00
Nicolas Barraud
204a90b1d1 Resolved new conflicts 2025-04-14 13:30:12 -04:00
Cliff Hall
8f7680d72b Merge pull request #311 from olaservo/bump-version-0-9-0
Bump version to 0.9.0
2025-04-14 11:36:19 -04:00
olaservo
e20c4fb4ff Bump version to 0.9.0 2025-04-14 08:23:08 -07:00
Ido Salomon
f461f29f18 Merge branch 'main' into set-header 2025-04-12 22:55:36 +03:00
Ido Salomon
87fad79e7d add bearer 2025-04-12 22:55:03 +03:00
Ido Salomon
cd1bcfb15f Update README.md
Co-authored-by: Ola Hungerford <olahungerford@gmail.com>
2025-04-12 22:52:47 +03:00
ZK
e4bfc058b2 fix README.md missing character 2025-04-13 00:06:04 +08:00
Nicolas Barraud
bbff5c5883 Merge branch 'main' into cli-and-config-file-support 2025-04-12 11:02:53 -04:00
Nicolas Barraud
8423776873 Fixed conflicts 2025-04-12 10:33:22 -04:00
Ola Hungerford
645a256994 Merge pull request #274 from nathanArseneau/dark-mode-fix
fix dark mode color and padding for the tab item
2025-04-12 06:04:28 -07:00
kavinkumarbaskar
1175af1074 fix: missing condition for lengthy strings 2025-04-12 17:54:17 +05:30
Cloudkkk
c4cc4144d9 test: 💍 Add test case property 2025-04-12 14:30:33 +08:00
Ido Salomon
80854d9183 Merge branch 'main' into set-header 2025-04-12 03:37:18 +03:00
Nathan Arseneau
98ea4a12d6 Merge branch 'main' into dark-mode-fix 2025-04-11 20:13:31 -04:00
Maxwell Gerber
2e8cc56744 Merge remote-tracking branch 'theirs/main' into max/default-tool-json 2025-04-11 15:36:25 -07:00
Maxwell Gerber
3e95d9d42a pr feedback: Only use form if object is simple 2025-04-11 15:34:41 -07:00
Ido Salomon
a010f10c26 remove bad merges 2025-04-12 00:50:37 +03:00
Cliff Hall
70dc1b766e Merge pull request #298 from Kavyapriya-1804/fix-lint-warnings-and-errors-in-client
Fix - Lint warnings and errors in client
2025-04-11 17:38:13 -04:00
Ido Salomon
d798d1a132 remove bad merge 2025-04-12 00:13:52 +03:00
KavyapriyaJG
eab6b42ac6 Fix - Lint warnings and errors in client
Lint issues fixed:
1. Removed unused error variable in catch block
2. Changed 'ActionTypes' type to enum
3. Removed unnecessary interface extensions
4. Removed unused export component
5. Added the missing dependencies to useMemo
6. Fixed the inline function issue by changing it to useMemo
2025-04-12 02:10:37 +05:30
Ido Salomon
53152e3fb1 fix build 2025-04-11 20:52:45 +03:00
Tadas Antanavicius
4a2ba7ce6e Merge pull request #290 from cliffhall/fix-reconnect
Fix Reconnect handler
2025-04-10 13:12:53 -07:00
Ido Salomon
aeac3ac914 Merge branch 'main' into set-header 2025-04-10 20:38:12 +03:00
Ido Salomon
a98db777c5 add auth tests 2025-04-10 20:34:40 +03:00
Shiv Deepak Muddada
f43a9140ef run prettier-fix 2025-04-09 21:09:32 -07:00
Shiv Deepak Muddada
638603c0f3 add support for streamable http server 2025-04-09 20:47:53 -07:00
Cliff Hall
4f6c30904a Merge branch 'main' into fix-reconnect 2025-04-09 14:07:11 -04:00
Cliff Hall
a3a1ad47fa Merge pull request #275 from kavinkumar807/highlight-tool-errors-in-red-text
feat: highlight tool errors in red text
2025-04-09 13:30:19 -04:00
kavinkumarbaskar
1596973b05 Merge branch 'main' into highlight-tool-errors-in-red-text 2025-04-09 22:47:12 +05:30
Cliff Hall
6c07559573 Merge pull request #266 from morinokami/patch-3
Enhance Sidebar component accessibility
2025-04-09 13:10:00 -04:00
cliffhall
727e0753e4 This fixes #273
* In Sidebar.tsx
  - In Reconnect button handler, call onDisconnect before onConnect

See: https://github.com/modelcontextprotocol/inspector/issues/273#issuecomment-2789895596
2025-04-09 11:52:31 -04:00
Cliff Hall
aad3262940 Merge pull request #264 from samuel871211/addUnitTest
refactor(json): Consolidate JSON utilities and type definitions
2025-04-09 10:28:33 -04:00
Shinya Fujino
7bc1088159 Merge remote-tracking branch 'origin/main' into patch-3 2025-04-09 22:16:28 +09:00
kavinkumarbaskar
256972a366 Merge branch 'main' into highlight-tool-errors-in-red-text 2025-04-09 17:40:30 +05:30
Cloudkkk
a15df913fe feat: 🎸 Add clear button for error notifications 2025-04-09 11:32:49 +08:00
yushengchen
068d43226f refactor: remove as any of file jsonUtils.test.ts
refactor: extract `DataType` as the return type of function `getDataType`
2025-04-09 09:24:42 +08:00
yushengchen
fe74dbea74 refactor(json): Consolidate JSON utilities and type definitions
Modified files:
- client/src/components/DynamicJsonForm.tsx
- client/src/components/JsonView.tsx
- client/src/components/ToolsTab.tsx
- client/src/components/__tests__/DynamicJsonForm.test.tsx
- client/src/utils/__tests__/jsonPathUtils.test.ts → client/src/utils/__tests__/jsonUtils.test.ts
- client/src/utils/__tests__/schemaUtils.test.ts
- client/src/utils/jsonPathUtils.ts → client/src/utils/jsonUtils.ts
- client/src/utils/schemaUtils.ts

Descriptions:
- Move JSON type definitions from DynamicJsonForm to centralized jsonUtils
- Consolidate utility functions (getDataType, tryParseJson) into jsonUtils
- Rename jsonPathUtils to jsonUtils for better semantic clarity
- Add comprehensive test coverage for new utility functions
- Update imports across all affected components
- Improve type references consistency throughout the codebase
2025-04-09 09:20:02 +08:00
Maxwell Gerber
f6ed09e9fb Merge remote-tracking branch 'theirs/main' into max/default-tool-json 2025-04-08 15:17:11 -07:00
Maxwell Gerber
4bc44c4d19 fix: When tool type cannot be determined, use DynamicJsonForm 2025-04-08 15:05:57 -07:00
Cliff Hall
da4e2fa844 Merge pull request #271 from pulkitsharma07/progress_flow_support
feat: Progress Support for Long Running Tool Calls 
2025-04-08 16:05:55 -04:00
Pulkit Sharma
9c6663c4c2 add label to configItem, use that in UI 2025-04-09 01:24:41 +05:30
Pulkit Sharma
cf20fe9142 merge main 2025-04-09 01:23:42 +05:30
Cliff Hall
6659d549ea Merge pull request #265 from morinokami/patch-2
Fix inconsistent gap between TabsList and TabsContent
2025-04-08 15:48:02 -04:00
Pulkit Sharma
48917ca4e5 don't show full config keys 2025-04-09 01:12:02 +05:30
Pulkit Sharma
779ca20568 Merge branch 'main' into progress_flow_support 2025-04-09 00:42:59 +05:30
Pulkit Sharma
f71613227f rename 2025-04-09 00:40:42 +05:30
Maxwell Gerber
6a16e7cd24 fix: Disconnecting should clear oauth state 2025-04-07 15:15:28 -07:00
Maxwell Gerber
3f9500f954 feat: QoL improvements for OAuth Callback 2025-04-07 14:58:31 -07:00
Cliff Hall
4053aa122d Merge pull request #278 from modelcontextprotocol/dependabot/npm_and_yarn/npm_and_yarn-13db4ee2ba
Bump vite from 5.4.16 to 5.4.17 in the npm_and_yarn group across 1 directory
2025-04-07 14:01:38 -04:00
Cliff Hall
ad7865a6ab Merge branch 'main' into dependabot/npm_and_yarn/npm_and_yarn-13db4ee2ba 2025-04-07 13:59:03 -04:00
Cliff Hall
d69934afcb Merge pull request #263 from samuel871211/moveTypesPackageToDevDependencies
chore: move `@types/prismjs` to `devDependencies`
2025-04-07 13:58:42 -04:00
dependabot[bot]
c5dc4ded5c Bump vite in the npm_and_yarn group across 1 directory
Bumps the npm_and_yarn group with 1 update in the / directory: [vite](https://github.com/vitejs/vite/tree/HEAD/packages/vite).


Updates `vite` from 5.4.16 to 5.4.17
- [Release notes](https://github.com/vitejs/vite/releases)
- [Changelog](https://github.com/vitejs/vite/blob/v5.4.17/packages/vite/CHANGELOG.md)
- [Commits](https://github.com/vitejs/vite/commits/v5.4.17/packages/vite)

---
updated-dependencies:
- dependency-name: vite
  dependency-version: 5.4.17
  dependency-type: direct:development
  dependency-group: npm_and_yarn
...

Signed-off-by: dependabot[bot] <support@github.com>
2025-04-07 17:30:21 +00:00
Cliff Hall
4a3f032f59 Merge pull request #277 from cliffhall/use-sdk-1.9.0
Use sdk 1.9.0
2025-04-07 12:42:55 -04:00
cliffhall
6bcf1531c3 Bump version to 0.8.2
* In README
  - Point to inspector screenshot's rawcontent address so it doesn't appear as a broken image in the NPM package view.
2025-04-07 12:32:06 -04:00
cliffhall
a506e4c419 Bump version to 0.8.2
* In package.json
  - Use inspector-[client|server] version 0.8.2
* In [client|server]/package.json
  - New version to 0.8.2
  - Use typescript SDK version 1.9.0
* In package-lock.json
  - above changes
  - sdk dependency's version increased: node_modules/@modelcontextprotocol/sdk/node_modules/pkce-challenge
2025-04-07 12:19:34 -04:00
Nathan Arseneau
71bb89ddf2 create sampling response form 2025-04-05 18:36:57 -04:00
kavinkumarbaskar
ca1854b071 ran npm run prettier-fix command to fix the code styling 2025-04-05 23:32:10 +05:30
kavinkumarbaskar
a3be8f6376 feat: highlight tool errors in red text 2025-04-05 23:24:10 +05:30
Nathan Arseneau
8d20044b33 fix darkmode color and padding for the tab item 2025-04-05 11:47:44 -04:00
Ido Salomon
eb9b2dd027 remove default value 2025-04-05 12:57:49 +03:00
Ido Salomon
91633de80f set header name 2025-04-05 12:46:25 +03:00
Pulkit Sharma
6be05c5278 update docs 2025-04-05 13:06:25 +05:30
Pulkit Sharma
f36061e4b9 merge main 2025-04-05 01:49:11 +05:30
Pulkit Sharma
e35343537c Add proper support for progress flow during tool calling 2025-04-05 01:46:57 +05:30
Shinya Fujino
402cde025b Enhance Sidebar component accessibility 2025-04-05 00:51:31 +09:00
Shinya Fujino
0fd2e12c7b Fix inconsistent gap between TabsList and TabsContent 2025-04-04 22:39:55 +09:00
yusheng chen
b8ab30fdf3 chore: move @types/prismjs to devDependencies 2025-04-04 19:26:11 +08:00
Cliff Hall
3032a67d4e Merge pull request #261 from cliffhall/bump-to-version-0.8.1
Bump to version 0.8.1 - package-lock.json
2025-04-03 18:07:31 -04:00
Cliff Hall
f0651baf4a Merge branch 'modelcontextprotocol:main' into bump-to-version-0.8.1 2025-04-03 16:33:52 -04:00
cliffhall
3f73ec83a2 Bump version to 0.8.1
* package-lock.json
2025-04-03 16:32:59 -04:00
Pulkit Sharma
06f237b1de Merge branch 'main' into offload_request_to_sdk 2025-04-04 01:45:11 +05:30
Pulkit Sharma
a8ffc704f0 add support for progress flow 2025-04-04 01:44:30 +05:30
Cliff Hall
bdab26dbeb Merge pull request #260 from cliffhall/bump-to-version-0.8.1
Bump version to 0.8.1
2025-04-03 15:36:00 -04:00
Cliff Hall
0f075af42c Merge branch 'main' into bump-to-version-0.8.1 2025-04-03 14:48:47 -04:00
Cliff Hall
06fcc74638 Merge pull request #247 from max-stytch/fix/use-https-protocol
fix: Use same protocol for proxy server URL
2025-04-03 14:48:02 -04:00
cliffhall
9092c780f7 Bump version to 0.8.1
* In client/package.json
  - version bumped to 0.8.1
  - typescript SDK version 0.8.0 (latest)
* In server/package.json
  - version bumped to 0.8.1
  - typescript SDK version 0.8.0 (latest)
* In client/package.json
  - version bumped to 0.8.1
  - inspector-client bumped to 0.8.1
  - inspector-server bumped to 0.8.1
2025-04-03 14:30:59 -04:00
Cliff Hall
a75dd7ba1f Merge pull request #253 from max-stytch/max/fix-reloads
fix: Do not reconnect on rerender
2025-04-03 13:38:11 -04:00
Maxwell Gerber
a414033354 fix: Use same protocol for proxy server URL 2025-04-03 09:18:11 -07:00
Cliff Hall
ce1a9d3905 Merge pull request #243 from pulkitsharma07/add_proxy_config
Add MCP proxy address config support, better error messages, redesigned Config panel
2025-04-02 18:40:57 -04:00
Maxwell Gerber
0bd51fa84a fix: Do not reconnect on rerender 2025-04-02 15:18:33 -07:00
Pulkit Sharma
2a544294ba merge main 2025-04-03 00:47:21 +05:30
Cliff Hall
897e637db4 Merge pull request #244 from NicolasMontone/feat/new-alert-and-copy-button
feat: add new toast and add copy button to JSON.
2025-04-02 13:04:54 -04:00
NicolasMontone
5db5fc26c7 fix prettier 2025-04-02 10:42:52 -03:00
NicolasMontone
8b31f495ba fix unkown type. 2025-04-02 10:41:33 -03:00
NicolasMontone
c964ff5cfe Use copy button insde JSON view component 2025-04-02 10:39:39 -03:00
Pulkit Sharma
e69bfc58bc prettier-fix 2025-04-02 13:45:09 +05:30
Pulkit Sharma
debb00344a Merge branch 'main' into add_proxy_config 2025-04-02 13:43:42 +05:30
NicolasMontone
c9ee22b781 fix(Select): add missing style. 2025-04-01 19:23:57 -03:00
NicolasMontone
cc70fbd0f5 add ring color 2025-04-01 19:14:32 -03:00
NicolasMontone
8586d63e6d Add shadcn alert to match project design 2025-04-01 17:38:25 -03:00
NicolasMontone
539de0fd85 add copy button 2025-04-01 17:18:40 -03:00
Cliff Hall
f9cb2c1bd0 Merge pull request #241 from NicolasMontone/main
Do not remove form on error in tool call tab.
2025-04-01 16:04:53 -04:00
NicolasMontone
80f2986fd6 remove unneeded test 2025-04-01 16:58:32 -03:00
NicolasMontone
1504d1307e Remove error 2025-04-01 16:49:10 -03:00
NicolasMontone
d1e155f984 Revert "Add copy button to JSON & fix button styles override."
This reverts commit c48670f426.
2025-04-01 16:48:01 -03:00
NicolasMontone
c48670f426 Add copy button to JSON & fix button styles override. 2025-04-01 16:43:23 -03:00
Cliff Hall
e9a90b9caf Merge branch 'main' into main 2025-04-01 15:35:12 -04:00
Cliff Hall
affd207c9e Merge pull request #238 from max-stytch/feat/disconnect
feat: Add lightweight Disconnect button
2025-04-01 15:17:45 -04:00
Cliff Hall
4afe2d6adb Merge branch 'main' into feat/disconnect 2025-04-01 14:53:10 -04:00
Nicolás Montone
e4d4ff0148 Merge branch 'main' into main 2025-04-01 15:10:10 -03:00
Cliff Hall
d127ee86ce Merge pull request #242 from olaservo/bump-version
Bump version to 0.8.0
2025-04-01 13:23:36 -04:00
Cliff Hall
f7d39fb252 Merge branch 'main' into bump-version 2025-04-01 13:22:03 -04:00
Cliff Hall
8faadc0588 Merge pull request #235 from olaservo/add-tests
Add failing test to repro issue 154
2025-04-01 12:23:55 -04:00
Pulkit Sharma
0dcd10c1dd Update readme 2025-04-01 19:48:48 +05:30
Ola Hungerford
65f38a4827 Bump version to 0.8.0 2025-04-01 07:07:57 -07:00
NicolasMontone
51f2f72677 fix: add tests 2025-04-01 11:07:43 -03:00
NicolasMontone
d2db697d89 fix: prettier. 2025-04-01 11:00:13 -03:00
Ola Hungerford
93c9c74dc9 Fix formatting 2025-04-01 06:59:50 -07:00
NicolasMontone
dada1c4ba6 do not remove form with alert 2025-04-01 10:59:30 -03:00
Ola Hungerford
c3117d0fea Merge branch 'main' into add-tests 2025-04-01 06:57:01 -07:00
Ola Hungerford
992fdb33ed Merge pull request #234 from katopz/fix-integer
fix: prop.type not accept integer
2025-04-01 06:56:37 -07:00
Ola Hungerford
2a9230d507 Merge branch 'main' into fix-integer 2025-04-01 06:51:58 -07:00
Pulkit Sharma
51c7eda6a6 Add MCP proxy address config support, better error messages 2025-04-01 19:21:19 +05:30
Ola Hungerford
b82c744583 Use actual rendered element spinbutton in test 2025-04-01 06:50:23 -07:00
Maxwell Gerber
9ab213bc89 feat: Add lightweight Disconnect button 2025-03-31 18:54:44 -07:00
katopz
2ee0a53e36 fix: prettier 2025-04-01 09:27:24 +09:00
Cliff Hall
fa7f9c80cd Merge pull request #236 from modelcontextprotocol/dependabot/npm_and_yarn/npm_and_yarn-7a62469a90
Bump vite from 5.4.15 to 5.4.16 in the npm_and_yarn group across 1 directory
2025-03-31 17:19:26 -04:00
dependabot[bot]
7dc2c6fb58 Bump vite in the npm_and_yarn group across 1 directory
Bumps the npm_and_yarn group with 1 update in the / directory: [vite](https://github.com/vitejs/vite/tree/HEAD/packages/vite).


Updates `vite` from 5.4.15 to 5.4.16
- [Release notes](https://github.com/vitejs/vite/releases)
- [Changelog](https://github.com/vitejs/vite/blob/v5.4.16/packages/vite/CHANGELOG.md)
- [Commits](https://github.com/vitejs/vite/commits/v5.4.16/packages/vite)

---
updated-dependencies:
- dependency-name: vite
  dependency-type: direct:development
  dependency-group: npm_and_yarn
...

Signed-off-by: dependabot[bot] <support@github.com>
2025-03-31 20:38:18 +00:00
Cliff Hall
f49b2d1442 Merge pull request #233 from seuros/main
refactor: Update default ports for MCPI client and MPCP server
2025-03-31 16:19:26 -04:00
Abdelkader Boudih
d1746f53a4 Update package.json 2025-03-31 20:11:40 +00:00
Abdelkader Boudih
b99cf276ae fix: linting 2025-03-31 18:34:12 +00:00
Abdelkader Boudih
6c67bf6d6d Merge branch 'main' into main 2025-03-31 18:32:18 +00:00
Abdelkader Boudih
80f5ab1136 fix: typo 2025-03-31 18:28:40 +00:00
Ola Hungerford
2f854304a7 Merge pull request #216 from Skn0tt/cleanup-old-transports
fix: clean up previous transport processes
2025-03-31 10:42:10 -07:00
Cliff Hall
6b63bacbcd Merge pull request #229 from modelcontextprotocol/dependabot/npm_and_yarn/npm_and_yarn-7631eb0223
Bump vite from 5.4.12 to 5.4.15 in the npm_and_yarn group across 1 directory
2025-03-31 13:21:19 -04:00
Cliff Hall
fb29ca0113 Merge branch 'main' into cleanup-old-transports 2025-03-31 12:36:34 -04:00
dependabot[bot]
83ceefca79 Bump vite in the npm_and_yarn group across 1 directory
Bumps the npm_and_yarn group with 1 update in the / directory: [vite](https://github.com/vitejs/vite/tree/HEAD/packages/vite).


Updates `vite` from 5.4.12 to 5.4.15
- [Release notes](https://github.com/vitejs/vite/releases)
- [Changelog](https://github.com/vitejs/vite/blob/v5.4.15/packages/vite/CHANGELOG.md)
- [Commits](https://github.com/vitejs/vite/commits/v5.4.15/packages/vite)

---
updated-dependencies:
- dependency-name: vite
  dependency-type: direct:development
  dependency-group: npm_and_yarn
...

Signed-off-by: dependabot[bot] <support@github.com>
2025-03-31 16:30:35 +00:00
Cliff Hall
c3bd1fb1c6 Merge pull request #224 from cliffhall/fix-214
Gracefully handle proxy server and inspector client startup errors
2025-03-31 12:29:15 -04:00
Cliff Hall
45d8202de8 Merge branch 'main' into fix-214 2025-03-31 12:27:41 -04:00
Ola Hungerford
180760c4db Fix formatting 2025-03-31 09:16:25 -07:00
Simon Knott
538fc97289 fix prettier 2025-03-31 18:10:16 +02:00
Simon Knott
04442b52a2 Merge branch 'main' into cleanup-old-transports 2025-03-31 18:10:00 +02:00
Nicolas Barraud
73d4cecdb1 prettier-fix 2025-03-31 11:43:23 -04:00
Nicolas Barraud
952e13edc1 Update cli-tests.js 2025-03-31 11:37:47 -04:00
Nicolas Barraud
6eb6b3f82e Update package-lock.json 2025-03-31 11:30:27 -04:00
Ola Hungerford
7753b275e5 Update test to fail more explicitly 2025-03-31 08:04:53 -07:00
Ola Hungerford
7ac1e40c9d Update tests 2025-03-31 07:51:28 -07:00
Ola Hungerford
d2696e48a5 Add failing test for integer input 2025-03-31 07:32:55 -07:00
Nicolas Barraud
3fc63017df Moved some dependencies in repos where they are being used. 2025-03-31 08:32:32 -04:00
Nicolas Barraud
cf86040df9 Update package-lock.json 2025-03-31 08:22:11 -04:00
Nicolas Barraud
86a1adefd9 Update package.json 2025-03-31 08:19:33 -04:00
Nicolas Barraud
1832be2f84 Update package.json 2025-03-31 08:15:42 -04:00
katopz
7b055b6b9a fix: prop.type not accept integer 2025-03-31 18:29:09 +09:00
Abdelkader Boudih
da9dd09765 refactor: Update default ports for MCPI client and MPCP server
Changes the default ports used by the MCP Inspector client UI and the MCP Proxy server to avoid conflicts with common development ports and provide a memorable mnemonic based on T9 mapping.
2025-03-31 00:31:28 +00:00
Nicolas Barraud
1dfe10bf42 Merge branch 'main' into cli-and-config-file-support 2025-03-30 17:10:01 -04:00
Nicolas Barraud
65c589c193 Fixes to the formatting 2025-03-30 17:05:07 -04:00
Nicolas Barraud
5b22143c85 CLI and config file support 2025-03-30 15:57:29 -04:00
Nicolas Barraud
a63de622f8 Update URL to use 127.0.0.1 instead of localhost 2025-03-30 13:13:36 -04:00
Cliff Hall
539f32bf3b Merge pull request #204 from pulkitsharma07/main
Add "Configuration" support in UI for configuring the request timeout (and more things in the future)
2025-03-29 16:36:19 -04:00
Pulkit Sharma
c6174116b0 update screenshot 2025-03-29 23:39:06 +05:30
Pulkit Sharma
65fc6d0490 prettier-fix, add contribution guidelines 2025-03-29 23:31:46 +05:30
Pulkit Sharma
834eb0c934 add Sidebar tests 2025-03-29 22:31:57 +05:30
cliffhall
054741be03 Run prettier. 2025-03-29 12:36:03 -04:00
Cliff Hall
eaa8055fd1 Merge branch 'main' into fix-214 2025-03-29 12:34:20 -04:00
Pulkit Sharma
9e1186f5ac Document configuration in Readme and add TSDoc for the same. 2025-03-29 09:40:13 +05:30
Pulkit Sharma
81c0ef29ab Merge branch 'main' into main 2025-03-29 09:11:01 +05:30
Ola Hungerford
75537c7cae Merge pull request #218 from cliffhall/fix-rules-of-hooks-warning
Fix ESLint rules-of-hooks warnings
2025-03-28 20:01:23 -07:00
Cliff Hall
dbaa731097 Merge branch 'main' into fix-rules-of-hooks-warning 2025-03-28 17:49:40 -04:00
Cliff Hall
dd0434c4ed Merge pull request #207 from samuel871211/perf_useTheme
perf: add `useMemo` to the return value of `useTheme`
2025-03-28 17:47:59 -04:00
Cliff Hall
ed31f9893f Merge branch 'main' into perf_useTheme 2025-03-28 17:46:00 -04:00
Cliff Hall
38fb710f2f Merge pull request #211 from cgoinglove/feat/json-view-component
feat: Add JSON View Component
2025-03-28 17:45:22 -04:00
Cliff Hall
240c67037c Merge branch 'main' into feat/json-view-component 2025-03-28 17:32:41 -04:00
Cliff Hall
02155570df Merge branch 'main' into cleanup-old-transports 2025-03-28 16:34:21 -04:00
cliffhall
7227909df3 Fix spurious linebreak 2025-03-28 16:03:39 -04:00
cliffhall
84335ae5f4 Remove else block wrapper for final component return to reduce indenting and hopefully make the PR diff easier to approve. 2025-03-28 15:57:11 -04:00
Pulkit Sharma
8486696240 Merge branch 'main' of github.com:pulkitsharma07/inspector 2025-03-29 01:23:29 +05:30
Pulkit Sharma
6a6b15ab45 don't disable rules-of-hooks 2025-03-29 01:22:35 +05:30
Cliff Hall
804a144ffb Merge branch 'main' into fix-rules-of-hooks-warning 2025-03-28 15:20:11 -04:00
Cliff Hall
1d4ca435b8 Merge branch 'main' into fix-214 2025-03-28 12:32:59 -04:00
cliffhall
1b754f52ca This fixes #214 where when the inspector is started, it can report that the inspector is up, when in fact it isn't because the address is already in use. It catches this condition, as well as the condition where the proxy server port is in use, reports it, and exits.
* In bin/cli.js
  - in the delay function, have the setTimeout return a true value.
  - try the server's spawnPromise call and within the try block, use Promise.race to get the return value of the first promise to resolve. If the server is up, it will not resolve and the 2 second delay will resolve with true, telling us the server is ok. Any error will have been reported by the server startup process, so we will not pile on with more output in the catch block.
  - If the server started ok, then we will await the spawnPromise call for starting the client. If the client fails to start it will report and exit, otherwise we are done and both servers are running and have reported as much. If an error is caught and it isn't SIGINT or if process.env.DEBUG is true then the error will be thrown before exiting.
* In client/bin/cli.js
  - add a "listening" handler to the server, logging that the MCP inspector is up at the given port
  - Add an "error" handler to the server that reports  that the client port is in use if the error message includes "EADDRINUSE", otherwise throw the error so the entire contents can be seen.
* In server/src/index.ts
  - add a "listening" handler to the server, logging that the Proxy server is up at the given port
  - Add an "error" handler to the server that reports  that the server port is in use if the error message includes "EADDRINUSE", otherwise throw the error so the entire contents can be seen.
* In package.json
  - in preview script
    - add --port 5173 to start the client on the proper port. This was useful in getting an instance of the client running before trying the start script. otherwise it starts on 4173
2025-03-28 11:59:21 -04:00
Ola Hungerford
e47b1d8f4d Merge pull request #200 from morinokami/patch-1
Restructure link buttons in sidebar to respect theme
2025-03-28 06:50:47 -07:00
Shinya Fujino
d2e211a597 Update Sidebar component icons to use 'text-foreground' for better visibility 2025-03-28 22:13:31 +09:00
Ola Hungerford
205e70736c Merge pull request #191 from nathanArseneau/show-all-notifications
Refactor notification handling to include all notifications
2025-03-28 06:04:39 -07:00
Shinya Fujino
827d867aae Merge branch 'main' into patch-1 2025-03-28 21:01:22 +09:00
Simon Knott
da0c855ef5 adapt title 2025-03-28 09:45:17 +01:00
cgoing
8180b0bd6f refactor: JsonEditor 2025-03-28 15:16:17 +09:00
yusheng chen
f09d2b6096 style: prettier format file client/src/lib/useTheme.ts 2025-03-28 07:05:22 +08:00
Cliff Hall
f846c154f5 Merge branch 'main' into perf_useTheme 2025-03-27 17:10:02 -04:00
Cliff Hall
9244ecf859 Merge branch 'main' into show-all-notifications 2025-03-27 16:42:44 -04:00
cliffhall
0891077402 This fixes the linter's warning that Hooks must be run in order each time.
* In App.tsx
  - move the conditional that returns suspense if the path is oauth/callback to the end of the component after all hooks, rendering either suspense or the normal component.
  - move handleApproveSampling and handleRejectSampling functions down below all the hooks for clarity. There are a lot of hooks so finding the end of them is a scroll, and these function constants aren't referenced until the rendering section below anyway.
2025-03-27 15:59:41 -04:00
Simon Knott
353d6b549b fix: clean up previous transport processes 2025-03-27 09:52:35 +01:00
cgoing
18ca6e28a7 Use <pre> tag inside JsonView component for consistency 2025-03-27 12:55:36 +09:00
cgoing
2d252a389c Remove escapeUnicode function from ToolsTab.tsx 2025-03-27 11:42:39 +09:00
cgoing
e6f5da8383 Improve JsonView component styling and change to use JsonView in PromptsTab 2025-03-27 10:49:37 +09:00
choi sung keun
196fd67ce9 Merge branch 'main' into feat/json-view-component 2025-03-27 09:40:29 +09:00
Cliff Hall
4d4bb9110c Merge pull request #208 from olaservo/update-readme
Add note on security considerations for proxy server
2025-03-26 17:43:52 -04:00
Cliff Hall
0d17082480 Merge branch 'main' into update-readme 2025-03-26 17:41:59 -04:00
Cliff Hall
cdf1f1508a Merge pull request #203 from olaservo/update-prism
Bump prismjs from 1.29.0 to 1.30.0
2025-03-26 16:22:54 -04:00
Cliff Hall
b97233f43a Merge branch 'main' into update-prism 2025-03-26 15:29:36 -04:00
choi sung keun
885932ac70 Merge branch 'main' into feat/json-view-component 2025-03-26 12:32:47 +09:00
Cliff Hall
00118f7cf9 Merge branch 'main' into show-all-notifications 2025-03-25 15:31:46 -04:00
Ola Hungerford
806cdb204f Merge pull request #186 from max-stytch/patch-1
fix: Prefer 127.0.0.1 over localhost
2025-03-25 09:13:16 -07:00
choi sung keun
fcc06ab556 Merge branch 'main' into feat/json-view-component 2025-03-26 00:11:57 +09:00
cgoing
03c1ba3092 Change JsonView default initialExpandDepth from 2 to 3 2025-03-26 00:11:07 +09:00
Max Gerber
029823bb92 Merge branch 'main' into patch-1 2025-03-25 11:05:42 -04:00
cgoing
2588f3aeb3 Change tooltip title from Korean to English 2025-03-26 00:02:10 +09:00
Ola Hungerford
88ffb5087e Merge pull request #210 from olaservo/add-ui-tests
Add preliminary UI tests
2025-03-25 07:03:30 -07:00
choi sung keun
1f17132ca1 Merge branch 'main' into feat/json-view-component 2025-03-25 22:14:29 +09:00
Ola Hungerford
c031831e71 Merge pull request #213 from olaservo/release/0.7.0
Bump version to 0.7.0
2025-03-25 03:40:18 -07:00
Pulkit Sharma
0e667acf7d Merge branch 'main' into main 2025-03-25 12:31:01 +05:30
choi sung keun
8e9e5facaf Merge branch 'main' into feat/json-view-component 2025-03-25 09:45:01 +09:00
Ola Hungerford
16b38071e7 Bump version to 0.7.0 2025-03-24 12:36:17 -07:00
Ola Hungerford
25f5bb7620 Merge branch 'main' into add-ui-tests 2025-03-24 12:01:41 -07:00
Ola Hungerford
731cee8511 Merge pull request #206 from markacianfrani/main
fix(sidebar): maintain order when changing values
2025-03-24 12:01:12 -07:00
Pulkit Sharma
6efdcb626f Merge branch 'main' of github.com:pulkitsharma07/inspector 2025-03-24 23:30:57 +05:30
Pulkit Sharma
0656e15a22 add configuration types 2025-03-24 23:30:35 +05:30
Mark Anthony Cianfrani
30e7a4d7b7 Merge branch 'main' into main 2025-03-24 12:59:13 -04:00
cgoing
d204dd6e7e feat: json view component - dark color 2025-03-25 01:56:53 +09:00
Mark Anthony Cianfrani
f2f209dbd3 fix(sidebar): maintain order when changing values 2025-03-24 12:56:41 -04:00
cgoing
f0b28d4760 feat: json view component 2025-03-25 01:48:29 +09:00
Ola Hungerford
65a0d46816 Fix formatting 2025-03-24 09:47:34 -07:00
Ola Hungerford
951db44bad Merge branch 'add-ui-tests' of https://github.com/olaservo/inspector into add-ui-tests 2025-03-24 09:43:52 -07:00
Ola Hungerford
379486b5ea Add failing test for pull/206 2025-03-24 09:43:48 -07:00
Ola Hungerford
40213bb1ed Merge branch 'main' into add-ui-tests 2025-03-24 09:30:35 -07:00
Ola Hungerford
f8b7b88a25 Merge pull request #198 from nathanArseneau/error-when-switching-Tools-without-changing-value
fix: set default value for input fields in ToolsTab component
2025-03-24 09:29:05 -07:00
Ola Hungerford
b7fa23676a Fix formatting 2025-03-24 09:27:51 -07:00
Ola Hungerford
a7f25153c4 Add failing ToolsTab test that should get fixed with pull/198 2025-03-24 09:18:58 -07:00
Ola Hungerford
fa3e2867c9 Fix formatting 2025-03-24 09:07:53 -07:00
Ola Hungerford
5735f2347a Add tests related to issues/187 to confirm fixed 2025-03-24 08:52:45 -07:00
Ola Hungerford
cab1ed3dd8 Add some json form tests and handle css in ui tests 2025-03-24 08:28:28 -07:00
Ola Hungerford
61e229a552 Add sidebar tests 2025-03-23 13:35:24 -07:00
Ola Hungerford
451704471c Remove setup 2025-03-23 13:25:06 -07:00
Ola Hungerford
668cc915e4 Add jest-dom types 2025-03-23 13:22:31 -07:00
Ola Hungerford
85f0e21679 Use commonjs for jest 2025-03-23 13:22:13 -07:00
Ola Hungerford
fc76a7c7d4 Add setup file and remove old testing mock that no longer exists from moduleNameMapper 2025-03-23 12:46:30 -07:00
Ola Hungerford
210975e385 Add test dependencies 2025-03-23 12:44:30 -07:00
Ola Hungerford
ec73831487 Fix formatting 2025-03-23 08:30:06 -07:00
Ola Hungerford
9b0da1f892 Add note on security considerations for proxy server 2025-03-23 08:19:52 -07:00
yusheng chen
3ac00598ff perf: add useMemo to the return value of useTheme 2025-03-23 21:29:46 +08:00
Pulkit Sharma
484e2820bc Merge branch 'main' into main 2025-03-23 11:08:55 +05:30
Ola Hungerford
2890e036ed Merge pull request #201 from Larmyliu/feat/proxyServerUrl
Update Vite configuration to enable host access and use `window.location.hostname` for Inspector URL
2025-03-22 21:13:39 -07:00
Ola Hungerford
008204fda5 Merge pull request #193 from seuros/main
feat: Add utility function to escape Unicode characters in tool results
2025-03-22 19:14:16 -07:00
Abdelkader Boudih
af44efb236 chore: extract utils escapeUnicode 2025-03-22 16:25:33 +00:00
Larmyliu
51f3135c76 Merge branch 'main' into feat/proxyServerUrl 2025-03-23 00:11:58 +08:00
Pulkit Sharma
4a23585066 Add support in UI to configure request timeout 2025-03-22 21:18:38 +05:30
Abdelkader Boudih
3488bdb613 feat: Add utility function to escape Unicode characters in tool results 2025-03-21 22:21:26 +00:00
Ola Hungerford
043f6040c6 Merge pull request #174 from ryanrozich/fix-env-var-parsing
Fix environment variable parsing to handle values with equals signs
2025-03-21 09:01:09 -07:00
Ola Hungerford
74d0fcf5a3 Merge branch 'main' into fix-env-var-parsing 2025-03-21 08:39:32 -07:00
Ola Hungerford
de8795106c Merge pull request #189 from cliffhall/add-log-level-setting
Add log level setting in UI
2025-03-21 08:38:58 -07:00
Cliff Hall
c726c53b00 Merge branch 'main' into add-log-level-setting 2025-03-21 11:06:31 -04:00
Ola Hungerford
20db043b40 Merge branch 'main' into fix-env-var-parsing 2025-03-21 07:07:04 -07:00
Ola Hungerford
dcbd1dad41 Bump prismjs from 1.29.0 to 1.30.0 to address 2025-03-21 06:54:46 -07:00
Ola Hungerford
dfc9cf7629 Merge pull request #159 from olaservo/handle-empty-json-fields
Improve on tool input handling and add tests
2025-03-21 06:36:44 -07:00
jazminliu
4fdbcee706 Update Vite configuration to enable host access and fix proxy server URL to use the current hostname. 2025-03-20 22:04:59 +08:00
Shinya Fujino
ce81fb976b Restructure link buttons in sidebar to respect theme 2025-03-20 22:18:44 +09:00
Nathan Arseneau
029e482e05 fix: set default value for input fields in ToolsTab component 2025-03-19 20:15:14 -04:00
Nathan Arseneau
27b54104c1 Add support for additional notification schemas in useConnection hook 2025-03-19 19:51:01 -04:00
Maxwell Gerber
536b7e0a99 fix: Update vite host 2025-03-18 09:29:48 -07:00
Ola Hungerford
c463dc58c2 Simplify check for defaults and add another test 2025-03-18 06:23:25 -07:00
Ola Hungerford
a85d5e7050 Fix formatting 2025-03-17 07:56:23 -07:00
Ola Hungerford
7ddba51b36 Generate empty objects and arrays for non required object and array fields 2025-03-17 06:36:35 -07:00
Nathan Arseneau
dd460bd877 Refactor notification handling to include all notifications 2025-03-17 02:44:59 -04:00
Ola Hungerford
50131c6960 Merge branch 'main' into handle-empty-json-fields 2025-03-16 15:56:24 -07:00
Ola Hungerford
28978ea24f Update package lock after re-running npm install 2025-03-16 15:42:16 -07:00
Ola Hungerford
cae7c76358 Fix formatting 2025-03-16 15:31:49 -07:00
Ola Hungerford
50a65d0c7a Use generateDefaultValue for object and array defaults 2025-03-16 15:29:59 -07:00
Ola Hungerford
e1b015e40d Add comments explaining extra parsing logic 2025-03-16 15:28:07 -07:00
Ola Hungerford
7c4ed6abca Use working-directory instead of cd to client 2025-03-16 15:24:48 -07:00
Ola Hungerford
a3740c4798 Remove unneeded DynamicJsonForm.tsx 2025-03-16 15:24:34 -07:00
cliffhall
d8b5bdb613 Run prettier 2025-03-15 17:03:22 -04:00
cliffhall
5104952239 Add log level setting in UI
* This fixes #188
* In App.tsx
  - import LoggingLevel from sdk
  - add [logLevel, setLogLevel] useState with value of type LoggingLevel initialized to "debug"
  - add useEffect that stores the new logLevel in localStorage as "logLevel"
  - added sendLogLevelRequest function that takes a level argument of type LoggingLevel and sends the appropriate request. It calls setLogLevel when done, to update the local UI
  - pass logLevel and sendLogLevelRequest to Sidebar component as props
* In Sidebar.tsx
  - Import LoggingLevel and LoggingLevelSchema from sdk
  - add props and prop types for  logLevel and sendLogLevelRequest and loggingSupported
  - add Select component populated with the enum values of LoggingLevelSchema, shown only if loggingSupported is true and connectionStatus is "connected"
*
2025-03-15 16:37:10 -04:00
Ryan Rozich
67722aea71 Merge branch 'main' into fix-env-var-parsing 2025-03-15 14:27:46 -05:00
Ola Hungerford
cedf02d152 Merge pull request #185 from cliffhall/add-logging-message-handler
Add support for server logging messages
2025-03-15 09:44:22 -07:00
Cliff Hall
f01f02d5be Merge branch 'modelcontextprotocol:main' into add-logging-message-handler 2025-03-15 12:38:27 -04:00
Ola Hungerford
56932e8a93 Merge pull request #178 from lloydzhou/main
Add SSE 'Accept' header
2025-03-15 06:29:18 -07:00
lloydzhou
aeaf32fa45 fix 2025-03-15 12:58:11 +08:00
lloydzhou
090b7efdea add sse accept header 2025-03-15 12:58:11 +08:00
Maxwell Gerber
cda3905e5a fix: Update URL in CONTRIBUTING.md too 2025-03-14 16:33:39 -07:00
Max Gerber
fb667fd4d0 fix: Prefer 127.0.0.1 over localhost 2025-03-14 16:16:31 -07:00
cliffhall
d70e6dc0e8 In useConnection.ts,
- import LoggingMessageNotificationSchema
- set onNotification as notification handler for LoggingMessageNotificationSchema
2025-03-13 15:17:17 -04:00
Ola Hungerford
1f214deeab Merge branch 'main' into handle-empty-json-fields 2025-03-13 06:17:18 -07:00
Ola Hungerford
c77252900a Merge pull request #180 from seuros/version
feat: Fetch version from package.json in useConnection hook
2025-03-12 13:48:11 -07:00
Ola Hungerford
498c02b0f1 Merge pull request #182 from leoshimo/leoshimo/181-sampling-dark-mode
fix: add dark mode support to SamplingTab JSON display (#181)
2025-03-12 13:06:24 -07:00
Ola Hungerford
60c4645eaf Fix formatting 2025-03-12 08:20:11 -07:00
Ryan Rozich
fe8b1ee88b remove comments 2025-03-11 22:46:38 -05:00
Ryan Rozich
04a90e8d89 Fix environment variable parsing to handle values with equals signs 2025-03-11 22:46:38 -05:00
leoshimo
e5ee00bf89 fix: add dark mode support to SamplingTab JSON display (#181) 2025-03-11 12:59:28 -07:00
Nicolas Barraud
dae389034a Change --tool-args to --tool-arg for consistency 2025-03-11 12:40:39 -04:00
Abdelkader Boudih
397a0f651f feat: Fetch version from package.json in useConnection hook 2025-03-11 13:33:45 +00:00
Justin Spahr-Summers
0281e5f821 Fix formatting 2025-03-11 10:56:53 +00:00
Justin Spahr-Summers
f56961ac62 Bump version 2025-03-11 10:55:14 +00:00
Justin Spahr-Summers
15bbb7502b Merge pull request #175 from avi1mizrahi/main
Add Bearer Token Support
2025-03-11 10:50:51 +00:00
Ola Hungerford
7caf6f8ba8 Merge pull request #170 from cliffhall/add-subscribe-to-resource
Add subscribe to resource functionality
2025-03-10 21:08:46 -07:00
Nicolas Barraud
f4e6f4d4ea Removed package-info.ts 2025-03-10 20:40:06 -04:00
Nicolas Barraud
9f42629b34 Forgot package files 2025-03-10 20:34:07 -04:00
Nicolas Barraud
4c4c8a0884 Add CLI and config file support 2025-03-10 20:19:23 -04:00
Avi Mizrahi
dbd616905c Support bearer token 2025-03-10 17:50:12 +02:00
Ola Hungerford
1ff410ca3d Merge branch 'main' into handle-empty-json-fields 2025-03-10 05:46:57 -07:00
Cliff Hall
35a0f4611a Merge branch 'main' into add-subscribe-to-resource 2025-03-08 15:35:54 -05:00
cliffhall
952bee2605 Fix prettier complaints 2025-03-08 15:08:12 -05:00
cliffhall
a669272fda Track subscribed resources and show the appropriate subscribe or unsubscribe button on selected resource panel.
If the server does not support resource subscriptions, do not show any subscription buttons.

* In App.tsx
  - useState for resourceSubscriptions, setResourceSubscriptions a Set of type string.
  - in subscribeToResource()
    - only make the request to subscribe if the uri is not in the resourceSubscriptions set
  - in unsubscribeFromResource()
    - only make the request to unsubscribe if the uri is in the resourceSubscriptions set
  - in ResourceTab element,
    - pass a boolean resourceSubscriptionsSupported as serverCapabilities.resources.subscribe
    - pass resourceSubscriptions as a prop
* In ResourcesTab.tsx
  - deconstruct resourceSubscriptions and resourceSubscriptionsSupported from props and add prop type
  - in selected resource panel
    - don't show subscribe or unsubscribe buttons unless resourceSubscriptionsSupported is true
    - only show subscribe button if selected resource uri is not in resourceSubscriptions set
    - only show unsubscribe button if selected resource uri is in resourceSubscriptions set
    - wrap buttons in a flex div that is
      - justified right
      - has a minimal gap between
      - 2/5 wide (just big enough to contain two buttons and leave the h3 text 3/5 of the row to render and not overflow.
2025-03-08 13:40:37 -05:00
cliffhall
747c0154c5 WIP: Subscribe to resources
* In App.tsx
  - added subscribeToResource()
    - takes a uri
    - sends a `resources/subscribe` message with the uri
  - added unsubscribeFromResource()
    - takes a uri
    - sends a `resources/unsubscribe` message with the uri
  - in ResourcesTab element,
    - pass subscribeToResource and subscribeToResource invokers to component
* In notificationTypes.ts
  - add ServerNotificationSchema to NotificationSchema to permit server update messages.

* In ResourcesTab.tsx
  - deconstruct subscribeToResource and unsubscribeFromResource and add prop types
  - Add Subscribe and Unsubscribe buttons to selected resource panel, left of the refresh button. They call the sub and unsub functions that came in on props, passing the selected resource URI.
  - [WIP]: Will show the appropriate button in a follow up commit.
* In useConnection.ts
  - import ResourceUpdatedNotificationSchema
  - in the connect function,
    - set onNotification as the handler for ResourceUpdatedNotificationSchema
2025-03-08 11:05:13 -05:00
Ola Hungerford
0870a81990 Merge pull request #169 from cliffhall/dial-back-ping-button-energy
Removing the all the hype from the ping button.
2025-03-07 19:02:37 -07:00
cliffhall
ca18faa7c3 Removing the all the hype from the ping button.
Discussion at:
https://github.com/orgs/modelcontextprotocol/discussions/186
2025-03-07 13:05:45 -05:00
Ola Hungerford
014730fb2f Merge pull request #164 from TornjV/patch-1
Restore timeout search param
2025-03-06 10:22:33 -07:00
Veljko Tornjanski
9c690e004b Update useConnection.ts 2025-03-05 18:17:39 +01:00
Ola Hungerford
b9b116a5f2 Remove duplicate react-dialog from merge 2025-03-05 07:55:15 -07:00
Ola Hungerford
4efe7d7899 Merge branch 'main' into handle-empty-json-fields 2025-03-05 07:52:40 -07:00
Jerome
027eb02422 Merge pull request #162 from modelcontextprotocol/jerome/fix/versioning
Bumped versions of sub packages
2025-03-05 13:02:58 +00:00
Jerome
b116264f90 Bumped versions of sub packages 2025-03-05 12:55:55 +00:00
Jerome
290d5ab49e Bumping version for 0.5.1 release 2025-03-05 11:59:19 +00:00
Jerome
826ce37d2c Merge pull request #143 from modelcontextprotocol/justin/sdk-auth
Refactor to use auth from SDK
2025-03-05 11:58:03 +00:00
Jerome
7a56a7200c Updated mcp sdk to 1.6.1 2025-03-05 11:52:16 +00:00
Jerome
1eba99c531 Merge branch 'main' into justin/sdk-auth 2025-03-05 11:43:20 +00:00
Ola Hungerford
00836dbf9e Fix formatting 2025-03-04 20:55:57 -07:00
Ola Hungerford
dd02b69036 Merge branch 'handle-empty-json-fields' of https://github.com/olaservo/inspector into handle-empty-json-fields 2025-03-04 20:54:16 -07:00
Ola Hungerford
f9b105c0ef Use debounce instead 2025-03-04 20:54:13 -07:00
Ola Hungerford
1ae77e9ef8 Merge branch 'main' into handle-empty-json-fields 2025-02-28 17:25:38 -07:00
Ashwin Bhat
13ae2b5659 Merge pull request #158 from modelcontextprotocol/ashwin/claudemd
docs: add CLAUDE.md for development guidance
2025-02-28 16:24:19 -08:00
Ola Hungerford
06773bb6dd Fix formatting 2025-02-28 09:13:33 -07:00
Ola Hungerford
b01e386659 Always use JSON mode if the schema type is object and has no properties 2025-02-28 09:06:51 -07:00
Ola Hungerford
e7f55f083f Fix formatting 2025-02-28 07:34:01 -07:00
Ola Hungerford
36aa7316ea Fix issue where array type defaults to object 2025-02-28 07:31:26 -07:00
Ola Hungerford
0e50b68f96 Fix formatting 2025-02-28 06:30:23 -07:00
Ola Hungerford
a1eb343b79 Remove unused function plus tests 2025-02-28 06:26:04 -07:00
Ola Hungerford
82bbe58a46 Fix formatting 2025-02-27 22:08:04 -07:00
Ola Hungerford
44982e6c97 Default to nulls and update tests 2025-02-27 21:33:37 -07:00
Ola Hungerford
6ec82e21b1 Remove some fluff 2025-02-27 07:48:19 -07:00
Ola Hungerford
abd4877dae Revert to only run on main 2025-02-27 07:37:47 -07:00
Ola Hungerford
d1f5b3b933 Fix formatting 2025-02-27 07:30:38 -07:00
Ola Hungerford
720480cbbb Remove console.warn and extra comments to reduce code noise 2025-02-27 07:28:13 -07:00
Ola Hungerford
8ac7ef0985 Fix path to client 2025-02-27 07:23:40 -07:00
Ola Hungerford
238c22830b Fix formatting 2025-02-27 07:21:04 -07:00
Ola Hungerford
426fb87640 Remove comment ans trigger workflow run 2025-02-27 07:15:31 -07:00
Ola Hungerford
90ce628040 Test workflow in my branch 2025-02-27 06:54:36 -07:00
Ola Hungerford
d4a64fb5d8 Add client tests to workflow 2025-02-27 06:52:19 -07:00
Ola Hungerford
ede1ea0faa Merge branch 'main' into handle-empty-json-fields 2025-02-27 06:42:17 -07:00
Ola Hungerford
0747479694 Handle edge case and add tests for functions 2025-02-27 06:40:01 -07:00
Justin Spahr-Summers
db1b5cbc45 Merge pull request #113 from gavinaboulhosn/feature/completions
Implement MCP Completion Support in Prompts and Resources Tabs
2025-02-27 11:51:47 +00:00
Ola Hungerford
0b105b29c1 Extract functions 2025-02-26 19:55:01 -07:00
Ola Hungerford
0e29e2c1cf Resolve issues where JSON fields are not being rendered in form mode 2025-02-26 19:34:33 -07:00
Ashwin Bhat
989efb2204 docs: add CLAUDE.md for development guidance
Created a CLAUDE.md file containing build commands, code style guidelines, and project organization information for future development work.

🤖 Generated with [Claude Code](https://docs.anthropic.com/s/claude-code)
Co-Authored-By: Claude <noreply@anthropic.com>
2025-02-26 11:17:54 -08:00
Ola Hungerford
592dacad39 Start adding changes to address json fields 2025-02-26 09:50:47 -07:00
Ola Hungerford
717c394d3b Merge pull request #157 from kshern/feature/add-array-proptype
Add an array input field to the ToolsTab using DynamicJsonForm.
2025-02-24 09:28:36 -07:00
kshern
8267e514ce fix: prettier write 2025-02-25 00:09:04 +08:00
kshern
18438dbdd0 feat: add error handling 2025-02-24 02:52:17 +08:00
kshern
07577fc94b feat:toolsbar add array support 2025-02-24 02:36:52 +08:00
Jerome
88984c7bc7 Linting 2025-02-23 15:15:28 +00:00
Ola Hungerford
b4870b3da3 Merge branch 'main' into feature/completions 2025-02-21 08:43:32 -07:00
Jerome
19ee9fa86a Merge remote-tracking branch 'origin/main' into justin/sdk-auth 2025-02-21 15:31:09 +00:00
Jerome
e28a64c932 Merge pull request #155 from modelcontextprotocol/jerome/fix/oauth-routing-in-prod-builds
Fix OAuth callback route in production builds
2025-02-21 15:08:25 +00:00
Jerome
02479d3ea9 Updating imports 2025-02-21 15:03:14 +00:00
Jerome
c3ece186a4 Using urlencoded params for refresh/auth tokens 2025-02-21 14:51:47 +00:00
Jerome
4201b31a24 Fix OAuth callback route in production builds
Add SPA routing configuration to serve-handler to ensure /oauth/callback
routes are correctly handled in production builds.
2025-02-21 14:47:31 +00:00
Ola Hungerford
50638806cb Merge branch 'main' into feature/completions 2025-02-21 06:19:41 -07:00
Justin Spahr-Summers
27880974a2 Merge pull request #148 from olaservo/add-note-for-dev-mode-on-windows
Add note for dev mode on windows
2025-02-19 15:31:58 +00:00
Ola Hungerford
266e8bec98 Fix formatting 2025-02-19 08:27:51 -07:00
Ola Hungerford
ed59974d65 Add dev:windows to server instead and reference from root package.json 2025-02-19 08:26:14 -07:00
Ola Hungerford
8e06165d73 Revert unintentional package-lock change 2025-02-19 08:23:01 -07:00
Ola Hungerford
e22d3c76bf Revert unintentional package-lock change 2025-02-19 08:22:02 -07:00
Ola Hungerford
02f53005db Merge branch 'main' into add-note-for-dev-mode-on-windows 2025-02-19 08:17:15 -07:00
Justin Spahr-Summers
3893807841 Merge pull request #153 from funwarioisii/fix-tool-call-textarea
Fix ToolsTab Textarea value for clearing when switch tool
2025-02-19 15:08:42 +00:00
Ola Hungerford
7b40aed43b Add dev:windows command 2025-02-19 08:08:28 -07:00
Justin Spahr-Summers
0f304a37ae Merge pull request #150 from olaservo/handle-boolean
Add checkbox for handling boolean input params
2025-02-19 15:06:56 +00:00
Ola Hungerford
39970db604 Merge branch 'main' into add-note-for-dev-mode-on-windows 2025-02-19 07:58:36 -07:00
funwarioisii
f505ae3d5a Fix ToolsTab Textarea value for clearing when switch tool 2025-02-19 23:55:24 +09:00
Ola Hungerford
89ee2b1b93 Merge branch 'main' into handle-boolean 2025-02-19 07:48:27 -07:00
Ola Hungerford
450405733a Merge: Integrate boolean checkbox support with SchemaProperty type system 2025-02-19 07:38:23 -07:00
Justin Spahr-Summers
d4df126112 Merge pull request #115 from jacksteamdev/bugfix/issue-114
fix(server) Avoid modifying path resolution for executables on MacOS
2025-02-19 14:16:51 +00:00
Justin Spahr-Summers
7065d70e34 Merge pull request #136 from olaservo/tool-input-improvements
Add enhanced object input editing
2025-02-19 14:08:24 +00:00
Jack Steam
ad004bc2f7 Merge branch 'main' into bugfix/issue-114 2025-02-18 11:54:09 -06:00
Jack Steam
db6494353c chore: update spawn-rx to v5.1.2 2025-02-18 11:53:56 -06:00
Jack Steam
3408be3e55 Merge branch 'bugfix/issue-114' of https://github.com/jacksteamdev/inspector into bugfix/issue-114 2025-02-18 11:53:04 -06:00
Jack Steam
406828ade2 Revert "fix(server) Differentiate command resolution by platform"
This reverts commit 0fa56e14d9.
2025-02-18 11:50:53 -06:00
Ola Hungerford
44d07b964c Fix styling 2025-02-15 05:05:29 -07:00
Ola Hungerford
5b2d54ae3b Revert package and check in package-lock 2025-02-15 04:47:20 -07:00
Ola Hungerford
f7312ab331 Add checkbox for Boolean input params 2025-02-15 04:33:08 -07:00
Ola Hungerford
59e7639d39 Revert package change 2025-02-14 07:44:50 -07:00
Ola Hungerford
133b785f79 Fix formatting 2025-02-14 07:33:37 -07:00
Ola Hungerford
f6860a88f9 Update package lock 2025-02-14 07:23:19 -07:00
Ola Hungerford
b3194ac56e Merge branch 'main' into tool-input-improvements 2025-02-14 07:20:45 -07:00
Ola Hungerford
7c57e823bd Fix style issues 2025-02-14 06:25:35 -07:00
Ola Hungerford
b8e73886dd Revert other changes 2025-02-14 06:18:44 -07:00
Ola Hungerford
2a1536d2ab Revert other changes 2025-02-14 06:16:02 -07:00
Ola Hungerford
348cff9872 Add note on dev mode for Windows users 2025-02-14 06:09:40 -07:00
Ola Hungerford
beee38387c Merge branch 'main' of https://github.com/olaservo/inspector 2025-02-14 06:07:46 -07:00
Justin Spahr-Summers
7b3dff68c0 Merge pull request #145 from matv-stripe/patch-1
Update README to include node before the command
2025-02-13 23:03:28 +00:00
Gavin Aboulhosn
d9df5ff860 refactor(completions): restore debouncing and improve MCP error handling 2025-02-12 20:19:36 -05:00
Gavin Aboulhosn
5b451a7cfe Merge branch 'modelcontextprotocol:main' into feature/completions 2025-02-12 19:10:06 -05:00
Gavin Aboulhosn
7f713fe40e refactor(completions): improve completion handling and error states
- Move completion logic from App.tsx to useConnection hook
- Replace useCompletion with simpler useCompletionState hook
- Add graceful fallback for servers without completion support
- Improve error handling and state management
- Update PromptsTab and ResourcesTab to use new completion API
- Add type safety improvements across completion interfaces
2025-02-12 19:05:51 -05:00
Justin Spahr-Summers
fa723abbe0 Merge pull request #146 from modelcontextprotocol/justin/fix-versions
Bump all versions to 0.4.1
2025-02-12 18:11:54 +00:00
Justin Spahr-Summers
410a6f33dc Format fixes 2025-02-12 18:10:25 +00:00
Justin Spahr-Summers
b324378b2c Bump all versions to 0.4.1 2025-02-12 18:08:31 +00:00
matv-stripe
e427f7bca5 Update README.md 2025-02-12 12:26:41 -05:00
Gavin Aboulhosn
c66feff37d update completions branch 2025-02-12 11:41:46 -05:00
Gavin Aboulhosn
9b624e8c87 feat(completions): integrate MCP Completion support into Prompts and Resources tabs
- create useCompletion hook to fetch completions with debouncing and abort control
- Updated `PromptsTab.tsx` and `ResourcesTab.tsx` to utilize the `Combobox` component and `useCompletions` hook, enabling argument autocompletion for prompts and resource URIs as per the MCP specification.
- Added a combobox to show completions
2025-02-12 11:21:27 -05:00
Justin Spahr-Summers
ba99638f48 Comment about SSEClientTransport auth API 2025-02-11 20:43:01 +00:00
Justin Spahr-Summers
f4aefa2706 npm audit fix 2025-02-11 20:36:35 +00:00
Justin Spahr-Summers
e9a50adde7 Update OAuth callback code 2025-02-11 17:42:49 +00:00
Justin Spahr-Summers
eb6af47b21 Refactor to use auth from SDK 2025-02-11 16:39:07 +00:00
Jerome
6d930ecae7 Merge pull request #135 from olaservo/add-server-startup-logging
Add server startup logging
2025-02-11 11:00:45 +13:00
Ola Hungerford
9c3fee1442 Merge branch 'main' into add-server-startup-logging 2025-02-08 13:13:14 -07:00
Justin Spahr-Summers
688752ea77 Merge pull request #139 from allenzhou101/oauth-refresh
Add Refresh Token Support for OAuth
2025-02-06 15:19:21 +00:00
Allen Zhou
1b13b574f8 Update auth.ts 2025-02-05 12:45:11 -08:00
Allen Zhou
95bbd60a38 Add zod parsing for OAuthMetadataSchema and OAuthTokensSchema 2025-02-05 12:42:09 -08:00
Allen Zhou
96ba6fd531 Convert OAuthMetadata and OAuthTokens to zod 2025-02-05 12:38:26 -08:00
Allen Zhou
8592cf2d07 Run prettier-fix 2025-02-05 11:22:11 -08:00
Allen Zhou
dd47b574b3 Update useConnection.ts 2025-02-04 15:02:12 -08:00
Allen Zhou
b4ae1327b5 Update useConnection.ts 2025-02-04 15:00:14 -08:00
Allen Zhou
b5762d53fd Handle infinite loop if server keeps returning 401 2025-02-04 14:53:41 -08:00
Allen Zhou
7957d9f577 Make OAuth start call modular 2025-02-03 20:06:21 -08:00
Allen Zhou
4c89aed4d9 Add check for expired refresh or session token that exists 2025-02-03 20:04:17 -08:00
Allen Zhou
79547143a8 Add refresh token handling if returned from server 2025-02-03 19:53:53 -08:00
Jerome
d438760e36 Merge pull request #99 from evalstate/feature/audio-rendering
Render Audio Player if Tool Result resource mime type is audio.
2025-02-03 12:28:41 +13:00
Jerome
d0ad677784 Update ToolsTab.tsx
Linting on originally approved commit
2025-02-03 12:24:52 +13:00
Ola Hungerford
98b26e9d06 Merge branch 'main' of https://github.com/olaservo/inspector 2025-01-31 05:54:12 -07:00
Ola Hungerford
d007f92302 Update deps 2025-01-29 20:21:26 -07:00
Ola Hungerford
6a3d901a72 Update dev command 2025-01-29 20:16:51 -07:00
Ola Hungerford
58ad8103f7 Remove vercel 2025-01-29 17:07:55 -07:00
Ola Hungerford
ee2c67e1af Test vercel config 2025-01-29 16:59:00 -07:00
Ola Hungerford
7c89a01c99 Test vercel config 2025-01-29 16:56:41 -07:00
Ola Hungerford
fb3d89c6e3 Test vercel config 2025-01-29 16:54:00 -07:00
Ola Hungerford
4b3bb5f34e Add description to array input fields 2025-01-29 11:36:10 -07:00
Justin Spahr-Summers
1d4e8885db Merge pull request #131 from modelcontextprotocol/justin/sse-auth
OAuth support for SSE
2025-01-29 11:20:48 +00:00
=
a87bd17f51 ❯ npx prettier --check .
Checking formatting...
[warn] client/src/components/ToolsTab.tsx
[warn] Code style issues found in the above file. Run Prettier with --write to fix.

inspector on  feature/audio-rendering [$⇡] is 📦 v0.3.0 via  v22.11.0
❯ npx prettier --write client/src/components/ToolsTab.tsx
client/src/components/ToolsTab.tsx 109ms
2025-01-28 08:28:25 +00:00
=
afe14bc883 Merge branch 'feature/audio-rendering' of https://github.com/evalstate/inspector into feature/audio-rendering 2025-01-28 08:18:24 +00:00
Jerome
04faff4757 Merge branch 'main' into feature/audio-rendering 2025-01-28 02:15:55 -05:00
Ola Hungerford
a4469f7895 Add draft version of enhanced object input editing 2025-01-27 21:05:11 -07:00
Ola Hungerford
f980763381 Specify proxy server 2025-01-26 20:46:08 -07:00
Ola Hungerford
d754395a9a Revert tsx watch change 2025-01-26 20:36:31 -07:00
Ola Hungerford
df955cfdb5 Remove other logging and just keep listening and try catch 2025-01-26 20:24:59 -07:00
Ola Hungerford
5b884b55b5 Add server startup logging 2025-01-26 20:13:11 -07:00
Justin Spahr-Summers
0882a3e0e5 Formatting 2025-01-24 15:23:24 +00:00
Justin Spahr-Summers
fce6644e30 Fix double fetching 2025-01-24 15:22:40 +00:00
Justin Spahr-Summers
51ea4bc6ac Add toast when OAuth succeeds 2025-01-24 15:19:41 +00:00
Justin Spahr-Summers
0648ba44e3 Auto-reconnect after OAuth 2025-01-24 15:17:03 +00:00
Justin Spahr-Summers
c22f91858c Remember last selected transport and SSE URL 2025-01-24 15:04:22 +00:00
Justin Spahr-Summers
99d7592ac9 Fix error state being briefly shown before OAuth 2025-01-24 15:02:34 +00:00
Justin Spahr-Summers
3bc776f7cd Fix Vite config 2025-01-24 14:55:10 +00:00
Justin Spahr-Summers
a6d22cf1e4 Bump SDK version 2025-01-24 14:54:46 +00:00
Justin Spahr-Summers
731ee588c2 Fix Authorization header passthrough
Node.js headers are lowercase
2025-01-24 13:55:43 +00:00
Justin Spahr-Summers
af8877064e Set Authorization header from client 2025-01-24 13:55:32 +00:00
Justin Spahr-Summers
874320ebe6 Token exchange body needs to be JSON 2025-01-24 13:44:26 +00:00
Justin Spahr-Summers
e470eb5c51 Fix React import 2025-01-24 13:27:20 +00:00
Justin Spahr-Summers
02cfb47c83 Extract session storage keys into constants 2025-01-24 13:09:58 +00:00
Justin Spahr-Summers
23f89e49b8 Implement OAuth callback 2025-01-24 13:08:39 +00:00
Justin Spahr-Summers
16cb59670c OAuth callback handler (not yet attached) 2025-01-24 11:37:35 +00:00
Justin Spahr-Summers
1c4ad60354 Redirect into OAuth flow upon receiving 401 2025-01-24 11:34:07 +00:00
Justin Spahr-Summers
8a20f7711a Use new SseError class from SDK 2025-01-24 11:27:40 +00:00
Justin Spahr-Summers
8bb5308797 Report SSE 401 errors to the client 2025-01-24 11:04:44 +00:00
Justin Spahr-Summers
14db05c2a2 Clarify inspector-server error logging 2025-01-23 17:19:39 +00:00
Justin Spahr-Summers
e7697eb5cd Pass through Authorization headers sent to inspector server 2025-01-23 16:45:37 +00:00
Justin Spahr-Summers
c1e06c4af0 Server doesn't need to inject eventsource anymore 2025-01-23 16:45:12 +00:00
Justin Spahr-Summers
60b8892dd3 Pre-emptively bump npm package versions
Before I forget!
2025-01-23 16:30:19 +00:00
Justin Spahr-Summers
2b53a8399c Bump SDK 2025-01-23 16:29:43 +00:00
Justin Spahr-Summers
361f9d109b Merge pull request #128 from modelcontextprotocol/dependabot/npm_and_yarn/npm_and_yarn-f25c717a0f
Bump vite from 5.4.11 to 5.4.12 in the npm_and_yarn group across 1 directory
2025-01-22 12:02:57 +00:00
dependabot[bot]
7ec661e8bd Bump vite in the npm_and_yarn group across 1 directory
Bumps the npm_and_yarn group with 1 update in the / directory: [vite](https://github.com/vitejs/vite/tree/HEAD/packages/vite).


Updates `vite` from 5.4.11 to 5.4.12
- [Release notes](https://github.com/vitejs/vite/releases)
- [Changelog](https://github.com/vitejs/vite/blob/v5.4.12/packages/vite/CHANGELOG.md)
- [Commits](https://github.com/vitejs/vite/commits/v5.4.12/packages/vite)

---
updated-dependencies:
- dependency-name: vite
  dependency-type: direct:development
  dependency-group: npm_and_yarn
...

Signed-off-by: dependabot[bot] <support@github.com>
2025-01-22 04:50:31 +00:00
Jack Steam
f8052dfcda Merge branch 'main' into bugfix/issue-114 2025-01-14 11:44:09 -07:00
Ashwin Bhat
98e6f0e5ec Merge pull request #124 from modelcontextprotocol/ashwin/envvar
allow passing env vars to server from command line
2025-01-13 12:11:25 -08:00
Ashwin Bhat
ec150eb8b4 prettier 2025-01-10 07:53:55 -08:00
Ashwin Bhat
052de8690d respond to PR feedback 2025-01-10 07:51:55 -08:00
Ashwin Bhat
a976aefb39 allow passing env vars to server from command line 2025-01-10 07:51:54 -08:00
Ashwin Bhat
5a5873277c Merge pull request #123 from modelcontextprotocol/ashwin/prettier
enforce prettier formatting
2025-01-10 07:28:29 -08:00
Ashwin Bhat
715936d747 run prettier 2025-01-09 11:01:35 -08:00
Ashwin Bhat
d973f58bef run prettier check in CI 2025-01-09 11:01:28 -08:00
Jack Steam
88ed9c088d Merge branch 'main' into bugfix/issue-114 2024-12-23 14:37:54 -07:00
David Soria Parra
1797fbfba8 Merge pull request #118 from modelcontextprotocol/ashwin/githublink
feat: add GitHub link to sidebar for bug reports and contributions
2024-12-20 10:57:01 +00:00
David Soria Parra
8f4013c42c Merge pull request #117 from modelcontextprotocol/ashwin/state
refactor: extract draggable pane and connection logic into hooks
2024-12-20 10:56:33 +00:00
David Soria Parra
1abb7ca59c Merge pull request #119 from modelcontextprotocol/ashwin/font
feat: use monospace font for all input fields in sidebar
2024-12-20 10:56:05 +00:00
Ashwin Bhat
dfb36e1792 feat: use monospace font for all input fields in sidebar
Makes command, arguments, URL and environment variables easier to read and edit.
2024-12-19 13:18:52 -08:00
Ashwin Bhat
ffc29663c8 fix: reduce theme selector width to 100px to prevent crowding with icon buttons 2024-12-19 13:17:16 -08:00
Ashwin Bhat
53226dd391 feat: add GitHub link to sidebar for bug reports and contributions 2024-12-19 13:06:00 -08:00
Jack Steam
243ee1a6b5 Merge branch 'main' into bugfix/issue-114 2024-12-19 08:24:44 -07:00
Ashwin Bhat
dc49d46baa refactor: extract draggable pane and connection logic into hooks
- Create useDraggablePane hook for history pane drag behavior
- Create useConnection hook for MCP client connection and requests
- Update App.tsx to use both hooks
2024-12-18 12:54:24 -08:00
Ashwin Bhat
ef32a8f289 Merge pull request #116 from modelcontextprotocol/claude/update-readme
feat: add help and debug links to sidebar
2024-12-18 09:14:31 -08:00
David Soria Parra
54e9957ec5 feat: add help and debug links to sidebar 2024-12-18 11:39:24 +00:00
Jack Steam
c78b0fbed6 Merge branch 'main' into bugfix/issue-114 2024-12-17 16:14:59 -07:00
Ashwin Bhat
7edde5001b Merge pull request #112 from modelcontextprotocol/devin/1734088716-fix-object-params
fix: properly handle object type parameters in tools
2024-12-17 14:50:23 -08:00
Jack Steam
0fa56e14d9 fix(server) Differentiate command resolution by platform 2024-12-17 16:49:55 -06:00
Devin AI
14bda1f030 chore: revert unrelated changes to TypeScript comments and formatting
- Reverted @ts-expect-error messages back to original text
- Removed unnecessary line breaks in placeholder and type properties
- Kept object parameter handling functionality intact

Co-Authored-By: ashwin@anthropic.com <ashwin@anthropic.com>
2024-12-13 12:12:33 +00:00
Devin AI
1f4d35f8a3 fix: properly handle object type parameters in tools
- Add special handling for object type parameters
- Parse JSON input for object parameters
- Maintain raw input if JSON parsing fails
- Fixes #110

Co-Authored-By: ashwin@anthropic.com <ashwin@anthropic.com>
2024-12-13 11:21:35 +00:00
Ashwin Bhat
eb70539958 Merge pull request #105 from devin-open-source/devin/1733551277-capability-negotiation
feat: implement capability negotiation for UI tabs
2024-12-09 03:56:58 -08:00
Jeffrey Ling
7878e1764a address comment 2024-12-09 04:52:15 -07:00
Jeffrey Ling
26f0cb3c8b merge conflict 2024-12-09 04:43:48 -07:00
Jeffrey Ling
8f40e052c1 Merge remote-tracking branch 'origin/main' into devin/1733551277-capability-negotiation 2024-12-09 04:31:45 -07:00
Jeffrey Ling
024f06c1b7 cleanup diffs 2024-12-09 04:29:30 -07:00
Devin AI
1ddc63b330 refactor: remove disabled state from Sampling and Roots tabs 2024-12-09 11:07:42 +00:00
Devin AI
27bd503240 fix: remove duplicate ServerCapabilities type declarations 2024-12-09 10:37:56 +00:00
Devin AI
b39c96de7c refactor: revert tab files to main and restore tab disabling 2024-12-09 10:36:56 +00:00
Devin AI
d857e1462b refactor: simplify capability handling and remove context provider
- Remove redundant useEffect for capability checking
- Remove CapabilityContext provider pattern
- Set default tab to first supported capability
- Add fallback UI for unsupported capabilities
- Delete unused contexts.ts file
2024-12-09 10:11:03 +00:00
Ashwin Bhat
2eae823d65 Merge pull request #107 from JensWallgren/tool-result-legacy-dark-fix
Add dark mode support for the legacy Tool Result display
2024-12-09 02:03:34 -08:00
David Soria Parra
79ba164fda Merge pull request #108 from 8enmann/ben/persist
feat: improve request history and tab persistence
2024-12-09 09:27:19 +00:00
Ben Mann
2f513df6c1 feat: improve request history and tab persistence
- Add failed requests to history with error messages for better debugging
- Persist selected tab in URL hash and restore on page load
- Fix formatting of timeout parameter parsing

🤖 Generated with Claude CLI.

Co-Authored-By: Claude <noreply@anthropic.com>
2024-12-08 21:15:34 +02:00
Jens Wallgren
ce68085e77 Add dark mode support for the legacy Tool Result display 2024-12-08 14:14:40 +01:00
devin-ai-integration[bot]
e96b3be159 feat: implement capability negotiation for UI tabs
- Add CapabilityContext to manage server capabilities
- Disable tabs when server doesn't support feature
- Show error message in tab content when capability missing
- Implements #85
2024-12-07 06:15:21 +00:00
Ashwin Bhat
034699524a Merge pull request #104 from devin-open-source/fix-shell-quote
Fix shell argument parsing issue: #96
2024-12-06 17:07:50 -08:00
Jeffrey Ling
fdc521646f no need to prettier format everything right now 2024-12-06 12:48:48 -07:00
devin-ai-integration[bot]
bd6586bbad style: apply prettier formatting 2024-12-06 19:43:48 +00:00
devin-ai-integration[bot]
c340e5f1ed chore: move shell-quote to main dependencies 2024-12-06 19:43:11 +00:00
devin-ai-integration[bot]
cc1ae05f9d fix: use shell-quote for proper argument parsing 2024-12-06 19:34:03 +00:00
devin-ai-integration[bot]
9ea77a729c chore: add shell-quote package and types 2024-12-06 19:33:08 +00:00
Ashwin Bhat
8c7b0c360e Merge pull request #103 from evalstate/fix/tool-tab-parameters
Tool Tab - Parameter Handling Fixes.
2024-12-05 17:51:05 -08:00
evalstate
35effc4d16 Merge branch 'main' into feature/audio-rendering 2024-12-05 19:50:21 +00:00
Ashwin Bhat
576ff0043a bump version to 0.3.0 2024-12-05 08:01:57 -08:00
Ashwin Bhat
18dc4d0a99 Merge pull request #100 from evalstate/fix/tool-timeout
Allow setting the timeout with the "timeout" URL parameter
2024-12-05 07:59:55 -08:00
evalstate
ed5017d73e Two fixes to the Tools Tab:
1) Tool Parameters were stale when switching between Tools causing incorrect messages to be sent.
2) Tool List is emptied when "Clear" is selected, so invalid messages can't be sent.
2024-12-05 15:32:55 +00:00
=
f04b161411 Allow setting timeout via "timeout" URL parameter 2024-12-05 08:11:35 +00:00
Ashwin Bhat
bd6a63603a Merge pull request #102 from modelcontextprotocol/ashwin/sdk
update sdk to 1.0.3
2024-12-04 14:20:09 -08:00
Ashwin Bhat
b845444fab update sdk to 1.0.3 2024-12-04 09:56:04 -08:00
evalstate
14802b8043 Merge branch 'main' into feature/audio-rendering 2024-12-03 17:11:47 +00:00
Justin Spahr-Summers
ace94c4d37 Merge pull request #95 from modelcontextprotocol/ashwin-ant-patch-1
link to MCP docs site in readme
2024-12-02 06:56:07 -06:00
Ashwin Bhat
50640bc9cc Merge pull request #98 from heuperman/add-button-to-clear-items
Add button to clear loaded items
2024-12-01 11:08:32 -05:00
=
068d21387a extended type for "audio" update to spec 2024-12-01 12:47:50 +00:00
=
66b1b73448 Render HTML5 Audio Player if Tool Result resource mimetype is audio. 2024-12-01 10:24:12 +00:00
Kees Heuperman
cc17ba8d56 feat: Add button to clear loaded items
Add a button to the ListPane component that clears loaded items. This
will allow the user to clear and reload resources, resource templates,
prompts or tools when they expect the available items to have changed.
2024-12-01 09:50:53 +01:00
Ashwin Bhat
764f02310d link to MCP docs site in readme 2024-11-29 16:26:56 -05:00
Ashwin Bhat
945299181d bump version to 0.2.7 2024-11-29 08:44:12 -05:00
David Soria Parra
79344bd495 Merge pull request #91 from modelcontextprotocol/ashwin/spawnfix
fix arg passing
2024-11-29 11:34:25 +00:00
Ashwin Bhat
295ccac27e fix arg passing 2024-11-27 19:17:47 -05:00
Ashwin Bhat
f3f424f21e bump version 2024-11-27 17:29:02 -05:00
Ashwin Bhat
6b6eeb8dcd bump version to 0.2.5 2024-11-27 17:24:19 -05:00
Ashwin Bhat
3110cf9343 Merge pull request #88 from modelcontextprotocol/ani/fix-npx
Enable using 'npx' as your command on Windows
2024-11-27 16:03:37 -05:00
Ani Betts
2c04fa31e8 Merge branch 'main' into ani/fix-npx 2024-11-27 21:57:44 +01:00
Ashwin Bhat
e700bc713a Merge pull request #87 from modelcontextprotocol/ashwin/versiondisplay
display inspector version in UI
2024-11-27 13:06:52 -05:00
Ashwin Bhat
bea86af65b Merge pull request #89 from evalstate/main
Dark Mode and Word Wrap for Resource Viewer
2024-11-27 13:06:06 -05:00
evalstate
68a6130b17 fix dark mode styling and add word wrap for resource viewer. 2024-11-27 17:56:22 +00:00
Ani Betts
853a3b4faf Enable using 'npx' as your command on Windows 2024-11-27 17:04:52 +01:00
Ashwin Bhat
6f62066d34 display inspector version in UI 2024-11-27 10:52:38 -05:00
ashwin-ant
c770d217e7 Merge pull request #86 from modelcontextprotocol/ani/debuggability
Make debugging Inspector easier for users
2024-11-27 10:04:00 -05:00
Ani Betts
98470a12f9 Make stdout/error echo for client and server 2024-11-27 15:57:02 +01:00
Ani Betts
a00564fafa Disable minification on production build, we don't need it here and it makes debugging annoying 2024-11-27 15:55:11 +01:00
Ashwin Bhat
62546dec58 bump version to 0.2.4 2024-11-27 09:33:15 -05:00
ashwin-ant
886ac5fc7b Merge pull request #81 from modelcontextprotocol/ashwin/serverport
Respect custom server port
2024-11-27 08:59:59 -05:00
ashwin-ant
722df4d798 Merge pull request #82 from jacksteamdev/fix-1
Add Runtime Type Validation for Tool Results
2024-11-26 15:32:58 -05:00
Jack Steam
407e304585 Merge branch 'main' into fix-1 2024-11-26 13:31:12 -07:00
Jack Steam
60578314aa Update client/src/components/ToolsTab.tsx
Co-authored-by: ashwin-ant <ashwin@anthropic.com>
2024-11-26 13:30:43 -07:00
Ashwin Bhat
3c4cb17d09 bump to 0.2.3 2024-11-26 14:14:19 -05:00
Jack Steam
fbac5b78bc feat: add data validation message 2024-11-26 12:47:39 -06:00
Ashwin Bhat
f876b1ec0d consolidate server URL configuration 2024-11-26 13:40:28 -05:00
Jack Steam
aecfa21d47 fix: add static type validation 2024-11-26 11:14:55 -07:00
Ashwin Bhat
a3d542c0a3 make server port configurable via URL query param 2024-11-26 13:12:45 -05:00
Ani Betts
2b79b6ffd4 Merge pull request #79 from modelcontextprotocol/ani/fix-windows
Fix launch issues on Windows
2024-11-26 18:12:48 +01:00
Ani Betts
1f28b4474c Don't eat the env, add PORT 2024-11-26 18:08:43 +01:00
Anaïs Betts
d69d67cb64 Fix server args 2024-11-26 17:33:22 +01:00
Anaïs Betts
7792070d81 Add debugging 2024-11-26 17:18:33 +01:00
Anaïs Betts
34a2843756 resolve usually better than join 2024-11-26 17:11:32 +01:00
Anaïs Betts
2a34770959 Don't 🔥 the hello message 2024-11-26 17:06:56 +01:00
Anaïs Betts
6b674b0827 Version bump MCP SDK to latest 2024-11-26 17:02:39 +01:00
Anaïs Betts
ca8db1f417 Handle spawning the client and server on Windows using correct paths 2024-11-26 17:02:39 +01:00
Anaïs Betts
eb4456d1e3 Add spawn-rx 2024-11-26 16:52:22 +01:00
Anaïs Betts
780b92274d Make tailwind config work on Windows 2024-11-26 16:51:50 +01:00
ashwin-ant
b825784b8f Merge pull request #75 from modelcontextprotocol/readmeupdate
clarify readme
2024-11-25 14:01:07 -08:00
Ashwin Bhat
52c7e98055 clarify readme 2024-11-25 17:00:04 -05:00
ashwin-ant
4862aa7c1d Merge pull request #74 from simonw/patch-1
Skip the dist/index.js bit
2024-11-25 13:58:02 -08:00
Simon Willison
561ea91504 Skip the dist/index.js bit
The `dist/index.js` bit is confusing. Running without that gives you a working web UI.
2024-11-25 10:26:35 -08:00
Ashwin Bhat
7c2be8d139 bump version to 0.2.2 2024-11-25 10:35:26 -05:00
ashwin-ant
97d469911e Merge pull request #73 from modelcontextprotocol/ashwin/darkmodetoggle
make theme selectable in UI, store setting in localstorage
2024-11-25 06:24:59 -08:00
Ashwin Bhat
11b891c6ca make theme selectable in UI 2024-11-25 09:23:26 -05:00
Justin Spahr-Summers
5139e723a4 Bump package versions 2024-11-25 07:20:05 -06:00
Justin Spahr-Summers
fc5b79c9a6 Merge pull request #72 from modelcontextprotocol/ashwin/darkmodetool
more dark mode fixes
2024-11-24 16:37:52 -06:00
Ashwin Bhat
47a87e1884 more dark mode fixes 2024-11-24 14:26:39 -08:00
Justin Spahr-Summers
d567ff37e8 Merge pull request #70 from modelcontextprotocol/ashwin/errorlog
show server stderr in inspector UI
2024-11-21 10:43:03 +00:00
Justin Spahr-Summers
2e4eedc6ef Add publish workflow 2024-11-21 10:41:25 +00:00
Justin Spahr-Summers
56ec9befd9 Add publish-all script 2024-11-21 10:40:10 +00:00
Justin Spahr-Summers
360d090ac9 Fix inconsistent capitalization 2024-11-21 10:31:01 +00:00
Justin Spahr-Summers
fda05836cb Merge branch 'main' into ashwin/errorlog 2024-11-21 10:30:29 +00:00
Justin Spahr-Summers
dac692e638 Fix type errors in server 2024-11-21 10:29:36 +00:00
Justin Spahr-Summers
7e4b276f7f Bump versions 2024-11-21 10:29:28 +00:00
Justin Spahr-Summers
668448b047 Merge pull request #71 from modelcontextprotocol/ashwin/tabs
remove unused tabs
2024-11-21 10:22:54 +00:00
Ashwin Bhat
4352c93660 remove unused tabs 2024-11-20 19:06:26 -08:00
Ashwin Bhat
22bf78720b show server stderr in inspector UI 2024-11-20 18:13:54 -08:00
Ashwin Bhat
9196c1ddaf update sdk 2024-11-20 18:09:16 -08:00
ashwin-ant
dfc10488b2 Merge pull request #69 from modelcontextprotocol/ashwin/darkmode
dark mode fixes
2024-11-20 14:10:57 -08:00
Ashwin Bhat
78182eab10 dark mode fixes 2024-11-20 11:25:06 -08:00
Justin Spahr-Summers
7dbaee47a2 Merge pull request #68 from modelcontextprotocol/justin/contributing
Add CONTRIBUTING.md
2024-11-20 16:12:06 +00:00
Justin Spahr-Summers
03193a9dc4 Merge pull request #67 from modelcontextprotocol/justin/update-readme
Update README instructions
2024-11-20 16:11:37 +00:00
Justin Spahr-Summers
60dea9a868 Clarify testing and submission steps 2024-11-20 16:02:21 +00:00
Justin Spahr-Summers
1341d73775 Fix issues link 2024-11-20 16:00:03 +00:00
Justin Spahr-Summers
f73770b143 Merge pull request #66 from modelcontextprotocol/justin/fix-homepage
Fix packages' homepage URL
2024-11-20 15:59:29 +00:00
ashwin-ant
33ab8dbd97 Merge pull request #65 from modelcontextprotocol/ashwin/startup
improve inspector startup message
2024-11-20 07:55:29 -08:00
Justin Spahr-Summers
2d5c866f82 Add CONTRIBUTING.md 2024-11-20 15:26:05 +00:00
Justin Spahr-Summers
232d5ffcf6 Update README instructions 2024-11-20 14:48:02 +00:00
Justin Spahr-Summers
4f930a61ab Fix packages' homepage URL 2024-11-20 13:53:33 +00:00
Ashwin Bhat
f684d2e891 improve inspector startup message 2024-11-19 16:58:33 -08:00
ashwin-ant
676de45bab Merge pull request #64 from modelcontextprotocol/ashwin/spaces
fix arg passing in cli
2024-11-19 15:46:17 -08:00
Ashwin Bhat
9a560e3f06 handle quotes better 2024-11-19 15:42:53 -08:00
ashwin-ant
64d2fea0f1 Merge pull request #62 from modelcontextprotocol/ashwin/defaults
add back default command and args
2024-11-19 14:50:41 -08:00
Ashwin Bhat
1843562dce bump version 2024-11-19 14:22:00 -08:00
ashwin-ant
31630b2870 Merge pull request #63 from modelcontextprotocol/ashwin/favicon
switch favicon
2024-11-19 14:21:42 -08:00
Ashwin Bhat
7c04df5e2e fix arg passing in cli 2024-11-19 14:19:59 -08:00
Ashwin Bhat
f8e26479d9 switch favicon 2024-11-19 14:13:19 -08:00
Ashwin Bhat
0c6b1ad1d2 add back default command and args 2024-11-19 13:30:04 -08:00
ashwin-ant
b97acb9b76 Merge pull request #61 from modelcontextprotocol/ashwin/npx
make inspector runnable via npx
2024-11-19 13:27:57 -08:00
Ashwin Bhat
1b06e50203 use published versions of subpackages 2024-11-19 13:19:21 -08:00
Ashwin Bhat
83abe4e00f command 2024-11-19 13:08:42 -08:00
Ashwin Bhat
75bc2d3f26 bump version 2024-11-19 11:51:01 -08:00
Ashwin Bhat
b127ba177a fix arg 2024-11-19 11:50:45 -08:00
Ashwin Bhat
ce350433f9 bump version 2024-11-19 11:42:32 -08:00
Ashwin Bhat
c1a56810fb pass in args 2024-11-19 11:42:16 -08:00
Ashwin Bhat
abff2486c1 deps 2024-11-19 11:42:16 -08:00
David Soria Parra
b096f3f991 Update SECURITY.md 2024-11-19 16:49:04 +00:00
David Soria Parra
e97ec8dbc7 Merge pull request #60 from modelcontextprotocol/dsp-ant-patch-1
Update SECURITY.md
2024-11-19 12:16:05 +00:00
David Soria Parra
05c22f6367 Update SECURITY.md 2024-11-19 12:15:55 +00:00
David Soria Parra
3b3a7e6015 Create SECURITY.md 2024-11-19 12:13:49 +00:00
David Soria Parra
8986c32bb4 Update LICENSE 2024-11-18 22:24:35 +00:00
David Soria Parra
69b25300da Merge pull request #59 from modelcontextprotocol/davidsp/coc
Add code of conduct
2024-11-18 16:02:29 +00:00
David Soria Parra
6e72c7583e Add code of conduct 2024-11-18 15:32:16 +00:00
Justin Spahr-Summers
d1c9acffc2 Merge pull request #58 from modelcontextprotocol/justin/upgrade-sdk
Upgrade to SDK 0.5.0, add default request timeout
2024-11-16 16:02:54 +00:00
Justin Spahr-Summers
d91d7e8ae0 Add default request timeout 2024-11-16 15:54:08 +00:00
Justin Spahr-Summers
6c27f5a263 Upgrade to SDK 0.5.0 2024-11-16 15:25:02 +00:00
Justin Spahr-Summers
2bf84a3ef3 Merge pull request #57 from modelcontextprotocol/justin/fix-env-vars
Fix typing environment variable keys
2024-11-14 09:54:19 +00:00
Justin Spahr-Summers
8aad8b4aac Fix typing environment variable keys 2024-11-13 21:00:20 +00:00
Justin Spahr-Summers
06267d28f4 Merge pull request #52 from modelcontextprotocol/justin/tab-specific-errors
Separate error states per tab, clear errors when clicking around
2024-11-12 15:44:15 +00:00
Justin Spahr-Summers
c1c8fc2f42 Use clearError in makeRequest 2024-11-12 15:42:23 +00:00
Justin Spahr-Summers
7a350785fe Merge branch 'main' into justin/tab-specific-errors 2024-11-12 15:40:57 +00:00
Justin Spahr-Summers
41f8ec0868 Merge pull request #53 from modelcontextprotocol/justin/server-connection-errors
Fix server dying when an error occurs
2024-11-12 15:31:36 +00:00
Justin Spahr-Summers
09d66ab704 Merge pull request #55 from modelcontextprotocol/justin/multiline-tool-inputs
Support multiline tool inputs
2024-11-12 15:31:30 +00:00
Justin Spahr-Summers
e4faa19acb Merge pull request #54 from modelcontextprotocol/justin/redo-sidebars
Revamp UI + panes
2024-11-12 15:31:21 +00:00
Justin Spahr-Summers
f7385dd961 Support multiline tool inputs
Resolves #39.
2024-11-12 14:59:36 +00:00
Justin Spahr-Summers
54012aca6a Make bottom pane resizable 2024-11-12 14:43:56 +00:00
Justin Spahr-Summers
0cf344bb6a Move "history and notifications" pane to bottom 2024-11-12 14:35:53 +00:00
Justin Spahr-Summers
a507bafc3e Remove big header in main pane 2024-11-12 14:28:56 +00:00
Justin Spahr-Summers
93b1ec4d61 Move connection settings UI into left sidebar 2024-11-12 14:27:02 +00:00
Justin Spahr-Summers
bf2ddc9b7b Fix server dying when an error occurs
Resolves #34.
2024-11-12 14:02:23 +00:00
Justin Spahr-Summers
da2ac8d423 Clear error states when clicking around 2024-11-12 13:51:00 +00:00
Justin Spahr-Summers
3bae26723a Use toasts for errors unassociated with a tab 2024-11-12 13:50:59 +00:00
Justin Spahr-Summers
9d0c643926 Install react-toastify 2024-11-12 13:50:59 +00:00
Justin Spahr-Summers
0716adafc6 Remove unused RequestsTab 2024-11-12 13:50:59 +00:00
Justin Spahr-Summers
733d2a6e6e Separate error states per tab
Resolves #40.
2024-11-12 13:50:59 +00:00
Justin Spahr-Summers
ab9c130610 Merge pull request #50 from modelcontextprotocol/justin/fix-dark-mode
Marginally better dark mode support
2024-11-12 13:46:24 +00:00
Justin Spahr-Summers
3e46011614 Marginally better dark mode support 2024-11-12 12:34:10 +00:00
Justin Spahr-Summers
584c1076a4 Merge pull request #49 from modelcontextprotocol/justin/fix-paths
Remove example paths now that SDK pathing works better
2024-11-11 19:45:13 +00:00
Justin Spahr-Summers
de9ee3956e Remove example paths now that SDK pathing works better 2024-11-11 17:45:07 +00:00
Justin Spahr-Summers
01fb48e6ef Merge pull request #48 from modelcontextprotocol/jspahrsummers-patch-1
Update setup instructions in README
2024-11-11 16:36:59 +00:00
Justin Spahr-Summers
5ceaa48cf3 Update setup instructions in README 2024-11-11 16:36:42 +00:00
Justin Spahr-Summers
6fdb2903a4 Merge pull request #47 from modelcontextprotocol/justin/pull-from-npm
Pull SDK from npm
2024-11-11 16:33:22 +00:00
Justin Spahr-Summers
b9d6695fbf Revert "Try restoring npm ci"
This reverts commit 3789ef984a.
2024-11-11 16:31:24 +00:00
Justin Spahr-Summers
3789ef984a Try restoring npm ci 2024-11-11 16:29:09 +00:00
Justin Spahr-Summers
e1aa419332 Pull SDK from npm 2024-11-11 16:28:51 +00:00
David Soria Parra
94e4e92618 Merge pull request #45 from modelcontextprotocol/davidsp/fix-capture 2024-11-11 12:33:27 +00:00
Justin Spahr-Summers
148e84388a Merge pull request #46 from modelcontextprotocol/justin/oss-prep
Add license and package metadata
2024-11-11 12:22:32 +00:00
Justin Spahr-Summers
6147640656 Remove client prepare script 2024-11-11 12:19:14 +00:00
Justin Spahr-Summers
1ddd2d7aaa Disallow publishing root package for now 2024-11-11 12:15:52 +00:00
Justin Spahr-Summers
94ddfed1ac Add concurrently dependency 2024-11-11 11:24:21 +00:00
Justin Spahr-Summers
448910d986 Make nested packages private, just install root package 2024-11-11 11:20:53 +00:00
Justin Spahr-Summers
3a9b08bd37 Pick non-conflicting default client port 2024-11-11 11:11:27 +00:00
Justin Spahr-Summers
bce3a7b8d6 Make root package installable/executable 2024-11-11 11:10:42 +00:00
Justin Spahr-Summers
196f2f801d Use serve to create npm package for the client 2024-11-11 11:04:42 +00:00
Justin Spahr-Summers
a0d8ec1e7e Make server executable on its own 2024-11-11 10:41:07 +00:00
Justin Spahr-Summers
6759c461f9 Add license and more package metadata 2024-11-11 10:37:09 +00:00
David Soria Parra
ea4484cc04 Fix bug that roots returned by roots/list are never updated
The roots state is capture at the initialization of the connectMcpServer.
This causes roots/list to always return empty roots despite updates
to the roots. We are now using a ref to reference it and avoid the closure
issue. roots/list now returns correctly the roots.
2024-11-10 23:45:38 +00:00
Justin Spahr-Summers
171b59bec6 Merge pull request #44 from modelcontextprotocol/justin/update-sdk
Update SDK; add UI for roots, resource templates, and env vars
2024-11-08 12:06:06 +00:00
Justin Spahr-Summers
2867173e7b Record 'roots list changed' notifications in history sidebar 2024-11-08 12:04:45 +00:00
Justin Spahr-Summers
57f0c49154 Remove redundant useCallbacks 2024-11-08 12:00:46 +00:00
Justin Spahr-Summers
5337baa116 Fix type error 2024-11-07 15:35:55 +00:00
Justin Spahr-Summers
afefcb3fa5 Make env vars UI toggleable 2024-11-07 15:28:21 +00:00
Justin Spahr-Summers
76e2cf6fdc Add UI for viewing and configuring environment variables 2024-11-07 15:28:21 +00:00
Justin Spahr-Summers
193032533b Support structured tool results 2024-11-07 15:28:21 +00:00
Justin Spahr-Summers
f3406ca43d Basic support for roots 2024-11-07 14:27:46 +00:00
Justin Spahr-Summers
645f2e942e Add support for listing and filling resource templates 2024-11-07 14:02:53 +00:00
Justin Spahr-Summers
d80214d0a2 Update SDK to 0.3.2 2024-11-07 13:46:21 +00:00
David Soria Parra
97b67ca1ae Merge pull request #43 from modelcontextprotocol/davidsp/prettier
run prettier
2024-11-05 10:40:07 +00:00
David Soria Parra
216c8a15d5 run prettier 2024-11-04 21:29:59 +00:00
104 changed files with 14215 additions and 2795 deletions

View File

@@ -4,6 +4,8 @@ on:
- main
pull_request:
release:
types: [published]
jobs:
build:
@@ -12,26 +14,53 @@ jobs:
steps:
- uses: actions/checkout@v4
- name: Check formatting
run: npx prettier --check .
- uses: actions/setup-node@v4
with:
node-version: 18
cache: npm
# Working around https://github.com/npm/cli/issues/4828
# - run: npm ci
- run: npm install --no-package-lock
- name: Check linting
working-directory: ./client
run: npm run lint
- name: Run client tests
working-directory: ./client
run: npm test
- run: npm run build
publish:
runs-on: ubuntu-latest
if: github.event_name == 'release'
environment: release
needs: build
permissions:
contents: read
id-token: write
steps:
- uses: actions/checkout@v4
- uses: actions/setup-node@v4
with:
repository: modelcontextprotocol/typescript-sdk
ssh-key: ${{ secrets.TYPESCRIPT_SDK_KEY }}
path: packages/@modelcontextprotocol/sdk
- run: npm ci
working-directory: packages/@modelcontextprotocol/sdk
- run: npm pack
working-directory: packages/@modelcontextprotocol/sdk
- run: npm install --save packages/@modelcontextprotocol/sdk/modelcontextprotocol-sdk-*.tgz
node-version: 18
cache: npm
registry-url: "https://registry.npmjs.org"
# Working around https://github.com/npm/cli/issues/4828
# - run: npm ci
- run: npm install --no-package-lock
- run: npm run build
# TODO: Add --provenance once the repo is public
- run: npm run publish-all
env:
NODE_AUTH_TOKEN: ${{ secrets.NPM_TOKEN }}

7
.gitignore vendored
View File

@@ -1,6 +1,11 @@
.DS_Store
node_modules
.vscode
.idea
node_modules/
*-workspace/
server/build
client/dist
client/tsconfig.app.tsbuildinfo
client/tsconfig.node.tsbuildinfo
cli/build
test-output

3
.npmrc
View File

@@ -1 +1,2 @@
registry = "https://registry.npmjs.org/"
registry="https://registry.npmjs.org/"
@modelcontextprotocol:registry="https://registry.npmjs.org/"

View File

@@ -1,2 +1,4 @@
packages
server/build
CODE_OF_CONDUCT.md
SECURITY.md

33
CLAUDE.md Normal file
View File

@@ -0,0 +1,33 @@
# MCP Inspector Development Guide
## Build Commands
- Build all: `npm run build`
- Build client: `npm run build-client`
- Build server: `npm run build-server`
- Development mode: `npm run dev` (use `npm run dev:windows` on Windows)
- Format code: `npm run prettier-fix`
- Client lint: `cd client && npm run lint`
## Code Style Guidelines
- Use TypeScript with proper type annotations
- Follow React functional component patterns with hooks
- Use ES modules (import/export) not CommonJS
- Use Prettier for formatting (auto-formatted on commit)
- Follow existing naming conventions:
- camelCase for variables and functions
- PascalCase for component names and types
- kebab-case for file names
- Use async/await for asynchronous operations
- Implement proper error handling with try/catch blocks
- Use Tailwind CSS for styling in the client
- Keep components small and focused on a single responsibility
## Project Organization
The project is organized as a monorepo with workspaces:
- `client/`: React frontend with Vite, TypeScript and Tailwind
- `server/`: Express backend with TypeScript
- `bin/`: CLI scripts

128
CODE_OF_CONDUCT.md Normal file
View File

@@ -0,0 +1,128 @@
# Contributor Covenant Code of Conduct
## Our Pledge
We as members, contributors, and leaders pledge to make participation in our
community a harassment-free experience for everyone, regardless of age, body
size, visible or invisible disability, ethnicity, sex characteristics, gender
identity and expression, level of experience, education, socio-economic status,
nationality, personal appearance, race, religion, or sexual identity
and orientation.
We pledge to act and interact in ways that contribute to an open, welcoming,
diverse, inclusive, and healthy community.
## Our Standards
Examples of behavior that contributes to a positive environment for our
community include:
* Demonstrating empathy and kindness toward other people
* Being respectful of differing opinions, viewpoints, and experiences
* Giving and gracefully accepting constructive feedback
* Accepting responsibility and apologizing to those affected by our mistakes,
and learning from the experience
* Focusing on what is best not just for us as individuals, but for the
overall community
Examples of unacceptable behavior include:
* The use of sexualized language or imagery, and sexual attention or
advances of any kind
* Trolling, insulting or derogatory comments, and personal or political attacks
* Public or private harassment
* Publishing others' private information, such as a physical or email
address, without their explicit permission
* Other conduct which could reasonably be considered inappropriate in a
professional setting
## Enforcement Responsibilities
Community leaders are responsible for clarifying and enforcing our standards of
acceptable behavior and will take appropriate and fair corrective action in
response to any behavior that they deem inappropriate, threatening, offensive,
or harmful.
Community leaders have the right and responsibility to remove, edit, or reject
comments, commits, code, wiki edits, issues, and other contributions that are
not aligned to this Code of Conduct, and will communicate reasons for moderation
decisions when appropriate.
## Scope
This Code of Conduct applies within all community spaces, and also applies when
an individual is officially representing the community in public spaces.
Examples of representing our community include using an official e-mail address,
posting via an official social media account, or acting as an appointed
representative at an online or offline event.
## Enforcement
Instances of abusive, harassing, or otherwise unacceptable behavior may be
reported to the community leaders responsible for enforcement at
mcp-coc@anthropic.com.
All complaints will be reviewed and investigated promptly and fairly.
All community leaders are obligated to respect the privacy and security of the
reporter of any incident.
## Enforcement Guidelines
Community leaders will follow these Community Impact Guidelines in determining
the consequences for any action they deem in violation of this Code of Conduct:
### 1. Correction
**Community Impact**: Use of inappropriate language or other behavior deemed
unprofessional or unwelcome in the community.
**Consequence**: A private, written warning from community leaders, providing
clarity around the nature of the violation and an explanation of why the
behavior was inappropriate. A public apology may be requested.
### 2. Warning
**Community Impact**: A violation through a single incident or series
of actions.
**Consequence**: A warning with consequences for continued behavior. No
interaction with the people involved, including unsolicited interaction with
those enforcing the Code of Conduct, for a specified period of time. This
includes avoiding interactions in community spaces as well as external channels
like social media. Violating these terms may lead to a temporary or
permanent ban.
### 3. Temporary Ban
**Community Impact**: A serious violation of community standards, including
sustained inappropriate behavior.
**Consequence**: A temporary ban from any sort of interaction or public
communication with the community for a specified period of time. No public or
private interaction with the people involved, including unsolicited interaction
with those enforcing the Code of Conduct, is allowed during this period.
Violating these terms may lead to a permanent ban.
### 4. Permanent Ban
**Community Impact**: Demonstrating a pattern of violation of community
standards, including sustained inappropriate behavior, harassment of an
individual, or aggression toward or disparagement of classes of individuals.
**Consequence**: A permanent ban from any sort of public interaction within
the community.
## Attribution
This Code of Conduct is adapted from the [Contributor Covenant][homepage],
version 2.0, available at
https://www.contributor-covenant.org/version/2/0/code_of_conduct.html.
Community Impact Guidelines were inspired by [Mozilla's code of conduct
enforcement ladder](https://github.com/mozilla/diversity).
[homepage]: https://www.contributor-covenant.org
For answers to common questions about this code of conduct, see the FAQ at
https://www.contributor-covenant.org/faq. Translations are available at
https://www.contributor-covenant.org/translations.

37
CONTRIBUTING.md Normal file
View File

@@ -0,0 +1,37 @@
# Contributing to Model Context Protocol Inspector
Thanks for your interest in contributing! This guide explains how to get involved.
## Getting Started
1. Fork the repository and clone it locally
2. Install dependencies with `npm install`
3. Run `npm run dev` to start both client and server in development mode
4. Use the web UI at http://127.0.0.1:6274 to interact with the inspector
## Development Process & Pull Requests
1. Create a new branch for your changes
2. Make your changes following existing code style and conventions. You can run `npm run prettier-check` and `npm run prettier-fix` as applicable.
3. Test changes locally by running `npm test`
4. Update documentation as needed
5. Use clear commit messages explaining your changes
6. Verify all changes work as expected
7. Submit a pull request
8. PRs will be reviewed by maintainers
## Code of Conduct
This project follows our [Code of Conduct](CODE_OF_CONDUCT.md). Please read it before contributing.
## Security
If you find a security vulnerability, please refer to our [Security Policy](SECURITY.md) for reporting instructions.
## Questions?
Feel free to [open an issue](https://github.com/modelcontextprotocol/mcp-inspector/issues) for questions or create a discussion for general topics.
## License
By contributing, you agree that your contributions will be licensed under the MIT license.

21
LICENSE Normal file
View File

@@ -0,0 +1,21 @@
MIT License
Copyright (c) 2024 Anthropic, PBC
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in all
copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
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.

162
README.md
View File

@@ -2,30 +2,172 @@
The MCP inspector is a developer tool for testing and debugging MCP servers.
## Getting started
![MCP Inspector Screenshot](https://raw.githubusercontent.com/modelcontextprotocol/inspector/main/mcp-inspector.png)
This repository depends on the [MCP TypeScript SDK](https://github.com/modelcontextprotocol/typescript-sdk/). Until these repositories are made public and published to npm, the SDK has to be preinstalled manually:
## Running the Inspector
1. Download the [latest release of the SDK](https://github.com/modelcontextprotocol/typescript-sdk/releases) (the file named something like `modelcontextprotocol-sdk-0.1.0.tgz`). You don't need to extract it.
2. From within your checkout of _this_ repository, run `npm install --save path/to/sdk.tgz`. This will overwrite the expected location for the SDK to allow you to proceed.
### Requirements
Then, you should be able to install the rest of the dependencies normally:
- Node.js: ^22.7.5
```sh
npm install
### From an MCP server repository
To inspect an MCP server implementation, there's no need to clone this repo. Instead, use `npx`. For example, if your server is built at `build/index.js`:
```bash
npx @modelcontextprotocol/inspector node build/index.js
```
You can run it in dev mode via:
You can pass both arguments and environment variables to your MCP server. Arguments are passed directly to your server, while environment variables can be set using the `-e` flag:
```bash
# Pass arguments only
npx @modelcontextprotocol/inspector node build/index.js arg1 arg2
# Pass environment variables only
npx @modelcontextprotocol/inspector -e key=value -e key2=$VALUE2 node build/index.js
# Pass both environment variables and arguments
npx @modelcontextprotocol/inspector -e key=value -e key2=$VALUE2 node build/index.js arg1 arg2
# Use -- to separate inspector flags from server arguments
npx @modelcontextprotocol/inspector -e key=$VALUE -- node build/index.js -e server-flag
```
The inspector runs both an MCP Inspector (MCPI) client UI (default port 6274) and an MCP Proxy (MCPP) server (default port 6277). Open the MCPI client UI in your browser to use the inspector. (These ports are derived from the T9 dialpad mapping of MCPI and MCPP respectively, as a mnemonic). You can customize the ports if needed:
```bash
CLIENT_PORT=8080 SERVER_PORT=9000 npx @modelcontextprotocol/inspector node build/index.js
```
For more details on ways to use the inspector, see the [Inspector section of the MCP docs site](https://modelcontextprotocol.io/docs/tools/inspector). For help with debugging, see the [Debugging guide](https://modelcontextprotocol.io/docs/tools/debugging).
### Authentication
The inspector supports bearer token authentication for SSE connections. Enter your token in the UI when connecting to an MCP server, and it will be sent in the Authorization header. You can override the header name using the input field in the sidebar.
### Security Considerations
The MCP Inspector includes a proxy server that can run and communicate with local MCP processes. The proxy server should not be exposed to untrusted networks as it has permissions to spawn local processes and can connect to any specified MCP server.
### Configuration
The MCP Inspector supports the following configuration settings. To change them, click on the `Configuration` button in the MCP Inspector UI:
| Setting | Description | Default |
| --------------------------------------- | ------------------------------------------------------------------------------------------------------------ | ------- |
| `MCP_SERVER_REQUEST_TIMEOUT` | Timeout for requests to the MCP server (ms) | 10000 |
| `MCP_REQUEST_TIMEOUT_RESET_ON_PROGRESS` | Reset timeout on progress notifications | true |
| `MCP_REQUEST_MAX_TOTAL_TIMEOUT` | Maximum total timeout for requests sent to the MCP server (ms) (Use with progress notifications) | 60000 |
| `MCP_PROXY_FULL_ADDRESS` | Set this if you are running the MCP Inspector Proxy on a non-default address. Example: http://10.1.1.22:5577 | "" |
These settings can be adjusted in real-time through the UI and will persist across sessions.
The inspector also supports configuration files to store settings for different MCP servers. This is useful when working with multiple servers or complex configurations:
```bash
npx @modelcontextprotocol/inspector --config path/to/config.json --server everything
```
Example server configuration file:
```json
{
"mcpServers": {
"everything": {
"command": "npx",
"args": ["@modelcontextprotocol/server-everything"],
"env": {
"hello": "Hello MCP!"
}
},
"my-server": {
"command": "node",
"args": ["build/index.js", "arg1", "arg2"],
"env": {
"key": "value",
"key2": "value2"
}
}
}
}
```
### From this repository
If you're working on the inspector itself:
Development mode:
```bash
npm run dev
```
This will start both the client and server.
> **Note for Windows users:**
> On Windows, use the following command instead:
>
> ```bash
> npm run dev:windows
> ```
To run in production mode:
Production mode:
```bash
npm run build
npm start
```
### CLI Mode
CLI mode enables programmatic interaction with MCP servers from the command line, ideal for scripting, automation, and integration with coding assistants. This creates an efficient feedback loop for MCP server development.
```bash
npx @modelcontextprotocol/inspector --cli node build/index.js
```
The CLI mode supports most operations across tools, resources, and prompts. A few examples:
```bash
# Basic usage
npx @modelcontextprotocol/inspector --cli node build/index.js
# With config file
npx @modelcontextprotocol/inspector --cli --config path/to/config.json --server myserver
# List available tools
npx @modelcontextprotocol/inspector --cli node build/index.js --method tools/list
# Call a specific tool
npx @modelcontextprotocol/inspector --cli node build/index.js --method tools/call --tool-name mytool --tool-arg key=value --tool-arg another=value2
# List available resources
npx @modelcontextprotocol/inspector --cli node build/index.js --method resources/list
# List available prompts
npx @modelcontextprotocol/inspector --cli node build/index.js --method prompts/list
# Connect to a remote MCP server
npx @modelcontextprotocol/inspector --cli https://my-mcp-server.example.com
# Call a tool on a remote server
npx @modelcontextprotocol/inspector --cli https://my-mcp-server.example.com --method tools/call --tool-name remotetool --tool-arg param=value
# List resources from a remote server
npx @modelcontextprotocol/inspector --cli https://my-mcp-server.example.com --method resources/list
```
### UI Mode vs CLI Mode: When to Use Each
| Use Case | UI Mode | CLI Mode |
| ------------------------ | ------------------------------------------------------------------------- | ---------------------------------------------------------------------------------------------------------------------------------------------------- |
| **Server Development** | Visual interface for interactive testing and debugging during development | Scriptable commands for quick testing and continuous integration; creates feedback loops with AI coding assistants like Cursor for rapid development |
| **Resource Exploration** | Interactive browser with hierarchical navigation and JSON visualization | Programmatic listing and reading for automation and scripting |
| **Tool Testing** | Form-based parameter input with real-time response visualization | Command-line tool execution with JSON output for scripting |
| **Prompt Engineering** | Interactive sampling with streaming responses and visual comparison | Batch processing of prompts with machine-readable output |
| **Debugging** | Request history, visualized errors, and real-time notifications | Direct JSON output for log analysis and integration with other tools |
| **Automation** | N/A | Ideal for CI/CD pipelines, batch processing, and integration with coding assistants |
| **Learning MCP** | Rich visual interface helps new users understand server capabilities | Simplified commands for focused learning of specific endpoints |
## License
This project is licensed under the MIT License—see the [LICENSE](LICENSE) file for details.

14
SECURITY.md Normal file
View File

@@ -0,0 +1,14 @@
# Security Policy
Thank you for helping us keep the inspector secure.
## Reporting Security Issues
This project is maintained by [Anthropic](https://www.anthropic.com/) as part of the Model Context Protocol project.
The security of our systems and user data is Anthropics top priority. We appreciate the work of security researchers acting in good faith in identifying and reporting potential vulnerabilities.
Our security program is managed on HackerOne and we ask that any validated vulnerability in this functionality be reported through their [submission form](https://hackerone.com/anthropic-vdp/reports/new?type=team&report_type=vulnerability).
## Vulnerability Disclosure Program
Our Vulnerability Program Guidelines are defined on our [HackerOne program page](https://hackerone.com/anthropic-vdp).

28
cli/package.json Normal file
View File

@@ -0,0 +1,28 @@
{
"name": "@modelcontextprotocol/inspector-cli",
"version": "0.10.2",
"description": "CLI for the Model Context Protocol inspector",
"license": "MIT",
"author": "Anthropic, PBC (https://anthropic.com)",
"homepage": "https://modelcontextprotocol.io",
"bugs": "https://github.com/modelcontextprotocol/inspector/issues",
"main": "build/cli.js",
"type": "module",
"bin": {
"mcp-inspector-cli": "build/cli.js"
},
"files": [
"build"
],
"scripts": {
"build": "tsc",
"postbuild": "node scripts/make-executable.js",
"test": "node scripts/cli-tests.js"
},
"devDependencies": {},
"dependencies": {
"@modelcontextprotocol/sdk": "^1.10.0",
"commander": "^13.1.0",
"spawn-rx": "^5.1.2"
}
}

633
cli/scripts/cli-tests.js Executable file
View File

@@ -0,0 +1,633 @@
#!/usr/bin/env node
// Colors for output
const colors = {
GREEN: "\x1b[32m",
YELLOW: "\x1b[33m",
RED: "\x1b[31m",
BLUE: "\x1b[34m",
ORANGE: "\x1b[33m",
NC: "\x1b[0m", // No Color
};
import fs from "fs";
import path from "path";
import { execSync, spawn } from "child_process";
import os from "os";
import { fileURLToPath } from "url";
// Get directory paths with ESM compatibility
const __filename = fileURLToPath(import.meta.url);
const __dirname = path.dirname(__filename);
// Track test results
let PASSED_TESTS = 0;
let FAILED_TESTS = 0;
let SKIPPED_TESTS = 0;
let TOTAL_TESTS = 0;
console.log(
`${colors.YELLOW}=== MCP Inspector CLI Test Script ===${colors.NC}`,
);
console.log(
`${colors.BLUE}This script tests the MCP Inspector CLI's ability to handle various command line options:${colors.NC}`,
);
console.log(`${colors.BLUE}- Basic CLI mode${colors.NC}`);
console.log(`${colors.BLUE}- Environment variables (-e)${colors.NC}`);
console.log(`${colors.BLUE}- Config file (--config)${colors.NC}`);
console.log(`${colors.BLUE}- Server selection (--server)${colors.NC}`);
console.log(`${colors.BLUE}- Method selection (--method)${colors.NC}`);
console.log(
`${colors.BLUE}- Tool-related options (--tool-name, --tool-arg)${colors.NC}`,
);
console.log(`${colors.BLUE}- Resource-related options (--uri)${colors.NC}`);
console.log(
`${colors.BLUE}- Prompt-related options (--prompt-name, --prompt-args)${colors.NC}`,
);
console.log(`${colors.BLUE}- Logging options (--log-level)${colors.NC}\n`);
// Get directory paths
const SCRIPTS_DIR = __dirname;
const PROJECT_ROOT = path.join(SCRIPTS_DIR, "../../");
const BUILD_DIR = path.resolve(SCRIPTS_DIR, "../build");
// Define the test server command using npx
const TEST_CMD = "npx";
const TEST_ARGS = ["@modelcontextprotocol/server-everything"];
// Create output directory for test results
const OUTPUT_DIR = path.join(SCRIPTS_DIR, "test-output");
if (!fs.existsSync(OUTPUT_DIR)) {
fs.mkdirSync(OUTPUT_DIR, { recursive: true });
}
// Create a temporary directory for test files
const TEMP_DIR = fs.mkdirSync(path.join(os.tmpdir(), "mcp-inspector-tests"), {
recursive: true,
});
process.on("exit", () => {
try {
fs.rmSync(TEMP_DIR, { recursive: true, force: true });
} catch (err) {
console.error(
`${colors.RED}Failed to remove temp directory: ${err.message}${colors.NC}`,
);
}
});
// Use the existing sample config file
console.log(
`${colors.BLUE}Using existing sample config file: ${PROJECT_ROOT}/sample-config.json${colors.NC}`,
);
try {
const sampleConfig = fs.readFileSync(
path.join(PROJECT_ROOT, "sample-config.json"),
"utf8",
);
console.log(sampleConfig);
} catch (error) {
console.error(
`${colors.RED}Error reading sample config: ${error.message}${colors.NC}`,
);
}
// Create an invalid config file for testing
const invalidConfigPath = path.join(TEMP_DIR, "invalid-config.json");
fs.writeFileSync(invalidConfigPath, '{\n "mcpServers": {\n "invalid": {');
// Function to run a basic test
async function runBasicTest(testName, ...args) {
const outputFile = path.join(
OUTPUT_DIR,
`${testName.replace(/\//g, "_")}.log`,
);
console.log(`\n${colors.YELLOW}Testing: ${testName}${colors.NC}`);
TOTAL_TESTS++;
// Run the command and capture output
console.log(
`${colors.BLUE}Command: node ${BUILD_DIR}/cli.js ${args.join(" ")}${colors.NC}`,
);
try {
// Create a write stream for the output file
const outputStream = fs.createWriteStream(outputFile);
// Spawn the process
return new Promise((resolve) => {
const child = spawn("node", [path.join(BUILD_DIR, "cli.js"), ...args], {
stdio: ["ignore", "pipe", "pipe"],
});
// Pipe stdout and stderr to the output file
child.stdout.pipe(outputStream);
child.stderr.pipe(outputStream);
// Also capture output for display
let output = "";
child.stdout.on("data", (data) => {
output += data.toString();
});
child.stderr.on("data", (data) => {
output += data.toString();
});
child.on("close", (code) => {
outputStream.end();
if (code === 0) {
console.log(`${colors.GREEN}✓ Test passed: ${testName}${colors.NC}`);
console.log(`${colors.BLUE}First few lines of output:${colors.NC}`);
const firstFewLines = output
.split("\n")
.slice(0, 5)
.map((line) => ` ${line}`)
.join("\n");
console.log(firstFewLines);
PASSED_TESTS++;
resolve(true);
} else {
console.log(`${colors.RED}✗ Test failed: ${testName}${colors.NC}`);
console.log(`${colors.RED}Error output:${colors.NC}`);
console.log(
output
.split("\n")
.map((line) => ` ${line}`)
.join("\n"),
);
FAILED_TESTS++;
// Stop after any error is encountered
console.log(
`${colors.YELLOW}Stopping tests due to error. Please validate and fix before continuing.${colors.NC}`,
);
process.exit(1);
}
});
});
} catch (error) {
console.error(
`${colors.RED}Error running test: ${error.message}${colors.NC}`,
);
FAILED_TESTS++;
process.exit(1);
}
}
// Function to run an error test (expected to fail)
async function runErrorTest(testName, ...args) {
const outputFile = path.join(
OUTPUT_DIR,
`${testName.replace(/\//g, "_")}.log`,
);
console.log(`\n${colors.YELLOW}Testing error case: ${testName}${colors.NC}`);
TOTAL_TESTS++;
// Run the command and capture output
console.log(
`${colors.BLUE}Command: node ${BUILD_DIR}/cli.js ${args.join(" ")}${colors.NC}`,
);
try {
// Create a write stream for the output file
const outputStream = fs.createWriteStream(outputFile);
// Spawn the process
return new Promise((resolve) => {
const child = spawn("node", [path.join(BUILD_DIR, "cli.js"), ...args], {
stdio: ["ignore", "pipe", "pipe"],
});
// Pipe stdout and stderr to the output file
child.stdout.pipe(outputStream);
child.stderr.pipe(outputStream);
// Also capture output for display
let output = "";
child.stdout.on("data", (data) => {
output += data.toString();
});
child.stderr.on("data", (data) => {
output += data.toString();
});
child.on("close", (code) => {
outputStream.end();
// For error tests, we expect a non-zero exit code
if (code !== 0) {
console.log(
`${colors.GREEN}✓ Error test passed: ${testName}${colors.NC}`,
);
console.log(`${colors.BLUE}Error output (expected):${colors.NC}`);
const firstFewLines = output
.split("\n")
.slice(0, 5)
.map((line) => ` ${line}`)
.join("\n");
console.log(firstFewLines);
PASSED_TESTS++;
resolve(true);
} else {
console.log(
`${colors.RED}✗ Error test failed: ${testName} (expected error but got success)${colors.NC}`,
);
console.log(`${colors.RED}Output:${colors.NC}`);
console.log(
output
.split("\n")
.map((line) => ` ${line}`)
.join("\n"),
);
FAILED_TESTS++;
// Stop after any error is encountered
console.log(
`${colors.YELLOW}Stopping tests due to error. Please validate and fix before continuing.${colors.NC}`,
);
process.exit(1);
}
});
});
} catch (error) {
console.error(
`${colors.RED}Error running test: ${error.message}${colors.NC}`,
);
FAILED_TESTS++;
process.exit(1);
}
}
// Run all tests
async function runTests() {
console.log(
`\n${colors.YELLOW}=== Running Basic CLI Mode Tests ===${colors.NC}`,
);
// Test 1: Basic CLI mode with method
await runBasicTest(
"basic_cli_mode",
TEST_CMD,
...TEST_ARGS,
"--cli",
"--method",
"tools/list",
);
// Test 2: CLI mode with non-existent method (should fail)
await runErrorTest(
"nonexistent_method",
TEST_CMD,
...TEST_ARGS,
"--cli",
"--method",
"nonexistent/method",
);
// Test 3: CLI mode without method (should fail)
await runErrorTest("missing_method", TEST_CMD, ...TEST_ARGS, "--cli");
console.log(
`\n${colors.YELLOW}=== Running Environment Variable Tests ===${colors.NC}`,
);
// Test 4: CLI mode with environment variables
await runBasicTest(
"env_variables",
TEST_CMD,
...TEST_ARGS,
"-e",
"KEY1=value1",
"-e",
"KEY2=value2",
"--cli",
"--method",
"tools/list",
);
// Test 5: CLI mode with invalid environment variable format (should fail)
await runErrorTest(
"invalid_env_format",
TEST_CMD,
...TEST_ARGS,
"-e",
"INVALID_FORMAT",
"--cli",
"--method",
"tools/list",
);
// Test 5b: CLI mode with environment variable containing equals sign in value
await runBasicTest(
"env_variable_with_equals",
TEST_CMD,
...TEST_ARGS,
"-e",
"API_KEY=abc123=xyz789==",
"--cli",
"--method",
"tools/list",
);
// Test 5c: CLI mode with environment variable containing base64-encoded value
await runBasicTest(
"env_variable_with_base64",
TEST_CMD,
...TEST_ARGS,
"-e",
"JWT_TOKEN=eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJzdWIiOiIxMjM0NTY3ODkwIn0=",
"--cli",
"--method",
"tools/list",
);
console.log(
`\n${colors.YELLOW}=== Running Config File Tests ===${colors.NC}`,
);
// Test 6: Using config file with CLI mode
await runBasicTest(
"config_file",
"--config",
path.join(PROJECT_ROOT, "sample-config.json"),
"--server",
"everything",
"--cli",
"--method",
"tools/list",
);
// Test 7: Using config file without server name (should fail)
await runErrorTest(
"config_without_server",
"--config",
path.join(PROJECT_ROOT, "sample-config.json"),
"--cli",
"--method",
"tools/list",
);
// Test 8: Using server name without config file (should fail)
await runErrorTest(
"server_without_config",
"--server",
"everything",
"--cli",
"--method",
"tools/list",
);
// Test 9: Using non-existent config file (should fail)
await runErrorTest(
"nonexistent_config",
"--config",
"./nonexistent-config.json",
"--server",
"everything",
"--cli",
"--method",
"tools/list",
);
// Test 10: Using invalid config file format (should fail)
await runErrorTest(
"invalid_config",
"--config",
invalidConfigPath,
"--server",
"everything",
"--cli",
"--method",
"tools/list",
);
// Test 11: Using config file with non-existent server (should fail)
await runErrorTest(
"nonexistent_server",
"--config",
path.join(PROJECT_ROOT, "sample-config.json"),
"--server",
"nonexistent",
"--cli",
"--method",
"tools/list",
);
console.log(
`\n${colors.YELLOW}=== Running Tool-Related Tests ===${colors.NC}`,
);
// Test 12: CLI mode with tool call
await runBasicTest(
"tool_call",
TEST_CMD,
...TEST_ARGS,
"--cli",
"--method",
"tools/call",
"--tool-name",
"echo",
"--tool-arg",
"message=Hello",
);
// Test 13: CLI mode with tool call but missing tool name (should fail)
await runErrorTest(
"missing_tool_name",
TEST_CMD,
...TEST_ARGS,
"--cli",
"--method",
"tools/call",
"--tool-arg",
"message=Hello",
);
// Test 14: CLI mode with tool call but invalid tool args format (should fail)
await runErrorTest(
"invalid_tool_args",
TEST_CMD,
...TEST_ARGS,
"--cli",
"--method",
"tools/call",
"--tool-name",
"echo",
"--tool-arg",
"invalid_format",
);
// Test 15: CLI mode with multiple tool args
await runBasicTest(
"multiple_tool_args",
TEST_CMD,
...TEST_ARGS,
"--cli",
"--method",
"tools/call",
"--tool-name",
"add",
"--tool-arg",
"a=1",
"b=2",
);
console.log(
`\n${colors.YELLOW}=== Running Resource-Related Tests ===${colors.NC}`,
);
// Test 16: CLI mode with resource read
await runBasicTest(
"resource_read",
TEST_CMD,
...TEST_ARGS,
"--cli",
"--method",
"resources/read",
"--uri",
"test://static/resource/1",
);
// Test 17: CLI mode with resource read but missing URI (should fail)
await runErrorTest(
"missing_uri",
TEST_CMD,
...TEST_ARGS,
"--cli",
"--method",
"resources/read",
);
console.log(
`\n${colors.YELLOW}=== Running Prompt-Related Tests ===${colors.NC}`,
);
// Test 18: CLI mode with prompt get
await runBasicTest(
"prompt_get",
TEST_CMD,
...TEST_ARGS,
"--cli",
"--method",
"prompts/get",
"--prompt-name",
"simple_prompt",
);
// Test 19: CLI mode with prompt get and args
await runBasicTest(
"prompt_get_with_args",
TEST_CMD,
...TEST_ARGS,
"--cli",
"--method",
"prompts/get",
"--prompt-name",
"complex_prompt",
"--prompt-args",
"temperature=0.7",
"style=concise",
);
// Test 20: CLI mode with prompt get but missing prompt name (should fail)
await runErrorTest(
"missing_prompt_name",
TEST_CMD,
...TEST_ARGS,
"--cli",
"--method",
"prompts/get",
);
console.log(`\n${colors.YELLOW}=== Running Logging Tests ===${colors.NC}`);
// Test 21: CLI mode with log level
await runBasicTest(
"log_level",
TEST_CMD,
...TEST_ARGS,
"--cli",
"--method",
"logging/setLevel",
"--log-level",
"debug",
);
// Test 22: CLI mode with invalid log level (should fail)
await runErrorTest(
"invalid_log_level",
TEST_CMD,
...TEST_ARGS,
"--cli",
"--method",
"logging/setLevel",
"--log-level",
"invalid",
);
console.log(
`\n${colors.YELLOW}=== Running Combined Option Tests ===${colors.NC}`,
);
// Note about the combined options issue
console.log(
`${colors.BLUE}Testing combined options with environment variables and config file.${colors.NC}`,
);
// Test 23: CLI mode with config file, environment variables, and tool call
await runBasicTest(
"combined_options",
"--config",
path.join(PROJECT_ROOT, "sample-config.json"),
"--server",
"everything",
"-e",
"CLI_ENV_VAR=cli_value",
"--cli",
"--method",
"tools/list",
);
// Test 24: CLI mode with all possible options (that make sense together)
await runBasicTest(
"all_options",
"--config",
path.join(PROJECT_ROOT, "sample-config.json"),
"--server",
"everything",
"-e",
"CLI_ENV_VAR=cli_value",
"--cli",
"--method",
"tools/call",
"--tool-name",
"echo",
"--tool-arg",
"message=Hello",
"--log-level",
"debug",
);
// Print test summary
console.log(`\n${colors.YELLOW}=== Test Summary ===${colors.NC}`);
console.log(`${colors.GREEN}Passed: ${PASSED_TESTS}${colors.NC}`);
console.log(`${colors.RED}Failed: ${FAILED_TESTS}${colors.NC}`);
console.log(`${colors.ORANGE}Skipped: ${SKIPPED_TESTS}${colors.NC}`);
console.log(`Total: ${TOTAL_TESTS}`);
console.log(
`${colors.BLUE}Detailed logs saved to: ${OUTPUT_DIR}${colors.NC}`,
);
console.log(`\n${colors.GREEN}All tests completed!${colors.NC}`);
}
// Run all tests
runTests().catch((error) => {
console.error(
`${colors.RED}Tests failed with error: ${error.message}${colors.NC}`,
);
process.exit(1);
});

29
cli/scripts/make-executable.js Executable file
View File

@@ -0,0 +1,29 @@
/**
* Cross-platform script to make a file executable
*/
import { promises as fs } from "fs";
import { platform } from "os";
import { execSync } from "child_process";
import path from "path";
const TARGET_FILE = path.resolve("build/cli.js");
async function makeExecutable() {
try {
// On Unix-like systems (Linux, macOS), use chmod
if (platform() !== "win32") {
execSync(`chmod +x "${TARGET_FILE}"`);
console.log("Made file executable with chmod");
} else {
// On Windows, no need to make files "executable" in the Unix sense
// Just ensure the file exists
await fs.access(TARGET_FILE);
console.log("File exists and is accessible on Windows");
}
} catch (error) {
console.error("Error making file executable:", error);
process.exit(1);
}
}
makeExecutable();

287
cli/src/cli.ts Normal file
View File

@@ -0,0 +1,287 @@
#!/usr/bin/env node
import { Command } from "commander";
import fs from "node:fs";
import path from "node:path";
import { dirname, resolve } from "path";
import { spawnPromise } from "spawn-rx";
import { fileURLToPath } from "url";
const __dirname = dirname(fileURLToPath(import.meta.url));
type Args = {
command: string;
args: string[];
envArgs: Record<string, string>;
cli: boolean;
};
type CliOptions = {
e?: Record<string, string>;
config?: string;
server?: string;
cli?: boolean;
};
type ServerConfig = {
command: string;
args?: string[];
env?: Record<string, string>;
};
function handleError(error: unknown): never {
let message: string;
if (error instanceof Error) {
message = error.message;
} else if (typeof error === "string") {
message = error;
} else {
message = "Unknown error";
}
console.error(message);
process.exit(1);
}
function delay(ms: number): Promise<void> {
return new Promise((resolve) => setTimeout(resolve, ms, true));
}
async function runWebClient(args: Args): Promise<void> {
const inspectorServerPath = resolve(
__dirname,
"../../",
"server",
"build",
"index.js",
);
// Path to the client entry point
const inspectorClientPath = resolve(
__dirname,
"../../",
"client",
"bin",
"client.js",
);
const CLIENT_PORT: string = process.env.CLIENT_PORT ?? "6274";
const SERVER_PORT: string = process.env.SERVER_PORT ?? "6277";
console.log("Starting MCP inspector...");
const abort = new AbortController();
let cancelled: boolean = false;
process.on("SIGINT", () => {
cancelled = true;
abort.abort();
});
let server: ReturnType<typeof spawnPromise>;
let serverOk: unknown;
try {
server = spawnPromise(
"node",
[
inspectorServerPath,
...(args.command ? [`--env`, args.command] : []),
...(args.args ? [`--args=${args.args.join(" ")}`] : []),
],
{
env: {
...process.env,
PORT: SERVER_PORT,
MCP_ENV_VARS: JSON.stringify(args.envArgs),
},
signal: abort.signal,
echoOutput: true,
},
);
// Make sure server started before starting client
serverOk = await Promise.race([server, delay(2 * 1000)]);
} catch (error) {}
if (serverOk) {
try {
await spawnPromise("node", [inspectorClientPath], {
env: { ...process.env, PORT: CLIENT_PORT },
signal: abort.signal,
echoOutput: true,
});
} catch (e) {
if (!cancelled || process.env.DEBUG) throw e;
}
}
}
async function runCli(args: Args): Promise<void> {
const projectRoot = resolve(__dirname, "..");
const cliPath = resolve(projectRoot, "build", "index.js");
const abort = new AbortController();
let cancelled = false;
process.on("SIGINT", () => {
cancelled = true;
abort.abort();
});
try {
await spawnPromise("node", [cliPath, args.command, ...args.args], {
env: { ...process.env, ...args.envArgs },
signal: abort.signal,
echoOutput: true,
});
} catch (e) {
if (!cancelled || process.env.DEBUG) {
throw e;
}
}
}
function loadConfigFile(configPath: string, serverName: string): ServerConfig {
try {
const resolvedConfigPath = path.isAbsolute(configPath)
? configPath
: path.resolve(process.cwd(), configPath);
if (!fs.existsSync(resolvedConfigPath)) {
throw new Error(`Config file not found: ${resolvedConfigPath}`);
}
const configContent = fs.readFileSync(resolvedConfigPath, "utf8");
const parsedConfig = JSON.parse(configContent);
if (!parsedConfig.mcpServers || !parsedConfig.mcpServers[serverName]) {
const availableServers = Object.keys(parsedConfig.mcpServers || {}).join(
", ",
);
throw new Error(
`Server '${serverName}' not found in config file. Available servers: ${availableServers}`,
);
}
const serverConfig = parsedConfig.mcpServers[serverName];
return serverConfig;
} catch (err: unknown) {
if (err instanceof SyntaxError) {
throw new Error(`Invalid JSON in config file: ${err.message}`);
}
throw err;
}
}
function parseKeyValuePair(
value: string,
previous: Record<string, string> = {},
): Record<string, string> {
const parts = value.split("=");
const key = parts[0];
const val = parts.slice(1).join("=");
if (val === undefined || val === "") {
throw new Error(
`Invalid parameter format: ${value}. Use key=value format.`,
);
}
return { ...previous, [key as string]: val };
}
function parseArgs(): Args {
const program = new Command();
const argSeparatorIndex = process.argv.indexOf("--");
let preArgs = process.argv;
let postArgs: string[] = [];
if (argSeparatorIndex !== -1) {
preArgs = process.argv.slice(0, argSeparatorIndex);
postArgs = process.argv.slice(argSeparatorIndex + 1);
}
program
.name("inspector-bin")
.allowExcessArguments()
.allowUnknownOption()
.option(
"-e <env>",
"environment variables in KEY=VALUE format",
parseKeyValuePair,
{},
)
.option("--config <path>", "config file path")
.option("--server <n>", "server name from config file")
.option("--cli", "enable CLI mode");
// Parse only the arguments before --
program.parse(preArgs);
const options = program.opts() as CliOptions;
const remainingArgs = program.args;
// Add back any arguments that came after --
const finalArgs = [...remainingArgs, ...postArgs];
// Validate that config and server are provided together
if (
(options.config && !options.server) ||
(!options.config && options.server)
) {
throw new Error(
"Both --config and --server must be provided together. If you specify one, you must specify the other.",
);
}
// If config file is specified, load and use the options from the file. We must merge the args
// from the command line and the file together, or we will miss the method options (--method,
// etc.)
if (options.config && options.server) {
const config = loadConfigFile(options.config, options.server);
return {
command: config.command,
args: [...(config.args || []), ...finalArgs],
envArgs: { ...(config.env || {}), ...(options.e || {}) },
cli: options.cli || false,
};
}
// Otherwise use command line arguments
const command = finalArgs[0] || "";
const args = finalArgs.slice(1);
return {
command,
args,
envArgs: options.e || {},
cli: options.cli || false,
};
}
async function main(): Promise<void> {
process.on("uncaughtException", (error) => {
handleError(error);
});
try {
const args = parseArgs();
if (args.cli) {
runCli(args);
} else {
await runWebClient(args);
}
} catch (error) {
handleError(error);
}
}
main();

View File

@@ -0,0 +1,51 @@
import { Client } from "@modelcontextprotocol/sdk/client/index.js";
import type { Transport } from "@modelcontextprotocol/sdk/shared/transport.js";
import { McpResponse } from "./types.js";
export const validLogLevels = [
"trace",
"debug",
"info",
"warn",
"error",
] as const;
export type LogLevel = (typeof validLogLevels)[number];
export async function connect(
client: Client,
transport: Transport,
): Promise<void> {
try {
await client.connect(transport);
} catch (error) {
throw new Error(
`Failed to connect to MCP server: ${error instanceof Error ? error.message : String(error)}`,
);
}
}
export async function disconnect(transport: Transport): Promise<void> {
try {
await transport.close();
} catch (error) {
throw new Error(
`Failed to disconnect from MCP server: ${error instanceof Error ? error.message : String(error)}`,
);
}
}
// Set logging level
export async function setLoggingLevel(
client: Client,
level: LogLevel,
): Promise<McpResponse> {
try {
const response = await client.setLoggingLevel(level as any);
return response;
} catch (error) {
throw new Error(
`Failed to set logging level: ${error instanceof Error ? error.message : String(error)}`,
);
}
}

6
cli/src/client/index.ts Normal file
View File

@@ -0,0 +1,6 @@
// Re-export everything from the client modules
export * from "./connection.js";
export * from "./prompts.js";
export * from "./resources.js";
export * from "./tools.js";
export * from "./types.js";

34
cli/src/client/prompts.ts Normal file
View File

@@ -0,0 +1,34 @@
import { Client } from "@modelcontextprotocol/sdk/client/index.js";
import { McpResponse } from "./types.js";
// List available prompts
export async function listPrompts(client: Client): Promise<McpResponse> {
try {
const response = await client.listPrompts();
return response;
} catch (error) {
throw new Error(
`Failed to list prompts: ${error instanceof Error ? error.message : String(error)}`,
);
}
}
// Get a prompt
export async function getPrompt(
client: Client,
name: string,
args?: Record<string, string>,
): Promise<McpResponse> {
try {
const response = await client.getPrompt({
name,
arguments: args || {},
});
return response;
} catch (error) {
throw new Error(
`Failed to get prompt: ${error instanceof Error ? error.message : String(error)}`,
);
}
}

View File

@@ -0,0 +1,43 @@
import { Client } from "@modelcontextprotocol/sdk/client/index.js";
import { McpResponse } from "./types.js";
// List available resources
export async function listResources(client: Client): Promise<McpResponse> {
try {
const response = await client.listResources();
return response;
} catch (error) {
throw new Error(
`Failed to list resources: ${error instanceof Error ? error.message : String(error)}`,
);
}
}
// Read a resource
export async function readResource(
client: Client,
uri: string,
): Promise<McpResponse> {
try {
const response = await client.readResource({ uri });
return response;
} catch (error) {
throw new Error(
`Failed to read resource ${uri}: ${error instanceof Error ? error.message : String(error)}`,
);
}
}
// List resource templates
export async function listResourceTemplates(
client: Client,
): Promise<McpResponse> {
try {
const response = await client.listResourceTemplates();
return response;
} catch (error) {
throw new Error(
`Failed to list resource templates: ${error instanceof Error ? error.message : String(error)}`,
);
}
}

95
cli/src/client/tools.ts Normal file
View File

@@ -0,0 +1,95 @@
import { Client } from "@modelcontextprotocol/sdk/client/index.js";
import { Tool } from "@modelcontextprotocol/sdk/types.js";
import { McpResponse } from "./types.js";
type JsonSchemaType = {
type: "string" | "number" | "integer" | "boolean" | "array" | "object";
description?: string;
properties?: Record<string, JsonSchemaType>;
items?: JsonSchemaType;
};
export async function listTools(client: Client): Promise<McpResponse> {
try {
const response = await client.listTools();
return response;
} catch (error) {
throw new Error(
`Failed to list tools: ${error instanceof Error ? error.message : String(error)}`,
);
}
}
function convertParameterValue(value: string, schema: JsonSchemaType): unknown {
if (!value) {
return value;
}
if (schema.type === "number" || schema.type === "integer") {
return Number(value);
}
if (schema.type === "boolean") {
return value.toLowerCase() === "true";
}
if (schema.type === "object" || schema.type === "array") {
try {
return JSON.parse(value);
} catch (error) {
return value;
}
}
return value;
}
function convertParameters(
tool: Tool,
params: Record<string, string>,
): Record<string, unknown> {
const result: Record<string, unknown> = {};
const properties = tool.inputSchema.properties || {};
for (const [key, value] of Object.entries(params)) {
const paramSchema = properties[key] as JsonSchemaType | undefined;
if (paramSchema) {
result[key] = convertParameterValue(value, paramSchema);
} else {
// If no schema is found for this parameter, keep it as string
result[key] = value;
}
}
return result;
}
export async function callTool(
client: Client,
name: string,
args: Record<string, string>,
): Promise<McpResponse> {
try {
const toolsResponse = await listTools(client);
const tools = toolsResponse.tools as Tool[];
const tool = tools.find((t) => t.name === name);
let convertedArgs: Record<string, unknown> = args;
if (tool) {
// Convert parameters based on the tool's schema
convertedArgs = convertParameters(tool, args);
}
const response = await client.callTool({
name: name,
arguments: convertedArgs,
});
return response;
} catch (error) {
throw new Error(
`Failed to call tool ${name}: ${error instanceof Error ? error.message : String(error)}`,
);
}
}

1
cli/src/client/types.ts Normal file
View File

@@ -0,0 +1 @@
export type McpResponse = Record<string, unknown>;

20
cli/src/error-handler.ts Normal file
View File

@@ -0,0 +1,20 @@
function formatError(error: unknown): string {
let message: string;
if (error instanceof Error) {
message = error.message;
} else if (typeof error === "string") {
message = error;
} else {
message = "Unknown error";
}
return message;
}
export function handleError(error: unknown): never {
const errorMessage = formatError(error);
console.error(errorMessage);
process.exit(1);
}

253
cli/src/index.ts Normal file
View File

@@ -0,0 +1,253 @@
#!/usr/bin/env node
import { Client } from "@modelcontextprotocol/sdk/client/index.js";
import { Command } from "commander";
import {
callTool,
connect,
disconnect,
getPrompt,
listPrompts,
listResources,
listResourceTemplates,
listTools,
LogLevel,
McpResponse,
readResource,
setLoggingLevel,
validLogLevels,
} from "./client/index.js";
import { handleError } from "./error-handler.js";
import { createTransport, TransportOptions } from "./transport.js";
type Args = {
target: string[];
method?: string;
promptName?: string;
promptArgs?: Record<string, string>;
uri?: string;
logLevel?: LogLevel;
toolName?: string;
toolArg?: Record<string, string>;
};
function createTransportOptions(target: string[]): TransportOptions {
if (target.length === 0) {
throw new Error(
"Target is required. Specify a URL or a command to execute.",
);
}
const [command, ...commandArgs] = target;
if (!command) {
throw new Error("Command is required.");
}
const isUrl = command.startsWith("http://") || command.startsWith("https://");
if (isUrl && commandArgs.length > 0) {
throw new Error("Arguments cannot be passed to a URL-based MCP server.");
}
return {
transportType: isUrl ? "sse" : "stdio",
command: isUrl ? undefined : command,
args: isUrl ? undefined : commandArgs,
url: isUrl ? command : undefined,
};
}
async function callMethod(args: Args): Promise<void> {
const transportOptions = createTransportOptions(args.target);
const transport = createTransport(transportOptions);
const client = new Client({
name: "inspector-cli",
version: "0.5.1",
});
try {
await connect(client, transport);
let result: McpResponse;
// Tools methods
if (args.method === "tools/list") {
result = await listTools(client);
} else if (args.method === "tools/call") {
if (!args.toolName) {
throw new Error(
"Tool name is required for tools/call method. Use --tool-name to specify the tool name.",
);
}
result = await callTool(client, args.toolName, args.toolArg || {});
}
// Resources methods
else if (args.method === "resources/list") {
result = await listResources(client);
} else if (args.method === "resources/read") {
if (!args.uri) {
throw new Error(
"URI is required for resources/read method. Use --uri to specify the resource URI.",
);
}
result = await readResource(client, args.uri);
} else if (args.method === "resources/templates/list") {
result = await listResourceTemplates(client);
}
// Prompts methods
else if (args.method === "prompts/list") {
result = await listPrompts(client);
} else if (args.method === "prompts/get") {
if (!args.promptName) {
throw new Error(
"Prompt name is required for prompts/get method. Use --prompt-name to specify the prompt name.",
);
}
result = await getPrompt(client, args.promptName, args.promptArgs || {});
}
// Logging methods
else if (args.method === "logging/setLevel") {
if (!args.logLevel) {
throw new Error(
"Log level is required for logging/setLevel method. Use --log-level to specify the log level.",
);
}
result = await setLoggingLevel(client, args.logLevel);
} else {
throw new Error(
`Unsupported method: ${args.method}. Supported methods include: tools/list, tools/call, resources/list, resources/read, resources/templates/list, prompts/list, prompts/get, logging/setLevel`,
);
}
console.log(JSON.stringify(result, null, 2));
} finally {
try {
await disconnect(transport);
} catch (disconnectError) {
throw disconnectError;
}
}
}
function parseKeyValuePair(
value: string,
previous: Record<string, string> = {},
): Record<string, string> {
const parts = value.split("=");
const key = parts[0];
const val = parts.slice(1).join("=");
if (val === undefined || val === "") {
throw new Error(
`Invalid parameter format: ${value}. Use key=value format.`,
);
}
return { ...previous, [key as string]: val };
}
function parseArgs(): Args {
const program = new Command();
// Find if there's a -- in the arguments and split them
const argSeparatorIndex = process.argv.indexOf("--");
let preArgs = process.argv;
let postArgs: string[] = [];
if (argSeparatorIndex !== -1) {
preArgs = process.argv.slice(0, argSeparatorIndex);
postArgs = process.argv.slice(argSeparatorIndex + 1);
}
program
.name("inspector-cli")
.allowUnknownOption()
.argument("<target...>", "Command and arguments or URL of the MCP server")
//
// Method selection
//
.option("--method <method>", "Method to invoke")
//
// Tool-related options
//
.option("--tool-name <toolName>", "Tool name (for tools/call method)")
.option(
"--tool-arg <pairs...>",
"Tool argument as key=value pair",
parseKeyValuePair,
{},
)
//
// Resource-related options
//
.option("--uri <uri>", "URI of the resource (for resources/read method)")
//
// Prompt-related options
//
.option(
"--prompt-name <promptName>",
"Name of the prompt (for prompts/get method)",
)
.option(
"--prompt-args <pairs...>",
"Prompt arguments as key=value pairs",
parseKeyValuePair,
{},
)
//
// Logging options
//
.option(
"--log-level <level>",
"Logging level (for logging/setLevel method)",
(value: string) => {
if (!validLogLevels.includes(value as any)) {
throw new Error(
`Invalid log level: ${value}. Valid levels are: ${validLogLevels.join(", ")}`,
);
}
return value as LogLevel;
},
);
// Parse only the arguments before --
program.parse(preArgs);
const options = program.opts() as Omit<Args, "target">;
let remainingArgs = program.args;
// Add back any arguments that came after --
const finalArgs = [...remainingArgs, ...postArgs];
if (!options.method) {
throw new Error(
"Method is required. Use --method to specify the method to invoke.",
);
}
return {
target: finalArgs,
...options,
};
}
async function main(): Promise<void> {
process.on("uncaughtException", (error) => {
handleError(error);
});
try {
const args = parseArgs();
await callMethod(args);
} catch (error) {
handleError(error);
}
}
main();

76
cli/src/transport.ts Normal file
View File

@@ -0,0 +1,76 @@
import { SSEClientTransport } from "@modelcontextprotocol/sdk/client/sse.js";
import {
getDefaultEnvironment,
StdioClientTransport,
} from "@modelcontextprotocol/sdk/client/stdio.js";
import type { Transport } from "@modelcontextprotocol/sdk/shared/transport.js";
import { findActualExecutable } from "spawn-rx";
export type TransportOptions = {
transportType: "sse" | "stdio";
command?: string;
args?: string[];
url?: string;
};
function createSSETransport(options: TransportOptions): Transport {
const baseUrl = new URL(options.url ?? "");
const sseUrl = new URL("/sse", baseUrl);
return new SSEClientTransport(sseUrl);
}
function createStdioTransport(options: TransportOptions): Transport {
let args: string[] = [];
if (options.args !== undefined) {
args = options.args;
}
const processEnv: Record<string, string> = {};
for (const [key, value] of Object.entries(process.env)) {
if (value !== undefined) {
processEnv[key] = value;
}
}
const defaultEnv = getDefaultEnvironment();
const env: Record<string, string> = {
...processEnv,
...defaultEnv,
};
const { cmd: actualCommand, args: actualArgs } = findActualExecutable(
options.command ?? "",
args,
);
return new StdioClientTransport({
command: actualCommand,
args: actualArgs,
env,
stderr: "pipe",
});
}
export function createTransport(options: TransportOptions): Transport {
const { transportType } = options;
try {
if (transportType === "stdio") {
return createStdioTransport(options);
}
if (transportType === "sse") {
return createSSETransport(options);
}
throw new Error(`Unsupported transport type: ${transportType}`);
} catch (error) {
throw new Error(
`Failed to create transport: ${error instanceof Error ? error.message : String(error)}`,
);
}
}

17
cli/tsconfig.json Normal file
View File

@@ -0,0 +1,17 @@
{
"compilerOptions": {
"target": "ES2022",
"module": "NodeNext",
"moduleResolution": "NodeNext",
"outDir": "./build",
"rootDir": "./src",
"strict": true,
"esModuleInterop": true,
"skipLibCheck": true,
"forceConsistentCasingInFileNames": true,
"resolveJsonModule": true,
"noUncheckedIndexedAccess": true
},
"include": ["src/**/*"],
"exclude": ["node_modules", "packages", "**/*.spec.ts", "build"]
}

33
client/bin/client.js Executable file
View File

@@ -0,0 +1,33 @@
#!/usr/bin/env node
import { join, dirname } from "path";
import { fileURLToPath } from "url";
import handler from "serve-handler";
import http from "http";
const __dirname = dirname(fileURLToPath(import.meta.url));
const distPath = join(__dirname, "../dist");
const server = http.createServer((request, response) => {
return handler(request, response, {
public: distPath,
rewrites: [{ source: "/**", destination: "/index.html" }],
});
});
const port = process.env.PORT || 6274;
server.on("listening", () => {
console.log(
`🔍 MCP Inspector is up and running at http://127.0.0.1:${port} 🚀`,
);
});
server.on("error", (err) => {
if (err.message.includes(`EADDRINUSE`)) {
console.error(
`❌ MCP Inspector PORT IS IN USE at http://127.0.0.1:${port}`,
);
} else {
throw err;
}
});
server.listen(port);

120
client/bin/start.js Executable file
View File

@@ -0,0 +1,120 @@
#!/usr/bin/env node
import { resolve, dirname } from "path";
import { spawnPromise } from "spawn-rx";
import { fileURLToPath } from "url";
const __dirname = dirname(fileURLToPath(import.meta.url));
function delay(ms) {
return new Promise((resolve) => setTimeout(resolve, ms, true));
}
async function main() {
// Parse command line arguments
const args = process.argv.slice(2);
const envVars = {};
const mcpServerArgs = [];
let command = null;
let parsingFlags = true;
for (let i = 0; i < args.length; i++) {
const arg = args[i];
if (parsingFlags && arg === "--") {
parsingFlags = false;
continue;
}
if (parsingFlags && arg === "-e" && i + 1 < args.length) {
const envVar = args[++i];
const equalsIndex = envVar.indexOf("=");
if (equalsIndex !== -1) {
const key = envVar.substring(0, equalsIndex);
const value = envVar.substring(equalsIndex + 1);
envVars[key] = value;
} else {
envVars[envVar] = "";
}
} else if (!command) {
command = arg;
} else {
mcpServerArgs.push(arg);
}
}
const inspectorServerPath = resolve(
__dirname,
"../..",
"server",
"build",
"index.js",
);
// Path to the client entry point
const inspectorClientPath = resolve(
__dirname,
"../..",
"client",
"bin",
"client.js",
);
const CLIENT_PORT = process.env.CLIENT_PORT ?? "6274";
const SERVER_PORT = process.env.SERVER_PORT ?? "6277";
console.log("Starting MCP inspector...");
const abort = new AbortController();
let cancelled = false;
process.on("SIGINT", () => {
cancelled = true;
abort.abort();
});
let server, serverOk;
try {
server = spawnPromise(
"node",
[
inspectorServerPath,
...(command ? [`--env`, command] : []),
...(mcpServerArgs ? [`--args=${mcpServerArgs.join(" ")}`] : []),
],
{
env: {
...process.env,
PORT: SERVER_PORT,
MCP_ENV_VARS: JSON.stringify(envVars),
},
signal: abort.signal,
echoOutput: true,
},
);
// Make sure server started before starting client
serverOk = await Promise.race([server, delay(2 * 1000)]);
} catch (error) {}
if (serverOk) {
try {
await spawnPromise("node", [inspectorClientPath], {
env: { ...process.env, PORT: CLIENT_PORT },
signal: abort.signal,
echoOutput: true,
});
} catch (e) {
if (!cancelled || process.env.DEBUG) throw e;
}
}
return 0;
}
main()
.then((_) => process.exit(0))
.catch((e) => {
console.error(e);
process.exit(1);
});

View File

@@ -17,4 +17,4 @@
"lib": "@/lib",
"hooks": "@/hooks"
}
}
}

View File

@@ -2,7 +2,7 @@
<html lang="en">
<head>
<meta charset="UTF-8" />
<link rel="icon" type="image/svg+xml" href="/vite.svg" />
<link rel="icon" type="image/svg+xml" href="/mcp.svg" />
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
<title>MCP Inspector</title>
</head>

33
client/jest.config.cjs Normal file
View File

@@ -0,0 +1,33 @@
module.exports = {
preset: "ts-jest",
testEnvironment: "jest-fixed-jsdom",
moduleNameMapper: {
"^@/(.*)$": "<rootDir>/src/$1",
"\\.css$": "<rootDir>/src/__mocks__/styleMock.js",
},
transform: {
"^.+\\.tsx?$": [
"ts-jest",
{
jsx: "react-jsx",
tsconfig: "tsconfig.jest.json",
},
],
},
extensionsToTreatAsEsm: [".ts", ".tsx"],
testRegex: "(/__tests__/.*|(\\.|/)(test|spec))\\.(jsx?|tsx?)$",
// Exclude directories and files that don't need to be tested
testPathIgnorePatterns: [
"/node_modules/",
"/dist/",
"/bin/",
"\\.config\\.(js|ts|cjs|mjs)$",
],
// Exclude the same patterns from coverage reports
coveragePathIgnorePatterns: [
"/node_modules/",
"/dist/",
"/bin/",
"\\.config\\.(js|ts|cjs|mjs)$",
],
};

View File

@@ -1,45 +1,77 @@
{
"name": "client",
"private": true,
"version": "0.0.0",
"name": "@modelcontextprotocol/inspector-client",
"version": "0.10.2",
"description": "Client-side application for the Model Context Protocol inspector",
"license": "MIT",
"author": "Anthropic, PBC (https://anthropic.com)",
"homepage": "https://modelcontextprotocol.io",
"bugs": "https://github.com/modelcontextprotocol/inspector/issues",
"type": "module",
"bin": {
"mcp-inspector-client": "./bin/start.js"
},
"files": [
"bin",
"dist"
],
"scripts": {
"dev": "vite",
"dev": "vite --port 6274",
"build": "tsc -b && vite build",
"lint": "eslint .",
"preview": "vite preview"
"preview": "vite preview --port 6274",
"test": "jest --config jest.config.cjs",
"test:watch": "jest --config jest.config.cjs --watch"
},
"dependencies": {
"@modelcontextprotocol/sdk": "*",
"@modelcontextprotocol/sdk": "^1.10.0",
"@radix-ui/react-checkbox": "^1.1.4",
"@radix-ui/react-dialog": "^1.1.3",
"@radix-ui/react-icons": "^1.3.0",
"@radix-ui/react-label": "^2.1.0",
"@radix-ui/react-popover": "^1.1.3",
"@radix-ui/react-select": "^2.1.2",
"@radix-ui/react-slot": "^1.1.0",
"@radix-ui/react-tabs": "^1.1.1",
"@radix-ui/react-toast": "^1.2.6",
"@radix-ui/react-tooltip": "^1.1.8",
"class-variance-authority": "^0.7.0",
"clsx": "^2.1.1",
"cmdk": "^1.0.4",
"lucide-react": "^0.447.0",
"pkce-challenge": "^4.1.0",
"prismjs": "^1.30.0",
"react": "^18.3.1",
"react-dom": "^18.3.1",
"react-simple-code-editor": "^0.14.1",
"serve-handler": "^6.1.6",
"tailwind-merge": "^2.5.3",
"tailwindcss-animate": "^1.0.7",
"zod": "^3.23.8"
},
"devDependencies": {
"@eslint/js": "^9.11.1",
"@testing-library/jest-dom": "^6.6.3",
"@testing-library/react": "^16.2.0",
"@types/jest": "^29.5.14",
"@types/node": "^22.7.5",
"@types/prismjs": "^1.26.5",
"@types/react": "^18.3.10",
"@types/react-dom": "^18.3.0",
"@types/serve-handler": "^6.1.4",
"@vitejs/plugin-react": "^4.3.2",
"autoprefixer": "^10.4.20",
"co": "^4.6.0",
"eslint": "^9.11.1",
"eslint-plugin-react-hooks": "^5.1.0-rc.0",
"eslint-plugin-react-refresh": "^0.4.12",
"globals": "^15.9.0",
"jest": "^29.7.0",
"jest-environment-jsdom": "^29.7.0",
"postcss": "^8.4.47",
"tailwindcss": "^3.4.13",
"ts-jest": "^29.2.6",
"typescript": "^5.5.3",
"typescript-eslint": "^8.7.0",
"vite": "^5.4.8"
"vite": "^6.3.0"
}
}

View File

@@ -3,4 +3,4 @@ export default {
tailwindcss: {},
autoprefixer: {},
},
}
};

12
client/public/mcp.svg Normal file
View File

@@ -0,0 +1,12 @@
<svg width="180" height="180" viewBox="0 0 180 180" fill="none" xmlns="http://www.w3.org/2000/svg">
<g clip-path="url(#clip0_19_13)">
<path d="M18 84.8528L85.8822 16.9706C95.2548 7.59798 110.451 7.59798 119.823 16.9706V16.9706C129.196 26.3431 129.196 41.5391 119.823 50.9117L68.5581 102.177" stroke="black" stroke-width="12" stroke-linecap="round"/>
<path d="M69.2652 101.47L119.823 50.9117C129.196 41.5391 144.392 41.5391 153.765 50.9117L154.118 51.2652C163.491 60.6378 163.491 75.8338 154.118 85.2063L92.7248 146.6C89.6006 149.724 89.6006 154.789 92.7248 157.913L105.331 170.52" stroke="black" stroke-width="12" stroke-linecap="round"/>
<path d="M102.853 33.9411L52.6482 84.1457C43.2756 93.5183 43.2756 108.714 52.6482 118.087V118.087C62.0208 127.459 77.2167 127.459 86.5893 118.087L136.794 67.8822" stroke="black" stroke-width="12" stroke-linecap="round"/>
</g>
<defs>
<clipPath id="clip0_19_13">
<rect width="180" height="180" fill="white"/>
</clipPath>
</defs>
</svg>

After

Width:  |  Height:  |  Size: 973 B

View File

@@ -1 +0,0 @@
<svg xmlns="http://www.w3.org/2000/svg" xmlns:xlink="http://www.w3.org/1999/xlink" aria-hidden="true" role="img" class="iconify iconify--logos" width="31.88" height="32" preserveAspectRatio="xMidYMid meet" viewBox="0 0 256 257"><defs><linearGradient id="IconifyId1813088fe1fbc01fb466" x1="-.828%" x2="57.636%" y1="7.652%" y2="78.411%"><stop offset="0%" stop-color="#41D1FF"></stop><stop offset="100%" stop-color="#BD34FE"></stop></linearGradient><linearGradient id="IconifyId1813088fe1fbc01fb467" x1="43.376%" x2="50.316%" y1="2.242%" y2="89.03%"><stop offset="0%" stop-color="#FFEA83"></stop><stop offset="8.333%" stop-color="#FFDD35"></stop><stop offset="100%" stop-color="#FFA800"></stop></linearGradient></defs><path fill="url(#IconifyId1813088fe1fbc01fb466)" d="M255.153 37.938L134.897 252.976c-2.483 4.44-8.862 4.466-11.382.048L.875 37.958c-2.746-4.814 1.371-10.646 6.827-9.67l120.385 21.517a6.537 6.537 0 0 0 2.322-.004l117.867-21.483c5.438-.991 9.574 4.796 6.877 9.62Z"></path><path fill="url(#IconifyId1813088fe1fbc01fb467)" d="M185.432.063L96.44 17.501a3.268 3.268 0 0 0-2.634 3.014l-5.474 92.456a3.268 3.268 0 0 0 3.997 3.378l24.777-5.718c2.318-.535 4.413 1.507 3.936 3.838l-7.361 36.047c-.495 2.426 1.782 4.5 4.151 3.78l15.304-4.649c2.372-.72 4.652 1.36 4.15 3.788l-11.698 56.621c-.732 3.542 3.979 5.473 5.943 2.437l1.313-2.028l72.516-144.72c1.215-2.423-.88-5.186-3.54-4.672l-25.505 4.922c-2.396.462-4.435-1.77-3.759-4.114l16.646-57.705c.677-2.35-1.37-4.583-3.769-4.113Z"></path></svg>

Before

Width:  |  Height:  |  Size: 1.5 KiB

View File

@@ -1,83 +1,132 @@
import { Client } from "@modelcontextprotocol/sdk/client/index.js";
import { SSEClientTransport } from "@modelcontextprotocol/sdk/client/sse.js";
import {
CallToolResultSchema,
ClientRequest,
CreateMessageRequestSchema,
CompatibilityCallToolResult,
CompatibilityCallToolResultSchema,
CreateMessageResult,
EmptyResultSchema,
GetPromptResultSchema,
ListPromptsResultSchema,
ListResourcesResultSchema,
ListResourceTemplatesResultSchema,
ListToolsResultSchema,
ProgressNotificationSchema,
ReadResourceResultSchema,
Resource,
ResourceTemplate,
Root,
ServerNotification,
Tool,
LoggingLevel,
} from "@modelcontextprotocol/sdk/types.js";
import { useEffect, useRef, useState } from "react";
import React, {
Suspense,
useCallback,
useEffect,
useRef,
useState,
} from "react";
import { useConnection } from "./lib/hooks/useConnection";
import { useDraggablePane } from "./lib/hooks/useDraggablePane";
import { StdErrNotification } from "./lib/notificationTypes";
import { Button } from "@/components/ui/button";
import { Input } from "@/components/ui/input";
import {
Select,
SelectContent,
SelectItem,
SelectTrigger,
SelectValue,
} from "@/components/ui/select";
import { Tabs, TabsList, TabsTrigger } from "@/components/ui/tabs";
import {
Bell,
Files,
FolderTree,
Hammer,
Hash,
MessageSquare,
Play,
Send,
Terminal,
} from "lucide-react";
import { AnyZodObject } from "zod";
import { z } from "zod";
import "./App.css";
import ConsoleTab from "./components/ConsoleTab";
import HistoryAndNotifications from "./components/History";
import PingTab from "./components/PingTab";
import PromptsTab, { Prompt } from "./components/PromptsTab";
import RequestsTab from "./components/RequestsTabs";
import ResourcesTab from "./components/ResourcesTab";
import RootsTab from "./components/RootsTab";
import SamplingTab, { PendingRequest } from "./components/SamplingTab";
import Sidebar from "./components/Sidebar";
import ToolsTab from "./components/ToolsTab";
import { DEFAULT_INSPECTOR_CONFIG } from "./lib/constants";
import { InspectorConfig } from "./lib/configurationTypes";
import { getMCPProxyAddress } from "./utils/configUtils";
const CONFIG_LOCAL_STORAGE_KEY = "inspectorConfig_v1";
const App = () => {
const [connectionStatus, setConnectionStatus] = useState<
"disconnected" | "connected" | "error"
>("disconnected");
const [resources, setResources] = useState<Resource[]>([]);
const [resourceTemplates, setResourceTemplates] = useState<
ResourceTemplate[]
>([]);
const [resourceContent, setResourceContent] = useState<string>("");
const [prompts, setPrompts] = useState<Prompt[]>([]);
const [promptContent, setPromptContent] = useState<string>("");
const [tools, setTools] = useState<Tool[]>([]);
const [toolResult, setToolResult] = useState<string>("");
const [error, setError] = useState<string | null>(null);
const [toolResult, setToolResult] =
useState<CompatibilityCallToolResult | null>(null);
const [errors, setErrors] = useState<Record<string, string | null>>({
resources: null,
prompts: null,
tools: null,
});
const [command, setCommand] = useState<string>(() => {
return (
localStorage.getItem("lastCommand") ||
"/Users/ashwin/.nvm/versions/node/v18.20.4/bin/node"
);
return localStorage.getItem("lastCommand") || "mcp-server-everything";
});
const [args, setArgs] = useState<string>(() => {
return localStorage.getItem("lastArgs") || "";
});
const [url, setUrl] = useState<string>("http://localhost:3001/sse");
const [transportType, setTransportType] = useState<"stdio" | "sse">("stdio");
const [requestHistory, setRequestHistory] = useState<
{ request: string; response: string }[]
>([]);
const [mcpClient, setMcpClient] = useState<Client | null>(null);
const [sseUrl, setSseUrl] = useState<string>(() => {
return localStorage.getItem("lastSseUrl") || "http://localhost:3001/sse";
});
const [transportType, setTransportType] = useState<
"stdio" | "sse" | "streamable-http"
>(() => {
return (
(localStorage.getItem("lastTransportType") as
| "stdio"
| "sse"
| "streamable-http") || "stdio"
);
});
const [logLevel, setLogLevel] = useState<LoggingLevel>("debug");
const [notifications, setNotifications] = useState<ServerNotification[]>([]);
const [stdErrNotifications, setStdErrNotifications] = useState<
StdErrNotification[]
>([]);
const [roots, setRoots] = useState<Root[]>([]);
const [env, setEnv] = useState<Record<string, string>>({});
const [config, setConfig] = useState<InspectorConfig>(() => {
const savedConfig = localStorage.getItem(CONFIG_LOCAL_STORAGE_KEY);
if (savedConfig) {
// merge default config with saved config
const mergedConfig = {
...DEFAULT_INSPECTOR_CONFIG,
...JSON.parse(savedConfig),
} as InspectorConfig;
// update description of keys to match the new description (in case of any updates to the default config description)
Object.entries(mergedConfig).forEach(([key, value]) => {
mergedConfig[key as keyof InspectorConfig] = {
...value,
label: DEFAULT_INSPECTOR_CONFIG[key as keyof InspectorConfig].label,
};
});
return mergedConfig;
}
return DEFAULT_INSPECTOR_CONFIG;
});
const [bearerToken, setBearerToken] = useState<string>(() => {
return localStorage.getItem("lastBearerToken") || "";
});
const [headerName, setHeaderName] = useState<string>(() => {
return localStorage.getItem("lastHeaderName") || "";
});
const [pendingSampleRequests, setPendingSampleRequests] = useState<
Array<
@@ -88,6 +137,134 @@ const App = () => {
>
>([]);
const nextRequestId = useRef(0);
const rootsRef = useRef<Root[]>([]);
const [selectedResource, setSelectedResource] = useState<Resource | null>(
null,
);
const [resourceSubscriptions, setResourceSubscriptions] = useState<
Set<string>
>(new Set<string>());
const [selectedPrompt, setSelectedPrompt] = useState<Prompt | null>(null);
const [selectedTool, setSelectedTool] = useState<Tool | null>(null);
const [nextResourceCursor, setNextResourceCursor] = useState<
string | undefined
>();
const [nextResourceTemplateCursor, setNextResourceTemplateCursor] = useState<
string | undefined
>();
const [nextPromptCursor, setNextPromptCursor] = useState<
string | undefined
>();
const [nextToolCursor, setNextToolCursor] = useState<string | undefined>();
const progressTokenRef = useRef(0);
const { height: historyPaneHeight, handleDragStart } = useDraggablePane(300);
const {
connectionStatus,
serverCapabilities,
mcpClient,
requestHistory,
makeRequest,
sendNotification,
handleCompletion,
completionsSupported,
connect: connectMcpServer,
disconnect: disconnectMcpServer,
} = useConnection({
transportType,
command,
args,
sseUrl,
env,
bearerToken,
headerName,
config,
onNotification: (notification) => {
setNotifications((prev) => [...prev, notification as ServerNotification]);
},
onStdErrNotification: (notification) => {
setStdErrNotifications((prev) => [
...prev,
notification as StdErrNotification,
]);
},
onPendingRequest: (request, resolve, reject) => {
setPendingSampleRequests((prev) => [
...prev,
{ id: nextRequestId.current++, request, resolve, reject },
]);
},
getRoots: () => rootsRef.current,
});
useEffect(() => {
localStorage.setItem("lastCommand", command);
}, [command]);
useEffect(() => {
localStorage.setItem("lastArgs", args);
}, [args]);
useEffect(() => {
localStorage.setItem("lastSseUrl", sseUrl);
}, [sseUrl]);
useEffect(() => {
localStorage.setItem("lastTransportType", transportType);
}, [transportType]);
useEffect(() => {
localStorage.setItem("lastBearerToken", bearerToken);
}, [bearerToken]);
useEffect(() => {
localStorage.setItem("lastHeaderName", headerName);
}, [headerName]);
useEffect(() => {
localStorage.setItem(CONFIG_LOCAL_STORAGE_KEY, JSON.stringify(config));
}, [config]);
// Auto-connect to previously saved serverURL after OAuth callback
const onOAuthConnect = useCallback(
(serverUrl: string) => {
setSseUrl(serverUrl);
setTransportType("sse");
void connectMcpServer();
},
[connectMcpServer],
);
useEffect(() => {
fetch(`${getMCPProxyAddress(config)}/config`)
.then((response) => response.json())
.then((data) => {
setEnv(data.defaultEnvironment);
if (data.defaultCommand) {
setCommand(data.defaultCommand);
}
if (data.defaultArgs) {
setArgs(data.defaultArgs);
}
})
.catch((error) =>
console.error("Error fetching default environment:", error),
);
// eslint-disable-next-line react-hooks/exhaustive-deps
}, []);
useEffect(() => {
rootsRef.current = roots;
}, [roots]);
useEffect(() => {
if (!window.location.hash) {
window.location.hash = "resources";
}
}, []);
const handleApproveSampling = (id: number, result: CreateMessageResult) => {
setPendingSampleRequests((prev) => {
@@ -105,330 +282,457 @@ const App = () => {
});
};
const [selectedResource, setSelectedResource] = useState<Resource | null>(
null,
);
const [selectedPrompt, setSelectedPrompt] = useState<Prompt | null>(null);
const [selectedTool, setSelectedTool] = useState<Tool | null>(null);
const [nextResourceCursor, setNextResourceCursor] = useState<
string | undefined
>();
const [nextPromptCursor, setNextPromptCursor] = useState<
string | undefined
>();
const [nextToolCursor, setNextToolCursor] = useState<string | undefined>();
const progressTokenRef = useRef(0);
useEffect(() => {
localStorage.setItem("lastCommand", command);
}, [command]);
useEffect(() => {
localStorage.setItem("lastArgs", args);
}, [args]);
const pushHistory = (request: object, response: object) => {
setRequestHistory((prev) => [
...prev,
{ request: JSON.stringify(request), response: JSON.stringify(response) },
]);
const clearError = (tabKey: keyof typeof errors) => {
setErrors((prev) => ({ ...prev, [tabKey]: null }));
};
const makeRequest = async <T extends AnyZodObject>(
const sendMCPRequest = async <T extends z.ZodType>(
request: ClientRequest,
schema: T,
tabKey?: keyof typeof errors,
) => {
if (!mcpClient) {
throw new Error("MCP client not connected");
}
try {
const response = await mcpClient.request(request, schema);
pushHistory(request, response);
const response = await makeRequest(request, schema);
if (tabKey !== undefined) {
clearError(tabKey);
}
return response;
} catch (e: unknown) {
setError((e as Error).message);
} catch (e) {
const errorString = (e as Error).message ?? String(e);
if (tabKey !== undefined) {
setErrors((prev) => ({
...prev,
[tabKey]: errorString,
}));
}
throw e;
}
};
const listResources = async () => {
const response = await makeRequest(
const response = await sendMCPRequest(
{
method: "resources/list" as const,
params: nextResourceCursor ? { cursor: nextResourceCursor } : {},
},
ListResourcesResultSchema,
"resources",
);
setResources(resources.concat(response.resources ?? []));
setNextResourceCursor(response.nextCursor);
};
const listResourceTemplates = async () => {
const response = await sendMCPRequest(
{
method: "resources/templates/list" as const,
params: nextResourceTemplateCursor
? { cursor: nextResourceTemplateCursor }
: {},
},
ListResourceTemplatesResultSchema,
"resources",
);
setResourceTemplates(
resourceTemplates.concat(response.resourceTemplates ?? []),
);
setNextResourceTemplateCursor(response.nextCursor);
};
const readResource = async (uri: string) => {
const response = await makeRequest(
const response = await sendMCPRequest(
{
method: "resources/read" as const,
params: { uri },
},
ReadResourceResultSchema,
"resources",
);
setResourceContent(JSON.stringify(response, null, 2));
};
const subscribeToResource = async (uri: string) => {
if (!resourceSubscriptions.has(uri)) {
await sendMCPRequest(
{
method: "resources/subscribe" as const,
params: { uri },
},
z.object({}),
"resources",
);
const clone = new Set(resourceSubscriptions);
clone.add(uri);
setResourceSubscriptions(clone);
}
};
const unsubscribeFromResource = async (uri: string) => {
if (resourceSubscriptions.has(uri)) {
await sendMCPRequest(
{
method: "resources/unsubscribe" as const,
params: { uri },
},
z.object({}),
"resources",
);
const clone = new Set(resourceSubscriptions);
clone.delete(uri);
setResourceSubscriptions(clone);
}
};
const listPrompts = async () => {
const response = await makeRequest(
const response = await sendMCPRequest(
{
method: "prompts/list" as const,
params: nextPromptCursor ? { cursor: nextPromptCursor } : {},
},
ListPromptsResultSchema,
"prompts",
);
setPrompts(response.prompts);
setNextPromptCursor(response.nextCursor);
};
const getPrompt = async (name: string, args: Record<string, string> = {}) => {
const response = await makeRequest(
const response = await sendMCPRequest(
{
method: "prompts/get" as const,
params: { name, arguments: args },
},
GetPromptResultSchema,
"prompts",
);
setPromptContent(JSON.stringify(response, null, 2));
};
const listTools = async () => {
const response = await makeRequest(
const response = await sendMCPRequest(
{
method: "tools/list" as const,
params: nextToolCursor ? { cursor: nextToolCursor } : {},
},
ListToolsResultSchema,
"tools",
);
setTools(response.tools);
setNextToolCursor(response.nextCursor);
};
const callTool = async (name: string, params: Record<string, unknown>) => {
const response = await makeRequest(
{
method: "tools/call" as const,
params: {
name,
arguments: params,
_meta: {
progressToken: progressTokenRef.current++,
try {
const response = await sendMCPRequest(
{
method: "tools/call" as const,
params: {
name,
arguments: params,
_meta: {
progressToken: progressTokenRef.current++,
},
},
},
},
CallToolResultSchema,
);
setToolResult(JSON.stringify(response.toolResult, null, 2));
};
const connectMcpServer = async () => {
try {
const client = new Client({
name: "mcp-inspector",
version: "0.0.1",
});
const backendUrl = new URL("http://localhost:3000/sse");
backendUrl.searchParams.append("transportType", transportType);
if (transportType === "stdio") {
backendUrl.searchParams.append("command", command);
backendUrl.searchParams.append("args", args);
} else {
backendUrl.searchParams.append("url", url);
}
const clientTransport = new SSEClientTransport(backendUrl);
await client.connect(clientTransport);
client.setNotificationHandler(
ProgressNotificationSchema,
(notification) => {
setNotifications((prevNotifications) => [
...prevNotifications,
notification,
]);
},
CompatibilityCallToolResultSchema,
"tools",
);
client.setRequestHandler(CreateMessageRequestSchema, (request) => {
return new Promise<CreateMessageResult>((resolve, reject) => {
setPendingSampleRequests((prev) => [
...prev,
{ id: nextRequestId.current++, request, resolve, reject },
]);
});
});
setMcpClient(client);
setConnectionStatus("connected");
setToolResult(response);
} catch (e) {
console.error(e);
setConnectionStatus("error");
const toolResult: CompatibilityCallToolResult = {
content: [
{
type: "text",
text: (e as Error).message ?? String(e),
},
],
isError: true,
};
setToolResult(toolResult);
}
};
const handleRootsChange = async () => {
await sendNotification({ method: "notifications/roots/list_changed" });
};
const sendLogLevelRequest = async (level: LoggingLevel) => {
await sendMCPRequest(
{
method: "logging/setLevel" as const,
params: { level },
},
z.object({}),
);
setLogLevel(level);
};
const clearStdErrNotifications = () => {
setStdErrNotifications([]);
};
if (window.location.pathname === "/oauth/callback") {
const OAuthCallback = React.lazy(
() => import("./components/OAuthCallback"),
);
return (
<Suspense fallback={<div>Loading...</div>}>
<OAuthCallback onConnect={onOAuthConnect} />
</Suspense>
);
}
return (
<div className="flex h-screen bg-gray-100">
<Sidebar connectionStatus={connectionStatus} />
<div className="flex h-screen bg-background">
<Sidebar
connectionStatus={connectionStatus}
transportType={transportType}
setTransportType={setTransportType}
command={command}
setCommand={setCommand}
args={args}
setArgs={setArgs}
sseUrl={sseUrl}
setSseUrl={setSseUrl}
env={env}
setEnv={setEnv}
config={config}
setConfig={setConfig}
bearerToken={bearerToken}
setBearerToken={setBearerToken}
headerName={headerName}
setHeaderName={setHeaderName}
onConnect={connectMcpServer}
onDisconnect={disconnectMcpServer}
stdErrNotifications={stdErrNotifications}
logLevel={logLevel}
sendLogLevelRequest={sendLogLevelRequest}
loggingSupported={!!serverCapabilities?.logging || false}
clearStdErrNotifications={clearStdErrNotifications}
/>
<div className="flex-1 flex flex-col overflow-hidden">
<h1 className="text-2xl font-bold p-4">MCP Inspector</h1>
<div className="flex-1 overflow-auto flex">
<div className="flex-1">
<div className="p-4 bg-white shadow-md m-4 rounded-md">
<h2 className="text-lg font-semibold mb-2">Connect MCP Server</h2>
<div className="flex space-x-2 mb-2">
<Select
value={transportType}
onValueChange={(value: "stdio" | "sse") =>
setTransportType(value)
}
<div className="flex-1 overflow-auto">
{mcpClient ? (
<Tabs
defaultValue={
Object.keys(serverCapabilities ?? {}).includes(
window.location.hash.slice(1),
)
? window.location.hash.slice(1)
: serverCapabilities?.resources
? "resources"
: serverCapabilities?.prompts
? "prompts"
: serverCapabilities?.tools
? "tools"
: "ping"
}
className="w-full p-4"
onValueChange={(value) => (window.location.hash = value)}
>
<TabsList className="mb-4 p-0">
<TabsTrigger
value="resources"
disabled={!serverCapabilities?.resources}
>
<SelectTrigger className="w-[180px]">
<SelectValue placeholder="Select transport type" />
</SelectTrigger>
<SelectContent>
<SelectItem value="stdio">STDIO</SelectItem>
<SelectItem value="sse">SSE</SelectItem>
</SelectContent>
</Select>
{transportType === "stdio" ? (
<Files className="w-4 h-4 mr-2" />
Resources
</TabsTrigger>
<TabsTrigger
value="prompts"
disabled={!serverCapabilities?.prompts}
>
<MessageSquare className="w-4 h-4 mr-2" />
Prompts
</TabsTrigger>
<TabsTrigger
value="tools"
disabled={!serverCapabilities?.tools}
>
<Hammer className="w-4 h-4 mr-2" />
Tools
</TabsTrigger>
<TabsTrigger value="ping">
<Bell className="w-4 h-4 mr-2" />
Ping
</TabsTrigger>
<TabsTrigger value="sampling" className="relative">
<Hash className="w-4 h-4 mr-2" />
Sampling
{pendingSampleRequests.length > 0 && (
<span className="absolute -top-1 -right-1 bg-red-500 text-white text-xs rounded-full h-4 w-4 flex items-center justify-center">
{pendingSampleRequests.length}
</span>
)}
</TabsTrigger>
<TabsTrigger value="roots">
<FolderTree className="w-4 h-4 mr-2" />
Roots
</TabsTrigger>
</TabsList>
<div className="w-full">
{!serverCapabilities?.resources &&
!serverCapabilities?.prompts &&
!serverCapabilities?.tools ? (
<div className="flex items-center justify-center p-4">
<p className="text-lg text-gray-500">
The connected server does not support any MCP capabilities
</p>
</div>
) : (
<>
<Input
placeholder="Command"
value={command}
onChange={(e) => setCommand(e.target.value)}
<ResourcesTab
resources={resources}
resourceTemplates={resourceTemplates}
listResources={() => {
clearError("resources");
listResources();
}}
clearResources={() => {
setResources([]);
setNextResourceCursor(undefined);
}}
listResourceTemplates={() => {
clearError("resources");
listResourceTemplates();
}}
clearResourceTemplates={() => {
setResourceTemplates([]);
setNextResourceTemplateCursor(undefined);
}}
readResource={(uri) => {
clearError("resources");
readResource(uri);
}}
selectedResource={selectedResource}
setSelectedResource={(resource) => {
clearError("resources");
setSelectedResource(resource);
}}
resourceSubscriptionsSupported={
serverCapabilities?.resources?.subscribe || false
}
resourceSubscriptions={resourceSubscriptions}
subscribeToResource={(uri) => {
clearError("resources");
subscribeToResource(uri);
}}
unsubscribeFromResource={(uri) => {
clearError("resources");
unsubscribeFromResource(uri);
}}
handleCompletion={handleCompletion}
completionsSupported={completionsSupported}
resourceContent={resourceContent}
nextCursor={nextResourceCursor}
nextTemplateCursor={nextResourceTemplateCursor}
error={errors.resources}
/>
<Input
placeholder="Arguments (space-separated)"
value={args}
onChange={(e) => setArgs(e.target.value)}
<PromptsTab
prompts={prompts}
listPrompts={() => {
clearError("prompts");
listPrompts();
}}
clearPrompts={() => {
setPrompts([]);
setNextPromptCursor(undefined);
}}
getPrompt={(name, args) => {
clearError("prompts");
getPrompt(name, args);
}}
selectedPrompt={selectedPrompt}
setSelectedPrompt={(prompt) => {
clearError("prompts");
setSelectedPrompt(prompt);
setPromptContent("");
}}
handleCompletion={handleCompletion}
completionsSupported={completionsSupported}
promptContent={promptContent}
nextCursor={nextPromptCursor}
error={errors.prompts}
/>
<ToolsTab
tools={tools}
listTools={() => {
clearError("tools");
listTools();
}}
clearTools={() => {
setTools([]);
setNextToolCursor(undefined);
}}
callTool={async (name, params) => {
clearError("tools");
setToolResult(null);
await callTool(name, params);
}}
selectedTool={selectedTool}
setSelectedTool={(tool) => {
clearError("tools");
setSelectedTool(tool);
setToolResult(null);
}}
toolResult={toolResult}
nextCursor={nextToolCursor}
error={errors.tools}
/>
<ConsoleTab />
<PingTab
onPingClick={() => {
void sendMCPRequest(
{
method: "ping" as const,
},
EmptyResultSchema,
);
}}
/>
<SamplingTab
pendingRequests={pendingSampleRequests}
onApprove={handleApproveSampling}
onReject={handleRejectSampling}
/>
<RootsTab
roots={roots}
setRoots={setRoots}
onRootsChange={handleRootsChange}
/>
</>
) : (
<Input
placeholder="URL"
value={url}
onChange={(e) => setUrl(e.target.value)}
/>
)}
<Button onClick={connectMcpServer}>
<Play className="w-4 h-4 mr-2" />
Connect
</Button>
</div>
</Tabs>
) : (
<div className="flex items-center justify-center h-full">
<p className="text-lg text-gray-500">
Connect to an MCP server to start inspecting
</p>
</div>
{mcpClient ? (
<Tabs defaultValue="resources" className="w-full p-4">
<TabsList className="mb-4 p-0">
<TabsTrigger value="resources">
<Files className="w-4 h-4 mr-2" />
Resources
</TabsTrigger>
<TabsTrigger value="prompts">
<MessageSquare className="w-4 h-4 mr-2" />
Prompts
</TabsTrigger>
<TabsTrigger value="requests" disabled>
<Send className="w-4 h-4 mr-2" />
Requests
</TabsTrigger>
<TabsTrigger value="tools">
<Hammer className="w-4 h-4 mr-2" />
Tools
</TabsTrigger>
<TabsTrigger value="console" disabled>
<Terminal className="w-4 h-4 mr-2" />
Console
</TabsTrigger>
<TabsTrigger value="ping">
<Bell className="w-4 h-4 mr-2" />
Ping
</TabsTrigger>
<TabsTrigger value="sampling" className="relative">
<Hash className="w-4 h-4 mr-2" />
Sampling
{pendingSampleRequests.length > 0 && (
<span className="absolute -top-1 -right-1 bg-red-500 text-white text-xs rounded-full h-4 w-4 flex items-center justify-center">
{pendingSampleRequests.length}
</span>
)}
</TabsTrigger>
</TabsList>
<div className="w-full">
<ResourcesTab
resources={resources}
listResources={listResources}
readResource={readResource}
selectedResource={selectedResource}
setSelectedResource={setSelectedResource}
resourceContent={resourceContent}
nextCursor={nextResourceCursor}
error={error}
/>
<PromptsTab
prompts={prompts}
listPrompts={listPrompts}
getPrompt={getPrompt}
selectedPrompt={selectedPrompt}
setSelectedPrompt={setSelectedPrompt}
promptContent={promptContent}
nextCursor={nextPromptCursor}
error={error}
/>
<RequestsTab />
<ToolsTab
tools={tools}
listTools={listTools}
callTool={callTool}
selectedTool={selectedTool}
setSelectedTool={(tool) => {
setSelectedTool(tool);
setToolResult("");
}}
toolResult={toolResult}
nextCursor={nextToolCursor}
error={error}
/>
<ConsoleTab />
<PingTab
onPingClick={() => {
void makeRequest(
{
method: "ping" as const,
},
EmptyResultSchema,
);
}}
/>
<SamplingTab
pendingRequests={pendingSampleRequests}
onApprove={handleApproveSampling}
onReject={handleRejectSampling}
/>
</div>
</Tabs>
) : (
<div className="flex items-center justify-center h-full">
<p className="text-lg text-gray-500">
Connect to an MCP server to start inspecting
</p>
</div>
)}
)}
</div>
<div
className="relative border-t border-border"
style={{
height: `${historyPaneHeight}px`,
}}
>
<div
className="absolute w-full h-4 -top-2 cursor-row-resize flex items-center justify-center hover:bg-accent/50"
onMouseDown={handleDragStart}
>
<div className="w-8 h-1 rounded-full bg-border" />
</div>
<div className="h-full overflow-auto">
<HistoryAndNotifications
requestHistory={requestHistory}
serverNotifications={notifications}
/>
</div>
</div>
</div>
<HistoryAndNotifications
requestHistory={requestHistory}
serverNotifications={notifications}
/>
</div>
);
};

View File

@@ -0,0 +1 @@
module.exports = {};

View File

@@ -1 +0,0 @@
<svg xmlns="http://www.w3.org/2000/svg" xmlns:xlink="http://www.w3.org/1999/xlink" aria-hidden="true" role="img" class="iconify iconify--logos" width="35.93" height="32" preserveAspectRatio="xMidYMid meet" viewBox="0 0 256 228"><path fill="#00D8FF" d="M210.483 73.824a171.49 171.49 0 0 0-8.24-2.597c.465-1.9.893-3.777 1.273-5.621c6.238-30.281 2.16-54.676-11.769-62.708c-13.355-7.7-35.196.329-57.254 19.526a171.23 171.23 0 0 0-6.375 5.848a155.866 155.866 0 0 0-4.241-3.917C100.759 3.829 77.587-4.822 63.673 3.233C50.33 10.957 46.379 33.89 51.995 62.588a170.974 170.974 0 0 0 1.892 8.48c-3.28.932-6.445 1.924-9.474 2.98C17.309 83.498 0 98.307 0 113.668c0 15.865 18.582 31.778 46.812 41.427a145.52 145.52 0 0 0 6.921 2.165a167.467 167.467 0 0 0-2.01 9.138c-5.354 28.2-1.173 50.591 12.134 58.266c13.744 7.926 36.812-.22 59.273-19.855a145.567 145.567 0 0 0 5.342-4.923a168.064 168.064 0 0 0 6.92 6.314c21.758 18.722 43.246 26.282 56.54 18.586c13.731-7.949 18.194-32.003 12.4-61.268a145.016 145.016 0 0 0-1.535-6.842c1.62-.48 3.21-.974 4.76-1.488c29.348-9.723 48.443-25.443 48.443-41.52c0-15.417-17.868-30.326-45.517-39.844Zm-6.365 70.984c-1.4.463-2.836.91-4.3 1.345c-3.24-10.257-7.612-21.163-12.963-32.432c5.106-11 9.31-21.767 12.459-31.957c2.619.758 5.16 1.557 7.61 2.4c23.69 8.156 38.14 20.213 38.14 29.504c0 9.896-15.606 22.743-40.946 31.14Zm-10.514 20.834c2.562 12.94 2.927 24.64 1.23 33.787c-1.524 8.219-4.59 13.698-8.382 15.893c-8.067 4.67-25.32-1.4-43.927-17.412a156.726 156.726 0 0 1-6.437-5.87c7.214-7.889 14.423-17.06 21.459-27.246c12.376-1.098 24.068-2.894 34.671-5.345a134.17 134.17 0 0 1 1.386 6.193ZM87.276 214.515c-7.882 2.783-14.16 2.863-17.955.675c-8.075-4.657-11.432-22.636-6.853-46.752a156.923 156.923 0 0 1 1.869-8.499c10.486 2.32 22.093 3.988 34.498 4.994c7.084 9.967 14.501 19.128 21.976 27.15a134.668 134.668 0 0 1-4.877 4.492c-9.933 8.682-19.886 14.842-28.658 17.94ZM50.35 144.747c-12.483-4.267-22.792-9.812-29.858-15.863c-6.35-5.437-9.555-10.836-9.555-15.216c0-9.322 13.897-21.212 37.076-29.293c2.813-.98 5.757-1.905 8.812-2.773c3.204 10.42 7.406 21.315 12.477 32.332c-5.137 11.18-9.399 22.249-12.634 32.792a134.718 134.718 0 0 1-6.318-1.979Zm12.378-84.26c-4.811-24.587-1.616-43.134 6.425-47.789c8.564-4.958 27.502 2.111 47.463 19.835a144.318 144.318 0 0 1 3.841 3.545c-7.438 7.987-14.787 17.08-21.808 26.988c-12.04 1.116-23.565 2.908-34.161 5.309a160.342 160.342 0 0 1-1.76-7.887Zm110.427 27.268a347.8 347.8 0 0 0-7.785-12.803c8.168 1.033 15.994 2.404 23.343 4.08c-2.206 7.072-4.956 14.465-8.193 22.045a381.151 381.151 0 0 0-7.365-13.322Zm-45.032-43.861c5.044 5.465 10.096 11.566 15.065 18.186a322.04 322.04 0 0 0-30.257-.006c4.974-6.559 10.069-12.652 15.192-18.18ZM82.802 87.83a323.167 323.167 0 0 0-7.227 13.238c-3.184-7.553-5.909-14.98-8.134-22.152c7.304-1.634 15.093-2.97 23.209-3.984a321.524 321.524 0 0 0-7.848 12.897Zm8.081 65.352c-8.385-.936-16.291-2.203-23.593-3.793c2.26-7.3 5.045-14.885 8.298-22.6a321.187 321.187 0 0 0 7.257 13.246c2.594 4.48 5.28 8.868 8.038 13.147Zm37.542 31.03c-5.184-5.592-10.354-11.779-15.403-18.433c4.902.192 9.899.29 14.978.29c5.218 0 10.376-.117 15.453-.343c-4.985 6.774-10.018 12.97-15.028 18.486Zm52.198-57.817c3.422 7.8 6.306 15.345 8.596 22.52c-7.422 1.694-15.436 3.058-23.88 4.071a382.417 382.417 0 0 0 7.859-13.026a347.403 347.403 0 0 0 7.425-13.565Zm-16.898 8.101a358.557 358.557 0 0 1-12.281 19.815a329.4 329.4 0 0 1-23.444.823c-7.967 0-15.716-.248-23.178-.732a310.202 310.202 0 0 1-12.513-19.846h.001a307.41 307.41 0 0 1-10.923-20.627a310.278 310.278 0 0 1 10.89-20.637l-.001.001a307.318 307.318 0 0 1 12.413-19.761c7.613-.576 15.42-.876 23.31-.876H128c7.926 0 15.743.303 23.354.883a329.357 329.357 0 0 1 12.335 19.695a358.489 358.489 0 0 1 11.036 20.54a329.472 329.472 0 0 1-11 20.722Zm22.56-122.124c8.572 4.944 11.906 24.881 6.52 51.026c-.344 1.668-.73 3.367-1.15 5.09c-10.622-2.452-22.155-4.275-34.23-5.408c-7.034-10.017-14.323-19.124-21.64-27.008a160.789 160.789 0 0 1 5.888-5.4c18.9-16.447 36.564-22.941 44.612-18.3ZM128 90.808c12.625 0 22.86 10.235 22.86 22.86s-10.235 22.86-22.86 22.86s-22.86-10.235-22.86-22.86s10.235-22.86 22.86-22.86Z"></path></svg>

Before

Width:  |  Height:  |  Size: 4.0 KiB

View File

@@ -0,0 +1,308 @@
import { useState, useEffect, useCallback, useRef } from "react";
import { Button } from "@/components/ui/button";
import { Input } from "@/components/ui/input";
import JsonEditor from "./JsonEditor";
import { updateValueAtPath } from "@/utils/jsonUtils";
import { generateDefaultValue } from "@/utils/schemaUtils";
import type { JsonValue, JsonSchemaType } from "@/utils/jsonUtils";
interface DynamicJsonFormProps {
schema: JsonSchemaType;
value: JsonValue;
onChange: (value: JsonValue) => void;
maxDepth?: number;
}
const isSimpleObject = (schema: JsonSchemaType): boolean => {
const supportedTypes = ["string", "number", "integer", "boolean", "null"];
if (supportedTypes.includes(schema.type)) return true;
if (schema.type !== "object") return false;
return Object.values(schema.properties ?? {}).every((prop) =>
supportedTypes.includes(prop.type),
);
};
const DynamicJsonForm = ({
schema,
value,
onChange,
maxDepth = 3,
}: DynamicJsonFormProps) => {
const isOnlyJSON = !isSimpleObject(schema);
const [isJsonMode, setIsJsonMode] = useState(isOnlyJSON);
const [jsonError, setJsonError] = useState<string>();
// Store the raw JSON string to allow immediate feedback during typing
// while deferring parsing until the user stops typing
const [rawJsonValue, setRawJsonValue] = useState<string>(
JSON.stringify(value ?? generateDefaultValue(schema), null, 2),
);
// Use a ref to manage debouncing timeouts to avoid parsing JSON
// on every keystroke which would be inefficient and error-prone
const timeoutRef = useRef<ReturnType<typeof setTimeout>>();
// Debounce JSON parsing and parent updates to handle typing gracefully
const debouncedUpdateParent = useCallback(
(jsonString: string) => {
// Clear any existing timeout
if (timeoutRef.current) {
clearTimeout(timeoutRef.current);
}
// Set a new timeout
timeoutRef.current = setTimeout(() => {
try {
const parsed = JSON.parse(jsonString);
onChange(parsed);
setJsonError(undefined);
} catch {
// Don't set error during normal typing
}
}, 300);
},
[onChange, setJsonError],
);
// Update rawJsonValue when value prop changes
useEffect(() => {
if (!isJsonMode) {
setRawJsonValue(
JSON.stringify(value ?? generateDefaultValue(schema), null, 2),
);
}
}, [value, schema, isJsonMode]);
const handleSwitchToFormMode = () => {
if (isJsonMode) {
// When switching to Form mode, ensure we have valid JSON
try {
const parsed = JSON.parse(rawJsonValue);
// Update the parent component's state with the parsed value
onChange(parsed);
// Switch to form mode
setIsJsonMode(false);
} catch (err) {
setJsonError(err instanceof Error ? err.message : "Invalid JSON");
}
} else {
// Update raw JSON value when switching to JSON mode
setRawJsonValue(
JSON.stringify(value ?? generateDefaultValue(schema), null, 2),
);
setIsJsonMode(true);
}
};
const formatJson = () => {
try {
const jsonStr = rawJsonValue.trim();
if (!jsonStr) {
return;
}
const formatted = JSON.stringify(JSON.parse(jsonStr), null, 2);
setRawJsonValue(formatted);
debouncedUpdateParent(formatted);
setJsonError(undefined);
} catch (err) {
setJsonError(err instanceof Error ? err.message : "Invalid JSON");
}
};
const renderFormFields = (
propSchema: JsonSchemaType,
currentValue: JsonValue,
path: string[] = [],
depth: number = 0,
) => {
if (
depth >= maxDepth &&
(propSchema.type === "object" || propSchema.type === "array")
) {
// Render as JSON editor when max depth is reached
return (
<JsonEditor
value={JSON.stringify(
currentValue ?? generateDefaultValue(propSchema),
null,
2,
)}
onChange={(newValue) => {
try {
const parsed = JSON.parse(newValue);
handleFieldChange(path, parsed);
setJsonError(undefined);
} catch (err) {
setJsonError(err instanceof Error ? err.message : "Invalid JSON");
}
}}
error={jsonError}
/>
);
}
switch (propSchema.type) {
case "string":
return (
<Input
type="text"
value={(currentValue as string) ?? ""}
onChange={(e) => {
const val = e.target.value;
// Allow clearing non-required fields by setting undefined
// This preserves the distinction between empty string and unset
if (!val && !propSchema.required) {
handleFieldChange(path, undefined);
} else {
handleFieldChange(path, val);
}
}}
placeholder={propSchema.description}
required={propSchema.required}
/>
);
case "number":
return (
<Input
type="number"
value={(currentValue as number)?.toString() ?? ""}
onChange={(e) => {
const val = e.target.value;
// Allow clearing non-required number fields
// This preserves the distinction between 0 and unset
if (!val && !propSchema.required) {
handleFieldChange(path, undefined);
} else {
const num = Number(val);
if (!isNaN(num)) {
handleFieldChange(path, num);
}
}
}}
placeholder={propSchema.description}
required={propSchema.required}
/>
);
case "integer":
return (
<Input
type="number"
step="1"
value={(currentValue as number)?.toString() ?? ""}
onChange={(e) => {
const val = e.target.value;
// Allow clearing non-required integer fields
// This preserves the distinction between 0 and unset
if (!val && !propSchema.required) {
handleFieldChange(path, undefined);
} else {
const num = Number(val);
// Only update if it's a valid integer
if (!isNaN(num) && Number.isInteger(num)) {
handleFieldChange(path, num);
}
}
}}
placeholder={propSchema.description}
required={propSchema.required}
/>
);
case "boolean":
return (
<Input
type="checkbox"
checked={(currentValue as boolean) ?? false}
onChange={(e) => handleFieldChange(path, e.target.checked)}
className="w-4 h-4"
required={propSchema.required}
/>
);
default:
return null;
}
};
const handleFieldChange = (path: string[], fieldValue: JsonValue) => {
if (path.length === 0) {
onChange(fieldValue);
return;
}
try {
const newValue = updateValueAtPath(value, path, fieldValue);
onChange(newValue);
} catch (error) {
console.error("Failed to update form value:", error);
onChange(value);
}
};
const shouldUseJsonMode =
schema.type === "object" &&
(!schema.properties || Object.keys(schema.properties).length === 0);
useEffect(() => {
if (shouldUseJsonMode && !isJsonMode) {
setIsJsonMode(true);
}
}, [shouldUseJsonMode, isJsonMode]);
return (
<div className="space-y-4">
<div className="flex justify-end space-x-2">
{isJsonMode && (
<Button
type="button"
variant="outline"
size="sm"
onClick={formatJson}
>
Format JSON
</Button>
)}
{!isOnlyJSON && (
<Button variant="outline" size="sm" onClick={handleSwitchToFormMode}>
{isJsonMode ? "Switch to Form" : "Switch to JSON"}
</Button>
)}
</div>
{isJsonMode ? (
<JsonEditor
value={rawJsonValue}
onChange={(newValue) => {
// Always update local state
setRawJsonValue(newValue);
// Use the debounced function to attempt parsing and updating parent
debouncedUpdateParent(newValue);
}}
error={jsonError}
/>
) : // If schema type is object but value is not an object or is empty, and we have actual JSON data,
// render a simple representation of the JSON data
schema.type === "object" &&
(typeof value !== "object" ||
value === null ||
Object.keys(value).length === 0) &&
rawJsonValue &&
rawJsonValue !== "{}" ? (
<div className="space-y-4 border rounded-md p-4">
<p className="text-sm text-gray-500">
Form view not available for this JSON structure. Using simplified
view:
</p>
<pre className="bg-gray-50 dark:bg-gray-800 dark:text-gray-100 p-4 rounded text-sm overflow-auto">
{rawJsonValue}
</pre>
<p className="text-sm text-gray-500">
Use JSON mode for full editing capabilities.
</p>
</div>
) : (
renderFormFields(schema, value)
)}
</div>
);
};
export default DynamicJsonForm;

View File

@@ -1,12 +1,12 @@
import { ServerNotification } from "@modelcontextprotocol/sdk/types.js";
import { Copy } from "lucide-react";
import { useState } from "react";
import JsonView from "./JsonView";
const HistoryAndNotifications = ({
requestHistory,
serverNotifications,
}: {
requestHistory: Array<{ request: string; response: string | null }>;
requestHistory: Array<{ request: string; response?: string }>;
serverNotifications: ServerNotification[];
}) => {
const [expandedRequests, setExpandedRequests] = useState<{
@@ -24,13 +24,9 @@ const HistoryAndNotifications = ({
setExpandedNotifications((prev) => ({ ...prev, [index]: !prev[index] }));
};
const copyToClipboard = (text: string) => {
navigator.clipboard.writeText(text);
};
return (
<div className="w-64 bg-white shadow-md p-4 overflow-hidden flex flex-col h-full">
<div className="flex-1 overflow-y-auto mb-4 border-b pb-4">
<div className="bg-card overflow-hidden flex h-full">
<div className="flex-1 overflow-y-auto p-4 border-r">
<h2 className="text-lg font-semibold mb-4">History</h2>
{requestHistory.length === 0 ? (
<p className="text-sm text-gray-500 italic">No history yet</p>
@@ -42,7 +38,7 @@ const HistoryAndNotifications = ({
.map((request, index) => (
<li
key={index}
className="text-sm text-gray-600 bg-gray-100 p-2 rounded"
className="text-sm text-foreground bg-secondary p-2 rounded"
>
<div
className="flex justify-between items-center cursor-pointer"
@@ -67,16 +63,12 @@ const HistoryAndNotifications = ({
<span className="font-semibold text-blue-600">
Request:
</span>
<button
onClick={() => copyToClipboard(request.request)}
className="text-blue-500 hover:text-blue-700"
>
<Copy size={16} />
</button>
</div>
<pre className="whitespace-pre-wrap break-words bg-blue-50 p-2 rounded">
{JSON.stringify(JSON.parse(request.request), null, 2)}
</pre>
<JsonView
data={request.request}
className="bg-background"
/>
</div>
{request.response && (
<div className="mt-2">
@@ -84,20 +76,11 @@ const HistoryAndNotifications = ({
<span className="font-semibold text-green-600">
Response:
</span>
<button
onClick={() => copyToClipboard(request.response!)}
className="text-blue-500 hover:text-blue-700"
>
<Copy size={16} />
</button>
</div>
<pre className="whitespace-pre-wrap break-words bg-green-50 p-2 rounded">
{JSON.stringify(
JSON.parse(request.response),
null,
2,
)}
</pre>
<JsonView
data={request.response}
className="bg-background"
/>
</div>
)}
</>
@@ -107,7 +90,7 @@ const HistoryAndNotifications = ({
</ul>
)}
</div>
<div className="flex-1 overflow-y-auto">
<div className="flex-1 overflow-y-auto p-4">
<h2 className="text-lg font-semibold mb-4">Server Notifications</h2>
{serverNotifications.length === 0 ? (
<p className="text-sm text-gray-500 italic">No notifications yet</p>
@@ -119,7 +102,7 @@ const HistoryAndNotifications = ({
.map((notification, index) => (
<li
key={index}
className="text-sm text-gray-600 bg-gray-100 p-2 rounded"
className="text-sm text-foreground bg-secondary p-2 rounded"
>
<div
className="flex justify-between items-center cursor-pointer"
@@ -137,18 +120,11 @@ const HistoryAndNotifications = ({
<span className="font-semibold text-purple-600">
Details:
</span>
<button
onClick={() =>
copyToClipboard(JSON.stringify(notification))
}
className="text-blue-500 hover:text-blue-700"
>
<Copy size={16} />
</button>
</div>
<pre className="whitespace-pre-wrap break-words bg-purple-50 p-2 rounded">
{JSON.stringify(notification, null, 2)}
</pre>
<JsonView
data={JSON.stringify(notification, null, 2)}
className="bg-background"
/>
</div>
)}
</li>

View File

@@ -0,0 +1,67 @@
import { useState, useEffect } from "react";
import Editor from "react-simple-code-editor";
import Prism from "prismjs";
import "prismjs/components/prism-json";
import "prismjs/themes/prism.css";
interface JsonEditorProps {
value: string;
onChange: (value: string) => void;
error?: string;
}
const JsonEditor = ({
value,
onChange,
error: externalError,
}: JsonEditorProps) => {
const [editorContent, setEditorContent] = useState(value || "");
const [internalError, setInternalError] = useState<string | undefined>(
undefined,
);
useEffect(() => {
setEditorContent(value || "");
}, [value]);
const handleEditorChange = (newContent: string) => {
setEditorContent(newContent);
setInternalError(undefined);
onChange(newContent);
};
const displayError = internalError || externalError;
return (
<div className="relative">
<div
className={`border rounded-md ${
displayError
? "border-red-500"
: "border-gray-200 dark:border-gray-800"
}`}
>
<Editor
value={editorContent}
onValueChange={handleEditorChange}
highlight={(code) =>
Prism.highlight(code, Prism.languages.json, "json")
}
padding={10}
style={{
fontFamily: '"Fira code", "Fira Mono", monospace',
fontSize: 14,
backgroundColor: "transparent",
minHeight: "100px",
}}
className="w-full"
/>
</div>
{displayError && (
<p className="text-sm text-red-500 mt-1">{displayError}</p>
)}
</div>
);
};
export default JsonEditor;

View File

@@ -0,0 +1,286 @@
import { useState, memo, useMemo, useCallback, useEffect } from "react";
import type { JsonValue } from "@/utils/jsonUtils";
import clsx from "clsx";
import { Copy, CheckCheck } from "lucide-react";
import { Button } from "@/components/ui/button";
import { useToast } from "@/hooks/use-toast";
import { getDataType, tryParseJson } from "@/utils/jsonUtils";
interface JsonViewProps {
data: unknown;
name?: string;
initialExpandDepth?: number;
className?: string;
withCopyButton?: boolean;
isError?: boolean;
}
const JsonView = memo(
({
data,
name,
initialExpandDepth = 3,
className,
withCopyButton = true,
isError = false,
}: JsonViewProps) => {
const { toast } = useToast();
const [copied, setCopied] = useState(false);
useEffect(() => {
let timeoutId: NodeJS.Timeout;
if (copied) {
timeoutId = setTimeout(() => {
setCopied(false);
}, 500);
}
return () => {
if (timeoutId) {
clearTimeout(timeoutId);
}
};
}, [copied]);
const normalizedData = useMemo(() => {
return typeof data === "string"
? tryParseJson(data).success
? tryParseJson(data).data
: data
: data;
}, [data]);
const handleCopy = useCallback(() => {
try {
navigator.clipboard.writeText(
typeof normalizedData === "string"
? normalizedData
: JSON.stringify(normalizedData, null, 2),
);
setCopied(true);
} catch (error) {
toast({
title: "Error",
description: `There was an error coping result into the clipboard: ${error instanceof Error ? error.message : String(error)}`,
variant: "destructive",
});
}
}, [toast, normalizedData]);
return (
<div className={clsx("p-4 border rounded relative", className)}>
{withCopyButton && (
<Button
size="icon"
variant="ghost"
className="absolute top-2 right-2"
onClick={handleCopy}
>
{copied ? (
<CheckCheck className="size-4 dark:text-green-700 text-green-600" />
) : (
<Copy className="size-4 text-foreground" />
)}
</Button>
)}
<div className="font-mono text-sm transition-all duration-300">
<JsonNode
data={normalizedData as JsonValue}
name={name}
depth={0}
initialExpandDepth={initialExpandDepth}
isError={isError}
/>
</div>
</div>
);
},
);
JsonView.displayName = "JsonView";
interface JsonNodeProps {
data: JsonValue;
name?: string;
depth: number;
initialExpandDepth: number;
isError?: boolean;
}
const JsonNode = memo(
({
data,
name,
depth = 0,
initialExpandDepth,
isError = false,
}: JsonNodeProps) => {
const [isExpanded, setIsExpanded] = useState(depth < initialExpandDepth);
const [typeStyleMap] = useState<Record<string, string>>({
number: "text-blue-600",
boolean: "text-amber-600",
null: "text-purple-600",
undefined: "text-gray-600",
string: "text-green-600 group-hover:text-green-500",
error: "text-red-600 group-hover:text-red-500",
default: "text-gray-700",
});
const dataType = getDataType(data);
const renderCollapsible = (isArray: boolean) => {
const items = isArray
? (data as JsonValue[])
: Object.entries(data as Record<string, JsonValue>);
const itemCount = items.length;
const isEmpty = itemCount === 0;
const symbolMap = {
open: isArray ? "[" : "{",
close: isArray ? "]" : "}",
collapsed: isArray ? "[ ... ]" : "{ ... }",
empty: isArray ? "[]" : "{}",
};
if (isEmpty) {
return (
<div className="flex items-center">
{name && (
<span className="mr-1 text-gray-600 dark:text-gray-400">
{name}:
</span>
)}
<span className="text-gray-500">{symbolMap.empty}</span>
</div>
);
}
return (
<div className="flex flex-col">
<div
className="flex items-center mr-1 rounded cursor-pointer group hover:bg-gray-800/10 dark:hover:bg-gray-800/20"
onClick={() => setIsExpanded(!isExpanded)}
>
{name && (
<span className="mr-1 text-gray-600 dark:text-gray-400 dark:group-hover:text-gray-100 group-hover:text-gray-400">
{name}:
</span>
)}
{isExpanded ? (
<span className="text-gray-600 dark:text-gray-400 dark:group-hover:text-gray-100 group-hover:text-gray-400">
{symbolMap.open}
</span>
) : (
<>
<span className="text-gray-600 dark:group-hover:text-gray-100 group-hover:text-gray-400">
{symbolMap.collapsed}
</span>
<span className="ml-1 text-gray-700 dark:group-hover:text-gray-100 group-hover:text-gray-400">
{itemCount} {itemCount === 1 ? "item" : "items"}
</span>
</>
)}
</div>
{isExpanded && (
<>
<div className="pl-2 ml-4 border-l border-gray-200 dark:border-gray-800">
{isArray
? (items as JsonValue[]).map((item, index) => (
<div key={index} className="my-1">
<JsonNode
data={item}
name={`${index}`}
depth={depth + 1}
initialExpandDepth={initialExpandDepth}
/>
</div>
))
: (items as [string, JsonValue][]).map(([key, value]) => (
<div key={key} className="my-1">
<JsonNode
data={value}
name={key}
depth={depth + 1}
initialExpandDepth={initialExpandDepth}
/>
</div>
))}
</div>
<div className="text-gray-600 dark:text-gray-400">
{symbolMap.close}
</div>
</>
)}
</div>
);
};
const renderString = (value: string) => {
const maxLength = 100;
const isTooLong = value.length > maxLength;
if (!isTooLong) {
return (
<div className="flex mr-1 rounded hover:bg-gray-800/20">
{name && (
<span className="mr-1 text-gray-600 dark:text-gray-400">
{name}:
</span>
)}
<pre
className={clsx(
isError ? typeStyleMap.error : typeStyleMap.string,
"break-all whitespace-pre-wrap",
)}
>
"{value}"
</pre>
</div>
);
}
return (
<div className="flex mr-1 rounded group hover:bg-gray-800/20">
{name && (
<span className="mr-1 text-gray-600 dark:text-gray-400 dark:group-hover:text-gray-100 group-hover:text-gray-400">
{name}:
</span>
)}
<pre
className={clsx(
isError ? typeStyleMap.error : typeStyleMap.string,
"cursor-pointer break-all whitespace-pre-wrap",
)}
onClick={() => setIsExpanded(!isExpanded)}
title={isExpanded ? "Click to collapse" : "Click to expand"}
>
{isExpanded ? `"${value}"` : `"${value.slice(0, maxLength)}..."`}
</pre>
</div>
);
};
switch (dataType) {
case "object":
case "array":
return renderCollapsible(dataType === "array");
case "string":
return renderString(data as string);
default:
return (
<div className="flex items-center mr-1 rounded hover:bg-gray-800/20">
{name && (
<span className="mr-1 text-gray-600 dark:text-gray-400">
{name}:
</span>
)}
<span className={typeStyleMap[dataType] || typeStyleMap.default}>
{data === null ? "null" : String(data)}
</span>
</div>
);
}
},
);
JsonNode.displayName = "JsonNode";
export default JsonView;

View File

@@ -3,6 +3,7 @@ import { Button } from "./ui/button";
type ListPaneProps<T> = {
items: T[];
listItems: () => void;
clearItems: () => void;
setSelectedItem: (item: T) => void;
renderItem: (item: T) => React.ReactNode;
title: string;
@@ -13,15 +14,16 @@ type ListPaneProps<T> = {
const ListPane = <T extends object>({
items,
listItems,
clearItems,
setSelectedItem,
renderItem,
title,
buttonText,
isButtonDisabled,
}: ListPaneProps<T>) => (
<div className="bg-white rounded-lg shadow">
<div className="p-4 border-b border-gray-200">
<h3 className="font-semibold">{title}</h3>
<div className="bg-card rounded-lg shadow">
<div className="p-4 border-b border-gray-200 dark:border-gray-800">
<h3 className="font-semibold dark:text-white">{title}</h3>
</div>
<div className="p-4">
<Button
@@ -32,11 +34,19 @@ const ListPane = <T extends object>({
>
{buttonText}
</Button>
<Button
variant="outline"
className="w-full mb-4"
onClick={clearItems}
disabled={items.length === 0}
>
Clear
</Button>
<div className="space-y-2 overflow-y-auto max-h-96">
{items.map((item, index) => (
<div
key={index}
className="flex items-center p-2 rounded hover:bg-gray-50 cursor-pointer"
className="flex items-center p-2 rounded hover:bg-gray-50 dark:hover:bg-gray-700 cursor-pointer"
onClick={() => setSelectedItem(item)}
>
{renderItem(item)}

View File

@@ -0,0 +1,85 @@
import { useEffect, useRef } from "react";
import { InspectorOAuthClientProvider } from "../lib/auth";
import { SESSION_KEYS } from "../lib/constants";
import { auth } from "@modelcontextprotocol/sdk/client/auth.js";
import { useToast } from "@/hooks/use-toast.ts";
import {
generateOAuthErrorDescription,
parseOAuthCallbackParams,
} from "@/utils/oauthUtils.ts";
interface OAuthCallbackProps {
onConnect: (serverUrl: string) => void;
}
const OAuthCallback = ({ onConnect }: OAuthCallbackProps) => {
const { toast } = useToast();
const hasProcessedRef = useRef(false);
useEffect(() => {
const handleCallback = async () => {
// Skip if we've already processed this callback
if (hasProcessedRef.current) {
return;
}
hasProcessedRef.current = true;
const notifyError = (description: string) =>
void toast({
title: "OAuth Authorization Error",
description,
variant: "destructive",
});
const params = parseOAuthCallbackParams(window.location.search);
if (!params.successful) {
return notifyError(generateOAuthErrorDescription(params));
}
const serverUrl = sessionStorage.getItem(SESSION_KEYS.SERVER_URL);
if (!serverUrl) {
return notifyError("Missing Server URL");
}
let result;
try {
// Create an auth provider with the current server URL
const serverAuthProvider = new InspectorOAuthClientProvider(serverUrl);
result = await auth(serverAuthProvider, {
serverUrl,
authorizationCode: params.code,
});
} catch (error) {
console.error("OAuth callback error:", error);
return notifyError(`Unexpected error occurred: ${error}`);
}
if (result !== "AUTHORIZED") {
return notifyError(
`Expected to be authorized after providing auth code, got: ${result}`,
);
}
// Finally, trigger auto-connect
toast({
title: "Success",
description: "Successfully authenticated with OAuth",
variant: "default",
});
onConnect(serverUrl);
};
handleCallback().finally(() => {
window.history.replaceState({}, document.title, "/");
});
}, [toast, onConnect]);
return (
<div className="flex items-center justify-center h-screen">
<p className="text-lg text-gray-500">Processing OAuth callback...</p>
</div>
);
};
export default OAuthCallback;

View File

@@ -3,16 +3,16 @@ import { Button } from "@/components/ui/button";
const PingTab = ({ onPingClick }: { onPingClick: () => void }) => {
return (
<TabsContent value="ping" className="grid grid-cols-2 gap-4">
<div className="col-span-2 flex justify-center items-center">
<Button
onClick={onPingClick}
className="bg-gradient-to-r from-purple-500 to-pink-500 hover:from-purple-600 hover:to-pink-600 text-white font-bold py-6 px-12 rounded-full shadow-lg transform transition duration-300 hover:scale-110 focus:outline-none focus:ring-4 focus:ring-purple-300 animate-pulse"
>
<span className="text-3xl mr-2">🚀</span>
MEGA PING
<span className="text-3xl ml-2">💥</span>
</Button>
<TabsContent value="ping">
<div className="grid grid-cols-2 gap-4">
<div className="col-span-2 flex justify-center items-center">
<Button
onClick={onPingClick}
className="font-bold py-6 px-12 rounded-full"
>
Ping Server
</Button>
</div>
</div>
</TabsContent>
);

View File

@@ -1,13 +1,19 @@
import { Alert, AlertDescription, AlertTitle } from "@/components/ui/alert";
import { Button } from "@/components/ui/button";
import { Input } from "@/components/ui/input";
import { Combobox } from "@/components/ui/combobox";
import { Label } from "@/components/ui/label";
import { TabsContent } from "@/components/ui/tabs";
import { Textarea } from "@/components/ui/textarea";
import { ListPromptsResult } from "@modelcontextprotocol/sdk/types.js";
import {
ListPromptsResult,
PromptReference,
ResourceReference,
} from "@modelcontextprotocol/sdk/types.js";
import { AlertCircle } from "lucide-react";
import { useState } from "react";
import { useEffect, useState } from "react";
import ListPane from "./ListPane";
import { useCompletionState } from "@/lib/hooks/useCompletionState";
import JsonView from "./JsonView";
export type Prompt = {
name: string;
@@ -22,26 +28,53 @@ export type Prompt = {
const PromptsTab = ({
prompts,
listPrompts,
clearPrompts,
getPrompt,
selectedPrompt,
setSelectedPrompt,
handleCompletion,
completionsSupported,
promptContent,
nextCursor,
error,
}: {
prompts: Prompt[];
listPrompts: () => void;
clearPrompts: () => void;
getPrompt: (name: string, args: Record<string, string>) => void;
selectedPrompt: Prompt | null;
setSelectedPrompt: (prompt: Prompt) => void;
setSelectedPrompt: (prompt: Prompt | null) => void;
handleCompletion: (
ref: PromptReference | ResourceReference,
argName: string,
value: string,
) => Promise<string[]>;
completionsSupported: boolean;
promptContent: string;
nextCursor: ListPromptsResult["nextCursor"];
error: string | null;
}) => {
const [promptArgs, setPromptArgs] = useState<Record<string, string>>({});
const { completions, clearCompletions, requestCompletions } =
useCompletionState(handleCompletion, completionsSupported);
const handleInputChange = (argName: string, value: string) => {
useEffect(() => {
clearCompletions();
}, [clearCompletions, selectedPrompt]);
const handleInputChange = async (argName: string, value: string) => {
setPromptArgs((prev) => ({ ...prev, [argName]: value }));
if (selectedPrompt) {
requestCompletions(
{
type: "ref/prompt",
name: selectedPrompt.name,
},
argName,
value,
);
}
};
const handleGetPrompt = () => {
@@ -51,84 +84,91 @@ const PromptsTab = ({
};
return (
<TabsContent value="prompts" className="grid grid-cols-2 gap-4">
<ListPane
items={prompts}
listItems={listPrompts}
setSelectedItem={(prompt) => {
setSelectedPrompt(prompt);
setPromptArgs({});
}}
renderItem={(prompt) => (
<>
<span className="flex-1">{prompt.name}</span>
<span className="text-sm text-gray-500">{prompt.description}</span>
</>
)}
title="Prompts"
buttonText={nextCursor ? "List More Prompts" : "List Prompts"}
isButtonDisabled={!nextCursor && prompts.length > 0}
/>
<div className="bg-white rounded-lg shadow">
<div className="p-4 border-b border-gray-200">
<h3 className="font-semibold">
{selectedPrompt ? selectedPrompt.name : "Select a prompt"}
</h3>
</div>
<div className="p-4">
{error ? (
<Alert variant="destructive">
<AlertCircle className="h-4 w-4" />
<AlertTitle>Error</AlertTitle>
<AlertDescription>{error}</AlertDescription>
</Alert>
) : selectedPrompt ? (
<div className="space-y-4">
{selectedPrompt.description && (
<p className="text-sm text-gray-600">
{selectedPrompt.description}
</p>
)}
{selectedPrompt.arguments?.map((arg) => (
<div key={arg.name}>
<Label htmlFor={arg.name}>{arg.name}</Label>
<Input
id={arg.name}
placeholder={`Enter ${arg.name}`}
value={promptArgs[arg.name] || ""}
onChange={(e) =>
handleInputChange(arg.name, e.target.value)
}
/>
{arg.description && (
<p className="text-xs text-gray-500 mt-1">
{arg.description}
{arg.required && (
<span className="text-xs mt-1 ml-1">(Required)</span>
)}
</p>
)}
</div>
))}
<Button onClick={handleGetPrompt} className="w-full">
Get Prompt
</Button>
{promptContent && (
<Textarea
value={promptContent}
readOnly
className="h-64 font-mono"
/>
)}
</div>
) : (
<Alert>
<AlertDescription>
Select a prompt from the list to view and use it
</AlertDescription>
</Alert>
<TabsContent value="prompts">
<div className="grid grid-cols-2 gap-4">
<ListPane
items={prompts}
listItems={listPrompts}
clearItems={() => {
clearPrompts();
setSelectedPrompt(null);
}}
setSelectedItem={(prompt) => {
setSelectedPrompt(prompt);
setPromptArgs({});
}}
renderItem={(prompt) => (
<>
<span className="flex-1">{prompt.name}</span>
<span className="text-sm text-gray-500">
{prompt.description}
</span>
</>
)}
title="Prompts"
buttonText={nextCursor ? "List More Prompts" : "List Prompts"}
isButtonDisabled={!nextCursor && prompts.length > 0}
/>
<div className="bg-card rounded-lg shadow">
<div className="p-4 border-b border-gray-200 dark:border-gray-800">
<h3 className="font-semibold">
{selectedPrompt ? selectedPrompt.name : "Select a prompt"}
</h3>
</div>
<div className="p-4">
{error ? (
<Alert variant="destructive">
<AlertCircle className="h-4 w-4" />
<AlertTitle>Error</AlertTitle>
<AlertDescription>{error}</AlertDescription>
</Alert>
) : selectedPrompt ? (
<div className="space-y-4">
{selectedPrompt.description && (
<p className="text-sm text-gray-600">
{selectedPrompt.description}
</p>
)}
{selectedPrompt.arguments?.map((arg) => (
<div key={arg.name}>
<Label htmlFor={arg.name}>{arg.name}</Label>
<Combobox
id={arg.name}
placeholder={`Enter ${arg.name}`}
value={promptArgs[arg.name] || ""}
onChange={(value) => handleInputChange(arg.name, value)}
onInputChange={(value) =>
handleInputChange(arg.name, value)
}
options={completions[arg.name] || []}
/>
{arg.description && (
<p className="text-xs text-gray-500 mt-1">
{arg.description}
{arg.required && (
<span className="text-xs mt-1 ml-1">(Required)</span>
)}
</p>
)}
</div>
))}
<Button onClick={handleGetPrompt} className="w-full">
Get Prompt
</Button>
{promptContent && (
<JsonView data={promptContent} withCopyButton={false} />
)}
</div>
) : (
<Alert>
<AlertDescription>
Select a prompt from the list to view and use it
</AlertDescription>
</Alert>
)}
</div>
</div>
</div>
</TabsContent>

View File

@@ -1,33 +0,0 @@
import { TabsContent } from "@/components/ui/tabs";
import { Button } from "@/components/ui/button";
import { Input } from "@/components/ui/input";
import { Textarea } from "@/components/ui/textarea";
import { Send } from "lucide-react";
const RequestsTab = () => (
<TabsContent value="requests" className="space-y-4">
<div className="grid grid-cols-2 gap-4">
<div className="space-y-4">
<div className="flex space-x-2">
<Input placeholder="Method name" />
<Button>
<Send className="w-4 h-4 mr-2" />
Send
</Button>
</div>
<Textarea
placeholder="Request parameters (JSON)"
className="h-64 font-mono"
/>
</div>
<div>
<div className="bg-gray-50 p-4 rounded-lg h-96 font-mono text-sm overflow-auto">
<div className="text-gray-500 mb-2">Response:</div>
{/* Response content would go here */}
</div>
</div>
</div>
</TabsContent>
);
export default RequestsTab;

View File

@@ -1,88 +1,284 @@
import { Alert, AlertDescription, AlertTitle } from "@/components/ui/alert";
import { Button } from "@/components/ui/button";
import { Label } from "@/components/ui/label";
import { Combobox } from "@/components/ui/combobox";
import { TabsContent } from "@/components/ui/tabs";
import { ListResourcesResult, Resource } from "@modelcontextprotocol/sdk/types.js";
import {
ListResourcesResult,
Resource,
ResourceTemplate,
ListResourceTemplatesResult,
ResourceReference,
PromptReference,
} from "@modelcontextprotocol/sdk/types.js";
import { AlertCircle, ChevronRight, FileText, RefreshCw } from "lucide-react";
import ListPane from "./ListPane";
import { useEffect, useState } from "react";
import { useCompletionState } from "@/lib/hooks/useCompletionState";
import JsonView from "./JsonView";
const ResourcesTab = ({
resources,
resourceTemplates,
listResources,
clearResources,
listResourceTemplates,
clearResourceTemplates,
readResource,
selectedResource,
setSelectedResource,
resourceSubscriptionsSupported,
resourceSubscriptions,
subscribeToResource,
unsubscribeFromResource,
handleCompletion,
completionsSupported,
resourceContent,
nextCursor,
nextTemplateCursor,
error,
}: {
resources: Resource[];
resourceTemplates: ResourceTemplate[];
listResources: () => void;
clearResources: () => void;
listResourceTemplates: () => void;
clearResourceTemplates: () => void;
readResource: (uri: string) => void;
selectedResource: Resource | null;
setSelectedResource: (resource: Resource) => void;
setSelectedResource: (resource: Resource | null) => void;
handleCompletion: (
ref: ResourceReference | PromptReference,
argName: string,
value: string,
) => Promise<string[]>;
completionsSupported: boolean;
resourceContent: string;
nextCursor: ListResourcesResult["nextCursor"];
nextTemplateCursor: ListResourceTemplatesResult["nextCursor"];
error: string | null;
}) => (
<TabsContent value="resources" className="grid grid-cols-2 gap-4">
<ListPane
items={resources}
listItems={listResources}
setSelectedItem={(resource) => {
setSelectedResource(resource);
readResource(resource.uri);
}}
renderItem={(resource) => (
<div className="flex items-center w-full">
<FileText className="w-4 h-4 mr-2 flex-shrink-0 text-gray-500" />
<span className="flex-1 truncate" title={resource.uri.toString()}>
{resource.name}
</span>
<ChevronRight className="w-4 h-4 flex-shrink-0 text-gray-400" />
</div>
)}
title="Resources"
buttonText={nextCursor ? "List More Resources" : "List Resources"}
isButtonDisabled={!nextCursor && resources.length > 0}
/>
resourceSubscriptionsSupported: boolean;
resourceSubscriptions: Set<string>;
subscribeToResource: (uri: string) => void;
unsubscribeFromResource: (uri: string) => void;
}) => {
const [selectedTemplate, setSelectedTemplate] =
useState<ResourceTemplate | null>(null);
const [templateValues, setTemplateValues] = useState<Record<string, string>>(
{},
);
<div className="bg-white rounded-lg shadow">
<div className="p-4 border-b border-gray-200 flex justify-between items-center">
<h3 className="font-semibold truncate" title={selectedResource?.name}>
{selectedResource ? selectedResource.name : "Select a resource"}
</h3>
{selectedResource && (
<Button
variant="outline"
size="sm"
onClick={() => readResource(selectedResource.uri)}
>
<RefreshCw className="w-4 h-4 mr-2" />
Refresh
</Button>
)}
const { completions, clearCompletions, requestCompletions } =
useCompletionState(handleCompletion, completionsSupported);
useEffect(() => {
clearCompletions();
}, [clearCompletions]);
const fillTemplate = (
template: string,
values: Record<string, string>,
): string => {
return template.replace(
/{([^}]+)}/g,
(_, key) => values[key] || `{${key}}`,
);
};
const handleTemplateValueChange = async (key: string, value: string) => {
setTemplateValues((prev) => ({ ...prev, [key]: value }));
if (selectedTemplate?.uriTemplate) {
requestCompletions(
{
type: "ref/resource",
uri: selectedTemplate.uriTemplate,
},
key,
value,
);
}
};
const handleReadTemplateResource = () => {
if (selectedTemplate) {
const uri = fillTemplate(selectedTemplate.uriTemplate, templateValues);
readResource(uri);
// We don't have the full Resource object here, so we create a partial one
setSelectedResource({ uri, name: uri } as Resource);
}
};
return (
<TabsContent value="resources">
<div className="grid grid-cols-3 gap-4">
<ListPane
items={resources}
listItems={listResources}
clearItems={() => {
clearResources();
// Condition to check if selected resource is not resource template's resource
if (!selectedTemplate) {
setSelectedResource(null);
}
}}
setSelectedItem={(resource) => {
setSelectedResource(resource);
readResource(resource.uri);
setSelectedTemplate(null);
}}
renderItem={(resource) => (
<div className="flex items-center w-full">
<FileText className="w-4 h-4 mr-2 flex-shrink-0 text-gray-500" />
<span className="flex-1 truncate" title={resource.uri.toString()}>
{resource.name}
</span>
<ChevronRight className="w-4 h-4 flex-shrink-0 text-gray-400" />
</div>
)}
title="Resources"
buttonText={nextCursor ? "List More Resources" : "List Resources"}
isButtonDisabled={!nextCursor && resources.length > 0}
/>
<ListPane
items={resourceTemplates}
listItems={listResourceTemplates}
clearItems={() => {
clearResourceTemplates();
// Condition to check if selected resource is resource template's resource
if (selectedTemplate) {
setSelectedResource(null);
}
setSelectedTemplate(null);
}}
setSelectedItem={(template) => {
setSelectedTemplate(template);
setSelectedResource(null);
setTemplateValues({});
}}
renderItem={(template) => (
<div className="flex items-center w-full">
<FileText className="w-4 h-4 mr-2 flex-shrink-0 text-gray-500" />
<span className="flex-1 truncate" title={template.uriTemplate}>
{template.name}
</span>
<ChevronRight className="w-4 h-4 flex-shrink-0 text-gray-400" />
</div>
)}
title="Resource Templates"
buttonText={
nextTemplateCursor ? "List More Templates" : "List Templates"
}
isButtonDisabled={!nextTemplateCursor && resourceTemplates.length > 0}
/>
<div className="bg-card rounded-lg shadow">
<div className="p-4 border-b border-gray-200 dark:border-gray-800 flex justify-between items-center">
<h3
className="font-semibold truncate"
title={selectedResource?.name || selectedTemplate?.name}
>
{selectedResource
? selectedResource.name
: selectedTemplate
? selectedTemplate.name
: "Select a resource or template"}
</h3>
{selectedResource && (
<div className="flex row-auto gap-1 justify-end w-2/5">
{resourceSubscriptionsSupported &&
!resourceSubscriptions.has(selectedResource.uri) && (
<Button
variant="outline"
size="sm"
onClick={() => subscribeToResource(selectedResource.uri)}
>
Subscribe
</Button>
)}
{resourceSubscriptionsSupported &&
resourceSubscriptions.has(selectedResource.uri) && (
<Button
variant="outline"
size="sm"
onClick={() =>
unsubscribeFromResource(selectedResource.uri)
}
>
Unsubscribe
</Button>
)}
<Button
variant="outline"
size="sm"
onClick={() => readResource(selectedResource.uri)}
>
<RefreshCw className="w-4 h-4 mr-2" />
Refresh
</Button>
</div>
)}
</div>
<div className="p-4">
{error ? (
<Alert variant="destructive">
<AlertCircle className="h-4 w-4" />
<AlertTitle>Error</AlertTitle>
<AlertDescription>{error}</AlertDescription>
</Alert>
) : selectedResource ? (
<JsonView
data={resourceContent}
className="bg-gray-50 dark:bg-gray-800 p-4 rounded text-sm overflow-auto max-h-96 text-gray-900 dark:text-gray-100"
/>
) : selectedTemplate ? (
<div className="space-y-4">
<p className="text-sm text-gray-600">
{selectedTemplate.description}
</p>
{selectedTemplate.uriTemplate
.match(/{([^}]+)}/g)
?.map((param) => {
const key = param.slice(1, -1);
return (
<div key={key}>
<Label htmlFor={key}>{key}</Label>
<Combobox
id={key}
placeholder={`Enter ${key}`}
value={templateValues[key] || ""}
onChange={(value) =>
handleTemplateValueChange(key, value)
}
onInputChange={(value) =>
handleTemplateValueChange(key, value)
}
options={completions[key] || []}
/>
</div>
);
})}
<Button
onClick={handleReadTemplateResource}
disabled={Object.keys(templateValues).length === 0}
>
Read Resource
</Button>
</div>
) : (
<Alert>
<AlertDescription>
Select a resource or template from the list to view its
contents
</AlertDescription>
</Alert>
)}
</div>
</div>
</div>
<div className="p-4">
{error ? (
<Alert variant="destructive">
<AlertCircle className="h-4 w-4" />
<AlertTitle>Error</AlertTitle>
<AlertDescription>{error}</AlertDescription>
</Alert>
) : selectedResource ? (
<pre className="bg-gray-50 p-4 rounded text-sm overflow-auto max-h-96 whitespace-pre-wrap break-words">
{resourceContent}
</pre>
) : (
<Alert>
<AlertDescription>
Select a resource from the list to view its contents
</AlertDescription>
</Alert>
)}
</div>
</div>
</TabsContent>
);
</TabsContent>
);
};
export default ResourcesTab;

View File

@@ -0,0 +1,79 @@
import { Alert, AlertDescription } from "@/components/ui/alert";
import { Button } from "@/components/ui/button";
import { Input } from "@/components/ui/input";
import { TabsContent } from "@/components/ui/tabs";
import { Root } from "@modelcontextprotocol/sdk/types.js";
import { Plus, Minus, Save } from "lucide-react";
const RootsTab = ({
roots,
setRoots,
onRootsChange,
}: {
roots: Root[];
setRoots: React.Dispatch<React.SetStateAction<Root[]>>;
onRootsChange: () => void;
}) => {
const addRoot = () => {
setRoots((currentRoots) => [...currentRoots, { uri: "file://", name: "" }]);
};
const removeRoot = (index: number) => {
setRoots((currentRoots) => currentRoots.filter((_, i) => i !== index));
};
const updateRoot = (index: number, field: keyof Root, value: string) => {
setRoots((currentRoots) =>
currentRoots.map((root, i) =>
i === index ? { ...root, [field]: value } : root,
),
);
};
const handleSave = () => {
onRootsChange();
};
return (
<TabsContent value="roots">
<div className="space-y-4">
<Alert>
<AlertDescription>
Configure the root directories that the server can access
</AlertDescription>
</Alert>
{roots.map((root, index) => (
<div key={index} className="flex gap-2 items-center">
<Input
placeholder="file:// URI"
value={root.uri}
onChange={(e) => updateRoot(index, "uri", e.target.value)}
className="flex-1"
/>
<Button
variant="destructive"
size="sm"
onClick={() => removeRoot(index)}
>
<Minus className="h-4 w-4" />
</Button>
</div>
))}
<div className="flex gap-2">
<Button variant="outline" onClick={addRoot}>
<Plus className="h-4 w-4 mr-2" />
Add Root
</Button>
<Button onClick={handleSave}>
<Save className="h-4 w-4 mr-2" />
Save Changes
</Button>
</div>
</div>
</TabsContent>
);
};
export default RootsTab;

View File

@@ -0,0 +1,167 @@
import { Button } from "@/components/ui/button";
import JsonView from "./JsonView";
import { useMemo, useState } from "react";
import {
CreateMessageResult,
CreateMessageResultSchema,
} from "@modelcontextprotocol/sdk/types.js";
import { PendingRequest } from "./SamplingTab";
import DynamicJsonForm from "./DynamicJsonForm";
import { useToast } from "@/hooks/use-toast";
import { JsonSchemaType, JsonValue } from "@/utils/jsonUtils";
export type SamplingRequestProps = {
request: PendingRequest;
onApprove: (id: number, result: CreateMessageResult) => void;
onReject: (id: number) => void;
};
const SamplingRequest = ({
onApprove,
request,
onReject,
}: SamplingRequestProps) => {
const { toast } = useToast();
const [messageResult, setMessageResult] = useState<JsonValue>({
model: "stub-model",
stopReason: "endTurn",
role: "assistant",
content: {
type: "text",
text: "",
},
});
const contentType = (
(messageResult as { [key: string]: JsonValue })?.content as {
[key: string]: JsonValue;
}
)?.type;
const schema = useMemo(() => {
const s: JsonSchemaType = {
type: "object",
description: "Message result",
properties: {
model: {
type: "string",
default: "stub-model",
description: "model name",
},
stopReason: {
type: "string",
default: "endTurn",
description: "Stop reason",
},
role: {
type: "string",
default: "endTurn",
description: "Role of the model",
},
content: {
type: "object",
properties: {
type: {
type: "string",
default: "text",
description: "Type of content",
},
},
},
},
};
if (contentType === "text" && s.properties) {
s.properties.content.properties = {
...s.properties.content.properties,
text: {
type: "string",
default: "",
description: "text content",
},
};
setMessageResult((prev) => ({
...(prev as { [key: string]: JsonValue }),
content: {
type: contentType,
text: "",
},
}));
} else if (contentType === "image" && s.properties) {
s.properties.content.properties = {
...s.properties.content.properties,
data: {
type: "string",
default: "",
description: "Base64 encoded image data",
},
mimeType: {
type: "string",
default: "",
description: "Mime type of the image",
},
};
setMessageResult((prev) => ({
...(prev as { [key: string]: JsonValue }),
content: {
type: contentType,
data: "",
mimeType: "",
},
}));
}
return s;
}, [contentType]);
const handleApprove = (id: number) => {
const validationResult = CreateMessageResultSchema.safeParse(messageResult);
if (!validationResult.success) {
toast({
title: "Error",
description: `There was an error validating the message result: ${validationResult.error.message}`,
variant: "destructive",
});
return;
}
onApprove(id, validationResult.data);
};
return (
<div
data-testid="sampling-request"
className="flex gap-4 p-4 border rounded-lg space-y-4"
>
<div className="flex-1 bg-gray-50 dark:bg-gray-800 dark:text-gray-100 p-2 rounded">
<JsonView data={JSON.stringify(request.request)} />
</div>
<form className="flex-1 space-y-4">
<div className="space-y-2">
<DynamicJsonForm
schema={schema}
value={messageResult}
onChange={(newValue: JsonValue) => {
setMessageResult(newValue);
}}
/>
</div>
<div className="flex space-x-2 mt-1">
<Button type="button" onClick={() => handleApprove(request.id)}>
Approve
</Button>
<Button
type="button"
variant="outline"
onClick={() => onReject(request.id)}
>
Reject
</Button>
</div>
</form>
</div>
);
};
export default SamplingRequest;

View File

@@ -1,10 +1,10 @@
import { Alert, AlertDescription } from "@/components/ui/alert";
import { Button } from "@/components/ui/button";
import { TabsContent } from "@/components/ui/tabs";
import {
CreateMessageRequest,
CreateMessageResult,
} from "@modelcontextprotocol/sdk/types.js";
import SamplingRequest from "./SamplingRequest";
export type PendingRequest = {
id: number;
@@ -18,45 +18,29 @@ export type Props = {
};
const SamplingTab = ({ pendingRequests, onApprove, onReject }: Props) => {
const handleApprove = (id: number) => {
// For now, just return a stub response
onApprove(id, {
model: "stub-model",
stopReason: "endTurn",
role: "assistant",
content: {
type: "text",
text: "This is a stub response.",
},
});
};
return (
<TabsContent value="sampling" className="h-96">
<Alert>
<AlertDescription>
When the server requests LLM sampling, requests will appear here for
approval.
</AlertDescription>
</Alert>
<div className="mt-4 space-y-4">
<h3 className="text-lg font-semibold">Recent Requests</h3>
{pendingRequests.map((request) => (
<div key={request.id} className="p-4 border rounded-lg space-y-4">
<pre className="bg-gray-50 p-2 rounded">
{JSON.stringify(request.request, null, 2)}
</pre>
<div className="flex space-x-2">
<Button onClick={() => handleApprove(request.id)}>Approve</Button>
<Button variant="outline" onClick={() => onReject(request.id)}>
Reject
</Button>
</div>
</div>
))}
{pendingRequests.length === 0 && (
<p className="text-gray-500">No pending requests</p>
)}
<TabsContent value="sampling">
<div className="h-96">
<Alert>
<AlertDescription>
When the server requests LLM sampling, requests will appear here for
approval.
</AlertDescription>
</Alert>
<div className="mt-4 space-y-4">
<h3 className="text-lg font-semibold">Recent Requests</h3>
{pendingRequests.map((request) => (
<SamplingRequest
key={request.id}
request={request}
onApprove={onApprove}
onReject={onReject}
/>
))}
{pendingRequests.length === 0 && (
<p className="text-gray-500">No pending requests</p>
)}
</div>
</div>
</TabsContent>
);

View File

@@ -1,39 +1,624 @@
import { Menu, Settings } from "lucide-react";
import { useState } from "react";
import {
Play,
ChevronDown,
ChevronRight,
CircleHelp,
Bug,
Github,
Eye,
EyeOff,
RotateCcw,
Settings,
HelpCircle,
RefreshCwOff,
} from "lucide-react";
import { Button } from "@/components/ui/button";
import { Input } from "@/components/ui/input";
import {
Select,
SelectContent,
SelectItem,
SelectTrigger,
SelectValue,
} from "@/components/ui/select";
import { StdErrNotification } from "@/lib/notificationTypes";
import {
LoggingLevel,
LoggingLevelSchema,
} from "@modelcontextprotocol/sdk/types.js";
import { InspectorConfig } from "@/lib/configurationTypes";
import { ConnectionStatus } from "@/lib/constants";
import useTheme from "../lib/useTheme";
import { version } from "../../../package.json";
import {
Tooltip,
TooltipTrigger,
TooltipContent,
} from "@/components/ui/tooltip";
const Sidebar = ({ connectionStatus }: { connectionStatus: string }) => (
<div className="w-64 bg-white border-r border-gray-200">
<div className="flex items-center p-4 border-b border-gray-200">
<Menu className="w-6 h-6 text-gray-500" />
<h1 className="ml-2 text-lg font-semibold">MCP Inspector</h1>
</div>
interface SidebarProps {
connectionStatus: ConnectionStatus;
transportType: "stdio" | "sse" | "streamable-http";
setTransportType: (type: "stdio" | "sse" | "streamable-http") => void;
command: string;
setCommand: (command: string) => void;
args: string;
setArgs: (args: string) => void;
sseUrl: string;
setSseUrl: (url: string) => void;
env: Record<string, string>;
setEnv: (env: Record<string, string>) => void;
bearerToken: string;
setBearerToken: (token: string) => void;
headerName?: string;
setHeaderName?: (name: string) => void;
onConnect: () => void;
onDisconnect: () => void;
stdErrNotifications: StdErrNotification[];
clearStdErrNotifications: () => void;
logLevel: LoggingLevel;
sendLogLevelRequest: (level: LoggingLevel) => void;
loggingSupported: boolean;
config: InspectorConfig;
setConfig: (config: InspectorConfig) => void;
}
<div className="p-4">
<div className="flex items-center space-x-2 mb-4">
<div
className={`w-2 h-2 rounded-full ${
connectionStatus === "connected"
? "bg-green-500"
: connectionStatus === "error"
? "bg-red-500"
: "bg-gray-500"
}`}
/>
<span className="text-sm text-gray-600">
{connectionStatus === "connected"
? "Connected"
: connectionStatus === "error"
? "Connection Error"
: "Disconnected"}
</span>
const Sidebar = ({
connectionStatus,
transportType,
setTransportType,
command,
setCommand,
args,
setArgs,
sseUrl,
setSseUrl,
env,
setEnv,
bearerToken,
setBearerToken,
headerName,
setHeaderName,
onConnect,
onDisconnect,
stdErrNotifications,
clearStdErrNotifications,
logLevel,
sendLogLevelRequest,
loggingSupported,
config,
setConfig,
}: SidebarProps) => {
const [theme, setTheme] = useTheme();
const [showEnvVars, setShowEnvVars] = useState(false);
const [showBearerToken, setShowBearerToken] = useState(false);
const [showConfig, setShowConfig] = useState(false);
const [shownEnvVars, setShownEnvVars] = useState<Set<string>>(new Set());
return (
<div className="w-80 bg-card border-r border-border flex flex-col h-full">
<div className="flex items-center justify-between p-4 border-b border-gray-200 dark:border-gray-800">
<div className="flex items-center">
<h1 className="ml-2 text-lg font-semibold">
MCP Inspector v{version}
</h1>
</div>
</div>
<Button variant="outline" className="w-full justify-start">
<Settings className="w-4 h-4 mr-2" />
Connection Settings
</Button>
<div className="p-4 flex-1 overflow-auto">
<div className="space-y-4">
<div className="space-y-2">
<label
className="text-sm font-medium"
htmlFor="transport-type-select"
>
Transport Type
</label>
<Select
value={transportType}
onValueChange={(value: "stdio" | "sse" | "streamable-http") =>
setTransportType(value)
}
>
<SelectTrigger id="transport-type-select">
<SelectValue placeholder="Select transport type" />
</SelectTrigger>
<SelectContent>
<SelectItem value="stdio">STDIO</SelectItem>
<SelectItem value="sse">SSE</SelectItem>
<SelectItem value="streamable-http">Streamable HTTP</SelectItem>
</SelectContent>
</Select>
</div>
{transportType === "stdio" ? (
<>
<div className="space-y-2">
<label className="text-sm font-medium" htmlFor="command-input">
Command
</label>
<Input
id="command-input"
placeholder="Command"
value={command}
onChange={(e) => setCommand(e.target.value)}
className="font-mono"
/>
</div>
<div className="space-y-2">
<label
className="text-sm font-medium"
htmlFor="arguments-input"
>
Arguments
</label>
<Input
id="arguments-input"
placeholder="Arguments (space-separated)"
value={args}
onChange={(e) => setArgs(e.target.value)}
className="font-mono"
/>
</div>
</>
) : (
<>
<div className="space-y-2">
<label className="text-sm font-medium" htmlFor="sse-url-input">
URL
</label>
<Input
id="sse-url-input"
placeholder="URL"
value={sseUrl}
onChange={(e) => setSseUrl(e.target.value)}
className="font-mono"
/>
</div>
<div className="space-y-2">
<Button
variant="outline"
onClick={() => setShowBearerToken(!showBearerToken)}
className="flex items-center w-full"
data-testid="auth-button"
aria-expanded={showBearerToken}
>
{showBearerToken ? (
<ChevronDown className="w-4 h-4 mr-2" />
) : (
<ChevronRight className="w-4 h-4 mr-2" />
)}
Authentication
</Button>
{showBearerToken && (
<div className="space-y-2">
<label className="text-sm font-medium">Header Name</label>
<Input
placeholder="Authorization"
onChange={(e) =>
setHeaderName && setHeaderName(e.target.value)
}
data-testid="header-input"
className="font-mono"
value={headerName}
/>
<label
className="text-sm font-medium"
htmlFor="bearer-token-input"
>
Bearer Token
</label>
<Input
id="bearer-token-input"
placeholder="Bearer Token"
value={bearerToken}
onChange={(e) => setBearerToken(e.target.value)}
data-testid="bearer-token-input"
className="font-mono"
type="password"
/>
</div>
)}
</div>
</>
)}
{transportType === "stdio" && (
<div className="space-y-2">
<Button
variant="outline"
onClick={() => setShowEnvVars(!showEnvVars)}
className="flex items-center w-full"
data-testid="env-vars-button"
aria-expanded={showEnvVars}
>
{showEnvVars ? (
<ChevronDown className="w-4 h-4 mr-2" />
) : (
<ChevronRight className="w-4 h-4 mr-2" />
)}
Environment Variables
</Button>
{showEnvVars && (
<div className="space-y-2">
{Object.entries(env).map(([key, value], idx) => (
<div key={idx} className="space-y-2 pb-4">
<div className="flex gap-2">
<Input
aria-label={`Environment variable key ${idx + 1}`}
placeholder="Key"
value={key}
onChange={(e) => {
const newKey = e.target.value;
const newEnv = Object.entries(env).reduce(
(acc, [k, v]) => {
if (k === key) {
acc[newKey] = value;
} else {
acc[k] = v;
}
return acc;
},
{} as Record<string, string>,
);
setEnv(newEnv);
setShownEnvVars((prev) => {
const next = new Set(prev);
if (next.has(key)) {
next.delete(key);
next.add(newKey);
}
return next;
});
}}
className="font-mono"
/>
<Button
variant="destructive"
size="icon"
className="h-9 w-9 p-0 shrink-0"
onClick={() => {
// eslint-disable-next-line @typescript-eslint/no-unused-vars
const { [key]: _removed, ...rest } = env;
setEnv(rest);
}}
>
×
</Button>
</div>
<div className="flex gap-2">
<Input
aria-label={`Environment variable value ${idx + 1}`}
type={shownEnvVars.has(key) ? "text" : "password"}
placeholder="Value"
value={value}
onChange={(e) => {
const newEnv = { ...env };
newEnv[key] = e.target.value;
setEnv(newEnv);
}}
className="font-mono"
/>
<Button
variant="outline"
size="icon"
className="h-9 w-9 p-0 shrink-0"
onClick={() => {
setShownEnvVars((prev) => {
const next = new Set(prev);
if (next.has(key)) {
next.delete(key);
} else {
next.add(key);
}
return next;
});
}}
aria-label={
shownEnvVars.has(key) ? "Hide value" : "Show value"
}
aria-pressed={shownEnvVars.has(key)}
title={
shownEnvVars.has(key) ? "Hide value" : "Show value"
}
>
{shownEnvVars.has(key) ? (
<Eye className="h-4 w-4" aria-hidden="true" />
) : (
<EyeOff className="h-4 w-4" aria-hidden="true" />
)}
</Button>
</div>
</div>
))}
<Button
variant="outline"
className="w-full mt-2"
onClick={() => {
const key = "";
const newEnv = { ...env };
newEnv[key] = "";
setEnv(newEnv);
}}
>
Add Environment Variable
</Button>
</div>
)}
</div>
)}
{/* Configuration */}
<div className="space-y-2">
<Button
variant="outline"
onClick={() => setShowConfig(!showConfig)}
className="flex items-center w-full"
data-testid="config-button"
aria-expanded={showConfig}
>
{showConfig ? (
<ChevronDown className="w-4 h-4 mr-2" />
) : (
<ChevronRight className="w-4 h-4 mr-2" />
)}
<Settings className="w-4 h-4 mr-2" />
Configuration
</Button>
{showConfig && (
<div className="space-y-2">
{Object.entries(config).map(([key, configItem]) => {
const configKey = key as keyof InspectorConfig;
return (
<div key={key} className="space-y-2">
<div className="flex items-center gap-1">
<label
className="text-sm font-medium text-green-600 break-all"
htmlFor={`${configKey}-input`}
>
{configItem.label}
</label>
<Tooltip>
<TooltipTrigger asChild>
<HelpCircle className="h-4 w-4 text-muted-foreground" />
</TooltipTrigger>
<TooltipContent>
{configItem.description}
</TooltipContent>
</Tooltip>
</div>
{typeof configItem.value === "number" ? (
<Input
id={`${configKey}-input`}
type="number"
data-testid={`${configKey}-input`}
value={configItem.value}
onChange={(e) => {
const newConfig = { ...config };
newConfig[configKey] = {
...configItem,
value: Number(e.target.value),
};
setConfig(newConfig);
}}
className="font-mono"
/>
) : typeof configItem.value === "boolean" ? (
<Select
data-testid={`${configKey}-select`}
value={configItem.value.toString()}
onValueChange={(val) => {
const newConfig = { ...config };
newConfig[configKey] = {
...configItem,
value: val === "true",
};
setConfig(newConfig);
}}
>
<SelectTrigger id={`${configKey}-input`}>
<SelectValue />
</SelectTrigger>
<SelectContent>
<SelectItem value="true">True</SelectItem>
<SelectItem value="false">False</SelectItem>
</SelectContent>
</Select>
) : (
<Input
id={`${configKey}-input`}
data-testid={`${configKey}-input`}
value={configItem.value}
onChange={(e) => {
const newConfig = { ...config };
newConfig[configKey] = {
...configItem,
value: e.target.value,
};
setConfig(newConfig);
}}
className="font-mono"
/>
)}
</div>
);
})}
</div>
)}
</div>
<div className="space-y-2">
{connectionStatus === "connected" && (
<div className="grid grid-cols-2 gap-4">
<Button
data-testid="connect-button"
onClick={() => {
onDisconnect();
onConnect();
}}
>
<RotateCcw className="w-4 h-4 mr-2" />
{transportType === "stdio" ? "Restart" : "Reconnect"}
</Button>
<Button onClick={onDisconnect}>
<RefreshCwOff className="w-4 h-4 mr-2" />
Disconnect
</Button>
</div>
)}
{connectionStatus !== "connected" && (
<Button className="w-full" onClick={onConnect}>
<Play className="w-4 h-4 mr-2" />
Connect
</Button>
)}
<div className="flex items-center justify-center space-x-2 mb-4">
<div
className={`w-2 h-2 rounded-full ${(() => {
switch (connectionStatus) {
case "connected":
return "bg-green-500";
case "error":
return "bg-red-500";
case "error-connecting-to-proxy":
return "bg-red-500";
default:
return "bg-gray-500";
}
})()}`}
/>
<span className="text-sm text-gray-600">
{(() => {
switch (connectionStatus) {
case "connected":
return "Connected";
case "error":
return "Connection Error, is your MCP server running?";
case "error-connecting-to-proxy":
return "Error Connecting to MCP Inspector Proxy - Check Console logs";
default:
return "Disconnected";
}
})()}
</span>
</div>
{loggingSupported && connectionStatus === "connected" && (
<div className="space-y-2">
<label
className="text-sm font-medium"
htmlFor="logging-level-select"
>
Logging Level
</label>
<Select
value={logLevel}
onValueChange={(value: LoggingLevel) =>
sendLogLevelRequest(value)
}
>
<SelectTrigger id="logging-level-select">
<SelectValue placeholder="Select logging level" />
</SelectTrigger>
<SelectContent>
{Object.values(LoggingLevelSchema.enum).map((level) => (
<SelectItem key={level} value={level}>
{level}
</SelectItem>
))}
</SelectContent>
</Select>
</div>
)}
{stdErrNotifications.length > 0 && (
<>
<div className="mt-4 border-t border-gray-200 pt-4">
<div className="flex justify-between items-center">
<h3 className="text-sm font-medium">
Error output from MCP server
</h3>
<Button
variant="outline"
size="sm"
onClick={clearStdErrNotifications}
className="h-8 px-2"
>
Clear
</Button>
</div>
<div className="mt-2 max-h-80 overflow-y-auto">
{stdErrNotifications.map((notification, index) => (
<div
key={index}
className="text-sm text-red-500 font-mono py-2 border-b border-gray-200 last:border-b-0"
>
{notification.params.content}
</div>
))}
</div>
</div>
</>
)}
</div>
</div>
</div>
<div className="p-4 border-t">
<div className="flex items-center justify-between">
<Select
value={theme}
onValueChange={(value: string) =>
setTheme(value as "system" | "light" | "dark")
}
>
<SelectTrigger className="w-[100px]" id="theme-select">
<SelectValue />
</SelectTrigger>
<SelectContent>
<SelectItem value="system">System</SelectItem>
<SelectItem value="light">Light</SelectItem>
<SelectItem value="dark">Dark</SelectItem>
</SelectContent>
</Select>
<div className="flex items-center space-x-2">
<Button variant="ghost" title="Inspector Documentation" asChild>
<a
href="https://modelcontextprotocol.io/docs/tools/inspector"
target="_blank"
rel="noopener noreferrer"
>
<CircleHelp className="w-4 h-4 text-foreground" />
</a>
</Button>
<Button variant="ghost" title="Debugging Guide" asChild>
<a
href="https://modelcontextprotocol.io/docs/tools/debugging"
target="_blank"
rel="noopener noreferrer"
>
<Bug className="w-4 h-4 text-foreground" />
</a>
</Button>
<Button
variant="ghost"
title="Report bugs or contribute on GitHub"
asChild
>
<a
href="https://github.com/modelcontextprotocol/inspector"
target="_blank"
rel="noopener noreferrer"
>
<Github className="w-4 h-4 text-foreground" />
</a>
</Button>
</div>
</div>
</div>
</div>
</div>
);
);
};
export default Sidebar;

View File

@@ -1,121 +1,300 @@
import { Alert, AlertDescription, AlertTitle } from "@/components/ui/alert";
import { Alert, AlertDescription } from "@/components/ui/alert";
import { Button } from "@/components/ui/button";
import { Checkbox } from "@/components/ui/checkbox";
import { Input } from "@/components/ui/input";
import { Label } from "@/components/ui/label";
import { TabsContent } from "@/components/ui/tabs";
import { ListToolsResult, Tool } from "@modelcontextprotocol/sdk/types.js";
import { AlertCircle, Send } from "lucide-react";
import { useState } from "react";
import { Textarea } from "@/components/ui/textarea";
import DynamicJsonForm from "./DynamicJsonForm";
import type { JsonValue, JsonSchemaType } from "@/utils/jsonUtils";
import { generateDefaultValue } from "@/utils/schemaUtils";
import {
CallToolResultSchema,
CompatibilityCallToolResult,
ListToolsResult,
Tool,
} from "@modelcontextprotocol/sdk/types.js";
import { Loader2, Send } from "lucide-react";
import { useEffect, useState } from "react";
import ListPane from "./ListPane";
import JsonView from "./JsonView";
const ToolsTab = ({
tools,
listTools,
clearTools,
callTool,
selectedTool,
setSelectedTool,
toolResult,
nextCursor,
error,
}: {
tools: Tool[];
listTools: () => void;
callTool: (name: string, params: Record<string, unknown>) => void;
clearTools: () => void;
callTool: (name: string, params: Record<string, unknown>) => Promise<void>;
selectedTool: Tool | null;
setSelectedTool: (tool: Tool) => void;
toolResult: string;
setSelectedTool: (tool: Tool | null) => void;
toolResult: CompatibilityCallToolResult | null;
nextCursor: ListToolsResult["nextCursor"];
error: string | null;
}) => {
const [params, setParams] = useState<Record<string, unknown>>({});
const [isToolRunning, setIsToolRunning] = useState(false);
useEffect(() => {
const params = Object.entries(
selectedTool?.inputSchema.properties ?? [],
).map(([key, value]) => [
key,
generateDefaultValue(value as JsonSchemaType),
]);
setParams(Object.fromEntries(params));
}, [selectedTool]);
const renderToolResult = () => {
if (!toolResult) return null;
if ("content" in toolResult) {
const parsedResult = CallToolResultSchema.safeParse(toolResult);
if (!parsedResult.success) {
return (
<>
<h4 className="font-semibold mb-2">Invalid Tool Result:</h4>
<JsonView data={toolResult} />
<h4 className="font-semibold mb-2">Errors:</h4>
{parsedResult.error.errors.map((error, idx) => (
<JsonView data={error} key={idx} />
))}
</>
);
}
const structuredResult = parsedResult.data;
const isError = structuredResult.isError ?? false;
return (
<>
<h4 className="font-semibold mb-2">
Tool Result:{" "}
{isError ? (
<span className="text-red-600 font-semibold">Error</span>
) : (
<span className="text-green-600 font-semibold">Success</span>
)}
</h4>
{structuredResult.content.map((item, index) => (
<div key={index} className="mb-2">
{item.type === "text" && (
<JsonView data={item.text} isError={isError} />
)}
{item.type === "image" && (
<img
src={`data:${item.mimeType};base64,${item.data}`}
alt="Tool result image"
className="max-w-full h-auto"
/>
)}
{item.type === "resource" &&
(item.resource?.mimeType?.startsWith("audio/") ? (
<audio
controls
src={`data:${item.resource.mimeType};base64,${item.resource.blob}`}
className="w-full"
>
<p>Your browser does not support audio playback</p>
</audio>
) : (
<JsonView data={item.resource} />
))}
</div>
))}
</>
);
} else if ("toolResult" in toolResult) {
return (
<>
<h4 className="font-semibold mb-2">Tool Result (Legacy):</h4>
<JsonView data={toolResult.toolResult} />
</>
);
}
};
return (
<TabsContent value="tools" className="grid grid-cols-2 gap-4">
<ListPane
items={tools}
listItems={listTools}
setSelectedItem={setSelectedTool}
renderItem={(tool) => (
<>
<span className="flex-1">{tool.name}</span>
<span className="text-sm text-gray-500 text-right">
{tool.description}
</span>
</>
)}
title="Tools"
buttonText={nextCursor ? "List More Tools" : "List Tools"}
isButtonDisabled={!nextCursor && tools.length > 0}
/>
<div className="bg-white rounded-lg shadow">
<div className="p-4 border-b border-gray-200">
<h3 className="font-semibold">
{selectedTool ? selectedTool.name : "Select a tool"}
</h3>
</div>
<div className="p-4">
{error ? (
<Alert variant="destructive">
<AlertCircle className="h-4 w-4" />
<AlertTitle>Error</AlertTitle>
<AlertDescription>{error}</AlertDescription>
</Alert>
) : selectedTool ? (
<div className="space-y-4">
<p className="text-sm text-gray-600">
{selectedTool.description}
</p>
{Object.entries(selectedTool.inputSchema.properties ?? []).map(
([key, value]) => (
<div key={key}>
<Label
htmlFor={key}
className="block text-sm font-medium text-gray-700"
>
{key}
</Label>
<Input
// @ts-expect-error value type is currently unknown
type={value.type === "number" ? "number" : "text"}
id={key}
name={key}
// @ts-expect-error value type is currently unknown
placeholder={value.description}
onChange={(e) =>
setParams({
...params,
[key]:
// @ts-expect-error value type is currently unknown
value.type === "number"
? Number(e.target.value)
: e.target.value,
})
}
/>
</div>
),
)}
<Button onClick={() => callTool(selectedTool.name, params)}>
<Send className="w-4 h-4 mr-2" />
Run Tool
</Button>
{toolResult && (
<>
<h4 className="font-semibold mb-2">Tool Result:</h4>
<pre className="bg-gray-50 p-4 rounded text-sm overflow-auto max-h-64">
{toolResult}
</pre>
</>
)}
</div>
) : (
<Alert>
<AlertDescription>
Select a tool from the list to view its details and run it
</AlertDescription>
</Alert>
<TabsContent value="tools">
<div className="grid grid-cols-2 gap-4">
<ListPane
items={tools}
listItems={listTools}
clearItems={() => {
clearTools();
setSelectedTool(null);
}}
setSelectedItem={setSelectedTool}
renderItem={(tool) => (
<>
<span className="flex-1">{tool.name}</span>
<span className="text-sm text-gray-500 text-right">
{tool.description}
</span>
</>
)}
title="Tools"
buttonText={nextCursor ? "List More Tools" : "List Tools"}
isButtonDisabled={!nextCursor && tools.length > 0}
/>
<div className="bg-card rounded-lg shadow">
<div className="p-4 border-b border-gray-200 dark:border-gray-800">
<h3 className="font-semibold">
{selectedTool ? selectedTool.name : "Select a tool"}
</h3>
</div>
<div className="p-4">
{selectedTool ? (
<div className="space-y-4">
<p className="text-sm text-gray-600">
{selectedTool.description}
</p>
{Object.entries(selectedTool.inputSchema.properties ?? []).map(
([key, value]) => {
const prop = value as JsonSchemaType;
return (
<div key={key}>
<Label
htmlFor={key}
className="block text-sm font-medium text-gray-700"
>
{key}
</Label>
{prop.type === "boolean" ? (
<div className="flex items-center space-x-2 mt-2">
<Checkbox
id={key}
name={key}
checked={!!params[key]}
onCheckedChange={(checked: boolean) =>
setParams({
...params,
[key]: checked,
})
}
/>
<label
htmlFor={key}
className="text-sm font-medium text-gray-700 dark:text-gray-300"
>
{prop.description || "Toggle this option"}
</label>
</div>
) : prop.type === "string" ? (
<Textarea
id={key}
name={key}
placeholder={prop.description}
value={(params[key] as string) ?? ""}
onChange={(e) =>
setParams({
...params,
[key]: e.target.value,
})
}
className="mt-1"
/>
) : prop.type === "object" || prop.type === "array" ? (
<div className="mt-1">
<DynamicJsonForm
schema={{
type: prop.type,
properties: prop.properties,
description: prop.description,
items: prop.items,
}}
value={
(params[key] as JsonValue) ??
generateDefaultValue(prop)
}
onChange={(newValue: JsonValue) => {
setParams({
...params,
[key]: newValue,
});
}}
/>
</div>
) : prop.type === "number" ||
prop.type === "integer" ? (
<Input
type="number"
id={key}
name={key}
placeholder={prop.description}
value={(params[key] as string) ?? ""}
onChange={(e) =>
setParams({
...params,
[key]: Number(e.target.value),
})
}
className="mt-1"
/>
) : (
<div className="mt-1">
<DynamicJsonForm
schema={{
type: prop.type,
properties: prop.properties,
description: prop.description,
items: prop.items,
}}
value={params[key] as JsonValue}
onChange={(newValue: JsonValue) => {
setParams({
...params,
[key]: newValue,
});
}}
/>
</div>
)}
</div>
);
},
)}
<Button
onClick={async () => {
try {
setIsToolRunning(true);
await callTool(selectedTool.name, params);
} finally {
setIsToolRunning(false);
}
}}
disabled={isToolRunning}
>
{isToolRunning ? (
<>
<Loader2 className="w-4 h-4 mr-2 animate-spin" />
Running...
</>
) : (
<>
<Send className="w-4 h-4 mr-2" />
Run Tool
</>
)}
</Button>
{toolResult && renderToolResult()}
</div>
) : (
<Alert>
<AlertDescription>
Select a tool from the list to view its details and run it
</AlertDescription>
</Alert>
)}
</div>
</div>
</div>
</TabsContent>

View File

@@ -0,0 +1,139 @@
import { render, screen, fireEvent, waitFor } from "@testing-library/react";
import { describe, it, expect, jest } from "@jest/globals";
import DynamicJsonForm from "../DynamicJsonForm";
import type { JsonSchemaType } from "@/utils/jsonUtils";
describe("DynamicJsonForm String Fields", () => {
const renderForm = (props = {}) => {
const defaultProps = {
schema: {
type: "string" as const,
description: "Test string field",
} satisfies JsonSchemaType,
value: undefined,
onChange: jest.fn(),
};
return render(<DynamicJsonForm {...defaultProps} {...props} />);
};
describe("Type Validation", () => {
it("should handle numeric input as string type", () => {
const onChange = jest.fn();
renderForm({ onChange });
const input = screen.getByRole("textbox");
fireEvent.change(input, { target: { value: "123321" } });
expect(onChange).toHaveBeenCalledWith("123321");
// Verify the value is a string, not a number
expect(typeof onChange.mock.calls[0][0]).toBe("string");
});
it("should render as text input, not number input", () => {
renderForm();
const input = screen.getByRole("textbox");
expect(input).toHaveProperty("type", "text");
});
});
});
describe("DynamicJsonForm Integer Fields", () => {
const renderForm = (props = {}) => {
const defaultProps = {
schema: {
type: "integer" as const,
description: "Test integer field",
} satisfies JsonSchemaType,
value: undefined,
onChange: jest.fn(),
};
return render(<DynamicJsonForm {...defaultProps} {...props} />);
};
describe("Basic Operations", () => {
it("should render number input with step=1", () => {
renderForm();
const input = screen.getByRole("spinbutton");
expect(input).toHaveProperty("type", "number");
expect(input).toHaveProperty("step", "1");
});
it("should pass integer values to onChange", () => {
const onChange = jest.fn();
renderForm({ onChange });
const input = screen.getByRole("spinbutton");
fireEvent.change(input, { target: { value: "42" } });
expect(onChange).toHaveBeenCalledWith(42);
// Verify the value is a number, not a string
expect(typeof onChange.mock.calls[0][0]).toBe("number");
});
it("should not pass string values to onChange", () => {
const onChange = jest.fn();
renderForm({ onChange });
const input = screen.getByRole("spinbutton");
fireEvent.change(input, { target: { value: "abc" } });
expect(onChange).not.toHaveBeenCalled();
});
});
describe("Edge Cases", () => {
it("should handle non-numeric input by not calling onChange", () => {
const onChange = jest.fn();
renderForm({ onChange });
const input = screen.getByRole("spinbutton");
fireEvent.change(input, { target: { value: "abc" } });
expect(onChange).not.toHaveBeenCalled();
});
});
});
describe("DynamicJsonForm Complex Fields", () => {
const renderForm = (props = {}) => {
const defaultProps = {
schema: {
type: "object",
properties: {
// The simplified JsonSchemaType does not accept oneOf fields
// But they exist in the more-complete JsonSchema7Type
nested: { oneOf: [{ type: "string" }, { type: "integer" }] },
},
} as unknown as JsonSchemaType,
value: undefined,
onChange: jest.fn(),
};
return render(<DynamicJsonForm {...defaultProps} {...props} />);
};
describe("Basic Operations", () => {
it("should render textbox and autoformat button, but no switch-to-form button", () => {
renderForm();
const input = screen.getByRole("textbox");
expect(input).toHaveProperty("type", "textarea");
const buttons = screen.getAllByRole("button");
expect(buttons).toHaveLength(1);
expect(buttons[0]).toHaveProperty("textContent", "Format JSON");
});
it("should pass changed values to onChange", () => {
const onChange = jest.fn();
renderForm({ onChange });
const input = screen.getByRole("textbox");
fireEvent.change(input, {
target: { value: `{ "nested": "i am string" }` },
});
// The onChange handler is debounced when using the JSON view, so we need to wait a little bit
waitFor(() => {
expect(onChange).toHaveBeenCalledWith(`{ "nested": "i am string" }`);
});
});
});
});

View File

@@ -0,0 +1,625 @@
import { render, screen, fireEvent } from "@testing-library/react";
import "@testing-library/jest-dom";
import { describe, it, beforeEach, jest } from "@jest/globals";
import Sidebar from "../Sidebar";
import { DEFAULT_INSPECTOR_CONFIG } from "@/lib/constants";
import { InspectorConfig } from "@/lib/configurationTypes";
import { TooltipProvider } from "@/components/ui/tooltip";
// Mock theme hook
jest.mock("../../lib/useTheme", () => ({
__esModule: true,
default: () => ["light", jest.fn()],
}));
describe("Sidebar Environment Variables", () => {
const defaultProps = {
connectionStatus: "disconnected" as const,
transportType: "stdio" as const,
setTransportType: jest.fn(),
command: "",
setCommand: jest.fn(),
args: "",
setArgs: jest.fn(),
sseUrl: "",
setSseUrl: jest.fn(),
env: {},
setEnv: jest.fn(),
bearerToken: "",
setBearerToken: jest.fn(),
onConnect: jest.fn(),
onDisconnect: jest.fn(),
stdErrNotifications: [],
clearStdErrNotifications: jest.fn(),
logLevel: "info" as const,
sendLogLevelRequest: jest.fn(),
loggingSupported: true,
config: DEFAULT_INSPECTOR_CONFIG,
setConfig: jest.fn(),
};
const renderSidebar = (props = {}) => {
return render(
<TooltipProvider>
<Sidebar {...defaultProps} {...props} />
</TooltipProvider>,
);
};
const openEnvVarsSection = () => {
const button = screen.getByTestId("env-vars-button");
fireEvent.click(button);
};
beforeEach(() => {
jest.clearAllMocks();
});
describe("Basic Operations", () => {
it("should add a new environment variable", () => {
const setEnv = jest.fn();
renderSidebar({ env: {}, setEnv });
openEnvVarsSection();
const addButton = screen.getByText("Add Environment Variable");
fireEvent.click(addButton);
expect(setEnv).toHaveBeenCalledWith({ "": "" });
});
it("should remove an environment variable", () => {
const setEnv = jest.fn();
const initialEnv = { TEST_KEY: "test_value" };
renderSidebar({ env: initialEnv, setEnv });
openEnvVarsSection();
const removeButton = screen.getByRole("button", { name: "×" });
fireEvent.click(removeButton);
expect(setEnv).toHaveBeenCalledWith({});
});
it("should update environment variable value", () => {
const setEnv = jest.fn();
const initialEnv = { TEST_KEY: "test_value" };
renderSidebar({ env: initialEnv, setEnv });
openEnvVarsSection();
const valueInput = screen.getByDisplayValue("test_value");
fireEvent.change(valueInput, { target: { value: "new_value" } });
expect(setEnv).toHaveBeenCalledWith({ TEST_KEY: "new_value" });
});
it("should toggle value visibility", () => {
const initialEnv = { TEST_KEY: "test_value" };
renderSidebar({ env: initialEnv });
openEnvVarsSection();
const valueInput = screen.getByDisplayValue("test_value");
expect(valueInput).toHaveProperty("type", "password");
const toggleButton = screen.getByRole("button", { name: /show value/i });
fireEvent.click(toggleButton);
expect(valueInput).toHaveProperty("type", "text");
});
});
describe("Authentication", () => {
const openAuthSection = () => {
const button = screen.getByTestId("auth-button");
fireEvent.click(button);
};
it("should update bearer token", () => {
const setBearerToken = jest.fn();
renderSidebar({
bearerToken: "",
setBearerToken,
transportType: "sse", // Set transport type to SSE
});
openAuthSection();
const tokenInput = screen.getByTestId("bearer-token-input");
fireEvent.change(tokenInput, { target: { value: "new_token" } });
expect(setBearerToken).toHaveBeenCalledWith("new_token");
});
it("should update header name", () => {
const setHeaderName = jest.fn();
renderSidebar({
headerName: "Authorization",
setHeaderName,
transportType: "sse",
});
openAuthSection();
const headerInput = screen.getByTestId("header-input");
fireEvent.change(headerInput, { target: { value: "X-Custom-Auth" } });
expect(setHeaderName).toHaveBeenCalledWith("X-Custom-Auth");
});
it("should clear bearer token", () => {
const setBearerToken = jest.fn();
renderSidebar({
bearerToken: "existing_token",
setBearerToken,
transportType: "sse", // Set transport type to SSE
});
openAuthSection();
const tokenInput = screen.getByTestId("bearer-token-input");
fireEvent.change(tokenInput, { target: { value: "" } });
expect(setBearerToken).toHaveBeenCalledWith("");
});
it("should properly render bearer token input", () => {
const { rerender } = renderSidebar({
bearerToken: "existing_token",
transportType: "sse", // Set transport type to SSE
});
openAuthSection();
// Token input should be a password field
const tokenInput = screen.getByTestId("bearer-token-input");
expect(tokenInput).toHaveProperty("type", "password");
// Update the token
fireEvent.change(tokenInput, { target: { value: "new_token" } });
// Rerender with updated token
rerender(
<TooltipProvider>
<Sidebar
{...defaultProps}
bearerToken="new_token"
transportType="sse"
/>
</TooltipProvider>,
);
// Token input should still exist after update
expect(screen.getByTestId("bearer-token-input")).toBeInTheDocument();
});
it("should maintain token visibility state after update", () => {
const { rerender } = renderSidebar({
bearerToken: "existing_token",
transportType: "sse", // Set transport type to SSE
});
openAuthSection();
// Token input should be a password field
const tokenInput = screen.getByTestId("bearer-token-input");
expect(tokenInput).toHaveProperty("type", "password");
// Update the token
fireEvent.change(tokenInput, { target: { value: "new_token" } });
// Rerender with updated token
rerender(
<TooltipProvider>
<Sidebar
{...defaultProps}
bearerToken="new_token"
transportType="sse"
/>
</TooltipProvider>,
);
// Token input should still exist after update
expect(screen.getByTestId("bearer-token-input")).toBeInTheDocument();
});
it("should maintain header name when toggling auth section", () => {
renderSidebar({
headerName: "X-API-Key",
transportType: "sse",
});
// Open auth section
openAuthSection();
// Verify header name is displayed
const headerInput = screen.getByTestId("header-input");
expect(headerInput).toHaveValue("X-API-Key");
// Close auth section
const authButton = screen.getByTestId("auth-button");
fireEvent.click(authButton);
// Reopen auth section
fireEvent.click(authButton);
// Verify header name is still preserved
expect(screen.getByTestId("header-input")).toHaveValue("X-API-Key");
});
it("should display default header name when not specified", () => {
renderSidebar({
headerName: undefined,
transportType: "sse",
});
openAuthSection();
const headerInput = screen.getByTestId("header-input");
expect(headerInput).toHaveAttribute("placeholder", "Authorization");
});
});
describe("Key Editing", () => {
it("should maintain order when editing first key", () => {
const setEnv = jest.fn();
const initialEnv = {
FIRST_KEY: "first_value",
SECOND_KEY: "second_value",
THIRD_KEY: "third_value",
};
renderSidebar({ env: initialEnv, setEnv });
openEnvVarsSection();
const firstKeyInput = screen.getByDisplayValue("FIRST_KEY");
fireEvent.change(firstKeyInput, { target: { value: "NEW_FIRST_KEY" } });
expect(setEnv).toHaveBeenCalledWith({
NEW_FIRST_KEY: "first_value",
SECOND_KEY: "second_value",
THIRD_KEY: "third_value",
});
});
it("should maintain order when editing middle key", () => {
const setEnv = jest.fn();
const initialEnv = {
FIRST_KEY: "first_value",
SECOND_KEY: "second_value",
THIRD_KEY: "third_value",
};
renderSidebar({ env: initialEnv, setEnv });
openEnvVarsSection();
const middleKeyInput = screen.getByDisplayValue("SECOND_KEY");
fireEvent.change(middleKeyInput, { target: { value: "NEW_SECOND_KEY" } });
expect(setEnv).toHaveBeenCalledWith({
FIRST_KEY: "first_value",
NEW_SECOND_KEY: "second_value",
THIRD_KEY: "third_value",
});
});
it("should maintain order when editing last key", () => {
const setEnv = jest.fn();
const initialEnv = {
FIRST_KEY: "first_value",
SECOND_KEY: "second_value",
THIRD_KEY: "third_value",
};
renderSidebar({ env: initialEnv, setEnv });
openEnvVarsSection();
const lastKeyInput = screen.getByDisplayValue("THIRD_KEY");
fireEvent.change(lastKeyInput, { target: { value: "NEW_THIRD_KEY" } });
expect(setEnv).toHaveBeenCalledWith({
FIRST_KEY: "first_value",
SECOND_KEY: "second_value",
NEW_THIRD_KEY: "third_value",
});
});
it("should maintain order during key editing", () => {
const setEnv = jest.fn();
const initialEnv = {
KEY1: "value1",
KEY2: "value2",
};
renderSidebar({ env: initialEnv, setEnv });
openEnvVarsSection();
// Type "NEW_" one character at a time
const key1Input = screen.getByDisplayValue("KEY1");
"NEW_".split("").forEach((char) => {
fireEvent.change(key1Input, {
target: { value: char + "KEY1".slice(1) },
});
});
// Verify the last setEnv call maintains the order
const lastCall = setEnv.mock.calls[
setEnv.mock.calls.length - 1
][0] as Record<string, string>;
const entries = Object.entries(lastCall);
// The values should stay with their original keys
expect(entries[0][1]).toBe("value1"); // First entry should still have value1
expect(entries[1][1]).toBe("value2"); // Second entry should still have value2
});
});
describe("Multiple Operations", () => {
it("should maintain state after multiple key edits", () => {
const setEnv = jest.fn();
const initialEnv = {
FIRST_KEY: "first_value",
SECOND_KEY: "second_value",
};
const { rerender } = renderSidebar({ env: initialEnv, setEnv });
openEnvVarsSection();
// First key edit
const firstKeyInput = screen.getByDisplayValue("FIRST_KEY");
fireEvent.change(firstKeyInput, { target: { value: "NEW_FIRST_KEY" } });
// Get the updated env from the first setEnv call
const updatedEnv = setEnv.mock.calls[0][0] as Record<string, string>;
// Rerender with the updated env
rerender(
<TooltipProvider>
<Sidebar {...defaultProps} env={updatedEnv} setEnv={setEnv} />
</TooltipProvider>,
);
// Second key edit
const secondKeyInput = screen.getByDisplayValue("SECOND_KEY");
fireEvent.change(secondKeyInput, { target: { value: "NEW_SECOND_KEY" } });
// Verify the final state matches what we expect
expect(setEnv).toHaveBeenLastCalledWith({
NEW_FIRST_KEY: "first_value",
NEW_SECOND_KEY: "second_value",
});
});
it("should maintain visibility state after key edit", () => {
const initialEnv = { TEST_KEY: "test_value" };
const { rerender } = renderSidebar({ env: initialEnv });
openEnvVarsSection();
// Show the value
const toggleButton = screen.getByRole("button", { name: /show value/i });
fireEvent.click(toggleButton);
const valueInput = screen.getByDisplayValue("test_value");
expect(valueInput).toHaveProperty("type", "text");
// Edit the key
const keyInput = screen.getByDisplayValue("TEST_KEY");
fireEvent.change(keyInput, { target: { value: "NEW_KEY" } });
// Rerender with updated env
rerender(
<TooltipProvider>
<Sidebar {...defaultProps} env={{ NEW_KEY: "test_value" }} />
</TooltipProvider>,
);
// Value should still be visible
const updatedValueInput = screen.getByDisplayValue("test_value");
expect(updatedValueInput).toHaveProperty("type", "text");
});
});
describe("Edge Cases", () => {
it("should handle empty key", () => {
const setEnv = jest.fn();
const initialEnv = { TEST_KEY: "test_value" };
renderSidebar({ env: initialEnv, setEnv });
openEnvVarsSection();
const keyInput = screen.getByDisplayValue("TEST_KEY");
fireEvent.change(keyInput, { target: { value: "" } });
expect(setEnv).toHaveBeenCalledWith({ "": "test_value" });
});
it("should handle special characters in key", () => {
const setEnv = jest.fn();
const initialEnv = { TEST_KEY: "test_value" };
renderSidebar({ env: initialEnv, setEnv });
openEnvVarsSection();
const keyInput = screen.getByDisplayValue("TEST_KEY");
fireEvent.change(keyInput, { target: { value: "TEST-KEY@123" } });
expect(setEnv).toHaveBeenCalledWith({ "TEST-KEY@123": "test_value" });
});
it("should handle unicode characters", () => {
const setEnv = jest.fn();
const initialEnv = { TEST_KEY: "test_value" };
renderSidebar({ env: initialEnv, setEnv });
openEnvVarsSection();
const keyInput = screen.getByDisplayValue("TEST_KEY");
fireEvent.change(keyInput, { target: { value: "TEST_🔑" } });
expect(setEnv).toHaveBeenCalledWith({ "TEST_🔑": "test_value" });
});
it("should handle very long key names", () => {
const setEnv = jest.fn();
const initialEnv = { TEST_KEY: "test_value" };
renderSidebar({ env: initialEnv, setEnv });
openEnvVarsSection();
const keyInput = screen.getByDisplayValue("TEST_KEY");
const longKey = "A".repeat(100);
fireEvent.change(keyInput, { target: { value: longKey } });
expect(setEnv).toHaveBeenCalledWith({ [longKey]: "test_value" });
});
});
describe("Configuration Operations", () => {
const openConfigSection = () => {
const button = screen.getByTestId("config-button");
fireEvent.click(button);
};
it("should update MCP server request timeout", () => {
const setConfig = jest.fn();
renderSidebar({ config: DEFAULT_INSPECTOR_CONFIG, setConfig });
openConfigSection();
const timeoutInput = screen.getByTestId(
"MCP_SERVER_REQUEST_TIMEOUT-input",
);
fireEvent.change(timeoutInput, { target: { value: "5000" } });
expect(setConfig).toHaveBeenCalledWith(
expect.objectContaining({
MCP_SERVER_REQUEST_TIMEOUT: {
label: "Request Timeout",
description: "Timeout for requests to the MCP server (ms)",
value: 5000,
},
}),
);
});
it("should update MCP server proxy address", () => {
const setConfig = jest.fn();
renderSidebar({ config: DEFAULT_INSPECTOR_CONFIG, setConfig });
openConfigSection();
const proxyAddressInput = screen.getByTestId(
"MCP_PROXY_FULL_ADDRESS-input",
);
fireEvent.change(proxyAddressInput, {
target: { value: "http://localhost:8080" },
});
expect(setConfig).toHaveBeenCalledWith(
expect.objectContaining({
MCP_PROXY_FULL_ADDRESS: {
label: "Inspector Proxy Address",
description:
"Set this if you are running the MCP Inspector Proxy on a non-default address. Example: http://10.1.1.22:5577",
value: "http://localhost:8080",
},
}),
);
});
it("should update max total timeout", () => {
const setConfig = jest.fn();
renderSidebar({ config: DEFAULT_INSPECTOR_CONFIG, setConfig });
openConfigSection();
const maxTotalTimeoutInput = screen.getByTestId(
"MCP_REQUEST_MAX_TOTAL_TIMEOUT-input",
);
fireEvent.change(maxTotalTimeoutInput, {
target: { value: "10000" },
});
expect(setConfig).toHaveBeenCalledWith(
expect.objectContaining({
MCP_REQUEST_MAX_TOTAL_TIMEOUT: {
label: "Maximum Total Timeout",
description:
"Maximum total timeout for requests sent to the MCP server (ms) (Use with progress notifications)",
value: 10000,
},
}),
);
});
it("should handle invalid timeout values entered by user", () => {
const setConfig = jest.fn();
renderSidebar({ config: DEFAULT_INSPECTOR_CONFIG, setConfig });
openConfigSection();
const timeoutInput = screen.getByTestId(
"MCP_SERVER_REQUEST_TIMEOUT-input",
);
fireEvent.change(timeoutInput, { target: { value: "abc1" } });
expect(setConfig).toHaveBeenCalledWith(
expect.objectContaining({
MCP_SERVER_REQUEST_TIMEOUT: {
label: "Request Timeout",
description: "Timeout for requests to the MCP server (ms)",
value: 0,
},
}),
);
});
it("should maintain configuration state after multiple updates", () => {
const setConfig = jest.fn();
const { rerender } = renderSidebar({
config: DEFAULT_INSPECTOR_CONFIG,
setConfig,
});
openConfigSection();
// First update
const timeoutInput = screen.getByTestId(
"MCP_SERVER_REQUEST_TIMEOUT-input",
);
fireEvent.change(timeoutInput, { target: { value: "5000" } });
// Get the updated config from the first setConfig call
const updatedConfig = setConfig.mock.calls[0][0] as InspectorConfig;
// Rerender with the updated config
rerender(
<TooltipProvider>
<Sidebar
{...defaultProps}
config={updatedConfig}
setConfig={setConfig}
/>
</TooltipProvider>,
);
// Second update
const updatedTimeoutInput = screen.getByTestId(
"MCP_SERVER_REQUEST_TIMEOUT-input",
);
fireEvent.change(updatedTimeoutInput, { target: { value: "3000" } });
// Verify the final state matches what we expect
expect(setConfig).toHaveBeenLastCalledWith(
expect.objectContaining({
MCP_SERVER_REQUEST_TIMEOUT: {
label: "Request Timeout",
description: "Timeout for requests to the MCP server (ms)",
value: 3000,
},
}),
);
});
});
});

View File

@@ -0,0 +1,144 @@
import { render, screen, fireEvent, act } from "@testing-library/react";
import { describe, it, expect, jest } from "@jest/globals";
import "@testing-library/jest-dom";
import ToolsTab from "../ToolsTab";
import { Tool } from "@modelcontextprotocol/sdk/types.js";
import { Tabs } from "@/components/ui/tabs";
describe("ToolsTab", () => {
const mockTools: Tool[] = [
{
name: "tool1",
description: "First tool",
inputSchema: {
type: "object" as const,
properties: {
num: { type: "number" as const },
},
},
},
{
name: "tool3",
description: "Integer tool",
inputSchema: {
type: "object" as const,
properties: {
count: { type: "integer" as const },
},
},
},
{
name: "tool2",
description: "Second tool",
inputSchema: {
type: "object" as const,
properties: {
num: { type: "number" as const },
},
},
},
];
const defaultProps = {
tools: mockTools,
listTools: jest.fn(),
clearTools: jest.fn(),
callTool: jest.fn(async () => {}),
selectedTool: null,
setSelectedTool: jest.fn(),
toolResult: null,
nextCursor: "",
error: null,
};
const renderToolsTab = (props = {}) => {
return render(
<Tabs defaultValue="tools">
<ToolsTab {...defaultProps} {...props} />
</Tabs>,
);
};
it("should reset input values when switching tools", async () => {
const { rerender } = renderToolsTab({
selectedTool: mockTools[0],
});
// Enter a value in the first tool's input
const input = screen.getByRole("spinbutton") as HTMLInputElement;
await act(async () => {
fireEvent.change(input, { target: { value: "42" } });
});
expect(input.value).toBe("42");
// Switch to second tool
rerender(
<Tabs defaultValue="tools">
<ToolsTab {...defaultProps} selectedTool={mockTools[2]} />
</Tabs>,
);
// Verify input is reset
const newInput = screen.getByRole("spinbutton") as HTMLInputElement;
expect(newInput.value).toBe("");
});
it("should handle integer type inputs", async () => {
renderToolsTab({
selectedTool: mockTools[1], // Use the tool with integer type
});
const input = screen.getByRole("spinbutton", {
name: /count/i,
}) as HTMLInputElement;
expect(input).toHaveProperty("type", "number");
fireEvent.change(input, { target: { value: "42" } });
expect(input.value).toBe("42");
const submitButton = screen.getByRole("button", { name: /run tool/i });
await act(async () => {
fireEvent.click(submitButton);
});
expect(defaultProps.callTool).toHaveBeenCalledWith(mockTools[1].name, {
count: 42,
});
});
it("should disable button and change text while tool is running", async () => {
// Create a promise that we can resolve later
let resolvePromise: ((value: unknown) => void) | undefined;
const mockPromise = new Promise((resolve) => {
resolvePromise = resolve;
});
// Mock callTool to return our promise
const mockCallTool = jest.fn().mockReturnValue(mockPromise);
renderToolsTab({
selectedTool: mockTools[0],
callTool: mockCallTool,
});
const submitButton = screen.getByRole("button", { name: /run tool/i });
expect(submitButton.getAttribute("disabled")).toBeNull();
// Click the button and verify immediate state changes
await act(async () => {
fireEvent.click(submitButton);
});
// Verify button is disabled and text changed
expect(submitButton.getAttribute("disabled")).not.toBeNull();
expect(submitButton.textContent).toBe("Running...");
// Resolve the promise to simulate tool completion
await act(async () => {
if (resolvePromise) {
await resolvePromise({});
}
});
expect(submitButton.getAttribute("disabled")).toBeNull();
});
});

View File

@@ -0,0 +1,73 @@
import { render, screen, fireEvent } from "@testing-library/react";
import SamplingRequest from "../SamplingRequest";
import { PendingRequest } from "../SamplingTab";
const mockRequest: PendingRequest = {
id: 1,
request: {
method: "sampling/createMessage",
params: {
messages: [
{
role: "user",
content: {
type: "text",
text: "What files are in the current directory?",
},
},
],
systemPrompt: "You are a helpful file system assistant.",
includeContext: "thisServer",
maxTokens: 100,
},
},
};
describe("Form to handle sampling response", () => {
const mockOnApprove = jest.fn();
const mockOnReject = jest.fn();
afterEach(() => {
jest.clearAllMocks();
});
it("should call onApprove with correct text content when Approve button is clicked", () => {
render(
<SamplingRequest
request={mockRequest}
onApprove={mockOnApprove}
onReject={mockOnReject}
/>,
);
// Click the Approve button
fireEvent.click(screen.getByRole("button", { name: /approve/i }));
// Assert that onApprove is called with the correct arguments
expect(mockOnApprove).toHaveBeenCalledWith(mockRequest.id, {
model: "stub-model",
stopReason: "endTurn",
role: "assistant",
content: {
type: "text",
text: "",
},
});
});
it("should call onReject with correct request id when Reject button is clicked", () => {
render(
<SamplingRequest
request={mockRequest}
onApprove={mockOnApprove}
onReject={mockOnReject}
/>,
);
// Click the Approve button
fireEvent.click(screen.getByRole("button", { name: /Reject/i }));
// Assert that onApprove is called with the correct arguments
expect(mockOnReject).toHaveBeenCalledWith(mockRequest.id);
});
});

View File

@@ -0,0 +1,55 @@
import { render, screen } from "@testing-library/react";
import { Tabs } from "@/components/ui/tabs";
import SamplingTab, { PendingRequest } from "../SamplingTab";
describe("Sampling tab", () => {
const mockOnApprove = jest.fn();
const mockOnReject = jest.fn();
const renderSamplingTab = (pendingRequests: PendingRequest[]) =>
render(
<Tabs defaultValue="sampling">
<SamplingTab
pendingRequests={pendingRequests}
onApprove={mockOnApprove}
onReject={mockOnReject}
/>
</Tabs>,
);
it("should render 'No pending requests' when there are no pending requests", () => {
renderSamplingTab([]);
expect(
screen.getByText(
"When the server requests LLM sampling, requests will appear here for approval.",
),
).toBeTruthy();
expect(screen.findByText("No pending requests")).toBeTruthy();
});
it("should render the correct number of requests", () => {
renderSamplingTab(
Array.from({ length: 5 }, (_, i) => ({
id: i,
request: {
method: "sampling/createMessage",
params: {
messages: [
{
role: "user",
content: {
type: "text",
text: "What files are in the current directory?",
},
},
],
systemPrompt: "You are a helpful file system assistant.",
includeContext: "thisServer",
maxTokens: 100,
},
},
})),
);
expect(screen.getAllByTestId("sampling-request").length).toBe(5);
});
});

View File

@@ -1,7 +1,7 @@
import * as React from "react"
import { cva, type VariantProps } from "class-variance-authority"
import * as React from "react";
import { cva, type VariantProps } from "class-variance-authority";
import { cn } from "@/lib/utils"
import { cn } from "@/lib/utils";
const alertVariants = cva(
"relative w-full rounded-lg border px-4 py-3 text-sm [&>svg+div]:translate-y-[-3px] [&>svg]:absolute [&>svg]:left-4 [&>svg]:top-4 [&>svg]:text-foreground [&>svg~*]:pl-7",
@@ -16,8 +16,8 @@ const alertVariants = cva(
defaultVariants: {
variant: "default",
},
}
)
},
);
const Alert = React.forwardRef<
HTMLDivElement,
@@ -29,8 +29,8 @@ const Alert = React.forwardRef<
className={cn(alertVariants({ variant }), className)}
{...props}
/>
))
Alert.displayName = "Alert"
));
Alert.displayName = "Alert";
const AlertTitle = React.forwardRef<
HTMLParagraphElement,
@@ -41,8 +41,8 @@ const AlertTitle = React.forwardRef<
className={cn("mb-1 font-medium leading-none tracking-tight", className)}
{...props}
/>
))
AlertTitle.displayName = "AlertTitle"
));
AlertTitle.displayName = "AlertTitle";
const AlertDescription = React.forwardRef<
HTMLParagraphElement,
@@ -53,7 +53,7 @@ const AlertDescription = React.forwardRef<
className={cn("text-sm [&_p]:leading-relaxed", className)}
{...props}
/>
))
AlertDescription.displayName = "AlertDescription"
));
AlertDescription.displayName = "AlertDescription";
export { Alert, AlertTitle, AlertDescription }
export { Alert, AlertTitle, AlertDescription };

View File

@@ -1,8 +1,8 @@
import * as React from "react"
import { Slot } from "@radix-ui/react-slot"
import { cva, type VariantProps } from "class-variance-authority"
import * as React from "react";
import { Slot } from "@radix-ui/react-slot";
import { cva, type VariantProps } from "class-variance-authority";
import { cn } from "@/lib/utils"
import { cn } from "@/lib/utils";
const buttonVariants = cva(
"inline-flex items-center justify-center whitespace-nowrap rounded-md text-sm font-medium transition-colors focus-visible:outline-none focus-visible:ring-1 focus-visible:ring-ring disabled:pointer-events-none disabled:opacity-50",
@@ -10,7 +10,7 @@ const buttonVariants = cva(
variants: {
variant: {
default:
"bg-primary text-primary-foreground shadow hover:bg-primary/90",
"bg-primary text-primary-foreground shadow hover:bg-primary/90 dark:bg-gray-800 dark:text-white dark:hover:bg-gray-700",
destructive:
"bg-destructive text-destructive-foreground shadow-sm hover:bg-destructive/90",
outline:
@@ -31,27 +31,27 @@ const buttonVariants = cva(
variant: "default",
size: "default",
},
}
)
},
);
export interface ButtonProps
extends React.ButtonHTMLAttributes<HTMLButtonElement>,
VariantProps<typeof buttonVariants> {
asChild?: boolean
asChild?: boolean;
}
const Button = React.forwardRef<HTMLButtonElement, ButtonProps>(
({ className, variant, size, asChild = false, ...props }, ref) => {
const Comp = asChild ? Slot : "button"
const Comp = asChild ? Slot : "button";
return (
<Comp
className={cn(buttonVariants({ variant, size, className }))}
ref={ref}
{...props}
/>
)
}
)
Button.displayName = "Button"
);
},
);
Button.displayName = "Button";
export { Button, buttonVariants }
export { Button };

View File

@@ -0,0 +1,30 @@
"use client";
import * as React from "react";
import * as CheckboxPrimitive from "@radix-ui/react-checkbox";
import { Check } from "lucide-react";
import { cn } from "@/lib/utils";
const Checkbox = React.forwardRef<
React.ElementRef<typeof CheckboxPrimitive.Root>,
React.ComponentPropsWithoutRef<typeof CheckboxPrimitive.Root>
>(({ className, ...props }, ref) => (
<CheckboxPrimitive.Root
ref={ref}
className={cn(
"peer h-4 w-4 shrink-0 rounded-sm border border-primary ring-offset-background focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-ring focus-visible:ring-offset-2 disabled:cursor-not-allowed disabled:opacity-50 data-[state=checked]:bg-primary data-[state=checked]:text-primary-foreground",
className,
)}
{...props}
>
<CheckboxPrimitive.Indicator
className={cn("flex items-center justify-center text-current")}
>
<Check className="h-4 w-4" />
</CheckboxPrimitive.Indicator>
</CheckboxPrimitive.Root>
));
Checkbox.displayName = CheckboxPrimitive.Root.displayName;
export { Checkbox };

View File

@@ -0,0 +1,97 @@
import React from "react";
import { Check, ChevronsUpDown } from "lucide-react";
import { cn } from "@/lib/utils";
import { Button } from "@/components/ui/button";
import {
Command,
CommandEmpty,
CommandGroup,
CommandInput,
CommandItem,
} from "@/components/ui/command";
import {
Popover,
PopoverContent,
PopoverTrigger,
} from "@/components/ui/popover";
interface ComboboxProps {
value: string;
onChange: (value: string) => void;
onInputChange: (value: string) => void;
options: string[];
placeholder?: string;
emptyMessage?: string;
id?: string;
}
export function Combobox({
value,
onChange,
onInputChange,
options = [],
placeholder = "Select...",
emptyMessage = "No results found.",
id,
}: ComboboxProps) {
const [open, setOpen] = React.useState(false);
const handleSelect = React.useCallback(
(option: string) => {
onChange(option);
setOpen(false);
},
[onChange],
);
const handleInputChange = React.useCallback(
(value: string) => {
onInputChange(value);
},
[onInputChange],
);
return (
<Popover open={open} onOpenChange={setOpen}>
<PopoverTrigger asChild>
<Button
variant="outline"
role="combobox"
aria-expanded={open}
aria-controls={id}
className="w-full justify-between"
>
{value || placeholder}
<ChevronsUpDown className="ml-2 h-4 w-4 shrink-0 opacity-50" />
</Button>
</PopoverTrigger>
<PopoverContent className="w-full p-0" align="start">
<Command shouldFilter={false} id={id}>
<CommandInput
placeholder={placeholder}
value={value}
onValueChange={handleInputChange}
/>
<CommandEmpty>{emptyMessage}</CommandEmpty>
<CommandGroup>
{options.map((option) => (
<CommandItem
key={option}
value={option}
onSelect={() => handleSelect(option)}
>
<Check
className={cn(
"mr-2 h-4 w-4",
value === option ? "opacity-100" : "opacity-0",
)}
/>
{option}
</CommandItem>
))}
</CommandGroup>
</Command>
</PopoverContent>
</Popover>
);
}

View File

@@ -0,0 +1,150 @@
import * as React from "react";
import { type DialogProps } from "@radix-ui/react-dialog";
import { Command as CommandPrimitive } from "cmdk";
import { cn } from "@/lib/utils";
import { Dialog, DialogContent } from "@/components/ui/dialog";
import { MagnifyingGlassIcon } from "@radix-ui/react-icons";
const Command = React.forwardRef<
React.ElementRef<typeof CommandPrimitive>,
React.ComponentPropsWithoutRef<typeof CommandPrimitive>
>(({ className, ...props }, ref) => (
<CommandPrimitive
ref={ref}
className={cn(
"flex h-full w-full flex-col overflow-hidden rounded-md bg-popover text-popover-foreground",
className,
)}
{...props}
/>
));
Command.displayName = CommandPrimitive.displayName;
const CommandDialog = ({ children, ...props }: DialogProps) => {
return (
<Dialog {...props}>
<DialogContent className="overflow-hidden p-0">
<Command className="[&_[cmdk-group-heading]]:px-2 [&_[cmdk-group-heading]]:font-medium [&_[cmdk-group-heading]]:text-muted-foreground [&_[cmdk-group]:not([hidden])_~[cmdk-group]]:pt-0 [&_[cmdk-group]]:px-2 [&_[cmdk-input-wrapper]_svg]:h-5 [&_[cmdk-input-wrapper]_svg]:w-5 [&_[cmdk-input]]:h-12 [&_[cmdk-item]]:px-2 [&_[cmdk-item]]:py-3 [&_[cmdk-item]_svg]:h-5 [&_[cmdk-item]_svg]:w-5">
{children}
</Command>
</DialogContent>
</Dialog>
);
};
const CommandInput = React.forwardRef<
React.ElementRef<typeof CommandPrimitive.Input>,
React.ComponentPropsWithoutRef<typeof CommandPrimitive.Input>
>(({ className, ...props }, ref) => (
<div className="flex items-center border-b px-3" cmdk-input-wrapper="">
<MagnifyingGlassIcon className="mr-2 h-4 w-4 shrink-0 opacity-50" />
<CommandPrimitive.Input
ref={ref}
className={cn(
"flex h-10 w-full rounded-md bg-transparent py-3 text-sm outline-none placeholder:text-muted-foreground disabled:cursor-not-allowed disabled:opacity-50",
className,
)}
{...props}
/>
</div>
));
CommandInput.displayName = CommandPrimitive.Input.displayName;
const CommandList = React.forwardRef<
React.ElementRef<typeof CommandPrimitive.List>,
React.ComponentPropsWithoutRef<typeof CommandPrimitive.List>
>(({ className, ...props }, ref) => (
<CommandPrimitive.List
ref={ref}
className={cn("max-h-[300px] overflow-y-auto overflow-x-hidden", className)}
{...props}
/>
));
CommandList.displayName = CommandPrimitive.List.displayName;
const CommandEmpty = React.forwardRef<
React.ElementRef<typeof CommandPrimitive.Empty>,
React.ComponentPropsWithoutRef<typeof CommandPrimitive.Empty>
>((props, ref) => (
<CommandPrimitive.Empty
ref={ref}
className="py-6 text-center text-sm"
{...props}
/>
));
CommandEmpty.displayName = CommandPrimitive.Empty.displayName;
const CommandGroup = React.forwardRef<
React.ElementRef<typeof CommandPrimitive.Group>,
React.ComponentPropsWithoutRef<typeof CommandPrimitive.Group>
>(({ className, ...props }, ref) => (
<CommandPrimitive.Group
ref={ref}
className={cn(
"overflow-hidden p-1 text-foreground [&_[cmdk-group-heading]]:px-2 [&_[cmdk-group-heading]]:py-1.5 [&_[cmdk-group-heading]]:text-xs [&_[cmdk-group-heading]]:font-medium [&_[cmdk-group-heading]]:text-muted-foreground",
className,
)}
{...props}
/>
));
CommandGroup.displayName = CommandPrimitive.Group.displayName;
const CommandSeparator = React.forwardRef<
React.ElementRef<typeof CommandPrimitive.Separator>,
React.ComponentPropsWithoutRef<typeof CommandPrimitive.Separator>
>(({ className, ...props }, ref) => (
<CommandPrimitive.Separator
ref={ref}
className={cn("-mx-1 h-px bg-border", className)}
{...props}
/>
));
CommandSeparator.displayName = CommandPrimitive.Separator.displayName;
const CommandItem = React.forwardRef<
React.ElementRef<typeof CommandPrimitive.Item>,
React.ComponentPropsWithoutRef<typeof CommandPrimitive.Item>
>(({ className, ...props }, ref) => (
<CommandPrimitive.Item
ref={ref}
className={cn(
"relative flex cursor-default gap-2 select-none items-center rounded-sm px-2 py-1.5 text-sm outline-none data-[disabled=true]:pointer-events-none data-[selected=true]:bg-accent data-[selected=true]:text-accent-foreground data-[disabled=true]:opacity-50 [&_svg]:pointer-events-none [&_svg]:size-4 [&_svg]:shrink-0",
className,
)}
{...props}
/>
));
CommandItem.displayName = CommandPrimitive.Item.displayName;
const CommandShortcut = ({
className,
...props
}: React.HTMLAttributes<HTMLSpanElement>) => {
return (
<span
className={cn(
"ml-auto text-xs tracking-widest text-muted-foreground",
className,
)}
{...props}
/>
);
};
CommandShortcut.displayName = "CommandShortcut";
export {
Command,
CommandDialog,
CommandInput,
CommandList,
CommandEmpty,
CommandGroup,
CommandItem,
CommandShortcut,
CommandSeparator,
};

View File

@@ -0,0 +1,121 @@
"use client";
import * as React from "react";
import * as DialogPrimitive from "@radix-ui/react-dialog";
import { cn } from "@/lib/utils";
import { Cross2Icon } from "@radix-ui/react-icons";
const Dialog = DialogPrimitive.Root;
const DialogTrigger = DialogPrimitive.Trigger;
const DialogPortal = DialogPrimitive.Portal;
const DialogClose = DialogPrimitive.Close;
const DialogOverlay = React.forwardRef<
React.ElementRef<typeof DialogPrimitive.Overlay>,
React.ComponentPropsWithoutRef<typeof DialogPrimitive.Overlay>
>(({ className, ...props }, ref) => (
<DialogPrimitive.Overlay
ref={ref}
className={cn(
"fixed inset-0 z-50 bg-black/80 data-[state=open]:animate-in data-[state=closed]:animate-out data-[state=closed]:fade-out-0 data-[state=open]:fade-in-0",
className,
)}
{...props}
/>
));
DialogOverlay.displayName = DialogPrimitive.Overlay.displayName;
const DialogContent = React.forwardRef<
React.ElementRef<typeof DialogPrimitive.Content>,
React.ComponentPropsWithoutRef<typeof DialogPrimitive.Content>
>(({ className, children, ...props }, ref) => (
<DialogPortal>
<DialogOverlay />
<DialogPrimitive.Content
ref={ref}
className={cn(
"fixed left-[50%] top-[50%] z-50 grid w-full max-w-lg translate-x-[-50%] translate-y-[-50%] gap-4 border bg-background p-6 shadow-lg duration-200 data-[state=open]:animate-in data-[state=closed]:animate-out data-[state=closed]:fade-out-0 data-[state=open]:fade-in-0 data-[state=closed]:zoom-out-95 data-[state=open]:zoom-in-95 data-[state=closed]:slide-out-to-left-1/2 data-[state=closed]:slide-out-to-top-[48%] data-[state=open]:slide-in-from-left-1/2 data-[state=open]:slide-in-from-top-[48%] sm:rounded-lg",
className,
)}
{...props}
>
{children}
<DialogPrimitive.Close className="absolute right-4 top-4 rounded-sm opacity-70 ring-offset-background transition-opacity hover:opacity-100 focus:outline-none focus:ring-2 focus:ring-ring focus:ring-offset-2 disabled:pointer-events-none data-[state=open]:bg-accent data-[state=open]:text-muted-foreground">
<Cross2Icon className="h-4 w-4" />
<span className="sr-only">Close</span>
</DialogPrimitive.Close>
</DialogPrimitive.Content>
</DialogPortal>
));
DialogContent.displayName = DialogPrimitive.Content.displayName;
const DialogHeader = ({
className,
...props
}: React.HTMLAttributes<HTMLDivElement>) => (
<div
className={cn(
"flex flex-col space-y-1.5 text-center sm:text-left",
className,
)}
{...props}
/>
);
DialogHeader.displayName = "DialogHeader";
const DialogFooter = ({
className,
...props
}: React.HTMLAttributes<HTMLDivElement>) => (
<div
className={cn(
"flex flex-col-reverse sm:flex-row sm:justify-end sm:space-x-2",
className,
)}
{...props}
/>
);
DialogFooter.displayName = "DialogFooter";
const DialogTitle = React.forwardRef<
React.ElementRef<typeof DialogPrimitive.Title>,
React.ComponentPropsWithoutRef<typeof DialogPrimitive.Title>
>(({ className, ...props }, ref) => (
<DialogPrimitive.Title
ref={ref}
className={cn(
"text-lg font-semibold leading-none tracking-tight",
className,
)}
{...props}
/>
));
DialogTitle.displayName = DialogPrimitive.Title.displayName;
const DialogDescription = React.forwardRef<
React.ElementRef<typeof DialogPrimitive.Description>,
React.ComponentPropsWithoutRef<typeof DialogPrimitive.Description>
>(({ className, ...props }, ref) => (
<DialogPrimitive.Description
ref={ref}
className={cn("text-sm text-muted-foreground", className)}
{...props}
/>
));
DialogDescription.displayName = DialogPrimitive.Description.displayName;
export {
Dialog,
DialogPortal,
DialogOverlay,
DialogTrigger,
DialogClose,
DialogContent,
DialogHeader,
DialogFooter,
DialogTitle,
DialogDescription,
};

View File

@@ -1,9 +1,8 @@
import * as React from "react"
import * as React from "react";
import { cn } from "@/lib/utils"
import { cn } from "@/lib/utils";
export interface InputProps
extends React.InputHTMLAttributes<HTMLInputElement> {}
export type InputProps = React.InputHTMLAttributes<HTMLInputElement>;
const Input = React.forwardRef<HTMLInputElement, InputProps>(
({ className, type, ...props }, ref) => {
@@ -12,14 +11,14 @@ const Input = React.forwardRef<HTMLInputElement, InputProps>(
type={type}
className={cn(
"flex h-9 w-full rounded-md border border-input bg-transparent px-3 py-1 text-sm shadow-sm transition-colors file:border-0 file:bg-transparent file:text-sm file:font-medium file:text-foreground placeholder:text-muted-foreground focus-visible:outline-none focus-visible:ring-1 focus-visible:ring-ring disabled:cursor-not-allowed disabled:opacity-50",
className
className,
)}
ref={ref}
{...props}
/>
)
}
)
Input.displayName = "Input"
);
},
);
Input.displayName = "Input";
export { Input }
export { Input };

View File

@@ -1,12 +1,12 @@
import * as React from "react"
import * as LabelPrimitive from "@radix-ui/react-label"
import { cva, type VariantProps } from "class-variance-authority"
import * as React from "react";
import * as LabelPrimitive from "@radix-ui/react-label";
import { cva, type VariantProps } from "class-variance-authority";
import { cn } from "@/lib/utils"
import { cn } from "@/lib/utils";
const labelVariants = cva(
"text-sm font-medium leading-none peer-disabled:cursor-not-allowed peer-disabled:opacity-70"
)
"text-sm font-medium leading-none peer-disabled:cursor-not-allowed peer-disabled:opacity-70",
);
const Label = React.forwardRef<
React.ElementRef<typeof LabelPrimitive.Root>,
@@ -18,7 +18,7 @@ const Label = React.forwardRef<
className={cn(labelVariants(), className)}
{...props}
/>
))
Label.displayName = LabelPrimitive.Root.displayName
));
Label.displayName = LabelPrimitive.Root.displayName;
export { Label }
export { Label };

View File

@@ -0,0 +1,31 @@
import * as React from "react";
import * as PopoverPrimitive from "@radix-ui/react-popover";
import { cn } from "@/lib/utils";
const Popover = PopoverPrimitive.Root;
const PopoverTrigger = PopoverPrimitive.Trigger;
const PopoverAnchor = PopoverPrimitive.Anchor;
const PopoverContent = React.forwardRef<
React.ElementRef<typeof PopoverPrimitive.Content>,
React.ComponentPropsWithoutRef<typeof PopoverPrimitive.Content>
>(({ className, align = "center", sideOffset = 4, ...props }, ref) => (
<PopoverPrimitive.Portal>
<PopoverPrimitive.Content
ref={ref}
align={align}
sideOffset={sideOffset}
className={cn(
"z-50 w-72 rounded-md border bg-popover p-4 text-popover-foreground shadow-md outline-none data-[state=open]:animate-in data-[state=closed]:animate-out data-[state=closed]:fade-out-0 data-[state=open]:fade-in-0 data-[state=closed]:zoom-out-95 data-[state=open]:zoom-in-95 data-[side=bottom]:slide-in-from-top-2 data-[side=left]:slide-in-from-right-2 data-[side=right]:slide-in-from-left-2 data-[side=top]:slide-in-from-bottom-2",
className,
)}
{...props}
/>
</PopoverPrimitive.Portal>
));
PopoverContent.displayName = PopoverPrimitive.Content.displayName;
export { Popover, PopoverTrigger, PopoverContent, PopoverAnchor };

View File

@@ -1,19 +1,19 @@
import * as React from "react"
import * as React from "react";
import {
CaretSortIcon,
CheckIcon,
ChevronDownIcon,
ChevronUpIcon,
} from "@radix-ui/react-icons"
import * as SelectPrimitive from "@radix-ui/react-select"
} from "@radix-ui/react-icons";
import * as SelectPrimitive from "@radix-ui/react-select";
import { cn } from "@/lib/utils"
import { cn } from "@/lib/utils";
const Select = SelectPrimitive.Root
const Select = SelectPrimitive.Root;
const SelectGroup = SelectPrimitive.Group
const SelectGroup = SelectPrimitive.Group;
const SelectValue = SelectPrimitive.Value
const SelectValue = SelectPrimitive.Value;
const SelectTrigger = React.forwardRef<
React.ElementRef<typeof SelectPrimitive.Trigger>,
@@ -22,8 +22,8 @@ const SelectTrigger = React.forwardRef<
<SelectPrimitive.Trigger
ref={ref}
className={cn(
"flex h-9 w-full items-center justify-between whitespace-nowrap rounded-md border border-input bg-transparent px-3 py-2 text-sm shadow-sm ring-offset-background placeholder:text-muted-foreground focus:outline-none focus:ring-1 focus:ring-ring disabled:cursor-not-allowed disabled:opacity-50 [&>span]:line-clamp-1",
className
"flex h-9 w-full items-center justify-between whitespace-nowrap rounded-md border border-input bg-transparent px-3 py-2 text-sm shadow-sm ring-offset-background placeholder:text-muted-foreground focus:outline-none focus:ring-1 focus:ring-ring disabled:cursor-not-allowed disabled:opacity-50 [&>span]:line-clamp-1 hover:border-[#646cff] hover:border-1",
className,
)}
{...props}
>
@@ -32,8 +32,8 @@ const SelectTrigger = React.forwardRef<
<CaretSortIcon className="h-4 w-4 opacity-50" />
</SelectPrimitive.Icon>
</SelectPrimitive.Trigger>
))
SelectTrigger.displayName = SelectPrimitive.Trigger.displayName
));
SelectTrigger.displayName = SelectPrimitive.Trigger.displayName;
const SelectScrollUpButton = React.forwardRef<
React.ElementRef<typeof SelectPrimitive.ScrollUpButton>,
@@ -43,14 +43,14 @@ const SelectScrollUpButton = React.forwardRef<
ref={ref}
className={cn(
"flex cursor-default items-center justify-center py-1",
className
className,
)}
{...props}
>
<ChevronUpIcon />
</SelectPrimitive.ScrollUpButton>
))
SelectScrollUpButton.displayName = SelectPrimitive.ScrollUpButton.displayName
));
SelectScrollUpButton.displayName = SelectPrimitive.ScrollUpButton.displayName;
const SelectScrollDownButton = React.forwardRef<
React.ElementRef<typeof SelectPrimitive.ScrollDownButton>,
@@ -60,15 +60,15 @@ const SelectScrollDownButton = React.forwardRef<
ref={ref}
className={cn(
"flex cursor-default items-center justify-center py-1",
className
className,
)}
{...props}
>
<ChevronDownIcon />
</SelectPrimitive.ScrollDownButton>
))
));
SelectScrollDownButton.displayName =
SelectPrimitive.ScrollDownButton.displayName
SelectPrimitive.ScrollDownButton.displayName;
const SelectContent = React.forwardRef<
React.ElementRef<typeof SelectPrimitive.Content>,
@@ -81,7 +81,7 @@ const SelectContent = React.forwardRef<
"relative z-50 max-h-96 min-w-[8rem] overflow-hidden rounded-md border bg-popover text-popover-foreground shadow-md data-[state=open]:animate-in data-[state=closed]:animate-out data-[state=closed]:fade-out-0 data-[state=open]:fade-in-0 data-[state=closed]:zoom-out-95 data-[state=open]:zoom-in-95 data-[side=bottom]:slide-in-from-top-2 data-[side=left]:slide-in-from-right-2 data-[side=right]:slide-in-from-left-2 data-[side=top]:slide-in-from-bottom-2",
position === "popper" &&
"data-[side=bottom]:translate-y-1 data-[side=left]:-translate-x-1 data-[side=right]:translate-x-1 data-[side=top]:-translate-y-1",
className
className,
)}
position={position}
{...props}
@@ -91,7 +91,7 @@ const SelectContent = React.forwardRef<
className={cn(
"p-1",
position === "popper" &&
"h-[var(--radix-select-trigger-height)] w-full min-w-[var(--radix-select-trigger-width)]"
"h-[var(--radix-select-trigger-height)] w-full min-w-[var(--radix-select-trigger-width)]",
)}
>
{children}
@@ -99,8 +99,8 @@ const SelectContent = React.forwardRef<
<SelectScrollDownButton />
</SelectPrimitive.Content>
</SelectPrimitive.Portal>
))
SelectContent.displayName = SelectPrimitive.Content.displayName
));
SelectContent.displayName = SelectPrimitive.Content.displayName;
const SelectLabel = React.forwardRef<
React.ElementRef<typeof SelectPrimitive.Label>,
@@ -111,8 +111,8 @@ const SelectLabel = React.forwardRef<
className={cn("px-2 py-1.5 text-sm font-semibold", className)}
{...props}
/>
))
SelectLabel.displayName = SelectPrimitive.Label.displayName
));
SelectLabel.displayName = SelectPrimitive.Label.displayName;
const SelectItem = React.forwardRef<
React.ElementRef<typeof SelectPrimitive.Item>,
@@ -122,7 +122,7 @@ const SelectItem = React.forwardRef<
ref={ref}
className={cn(
"relative flex w-full cursor-default select-none items-center rounded-sm py-1.5 pl-2 pr-8 text-sm outline-none focus:bg-accent focus:text-accent-foreground data-[disabled]:pointer-events-none data-[disabled]:opacity-50",
className
className,
)}
{...props}
>
@@ -133,8 +133,8 @@ const SelectItem = React.forwardRef<
</span>
<SelectPrimitive.ItemText>{children}</SelectPrimitive.ItemText>
</SelectPrimitive.Item>
))
SelectItem.displayName = SelectPrimitive.Item.displayName
));
SelectItem.displayName = SelectPrimitive.Item.displayName;
const SelectSeparator = React.forwardRef<
React.ElementRef<typeof SelectPrimitive.Separator>,
@@ -145,8 +145,8 @@ const SelectSeparator = React.forwardRef<
className={cn("-mx-1 my-1 h-px bg-muted", className)}
{...props}
/>
))
SelectSeparator.displayName = SelectPrimitive.Separator.displayName
));
SelectSeparator.displayName = SelectPrimitive.Separator.displayName;
export {
Select,
@@ -159,4 +159,4 @@ export {
SelectSeparator,
SelectScrollUpButton,
SelectScrollDownButton,
}
};

View File

@@ -1,9 +1,9 @@
import * as React from "react"
import * as TabsPrimitive from "@radix-ui/react-tabs"
import * as React from "react";
import * as TabsPrimitive from "@radix-ui/react-tabs";
import { cn } from "@/lib/utils"
import { cn } from "@/lib/utils";
const Tabs = TabsPrimitive.Root
const Tabs = TabsPrimitive.Root;
const TabsList = React.forwardRef<
React.ElementRef<typeof TabsPrimitive.List>,
@@ -13,12 +13,12 @@ const TabsList = React.forwardRef<
ref={ref}
className={cn(
"inline-flex h-9 items-center justify-center rounded-lg bg-muted p-1 text-muted-foreground",
className
className,
)}
{...props}
/>
))
TabsList.displayName = TabsPrimitive.List.displayName
));
TabsList.displayName = TabsPrimitive.List.displayName;
const TabsTrigger = React.forwardRef<
React.ElementRef<typeof TabsPrimitive.Trigger>,
@@ -27,13 +27,13 @@ const TabsTrigger = React.forwardRef<
<TabsPrimitive.Trigger
ref={ref}
className={cn(
"inline-flex items-center justify-center whitespace-nowrap rounded-md px-3 py-1 text-sm font-medium ring-offset-background transition-all focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-ring focus-visible:ring-offset-2 disabled:pointer-events-none disabled:opacity-50 data-[state=active]:bg-background data-[state=active]:text-foreground data-[state=active]:shadow",
className
"inline-flex items-center justify-center whitespace-nowrap rounded-md px-3 py-1 text-sm font-medium ring-offset-background transition-all focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-ring focus-visible:ring-offset-2 disabled:pointer-events-none disabled:opacity-50 bg-muted data-[state=active]:bg-background data-[state=active]:text-foreground data-[state=active]:shadow",
className,
)}
{...props}
/>
))
TabsTrigger.displayName = TabsPrimitive.Trigger.displayName
));
TabsTrigger.displayName = TabsPrimitive.Trigger.displayName;
const TabsContent = React.forwardRef<
React.ElementRef<typeof TabsPrimitive.Content>,
@@ -43,11 +43,11 @@ const TabsContent = React.forwardRef<
ref={ref}
className={cn(
"mt-2 ring-offset-background focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-ring focus-visible:ring-offset-2",
className
className,
)}
{...props}
/>
))
TabsContent.displayName = TabsPrimitive.Content.displayName
));
TabsContent.displayName = TabsPrimitive.Content.displayName;
export { Tabs, TabsList, TabsTrigger, TabsContent }
export { Tabs, TabsList, TabsTrigger, TabsContent };

View File

@@ -1,9 +1,8 @@
import * as React from "react"
import * as React from "react";
import { cn } from "@/lib/utils"
import { cn } from "@/lib/utils";
export interface TextareaProps
extends React.TextareaHTMLAttributes<HTMLTextAreaElement> {}
export type TextareaProps = React.TextareaHTMLAttributes<HTMLTextAreaElement>;
const Textarea = React.forwardRef<HTMLTextAreaElement, TextareaProps>(
({ className, ...props }, ref) => {
@@ -11,14 +10,14 @@ const Textarea = React.forwardRef<HTMLTextAreaElement, TextareaProps>(
<textarea
className={cn(
"flex min-h-[60px] w-full rounded-md border border-input bg-transparent px-3 py-2 text-sm shadow-sm placeholder:text-muted-foreground focus-visible:outline-none focus-visible:ring-1 focus-visible:ring-ring disabled:cursor-not-allowed disabled:opacity-50",
className
className,
)}
ref={ref}
{...props}
/>
)
}
)
Textarea.displayName = "Textarea"
);
},
);
Textarea.displayName = "Textarea";
export { Textarea }
export { Textarea };

View File

@@ -0,0 +1,126 @@
import * as React from "react";
import * as ToastPrimitives from "@radix-ui/react-toast";
import { cva, type VariantProps } from "class-variance-authority";
import { cn } from "@/lib/utils";
import { Cross2Icon } from "@radix-ui/react-icons";
const ToastProvider = ToastPrimitives.Provider;
const ToastViewport = React.forwardRef<
React.ElementRef<typeof ToastPrimitives.Viewport>,
React.ComponentPropsWithoutRef<typeof ToastPrimitives.Viewport>
>(({ className, ...props }, ref) => (
<ToastPrimitives.Viewport
ref={ref}
className={cn(
"fixed top-0 z-[100] flex max-h-screen w-full flex-col-reverse p-4 sm:bottom-0 sm:right-0 sm:top-auto sm:flex-col md:max-w-[420px]",
className,
)}
{...props}
/>
));
ToastViewport.displayName = ToastPrimitives.Viewport.displayName;
const toastVariants = cva(
"group pointer-events-auto relative flex w-full items-center justify-between space-x-2 overflow-hidden rounded-md border p-4 pr-6 shadow-lg transition-all data-[swipe=cancel]:translate-x-0 data-[swipe=end]:translate-x-[var(--radix-toast-swipe-end-x)] data-[swipe=move]:translate-x-[var(--radix-toast-swipe-move-x)] data-[swipe=move]:transition-none data-[state=open]:animate-in data-[state=closed]:animate-out data-[swipe=end]:animate-out data-[state=closed]:fade-out-80 data-[state=closed]:slide-out-to-right-full data-[state=open]:slide-in-from-top-full data-[state=open]:sm:slide-in-from-bottom-full",
{
variants: {
variant: {
default: "border bg-background text-foreground",
destructive:
"destructive group border-destructive bg-destructive text-destructive-foreground",
},
},
defaultVariants: {
variant: "default",
},
},
);
const Toast = React.forwardRef<
React.ElementRef<typeof ToastPrimitives.Root>,
React.ComponentPropsWithoutRef<typeof ToastPrimitives.Root> &
VariantProps<typeof toastVariants>
>(({ className, variant, ...props }, ref) => {
return (
<ToastPrimitives.Root
ref={ref}
className={cn(toastVariants({ variant }), className)}
{...props}
/>
);
});
Toast.displayName = ToastPrimitives.Root.displayName;
const ToastAction = React.forwardRef<
React.ElementRef<typeof ToastPrimitives.Action>,
React.ComponentPropsWithoutRef<typeof ToastPrimitives.Action>
>(({ className, ...props }, ref) => (
<ToastPrimitives.Action
ref={ref}
className={cn(
"inline-flex h-8 shrink-0 items-center justify-center rounded-md border bg-transparent px-3 text-sm font-medium transition-colors hover:bg-secondary focus:outline-none focus:ring-1 focus:ring-ring disabled:pointer-events-none disabled:opacity-50 group-[.destructive]:border-muted/40 group-[.destructive]:hover:border-destructive/30 group-[.destructive]:hover:bg-destructive group-[.destructive]:hover:text-destructive-foreground group-[.destructive]:focus:ring-destructive",
className,
)}
{...props}
/>
));
ToastAction.displayName = ToastPrimitives.Action.displayName;
const ToastClose = React.forwardRef<
React.ElementRef<typeof ToastPrimitives.Close>,
React.ComponentPropsWithoutRef<typeof ToastPrimitives.Close>
>(({ className, ...props }, ref) => (
<ToastPrimitives.Close
ref={ref}
className={cn(
"absolute right-1 top-1 rounded-md p-1 text-foreground/50 opacity-0 transition-opacity hover:text-foreground focus:opacity-100 focus:outline-none focus:ring-1 group-hover:opacity-100 group-[.destructive]:text-red-300 group-[.destructive]:hover:text-red-50 group-[.destructive]:focus:ring-red-400 group-[.destructive]:focus:ring-offset-red-600",
className,
)}
toast-close=""
{...props}
>
<Cross2Icon className="h-4 w-4" />
</ToastPrimitives.Close>
));
ToastClose.displayName = ToastPrimitives.Close.displayName;
const ToastTitle = React.forwardRef<
React.ElementRef<typeof ToastPrimitives.Title>,
React.ComponentPropsWithoutRef<typeof ToastPrimitives.Title>
>(({ className, ...props }, ref) => (
<ToastPrimitives.Title
ref={ref}
className={cn("text-sm font-semibold [&+div]:text-xs", className)}
{...props}
/>
));
ToastTitle.displayName = ToastPrimitives.Title.displayName;
const ToastDescription = React.forwardRef<
React.ElementRef<typeof ToastPrimitives.Description>,
React.ComponentPropsWithoutRef<typeof ToastPrimitives.Description>
>(({ className, ...props }, ref) => (
<ToastPrimitives.Description
ref={ref}
className={cn("text-sm opacity-90", className)}
{...props}
/>
));
ToastDescription.displayName = ToastPrimitives.Description.displayName;
type ToastProps = React.ComponentPropsWithoutRef<typeof Toast>;
type ToastActionElement = React.ReactElement<typeof ToastAction>;
export {
type ToastProps,
type ToastActionElement,
ToastProvider,
ToastViewport,
Toast,
ToastTitle,
ToastDescription,
ToastClose,
ToastAction,
};

View File

@@ -0,0 +1,33 @@
import { useToast } from "@/hooks/use-toast";
import {
Toast,
ToastClose,
ToastDescription,
ToastProvider,
ToastTitle,
ToastViewport,
} from "@/components/ui/toast";
export function Toaster() {
const { toasts } = useToast();
return (
<ToastProvider>
{toasts.map(function ({ id, title, description, action, ...props }) {
return (
<Toast key={id} {...props}>
<div className="grid gap-1">
{title && <ToastTitle>{title}</ToastTitle>}
{description && (
<ToastDescription>{description}</ToastDescription>
)}
</div>
{action}
<ToastClose />
</Toast>
);
})}
<ToastViewport />
</ToastProvider>
);
}

View File

@@ -0,0 +1,30 @@
"use client";
import * as React from "react";
import * as TooltipPrimitive from "@radix-ui/react-tooltip";
import { cn } from "@/lib/utils";
const TooltipProvider = TooltipPrimitive.Provider;
const Tooltip = TooltipPrimitive.Root;
const TooltipTrigger = TooltipPrimitive.Trigger;
const TooltipContent = React.forwardRef<
React.ElementRef<typeof TooltipPrimitive.Content>,
React.ComponentPropsWithoutRef<typeof TooltipPrimitive.Content>
>(({ className, sideOffset = 4, ...props }, ref) => (
<TooltipPrimitive.Content
ref={ref}
sideOffset={sideOffset}
className={cn(
"z-50 overflow-hidden rounded-md border bg-popover px-3 py-1.5 text-sm text-popover-foreground shadow-md animate-in fade-in-0 zoom-in-95 data-[state=closed]:animate-out data-[state=closed]:fade-out-0 data-[state=closed]:zoom-out-95 data-[side=bottom]:slide-in-from-top-2 data-[side=left]:slide-in-from-right-2 data-[side=right]:slide-in-from-left-2 data-[side=top]:slide-in-from-bottom-2 origin-[--radix-tooltip-content-transform-origin]",
className,
)}
{...props}
/>
));
TooltipContent.displayName = TooltipPrimitive.Content.displayName;
export { Tooltip, TooltipTrigger, TooltipContent, TooltipProvider };

View File

@@ -0,0 +1,191 @@
"use client";
// Inspired by react-hot-toast library
import * as React from "react";
import type { ToastActionElement, ToastProps } from "@/components/ui/toast";
const TOAST_LIMIT = 1;
const TOAST_REMOVE_DELAY = 1000000;
type ToasterToast = ToastProps & {
id: string;
title?: React.ReactNode;
description?: React.ReactNode;
action?: ToastActionElement;
};
let count = 0;
function genId() {
count = (count + 1) % Number.MAX_SAFE_INTEGER;
return count.toString();
}
const enum ActionType {
ADD_TOAST = "ADD_TOAST",
UPDATE_TOAST = "UPDATE_TOAST",
DISMISS_TOAST = "DISMISS_TOAST",
REMOVE_TOAST = "REMOVE_TOAST",
}
type Action =
| {
type: ActionType.ADD_TOAST;
toast: ToasterToast;
}
| {
type: ActionType.UPDATE_TOAST;
toast: Partial<ToasterToast>;
}
| {
type: ActionType.DISMISS_TOAST;
toastId?: ToasterToast["id"];
}
| {
type: ActionType.REMOVE_TOAST;
toastId?: ToasterToast["id"];
};
interface State {
toasts: ToasterToast[];
}
const toastTimeouts = new Map<string, ReturnType<typeof setTimeout>>();
const addToRemoveQueue = (toastId: string) => {
if (toastTimeouts.has(toastId)) {
return;
}
const timeout = setTimeout(() => {
toastTimeouts.delete(toastId);
dispatch({
type: ActionType.REMOVE_TOAST,
toastId: toastId,
});
}, TOAST_REMOVE_DELAY);
toastTimeouts.set(toastId, timeout);
};
export const reducer = (state: State, action: Action): State => {
switch (action.type) {
case ActionType.ADD_TOAST:
return {
...state,
toasts: [action.toast, ...state.toasts].slice(0, TOAST_LIMIT),
};
case ActionType.UPDATE_TOAST:
return {
...state,
toasts: state.toasts.map((t) =>
t.id === action.toast.id ? { ...t, ...action.toast } : t,
),
};
case ActionType.DISMISS_TOAST: {
const { toastId } = action;
// ! Side effects ! - This could be extracted into a dismissToast() action,
// but I'll keep it here for simplicity
if (toastId) {
addToRemoveQueue(toastId);
} else {
state.toasts.forEach((toast) => {
addToRemoveQueue(toast.id);
});
}
return {
...state,
toasts: state.toasts.map((t) =>
t.id === toastId || toastId === undefined
? {
...t,
open: false,
}
: t,
),
};
}
case ActionType.REMOVE_TOAST:
if (action.toastId === undefined) {
return {
...state,
toasts: [],
};
}
return {
...state,
toasts: state.toasts.filter((t) => t.id !== action.toastId),
};
}
};
const listeners: Array<(state: State) => void> = [];
let memoryState: State = { toasts: [] };
function dispatch(action: Action) {
memoryState = reducer(memoryState, action);
listeners.forEach((listener) => {
listener(memoryState);
});
}
type Toast = Omit<ToasterToast, "id">;
function toast({ ...props }: Toast) {
const id = genId();
const update = (props: ToasterToast) =>
dispatch({
type: ActionType.UPDATE_TOAST,
toast: { ...props, id },
});
const dismiss = () =>
dispatch({ type: ActionType.DISMISS_TOAST, toastId: id });
dispatch({
type: ActionType.ADD_TOAST,
toast: {
...props,
id,
open: true,
onOpenChange: (open) => {
if (!open) dismiss();
},
},
});
return {
id: id,
dismiss,
update,
};
}
function useToast() {
const [state, setState] = React.useState<State>(memoryState);
React.useEffect(() => {
listeners.push(setState);
return () => {
const index = listeners.indexOf(setState);
if (index > -1) {
listeners.splice(index, 1);
}
};
}, [state]);
return {
...state,
toast,
dismiss: (toastId?: string) =>
dispatch({ type: ActionType.DISMISS_TOAST, toastId }),
};
}
export { useToast, toast };

View File

@@ -38,25 +38,6 @@ h1 {
line-height: 1.1;
}
button {
border-radius: 8px;
border: 1px solid transparent;
padding: 0.6em 1.2em;
font-size: 1em;
font-weight: 500;
font-family: inherit;
background-color: #1a1a1a;
cursor: pointer;
transition: border-color 0.25s;
}
button:hover {
border-color: #646cff;
}
button:focus,
button:focus-visible {
outline: 4px auto -webkit-focus-ring-color;
}
@media (prefers-color-scheme: light) {
:root {
color: #213547;
@@ -65,9 +46,6 @@ button:focus-visible {
a:hover {
color: #747bff;
}
button {
background-color: #f9f9f9;
}
}
@layer base {

103
client/src/lib/auth.ts Normal file
View File

@@ -0,0 +1,103 @@
import { OAuthClientProvider } from "@modelcontextprotocol/sdk/client/auth.js";
import {
OAuthClientInformationSchema,
OAuthClientInformation,
OAuthTokens,
OAuthTokensSchema,
} from "@modelcontextprotocol/sdk/shared/auth.js";
import { SESSION_KEYS, getServerSpecificKey } from "./constants";
export class InspectorOAuthClientProvider implements OAuthClientProvider {
constructor(private serverUrl: string) {
// Save the server URL to session storage
sessionStorage.setItem(SESSION_KEYS.SERVER_URL, serverUrl);
}
get redirectUrl() {
return window.location.origin + "/oauth/callback";
}
get clientMetadata() {
return {
redirect_uris: [this.redirectUrl],
token_endpoint_auth_method: "none",
grant_types: ["authorization_code", "refresh_token"],
response_types: ["code"],
client_name: "MCP Inspector",
client_uri: "https://github.com/modelcontextprotocol/inspector",
};
}
async clientInformation() {
const key = getServerSpecificKey(
SESSION_KEYS.CLIENT_INFORMATION,
this.serverUrl,
);
const value = sessionStorage.getItem(key);
if (!value) {
return undefined;
}
return await OAuthClientInformationSchema.parseAsync(JSON.parse(value));
}
saveClientInformation(clientInformation: OAuthClientInformation) {
const key = getServerSpecificKey(
SESSION_KEYS.CLIENT_INFORMATION,
this.serverUrl,
);
sessionStorage.setItem(key, JSON.stringify(clientInformation));
}
async tokens() {
const key = getServerSpecificKey(SESSION_KEYS.TOKENS, this.serverUrl);
const tokens = sessionStorage.getItem(key);
if (!tokens) {
return undefined;
}
return await OAuthTokensSchema.parseAsync(JSON.parse(tokens));
}
saveTokens(tokens: OAuthTokens) {
const key = getServerSpecificKey(SESSION_KEYS.TOKENS, this.serverUrl);
sessionStorage.setItem(key, JSON.stringify(tokens));
}
redirectToAuthorization(authorizationUrl: URL) {
window.location.href = authorizationUrl.href;
}
saveCodeVerifier(codeVerifier: string) {
const key = getServerSpecificKey(
SESSION_KEYS.CODE_VERIFIER,
this.serverUrl,
);
sessionStorage.setItem(key, codeVerifier);
}
codeVerifier() {
const key = getServerSpecificKey(
SESSION_KEYS.CODE_VERIFIER,
this.serverUrl,
);
const verifier = sessionStorage.getItem(key);
if (!verifier) {
throw new Error("No code verifier saved for session");
}
return verifier;
}
clear() {
sessionStorage.removeItem(
getServerSpecificKey(SESSION_KEYS.CLIENT_INFORMATION, this.serverUrl),
);
sessionStorage.removeItem(
getServerSpecificKey(SESSION_KEYS.TOKENS, this.serverUrl),
);
sessionStorage.removeItem(
getServerSpecificKey(SESSION_KEYS.CODE_VERIFIER, this.serverUrl),
);
}
}

View File

@@ -0,0 +1,36 @@
export type ConfigItem = {
label: string;
description: string;
value: string | number | boolean;
};
/**
* Configuration interface for the MCP Inspector, including settings for the MCP Client,
* Proxy Server, and Inspector UI/UX.
*
* Note: Configuration related to which MCP Server to use or any other MCP Server
* specific settings are outside the scope of this interface as of now.
*/
export type InspectorConfig = {
/**
* Maximum time in milliseconds to wait for a response from the MCP server before timing out.
*/
MCP_SERVER_REQUEST_TIMEOUT: ConfigItem;
/**
* Whether to reset the timeout on progress notifications. Useful for long-running operations that send periodic progress updates.
* Refer: https://spec.modelcontextprotocol.io/specification/2025-03-26/basic/utilities/progress/#progress-flow
*/
MCP_REQUEST_TIMEOUT_RESET_ON_PROGRESS: ConfigItem;
/**
* Maximum total time in milliseconds to wait for a response from the MCP server before timing out. Used in conjunction with MCP_SERVER_REQUEST_TIMEOUT_RESET_ON_PROGRESS.
* Refer: https://spec.modelcontextprotocol.io/specification/2025-03-26/basic/utilities/progress/#progress-flow
*/
MCP_REQUEST_MAX_TOTAL_TIMEOUT: ConfigItem;
/**
* The full address of the MCP Proxy Server, in case it is running on a non-default address. Example: http://10.1.1.22:5577
*/
MCP_PROXY_FULL_ADDRESS: ConfigItem;
};

View File

@@ -0,0 +1,55 @@
import { InspectorConfig } from "./configurationTypes";
// OAuth-related session storage keys
export const SESSION_KEYS = {
CODE_VERIFIER: "mcp_code_verifier",
SERVER_URL: "mcp_server_url",
TOKENS: "mcp_tokens",
CLIENT_INFORMATION: "mcp_client_information",
} as const;
// Generate server-specific session storage keys
export const getServerSpecificKey = (
baseKey: string,
serverUrl?: string,
): string => {
if (!serverUrl) return baseKey;
return `[${serverUrl}] ${baseKey}`;
};
export type ConnectionStatus =
| "disconnected"
| "connected"
| "error"
| "error-connecting-to-proxy";
export const DEFAULT_MCP_PROXY_LISTEN_PORT = "6277";
/**
* Default configuration for the MCP Inspector, Currently persisted in local_storage in the Browser.
* Future plans: Provide json config file + Browser local_storage to override default values
**/
export const DEFAULT_INSPECTOR_CONFIG: InspectorConfig = {
MCP_SERVER_REQUEST_TIMEOUT: {
label: "Request Timeout",
description: "Timeout for requests to the MCP server (ms)",
value: 10000,
},
MCP_REQUEST_TIMEOUT_RESET_ON_PROGRESS: {
label: "Reset Timeout on Progress",
description: "Reset timeout on progress notifications",
value: true,
},
MCP_REQUEST_MAX_TOTAL_TIMEOUT: {
label: "Maximum Total Timeout",
description:
"Maximum total timeout for requests sent to the MCP server (ms) (Use with progress notifications)",
value: 60000,
},
MCP_PROXY_FULL_ADDRESS: {
label: "Inspector Proxy Address",
description:
"Set this if you are running the MCP Inspector Proxy on a non-default address. Example: http://10.1.1.22:5577",
value: "",
},
} as const;

View File

@@ -0,0 +1,166 @@
import { renderHook, act } from "@testing-library/react";
import { useConnection } from "../useConnection";
import { z } from "zod";
import { ClientRequest } from "@modelcontextprotocol/sdk/types.js";
import { DEFAULT_INSPECTOR_CONFIG } from "../../constants";
// Mock fetch
global.fetch = jest.fn().mockResolvedValue({
json: () => Promise.resolve({ status: "ok" }),
});
// Mock the SDK dependencies
const mockRequest = jest.fn().mockResolvedValue({ test: "response" });
const mockClient = {
request: mockRequest,
notification: jest.fn(),
connect: jest.fn().mockResolvedValue(undefined),
close: jest.fn(),
getServerCapabilities: jest.fn(),
getServerVersion: jest.fn(),
getInstructions: jest.fn(),
setNotificationHandler: jest.fn(),
setRequestHandler: jest.fn(),
};
jest.mock("@modelcontextprotocol/sdk/client/index.js", () => ({
Client: jest.fn().mockImplementation(() => mockClient),
}));
jest.mock("@modelcontextprotocol/sdk/client/sse.js", () => ({
SSEClientTransport: jest.fn(),
SseError: jest.fn(),
}));
jest.mock("@modelcontextprotocol/sdk/client/auth.js", () => ({
auth: jest.fn().mockResolvedValue("AUTHORIZED"),
}));
// Mock the toast hook
jest.mock("@/hooks/use-toast", () => ({
useToast: () => ({
toast: jest.fn(),
}),
}));
// Mock the auth provider
jest.mock("../../auth", () => ({
InspectorOAuthClientProvider: jest.fn().mockImplementation(() => ({
tokens: jest.fn().mockResolvedValue({ access_token: "mock-token" }),
})),
}));
describe("useConnection", () => {
const defaultProps = {
transportType: "sse" as const,
command: "",
args: "",
sseUrl: "http://localhost:8080",
env: {},
config: DEFAULT_INSPECTOR_CONFIG,
};
describe("Request Configuration", () => {
beforeEach(() => {
jest.clearAllMocks();
});
test("uses the default config values in makeRequest", async () => {
const { result } = renderHook(() => useConnection(defaultProps));
// Connect the client
await act(async () => {
await result.current.connect();
});
// Wait for state update
await act(async () => {
await new Promise((resolve) => setTimeout(resolve, 0));
});
const mockRequest: ClientRequest = {
method: "ping",
params: {},
};
const mockSchema = z.object({
test: z.string(),
});
await act(async () => {
await result.current.makeRequest(mockRequest, mockSchema);
});
expect(mockClient.request).toHaveBeenCalledWith(
mockRequest,
mockSchema,
expect.objectContaining({
timeout: DEFAULT_INSPECTOR_CONFIG.MCP_SERVER_REQUEST_TIMEOUT.value,
maxTotalTimeout:
DEFAULT_INSPECTOR_CONFIG.MCP_REQUEST_MAX_TOTAL_TIMEOUT.value,
resetTimeoutOnProgress:
DEFAULT_INSPECTOR_CONFIG.MCP_REQUEST_TIMEOUT_RESET_ON_PROGRESS
.value,
}),
);
});
test("overrides the default config values when passed in options in makeRequest", async () => {
const { result } = renderHook(() => useConnection(defaultProps));
// Connect the client
await act(async () => {
await result.current.connect();
});
// Wait for state update
await act(async () => {
await new Promise((resolve) => setTimeout(resolve, 0));
});
const mockRequest: ClientRequest = {
method: "ping",
params: {},
};
const mockSchema = z.object({
test: z.string(),
});
await act(async () => {
await result.current.makeRequest(mockRequest, mockSchema, {
timeout: 1000,
maxTotalTimeout: 2000,
resetTimeoutOnProgress: false,
});
});
expect(mockClient.request).toHaveBeenCalledWith(
mockRequest,
mockSchema,
expect.objectContaining({
timeout: 1000,
maxTotalTimeout: 2000,
resetTimeoutOnProgress: false,
}),
);
});
});
test("throws error when mcpClient is not connected", async () => {
const { result } = renderHook(() => useConnection(defaultProps));
const mockRequest: ClientRequest = {
method: "ping",
params: {},
};
const mockSchema = z.object({
test: z.string(),
});
await expect(
result.current.makeRequest(mockRequest, mockSchema),
).rejects.toThrow("MCP client not connected");
});
});

View File

@@ -0,0 +1,129 @@
import { useState, useCallback, useEffect, useRef, useMemo } from "react";
import {
ResourceReference,
PromptReference,
} from "@modelcontextprotocol/sdk/types.js";
interface CompletionState {
completions: Record<string, string[]>;
loading: Record<string, boolean>;
}
// eslint-disable-next-line @typescript-eslint/no-explicit-any
function debounce<T extends (...args: any[]) => PromiseLike<void>>(
func: T,
wait: number,
): (...args: Parameters<T>) => void {
let timeout: ReturnType<typeof setTimeout>;
return (...args: Parameters<T>) => {
clearTimeout(timeout);
timeout = setTimeout(() => {
void func(...args);
}, wait);
};
}
export function useCompletionState(
handleCompletion: (
ref: ResourceReference | PromptReference,
argName: string,
value: string,
signal?: AbortSignal,
) => Promise<string[]>,
completionsSupported: boolean = true,
debounceMs: number = 300,
) {
const [state, setState] = useState<CompletionState>({
completions: {},
loading: {},
});
const abortControllerRef = useRef<AbortController | null>(null);
const cleanup = useCallback(() => {
if (abortControllerRef.current) {
abortControllerRef.current.abort();
abortControllerRef.current = null;
}
}, []);
// Cleanup on unmount
useEffect(() => {
return cleanup;
}, [cleanup]);
const clearCompletions = useCallback(() => {
cleanup();
setState({
completions: {},
loading: {},
});
}, [cleanup]);
const requestCompletions = useMemo(() => {
return debounce(
async (
ref: ResourceReference | PromptReference,
argName: string,
value: string,
) => {
if (!completionsSupported) {
return;
}
cleanup();
const abortController = new AbortController();
abortControllerRef.current = abortController;
setState((prev) => ({
...prev,
loading: { ...prev.loading, [argName]: true },
}));
try {
const values = await handleCompletion(
ref,
argName,
value,
abortController.signal,
);
if (!abortController.signal.aborted) {
setState((prev) => ({
...prev,
completions: { ...prev.completions, [argName]: values },
loading: { ...prev.loading, [argName]: false },
}));
}
} catch {
if (!abortController.signal.aborted) {
setState((prev) => ({
...prev,
loading: { ...prev.loading, [argName]: false },
}));
}
} finally {
if (abortControllerRef.current === abortController) {
abortControllerRef.current = null;
}
}
},
debounceMs,
);
}, [handleCompletion, completionsSupported, cleanup, debounceMs]);
// Clear completions when support status changes
useEffect(() => {
if (!completionsSupported) {
clearCompletions();
}
}, [completionsSupported, clearCompletions]);
return {
...state,
clearCompletions,
requestCompletions,
completionsSupported,
};
}

View File

@@ -0,0 +1,444 @@
import { Client } from "@modelcontextprotocol/sdk/client/index.js";
import {
SSEClientTransport,
SseError,
} from "@modelcontextprotocol/sdk/client/sse.js";
import { StreamableHTTPClientTransport } from "@modelcontextprotocol/sdk/client/streamableHttp.js";
import {
ClientNotification,
ClientRequest,
CreateMessageRequestSchema,
ListRootsRequestSchema,
ResourceUpdatedNotificationSchema,
LoggingMessageNotificationSchema,
Request,
Result,
ServerCapabilities,
PromptReference,
ResourceReference,
McpError,
CompleteResultSchema,
ErrorCode,
CancelledNotificationSchema,
ResourceListChangedNotificationSchema,
ToolListChangedNotificationSchema,
PromptListChangedNotificationSchema,
Progress,
} from "@modelcontextprotocol/sdk/types.js";
import { RequestOptions } from "@modelcontextprotocol/sdk/shared/protocol.js";
import { useState } from "react";
import { useToast } from "@/hooks/use-toast";
import { z } from "zod";
import { ConnectionStatus } from "../constants";
import { Notification, StdErrNotificationSchema } from "../notificationTypes";
import { auth } from "@modelcontextprotocol/sdk/client/auth.js";
import { InspectorOAuthClientProvider } from "../auth";
import packageJson from "../../../package.json";
import {
getMCPProxyAddress,
getMCPServerRequestMaxTotalTimeout,
resetRequestTimeoutOnProgress,
} from "@/utils/configUtils";
import { getMCPServerRequestTimeout } from "@/utils/configUtils";
import { InspectorConfig } from "../configurationTypes";
interface UseConnectionOptions {
transportType: "stdio" | "sse" | "streamable-http";
command: string;
args: string;
sseUrl: string;
env: Record<string, string>;
bearerToken?: string;
headerName?: string;
config: InspectorConfig;
onNotification?: (notification: Notification) => void;
onStdErrNotification?: (notification: Notification) => void;
// eslint-disable-next-line @typescript-eslint/no-explicit-any
onPendingRequest?: (request: any, resolve: any, reject: any) => void;
// eslint-disable-next-line @typescript-eslint/no-explicit-any
getRoots?: () => any[];
}
export function useConnection({
transportType,
command,
args,
sseUrl,
env,
bearerToken,
headerName,
config,
onNotification,
onStdErrNotification,
onPendingRequest,
getRoots,
}: UseConnectionOptions) {
const [connectionStatus, setConnectionStatus] =
useState<ConnectionStatus>("disconnected");
const { toast } = useToast();
const [serverCapabilities, setServerCapabilities] =
useState<ServerCapabilities | null>(null);
const [mcpClient, setMcpClient] = useState<Client | null>(null);
const [requestHistory, setRequestHistory] = useState<
{ request: string; response?: string }[]
>([]);
const [completionsSupported, setCompletionsSupported] = useState(true);
const pushHistory = (request: object, response?: object) => {
setRequestHistory((prev) => [
...prev,
{
request: JSON.stringify(request),
response: response !== undefined ? JSON.stringify(response) : undefined,
},
]);
};
const makeRequest = async <T extends z.ZodType>(
request: ClientRequest,
schema: T,
options?: RequestOptions & { suppressToast?: boolean },
): Promise<z.output<T>> => {
if (!mcpClient) {
throw new Error("MCP client not connected");
}
try {
const abortController = new AbortController();
// prepare MCP Client request options
const mcpRequestOptions: RequestOptions = {
signal: options?.signal ?? abortController.signal,
resetTimeoutOnProgress:
options?.resetTimeoutOnProgress ??
resetRequestTimeoutOnProgress(config),
timeout: options?.timeout ?? getMCPServerRequestTimeout(config),
maxTotalTimeout:
options?.maxTotalTimeout ??
getMCPServerRequestMaxTotalTimeout(config),
};
// If progress notifications are enabled, add an onprogress hook to the MCP Client request options
// This is required by SDK to reset the timeout on progress notifications
if (mcpRequestOptions.resetTimeoutOnProgress) {
mcpRequestOptions.onprogress = (params: Progress) => {
// Add progress notification to `Server Notification` window in the UI
if (onNotification) {
onNotification({
method: "notification/progress",
params,
});
}
};
}
let response;
try {
response = await mcpClient.request(request, schema, mcpRequestOptions);
pushHistory(request, response);
} catch (error) {
const errorMessage =
error instanceof Error ? error.message : String(error);
pushHistory(request, { error: errorMessage });
throw error;
}
return response;
} catch (e: unknown) {
if (!options?.suppressToast) {
const errorString = (e as Error).message ?? String(e);
toast({
title: "Error",
description: errorString,
variant: "destructive",
});
}
throw e;
}
};
const handleCompletion = async (
ref: ResourceReference | PromptReference,
argName: string,
value: string,
signal?: AbortSignal,
): Promise<string[]> => {
if (!mcpClient || !completionsSupported) {
return [];
}
const request: ClientRequest = {
method: "completion/complete",
params: {
argument: {
name: argName,
value,
},
ref,
},
};
try {
const response = await makeRequest(request, CompleteResultSchema, {
signal,
suppressToast: true,
});
return response?.completion.values || [];
} catch (e: unknown) {
// Disable completions silently if the server doesn't support them.
// See https://github.com/modelcontextprotocol/specification/discussions/122
if (e instanceof McpError && e.code === ErrorCode.MethodNotFound) {
setCompletionsSupported(false);
return [];
}
// Unexpected errors - show toast and rethrow
toast({
title: "Error",
description: e instanceof Error ? e.message : String(e),
variant: "destructive",
});
throw e;
}
};
const sendNotification = async (notification: ClientNotification) => {
if (!mcpClient) {
const error = new Error("MCP client not connected");
toast({
title: "Error",
description: error.message,
variant: "destructive",
});
throw error;
}
try {
await mcpClient.notification(notification);
// Log successful notifications
pushHistory(notification);
} catch (e: unknown) {
if (e instanceof McpError) {
// Log MCP protocol errors
pushHistory(notification, { error: e.message });
}
toast({
title: "Error",
description: e instanceof Error ? e.message : String(e),
variant: "destructive",
});
throw e;
}
};
const checkProxyHealth = async () => {
try {
const proxyHealthUrl = new URL(`${getMCPProxyAddress(config)}/health`);
const proxyHealthResponse = await fetch(proxyHealthUrl);
const proxyHealth = await proxyHealthResponse.json();
if (proxyHealth?.status !== "ok") {
throw new Error("MCP Proxy Server is not healthy");
}
} catch (e) {
console.error("Couldn't connect to MCP Proxy Server", e);
throw e;
}
};
const handleAuthError = async (error: unknown) => {
if (error instanceof SseError && error.code === 401) {
// Create a new auth provider with the current server URL
const serverAuthProvider = new InspectorOAuthClientProvider(sseUrl);
const result = await auth(serverAuthProvider, { serverUrl: sseUrl });
return result === "AUTHORIZED";
}
return false;
};
const connect = async (_e?: unknown, retryCount: number = 0) => {
const client = new Client<Request, Notification, Result>(
{
name: "mcp-inspector",
version: packageJson.version,
},
{
capabilities: {
sampling: {},
roots: {
listChanged: true,
},
},
},
);
try {
await checkProxyHealth();
} catch {
setConnectionStatus("error-connecting-to-proxy");
return;
}
let mcpProxyServerUrl;
switch (transportType) {
case "stdio":
mcpProxyServerUrl = new URL(`${getMCPProxyAddress(config)}/stdio`);
mcpProxyServerUrl.searchParams.append("command", command);
mcpProxyServerUrl.searchParams.append("args", args);
mcpProxyServerUrl.searchParams.append("env", JSON.stringify(env));
break;
case "sse":
mcpProxyServerUrl = new URL(`${getMCPProxyAddress(config)}/sse`);
mcpProxyServerUrl.searchParams.append("url", sseUrl);
break;
case "streamable-http":
mcpProxyServerUrl = new URL(`${getMCPProxyAddress(config)}/mcp`);
mcpProxyServerUrl.searchParams.append("url", sseUrl);
break;
}
(mcpProxyServerUrl as URL).searchParams.append(
"transportType",
transportType,
);
try {
// Inject auth manually instead of using SSEClientTransport, because we're
// proxying through the inspector server first.
const headers: HeadersInit = {};
// Create an auth provider with the current server URL
const serverAuthProvider = new InspectorOAuthClientProvider(sseUrl);
// Use manually provided bearer token if available, otherwise use OAuth tokens
const token =
bearerToken || (await serverAuthProvider.tokens())?.access_token;
if (token) {
const authHeaderName = headerName || "Authorization";
headers[authHeaderName] = `Bearer ${token}`;
}
// Create appropriate transport
const transportOptions = {
eventSourceInit: {
fetch: (
url: string | URL | globalThis.Request,
init: RequestInit | undefined,
) => fetch(url, { ...init, headers }),
},
requestInit: {
headers,
},
};
const clientTransport =
transportType === "streamable-http"
? new StreamableHTTPClientTransport(mcpProxyServerUrl as URL, {
sessionId: undefined,
})
: new SSEClientTransport(mcpProxyServerUrl as URL, transportOptions);
if (onNotification) {
[
CancelledNotificationSchema,
LoggingMessageNotificationSchema,
ResourceUpdatedNotificationSchema,
ResourceListChangedNotificationSchema,
ToolListChangedNotificationSchema,
PromptListChangedNotificationSchema,
].forEach((notificationSchema) => {
client.setNotificationHandler(notificationSchema, onNotification);
});
client.fallbackNotificationHandler = (
notification: Notification,
): Promise<void> => {
onNotification(notification);
return Promise.resolve();
};
}
if (onStdErrNotification) {
client.setNotificationHandler(
StdErrNotificationSchema,
onStdErrNotification,
);
}
let capabilities;
try {
await client.connect(clientTransport);
capabilities = client.getServerCapabilities();
const initializeRequest = {
method: "initialize",
};
pushHistory(initializeRequest, {
capabilities,
serverInfo: client.getServerVersion(),
instructions: client.getInstructions(),
});
} catch (error) {
console.error(
`Failed to connect to MCP Server via the MCP Inspector Proxy: ${mcpProxyServerUrl}:`,
error,
);
const shouldRetry = await handleAuthError(error);
if (shouldRetry) {
return connect(undefined, retryCount + 1);
}
if (error instanceof SseError && error.code === 401) {
// Don't set error state if we're about to redirect for auth
return;
}
throw error;
}
setServerCapabilities(capabilities ?? null);
setCompletionsSupported(true); // Reset completions support on new connection
if (onPendingRequest) {
client.setRequestHandler(CreateMessageRequestSchema, (request) => {
return new Promise((resolve, reject) => {
onPendingRequest(request, resolve, reject);
});
});
}
if (getRoots) {
client.setRequestHandler(ListRootsRequestSchema, async () => {
return { roots: getRoots() };
});
}
setMcpClient(client);
setConnectionStatus("connected");
} catch (e) {
console.error(e);
setConnectionStatus("error");
}
};
const disconnect = async () => {
await mcpClient?.close();
const authProvider = new InspectorOAuthClientProvider(sseUrl);
authProvider.clear();
setMcpClient(null);
setConnectionStatus("disconnected");
setCompletionsSupported(false);
setServerCapabilities(null);
};
return {
connectionStatus,
serverCapabilities,
mcpClient,
requestHistory,
makeRequest,
sendNotification,
handleCompletion,
completionsSupported,
connect,
disconnect,
};
}

View File

@@ -0,0 +1,53 @@
import { useCallback, useEffect, useRef, useState } from "react";
export function useDraggablePane(initialHeight: number) {
const [height, setHeight] = useState(initialHeight);
const [isDragging, setIsDragging] = useState(false);
const dragStartY = useRef<number>(0);
const dragStartHeight = useRef<number>(0);
const handleDragStart = useCallback(
(e: React.MouseEvent) => {
setIsDragging(true);
dragStartY.current = e.clientY;
dragStartHeight.current = height;
document.body.style.userSelect = "none";
},
[height],
);
const handleDragMove = useCallback(
(e: MouseEvent) => {
if (!isDragging) return;
const deltaY = dragStartY.current - e.clientY;
const newHeight = Math.max(
100,
Math.min(800, dragStartHeight.current + deltaY),
);
setHeight(newHeight);
},
[isDragging],
);
const handleDragEnd = useCallback(() => {
setIsDragging(false);
document.body.style.userSelect = "";
}, []);
useEffect(() => {
if (isDragging) {
window.addEventListener("mousemove", handleDragMove);
window.addEventListener("mouseup", handleDragEnd);
return () => {
window.removeEventListener("mousemove", handleDragMove);
window.removeEventListener("mouseup", handleDragEnd);
};
}
}, [isDragging, handleDragMove, handleDragEnd]);
return {
height,
isDragging,
handleDragStart,
};
}

View File

@@ -0,0 +1,22 @@
import {
NotificationSchema as BaseNotificationSchema,
ClientNotificationSchema,
ServerNotificationSchema,
} from "@modelcontextprotocol/sdk/types.js";
import { z } from "zod";
export const StdErrNotificationSchema = BaseNotificationSchema.extend({
method: z.literal("notifications/stderr"),
params: z.object({
content: z.string(),
}),
});
export const NotificationSchema = ClientNotificationSchema.or(
StdErrNotificationSchema,
)
.or(ServerNotificationSchema)
.or(BaseNotificationSchema);
export type StdErrNotification = z.infer<typeof StdErrNotificationSchema>;
export type Notification = z.infer<typeof NotificationSchema>;

View File

@@ -0,0 +1,52 @@
import { useCallback, useEffect, useMemo, useState } from "react";
type Theme = "light" | "dark" | "system";
const useTheme = (): [Theme, (mode: Theme) => void] => {
const [theme, setTheme] = useState<Theme>(() => {
const savedTheme = localStorage.getItem("theme") as Theme;
return savedTheme || "system";
});
useEffect(() => {
const darkModeMediaQuery = window.matchMedia(
"(prefers-color-scheme: dark)",
);
const handleDarkModeChange = (e: MediaQueryListEvent) => {
if (theme === "system") {
updateDocumentTheme(e.matches ? "dark" : "light");
}
};
const updateDocumentTheme = (newTheme: "light" | "dark") => {
document.documentElement.classList.toggle("dark", newTheme === "dark");
};
// Set initial theme based on current mode
if (theme === "system") {
updateDocumentTheme(darkModeMediaQuery.matches ? "dark" : "light");
} else {
updateDocumentTheme(theme);
}
darkModeMediaQuery.addEventListener("change", handleDarkModeChange);
return () => {
darkModeMediaQuery.removeEventListener("change", handleDarkModeChange);
};
}, [theme]);
const setThemeWithSideEffect = useCallback((newTheme: Theme) => {
setTheme(newTheme);
localStorage.setItem("theme", newTheme);
if (newTheme !== "system") {
document.documentElement.classList.toggle("dark", newTheme === "dark");
}
}, []);
return useMemo(
() => [theme, setThemeWithSideEffect],
[theme, setThemeWithSideEffect],
);
};
export default useTheme;

View File

@@ -1,6 +1,6 @@
import { clsx, type ClassValue } from "clsx"
import { twMerge } from "tailwind-merge"
import { clsx, type ClassValue } from "clsx";
import { twMerge } from "tailwind-merge";
export function cn(...inputs: ClassValue[]) {
return twMerge(clsx(inputs))
return twMerge(clsx(inputs));
}

View File

@@ -1,10 +1,15 @@
import { StrictMode } from "react";
import { createRoot } from "react-dom/client";
import { Toaster } from "@/components/ui/toaster.tsx";
import App from "./App.tsx";
import "./index.css";
import { TooltipProvider } from "./components/ui/tooltip.tsx";
createRoot(document.getElementById("root")!).render(
<StrictMode>
<App />
<TooltipProvider>
<App />
</TooltipProvider>
<Toaster />
</StrictMode>,
);

View File

@@ -0,0 +1,27 @@
import { escapeUnicode } from "../escapeUnicode";
describe("escapeUnicode", () => {
it("should escape Unicode characters in a string", () => {
const input = { text: "你好世界" };
const expected = '{\n "text": "\\\\u4f60\\\\u597d\\\\u4e16\\\\u754c"\n}';
expect(escapeUnicode(input)).toBe(expected);
});
it("should handle empty strings", () => {
const input = { text: "" };
const expected = '{\n "text": ""\n}';
expect(escapeUnicode(input)).toBe(expected);
});
it("should handle null and undefined values", () => {
const input = { text: null, value: undefined };
const expected = '{\n "text": null\n}';
expect(escapeUnicode(input)).toBe(expected);
});
it("should handle numbers and booleans", () => {
const input = { number: 123, boolean: true };
const expected = '{\n "number": 123,\n "boolean": true\n}';
expect(escapeUnicode(input)).toBe(expected);
});
});

View File

@@ -0,0 +1,319 @@
import {
getDataType,
tryParseJson,
updateValueAtPath,
getValueAtPath,
} from "../jsonUtils";
import type { JsonValue } from "../jsonUtils";
describe("getDataType", () => {
test("should return 'string' for string values", () => {
expect(getDataType("hello")).toBe("string");
expect(getDataType("")).toBe("string");
});
test("should return 'number' for number values", () => {
expect(getDataType(123)).toBe("number");
expect(getDataType(0)).toBe("number");
expect(getDataType(-10)).toBe("number");
expect(getDataType(1.5)).toBe("number");
expect(getDataType(NaN)).toBe("number");
expect(getDataType(Infinity)).toBe("number");
});
test("should return 'boolean' for boolean values", () => {
expect(getDataType(true)).toBe("boolean");
expect(getDataType(false)).toBe("boolean");
});
test("should return 'undefined' for undefined value", () => {
expect(getDataType(undefined)).toBe("undefined");
});
test("should return 'object' for object values", () => {
expect(getDataType({})).toBe("object");
expect(getDataType({ key: "value" })).toBe("object");
});
test("should return 'array' for array values", () => {
expect(getDataType([])).toBe("array");
expect(getDataType([1, 2, 3])).toBe("array");
expect(getDataType(["a", "b", "c"])).toBe("array");
expect(getDataType([{}, { nested: true }])).toBe("array");
});
test("should return 'null' for null value", () => {
expect(getDataType(null)).toBe("null");
});
});
describe("tryParseJson", () => {
test("should correctly parse valid JSON object", () => {
const jsonString = '{"name":"test","value":123}';
const result = tryParseJson(jsonString);
expect(result.success).toBe(true);
expect(result.data).toEqual({ name: "test", value: 123 });
});
test("should correctly parse valid JSON array", () => {
const jsonString = '[1,2,3,"test"]';
const result = tryParseJson(jsonString);
expect(result.success).toBe(true);
expect(result.data).toEqual([1, 2, 3, "test"]);
});
test("should correctly parse JSON with whitespace", () => {
const jsonString = ' { "name" : "test" } ';
const result = tryParseJson(jsonString);
expect(result.success).toBe(true);
expect(result.data).toEqual({ name: "test" });
});
test("should correctly parse nested JSON structures", () => {
const jsonString =
'{"user":{"name":"test","details":{"age":30}},"items":[1,2,3]}';
const result = tryParseJson(jsonString);
expect(result.success).toBe(true);
expect(result.data).toEqual({
user: {
name: "test",
details: {
age: 30,
},
},
items: [1, 2, 3],
});
});
test("should correctly parse empty objects and arrays", () => {
expect(tryParseJson("{}").success).toBe(true);
expect(tryParseJson("{}").data).toEqual({});
expect(tryParseJson("[]").success).toBe(true);
expect(tryParseJson("[]").data).toEqual([]);
});
test("should return failure for non-JSON strings", () => {
const nonJsonString = "this is not json";
const result = tryParseJson(nonJsonString);
expect(result.success).toBe(false);
expect(result.data).toBe(nonJsonString);
});
test("should return failure for malformed JSON", () => {
const malformedJson = '{"name":"test",}';
const result = tryParseJson(malformedJson);
expect(result.success).toBe(false);
expect(result.data).toBe(malformedJson);
});
test("should return failure for strings with correct delimiters but invalid JSON", () => {
const invalidJson = "{name:test}";
const result = tryParseJson(invalidJson);
expect(result.success).toBe(false);
expect(result.data).toBe(invalidJson);
});
test("should handle edge cases", () => {
expect(tryParseJson("").success).toBe(false);
expect(tryParseJson("").data).toBe("");
expect(tryParseJson(" ").success).toBe(false);
expect(tryParseJson(" ").data).toBe(" ");
expect(tryParseJson("null").success).toBe(false);
expect(tryParseJson("null").data).toBe("null");
expect(tryParseJson('"string"').success).toBe(false);
expect(tryParseJson('"string"').data).toBe('"string"');
expect(tryParseJson("123").success).toBe(false);
expect(tryParseJson("123").data).toBe("123");
expect(tryParseJson("true").success).toBe(false);
expect(tryParseJson("true").data).toBe("true");
});
});
describe("updateValueAtPath", () => {
// Basic functionality tests
test("returns the new value when path is empty", () => {
expect(updateValueAtPath({ foo: "bar" }, [], "newValue")).toBe("newValue");
});
test("initializes an empty object when input is null/undefined and path starts with a string", () => {
expect(updateValueAtPath(null, ["foo"], "bar")).toEqual({
foo: "bar",
});
expect(updateValueAtPath(undefined, ["foo"], "bar")).toEqual({
foo: "bar",
});
});
test("initializes an empty array when input is null/undefined and path starts with a number", () => {
expect(updateValueAtPath(null, ["0"], "bar")).toEqual(["bar"]);
expect(updateValueAtPath(undefined, ["0"], "bar")).toEqual(["bar"]);
});
// Object update tests
test("updates a simple object property", () => {
const obj = { name: "John", age: 30 };
expect(updateValueAtPath(obj, ["age"], 31)).toEqual({
name: "John",
age: 31,
});
});
test("updates a nested object property", () => {
const obj = { user: { name: "John", address: { city: "New York" } } };
expect(
updateValueAtPath(obj, ["user", "address", "city"], "Boston"),
).toEqual({ user: { name: "John", address: { city: "Boston" } } });
});
test("creates missing object properties", () => {
const obj = { user: { name: "John" } };
expect(
updateValueAtPath(obj, ["user", "address", "city"], "Boston"),
).toEqual({ user: { name: "John", address: { city: "Boston" } } });
});
// Array update tests
test("updates an array item", () => {
const arr = [1, 2, 3, 4];
expect(updateValueAtPath(arr, ["2"], 5)).toEqual([1, 2, 5, 4]);
});
test("extends an array when index is out of bounds", () => {
const arr = [1, 2, 3];
const result = updateValueAtPath(arr, ["5"], "new") as JsonValue[];
// Check overall array structure
expect(result).toEqual([1, 2, 3, null, null, "new"]);
// Explicitly verify that indices 3 and 4 contain null, not undefined
expect(result[3]).toBe(null);
expect(result[4]).toBe(null);
// Verify these aren't "holes" in the array (important distinction)
expect(3 in result).toBe(true);
expect(4 in result).toBe(true);
// Verify the array has the correct length
expect(result.length).toBe(6);
// Verify the array doesn't have holes by checking every index exists
expect(result.every((_, index: number) => index in result)).toBe(true);
});
test("updates a nested array item", () => {
const obj = { users: [{ name: "John" }, { name: "Jane" }] };
expect(updateValueAtPath(obj, ["users", "1", "name"], "Janet")).toEqual({
users: [{ name: "John" }, { name: "Janet" }],
});
});
// Error handling tests
test("returns original value when trying to update a primitive with a path", () => {
const spy = jest.spyOn(console, "error").mockImplementation();
const result = updateValueAtPath("string", ["foo"], "bar");
expect(result).toBe("string");
expect(spy).toHaveBeenCalled();
spy.mockRestore();
});
test("returns original array when index is invalid", () => {
const spy = jest.spyOn(console, "error").mockImplementation();
const arr = [1, 2, 3];
expect(updateValueAtPath(arr, ["invalid"], 4)).toEqual(arr);
expect(spy).toHaveBeenCalled();
spy.mockRestore();
});
test("returns original array when index is negative", () => {
const spy = jest.spyOn(console, "error").mockImplementation();
const arr = [1, 2, 3];
expect(updateValueAtPath(arr, ["-1"], 4)).toEqual(arr);
expect(spy).toHaveBeenCalled();
spy.mockRestore();
});
test("handles sparse arrays correctly by filling holes with null", () => {
// Create a sparse array by deleting an element
const sparseArr = [1, 2, 3];
delete sparseArr[1]; // Now sparseArr is [1, <1 empty item>, 3]
// Update a value beyond the array length
const result = updateValueAtPath(sparseArr, ["5"], "new") as JsonValue[];
// Check overall array structure
expect(result).toEqual([1, null, 3, null, null, "new"]);
// Explicitly verify that index 1 (the hole) contains null, not undefined
expect(result[1]).toBe(null);
// Verify this isn't a hole in the array
expect(1 in result).toBe(true);
// Verify all indices contain null (not undefined)
expect(result[1]).not.toBe(undefined);
expect(result[3]).toBe(null);
expect(result[4]).toBe(null);
});
});
describe("getValueAtPath", () => {
test("returns the original value when path is empty", () => {
const obj = { foo: "bar" };
expect(getValueAtPath(obj, [])).toBe(obj);
});
test("returns the value at a simple path", () => {
const obj = { name: "John", age: 30 };
expect(getValueAtPath(obj, ["name"])).toBe("John");
});
test("returns the value at a nested path", () => {
const obj = { user: { name: "John", address: { city: "New York" } } };
expect(getValueAtPath(obj, ["user", "address", "city"])).toBe("New York");
});
test("returns default value when path does not exist", () => {
const obj = { user: { name: "John" } };
expect(getValueAtPath(obj, ["user", "address", "city"], "Unknown")).toBe(
"Unknown",
);
});
test("returns default value when input is null/undefined", () => {
expect(getValueAtPath(null, ["foo"], "default")).toBe("default");
expect(getValueAtPath(undefined, ["foo"], "default")).toBe("default");
});
test("handles array indices correctly", () => {
const arr = ["a", "b", "c"];
expect(getValueAtPath(arr, ["1"])).toBe("b");
});
test("returns default value for out of bounds array indices", () => {
const arr = ["a", "b", "c"];
expect(getValueAtPath(arr, ["5"], "default")).toBe("default");
});
test("returns default value for invalid array indices", () => {
const arr = ["a", "b", "c"];
expect(getValueAtPath(arr, ["invalid"], "default")).toBe("default");
});
test("navigates through mixed object and array paths", () => {
const obj = { users: [{ name: "John" }, { name: "Jane" }] };
expect(getValueAtPath(obj, ["users", "1", "name"])).toBe("Jane");
});
});

View File

@@ -0,0 +1,78 @@
import {
generateOAuthErrorDescription,
parseOAuthCallbackParams,
} from "@/utils/oauthUtils.ts";
describe("parseOAuthCallbackParams", () => {
it("Returns successful: true and code when present", () => {
expect(parseOAuthCallbackParams("?code=fake-code")).toEqual({
successful: true,
code: "fake-code",
});
});
it("Returns successful: false and error when error is present", () => {
expect(parseOAuthCallbackParams("?error=access_denied")).toEqual({
successful: false,
error: "access_denied",
error_description: null,
error_uri: null,
});
});
it("Returns optional error metadata fields when present", () => {
const search =
"?error=access_denied&" +
"error_description=User%20Denied%20Request&" +
"error_uri=https%3A%2F%2Fexample.com%2Ferror-docs";
expect(parseOAuthCallbackParams(search)).toEqual({
successful: false,
error: "access_denied",
error_description: "User Denied Request",
error_uri: "https://example.com/error-docs",
});
});
it("Returns error when nothing present", () => {
expect(parseOAuthCallbackParams("?")).toEqual({
successful: false,
error: "invalid_request",
error_description: "Missing code or error in response",
error_uri: null,
});
});
});
describe("generateOAuthErrorDescription", () => {
it("When only error is present", () => {
expect(
generateOAuthErrorDescription({
successful: false,
error: "invalid_request",
error_description: null,
error_uri: null,
}),
).toBe("Error: invalid_request.");
});
it("When error description is present", () => {
expect(
generateOAuthErrorDescription({
successful: false,
error: "invalid_request",
error_description: "The request could not be completed as dialed",
error_uri: null,
}),
).toEqual(
"Error: invalid_request.\nDetails: The request could not be completed as dialed.",
);
});
it("When all fields present", () => {
expect(
generateOAuthErrorDescription({
successful: false,
error: "invalid_request",
error_description: "The request could not be completed as dialed",
error_uri: "https://example.com/error-docs",
}),
).toEqual(
"Error: invalid_request.\nDetails: The request could not be completed as dialed.\nMore info: https://example.com/error-docs.",
);
});
});

View File

@@ -0,0 +1,139 @@
import { generateDefaultValue, formatFieldLabel } from "../schemaUtils";
import type { JsonSchemaType } from "../jsonUtils";
describe("generateDefaultValue", () => {
test("generates default string", () => {
expect(generateDefaultValue({ type: "string", required: true })).toBe("");
});
test("generates default number", () => {
expect(generateDefaultValue({ type: "number", required: true })).toBe(0);
});
test("generates default integer", () => {
expect(generateDefaultValue({ type: "integer", required: true })).toBe(0);
});
test("generates default boolean", () => {
expect(generateDefaultValue({ type: "boolean", required: true })).toBe(
false,
);
});
test("generates default array", () => {
expect(generateDefaultValue({ type: "array", required: true })).toEqual([]);
});
test("generates default empty object", () => {
expect(generateDefaultValue({ type: "object", required: true })).toEqual(
{},
);
});
test("generates default null for unknown types", () => {
// @ts-expect-error Testing with invalid type
expect(generateDefaultValue({ type: "unknown", required: true })).toBe(
null,
);
});
test("generates empty array for non-required array", () => {
expect(generateDefaultValue({ type: "array", required: false })).toEqual(
[],
);
});
test("generates empty object for non-required object", () => {
expect(generateDefaultValue({ type: "object", required: false })).toEqual(
{},
);
});
test("generates null for non-required primitive types", () => {
expect(generateDefaultValue({ type: "string", required: false })).toBe(
undefined,
);
expect(generateDefaultValue({ type: "number", required: false })).toBe(
undefined,
);
expect(generateDefaultValue({ type: "boolean", required: false })).toBe(
undefined,
);
});
test("generates object with properties", () => {
const schema: JsonSchemaType = {
type: "object",
required: true,
properties: {
name: { type: "string", required: true },
age: { type: "number", required: true },
isActive: { type: "boolean", required: true },
},
};
expect(generateDefaultValue(schema)).toEqual({
name: "",
age: 0,
isActive: false,
});
});
test("handles nested objects", () => {
const schema: JsonSchemaType = {
type: "object",
required: true,
properties: {
user: {
type: "object",
required: true,
properties: {
name: { type: "string", required: true },
address: {
type: "object",
required: true,
properties: {
city: { type: "string", required: true },
},
},
},
},
},
};
expect(generateDefaultValue(schema)).toEqual({
user: {
name: "",
address: {
city: "",
},
},
});
});
test("uses schema default value when provided", () => {
expect(generateDefaultValue({ type: "string", default: "test" })).toBe(
"test",
);
});
});
describe("formatFieldLabel", () => {
test("formats camelCase", () => {
expect(formatFieldLabel("firstName")).toBe("First Name");
});
test("formats snake_case", () => {
expect(formatFieldLabel("first_name")).toBe("First name");
});
test("formats single word", () => {
expect(formatFieldLabel("name")).toBe("Name");
});
test("formats mixed case with underscores", () => {
expect(formatFieldLabel("user_firstName")).toBe("User first Name");
});
test("handles empty string", () => {
expect(formatFieldLabel("")).toBe("");
});
});

View File

@@ -0,0 +1,26 @@
import { InspectorConfig } from "@/lib/configurationTypes";
import { DEFAULT_MCP_PROXY_LISTEN_PORT } from "@/lib/constants";
export const getMCPProxyAddress = (config: InspectorConfig): string => {
const proxyFullAddress = config.MCP_PROXY_FULL_ADDRESS.value as string;
if (proxyFullAddress) {
return proxyFullAddress;
}
return `${window.location.protocol}//${window.location.hostname}:${DEFAULT_MCP_PROXY_LISTEN_PORT}`;
};
export const getMCPServerRequestTimeout = (config: InspectorConfig): number => {
return config.MCP_SERVER_REQUEST_TIMEOUT.value as number;
};
export const resetRequestTimeoutOnProgress = (
config: InspectorConfig,
): boolean => {
return config.MCP_REQUEST_TIMEOUT_RESET_ON_PROGRESS.value as boolean;
};
export const getMCPServerRequestMaxTotalTimeout = (
config: InspectorConfig,
): number => {
return config.MCP_REQUEST_MAX_TOTAL_TIMEOUT.value as number;
};

View File

@@ -0,0 +1,16 @@
// Utility function to escape Unicode characters
export function escapeUnicode(obj: unknown): string {
return JSON.stringify(
obj,
(_key: string, value) => {
if (typeof value === "string") {
// Replace non-ASCII characters with their Unicode escape sequences
return value.replace(/[^\0-\x7F]/g, (char) => {
return "\\u" + ("0000" + char.charCodeAt(0).toString(16)).slice(-4);
});
}
return value;
},
2,
);
}

View File

@@ -0,0 +1,208 @@
export type JsonValue =
| string
| number
| boolean
| null
| undefined
| JsonValue[]
| { [key: string]: JsonValue };
export type JsonSchemaType = {
type:
| "string"
| "number"
| "integer"
| "boolean"
| "array"
| "object"
| "null";
description?: string;
required?: boolean;
default?: JsonValue;
properties?: Record<string, JsonSchemaType>;
items?: JsonSchemaType;
};
export type JsonObject = { [key: string]: JsonValue };
export type DataType =
| "string"
| "number"
| "bigint"
| "boolean"
| "symbol"
| "undefined"
| "object"
| "function"
| "array"
| "null";
export function getDataType(value: JsonValue): DataType {
if (Array.isArray(value)) return "array";
if (value === null) return "null";
return typeof value;
}
export function tryParseJson(str: string): {
success: boolean;
data: JsonValue;
} {
const trimmed = str.trim();
if (
!(trimmed.startsWith("{") && trimmed.endsWith("}")) &&
!(trimmed.startsWith("[") && trimmed.endsWith("]"))
) {
return { success: false, data: str };
}
try {
return { success: true, data: JSON.parse(str) };
} catch {
return { success: false, data: str };
}
}
/**
* Updates a value at a specific path in a nested JSON structure
* @param obj The original JSON value
* @param path Array of keys/indices representing the path to the value
* @param value The new value to set
* @returns A new JSON value with the updated path
*/
export function updateValueAtPath(
obj: JsonValue,
path: string[],
value: JsonValue,
): JsonValue {
if (path.length === 0) return value;
if (obj === null || obj === undefined) {
obj = !isNaN(Number(path[0])) ? [] : {};
}
if (Array.isArray(obj)) {
return updateArray(obj, path, value);
} else if (typeof obj === "object" && obj !== null) {
return updateObject(obj as JsonObject, path, value);
} else {
console.error(
`Cannot update path ${path.join(".")} in non-object/array value:`,
obj,
);
return obj;
}
}
/**
* Updates an array at a specific path
*/
function updateArray(
array: JsonValue[],
path: string[],
value: JsonValue,
): JsonValue[] {
const [index, ...restPath] = path;
const arrayIndex = Number(index);
if (isNaN(arrayIndex)) {
console.error(`Invalid array index: ${index}`);
return array;
}
if (arrayIndex < 0) {
console.error(`Array index out of bounds: ${arrayIndex} < 0`);
return array;
}
let newArray: JsonValue[] = [];
for (let i = 0; i < array.length; i++) {
newArray[i] = i in array ? array[i] : null;
}
if (arrayIndex >= newArray.length) {
const extendedArray: JsonValue[] = new Array(arrayIndex).fill(null);
// Copy over the existing elements (now guaranteed to be dense)
for (let i = 0; i < newArray.length; i++) {
extendedArray[i] = newArray[i];
}
newArray = extendedArray;
}
if (restPath.length === 0) {
newArray[arrayIndex] = value;
} else {
newArray[arrayIndex] = updateValueAtPath(
newArray[arrayIndex],
restPath,
value,
);
}
return newArray;
}
/**
* Updates an object at a specific path
*/
function updateObject(
obj: JsonObject,
path: string[],
value: JsonValue,
): JsonObject {
const [key, ...restPath] = path;
// Validate object key
if (typeof key !== "string") {
console.error(`Invalid object key: ${key}`);
return obj;
}
const newObj = { ...obj };
if (restPath.length === 0) {
newObj[key] = value;
} else {
// Ensure key exists
if (!(key in newObj)) {
newObj[key] = {};
}
newObj[key] = updateValueAtPath(newObj[key], restPath, value);
}
return newObj;
}
/**
* Gets a value at a specific path in a nested JSON structure
* @param obj The JSON value to traverse
* @param path Array of keys/indices representing the path to the value
* @param defaultValue Value to return if path doesn't exist
* @returns The value at the path, or defaultValue if not found
*/
export function getValueAtPath(
obj: JsonValue,
path: string[],
defaultValue: JsonValue = null,
): JsonValue {
if (path.length === 0) return obj;
const [first, ...rest] = path;
if (obj === null || obj === undefined) {
return defaultValue;
}
if (Array.isArray(obj)) {
const index = Number(first);
if (isNaN(index) || index < 0 || index >= obj.length) {
return defaultValue;
}
return getValueAtPath(obj[index], rest, defaultValue);
}
if (typeof obj === "object" && obj !== null) {
if (!(first in obj)) {
return defaultValue;
}
return getValueAtPath((obj as JsonObject)[first], rest, defaultValue);
}
return defaultValue;
}

View File

@@ -0,0 +1,65 @@
// The parsed query parameters returned by the Authorization Server
// representing either a valid authorization_code or an error
// ref: https://datatracker.ietf.org/doc/html/draft-ietf-oauth-v2-1-12#section-4.1.2
type CallbackParams =
| {
successful: true;
// The authorization code is generated by the authorization server.
code: string;
}
| {
successful: false;
// The OAuth 2.1 Error Code.
// Usually one of:
// ```
// invalid_request, unauthorized_client, access_denied, unsupported_response_type,
// invalid_scope, server_error, temporarily_unavailable
// ```
error: string;
// Human-readable ASCII text providing additional information, used to assist the
// developer in understanding the error that occurred.
error_description: string | null;
// A URI identifying a human-readable web page with information about the error,
// used to provide the client developer with additional information about the error.
error_uri: string | null;
};
export const parseOAuthCallbackParams = (location: string): CallbackParams => {
const params = new URLSearchParams(location);
const code = params.get("code");
if (code) {
return { successful: true, code };
}
const error = params.get("error");
const error_description = params.get("error_description");
const error_uri = params.get("error_uri");
if (error) {
return { successful: false, error, error_description, error_uri };
}
return {
successful: false,
error: "invalid_request",
error_description: "Missing code or error in response",
error_uri: null,
};
};
export const generateOAuthErrorDescription = (
params: Extract<CallbackParams, { successful: false }>,
): string => {
const error = params.error;
const errorDescription = params.error_description;
const errorUri = params.error_uri;
return [
`Error: ${error}.`,
errorDescription ? `Details: ${errorDescription}.` : "",
errorUri ? `More info: ${errorUri}.` : "",
]
.filter(Boolean)
.join("\n");
};

View File

@@ -0,0 +1,56 @@
import type { JsonValue, JsonSchemaType, JsonObject } from "./jsonUtils";
/**
* Generates a default value based on a JSON schema type
* @param schema The JSON schema definition
* @returns A default value matching the schema type, or null for non-required fields
*/
export function generateDefaultValue(schema: JsonSchemaType): JsonValue {
if ("default" in schema) {
return schema.default;
}
if (!schema.required) {
if (schema.type === "array") return [];
if (schema.type === "object") return {};
return undefined;
}
switch (schema.type) {
case "string":
return "";
case "number":
case "integer":
return 0;
case "boolean":
return false;
case "array":
return [];
case "object": {
if (!schema.properties) return {};
const obj: JsonObject = {};
Object.entries(schema.properties)
.filter(([, prop]) => prop.required)
.forEach(([key, prop]) => {
const value = generateDefaultValue(prop);
obj[key] = value;
});
return obj;
}
default:
return null;
}
}
/**
* Formats a field key into a human-readable label
* @param key The field key to format
* @returns A formatted label string
*/
export function formatFieldLabel(key: string): string {
return key
.replace(/([A-Z])/g, " $1") // Insert space before capital letters
.replace(/_/g, " ") // Replace underscores with spaces
.replace(/^\w/, (c) => c.toUpperCase()); // Capitalize first letter
}

View File

@@ -1,4 +1,5 @@
/** @type {import('tailwindcss').Config} */
import animate from "tailwindcss-animate";
export default {
darkMode: ["class"],
content: ["./index.html", "./src/**/*.{js,ts,jsx,tsx}"],
@@ -53,5 +54,5 @@ export default {
},
},
},
plugins: [require("tailwindcss-animate")],
plugins: [animate],
};

View File

@@ -2,9 +2,7 @@
"compilerOptions": {
"baseUrl": ".",
"paths": {
"@/*": [
"./src/*"
]
"@/*": ["./src/*"]
},
"target": "ES2020",
@@ -25,7 +23,9 @@
"strict": true,
"noUnusedLocals": true,
"noUnusedParameters": true,
"noFallthroughCasesInSwitch": true
"noFallthroughCasesInSwitch": true,
"resolveJsonModule": true,
"types": ["jest", "@testing-library/jest-dom", "node"]
},
"include": ["src"]
}

10
client/tsconfig.jest.json Normal file
View File

@@ -0,0 +1,10 @@
{
"extends": "./tsconfig.app.json",
"compilerOptions": {
"jsx": "react-jsx",
"esModuleInterop": true,
"module": "ESNext",
"moduleResolution": "node"
},
"include": ["src"]
}

View File

@@ -1,13 +1,24 @@
import react from "@vitejs/plugin-react";
import path from "path";
import { defineConfig } from "vite";
import react from "@vitejs/plugin-react";
// https://vitejs.dev/config/
export default defineConfig({
plugins: [react()],
server: {
host: true,
},
resolve: {
alias: {
"@": path.resolve(__dirname, "./src"),
},
},
build: {
minify: false,
rollupOptions: {
output: {
manualChunks: undefined,
},
},
},
});

BIN
mcp-inspector.png Normal file

Binary file not shown.

After

Width:  |  Height:  |  Size: 385 KiB

6555
package-lock.json generated

File diff suppressed because it is too large Load Diff

View File

@@ -1,24 +1,59 @@
{
"name": "mcp-inspector",
"private": true,
"version": "0.0.1",
"name": "@modelcontextprotocol/inspector",
"version": "0.10.2",
"description": "Model Context Protocol inspector",
"license": "MIT",
"author": "Anthropic, PBC (https://anthropic.com)",
"homepage": "https://modelcontextprotocol.io",
"bugs": "https://github.com/modelcontextprotocol/inspector/issues",
"type": "module",
"bin": {
"mcp-inspector": "cli/build/cli.js"
},
"files": [
"client/bin",
"client/dist",
"server/build",
"cli/build"
],
"workspaces": [
"client",
"server"
"server",
"cli"
],
"scripts": {
"dev": "concurrently \"cd client && npm run dev\" \"cd server && npm run dev\"",
"build": "npm run build-server && npm run build-client && npm run build-cli",
"build-server": "cd server && npm run build",
"build-client": "cd client && npm run build",
"build": "npm run build-server && npm run build-client",
"build-cli": "cd cli && npm run build",
"dev": "concurrently \"cd client && npm run dev\" \"cd server && npm run dev\"",
"dev:windows": "concurrently \"cd client && npm run dev\" \"cd server && npm run dev:windows\"",
"start": "node client/bin/start.js",
"start-server": "cd server && npm run start",
"start-client": "cd client && npm run preview",
"start": "concurrently \"npm run start-server\" \"npm run start-client\"",
"prettier-fix": "prettier --write ."
"test": "npm run prettier-check && cd client && npm test",
"test-cli": "cd cli && npm run test",
"prettier-fix": "prettier --write .",
"prettier-check": "prettier --check .",
"publish-all": "npm publish --workspaces --access public && npm publish --access public"
},
"dependencies": {
"@modelcontextprotocol/inspector-cli": "^0.10.2",
"@modelcontextprotocol/inspector-client": "^0.10.2",
"@modelcontextprotocol/inspector-server": "^0.10.2",
"@modelcontextprotocol/sdk": "^1.10.2",
"concurrently": "^9.0.1",
"shell-quote": "^1.8.2",
"spawn-rx": "^5.1.2",
"ts-node": "^10.9.2",
"zod": "^3.23.8"
},
"devDependencies": {
"concurrently": "^9.0.1",
"prettier": "3.3.3"
"@types/jest": "^29.5.14",
"@types/node": "^22.7.5",
"@types/shell-quote": "^1.7.5",
"jest-fixed-jsdom": "^0.0.9",
"prettier": "3.3.3",
"typescript": "^5.4.2"
}
}

Some files were not shown because too many files have changed in this diff Show More