* feat(web,core): import client configs and registry server.json (#1348) Wire up the two server-import affordances that were previously todoNoop: - Import config: source picker (Claude Desktop / Cursor / Cline / VS Code) read on the backend via a new GET /api/import-source, plus a file-upload fallback. Per-server review with import/skip on new servers and overwrite/skip/rename on id conflicts, then a per-server outcome summary. - Import server.json: parse the MCP registry single-server format (npm/pypi/oci packages + remotes, env vars, package/runtime args, URL template vars) into a runnable config, with a file picker and debounced live validation; Add Server is disabled until validation passes. Core gains an isomorphic import strategy layer (core/mcp/import) with a strategy registry, client-config + server.json parsers, a strategy-agnostic merge, and a dependency-injected source resolver. useServers exposes importSource(). Modal headers are bold and the redundant server.json section header is folded into the modal title. Co-Authored-By: Claude Opus 4.8 (1M context) <noreply@anthropic.com> * feat(web): collapse the server.json textarea into a File Contents disclosure Co-Authored-By: Claude Opus 4.8 (1M context) <noreply@anthropic.com> * feat(web): auto-collapse File Contents disclosure after content loads Once content is pasted or a file is loaded, collapse the File Contents disclosure after ~1s with Mantine's built-in accordion animation, signaling the input was accepted and surfacing the validation/env-var sections. The disclosure becomes controlled by the modal; clearing the textarea re-opens it. Co-Authored-By: Claude Opus 4.8 (1M context) <noreply@anthropic.com> * feat(web): flash File Contents hover highlight before auto-collapse Before the File Contents disclosure auto-collapses, paint it with its hover background for 250ms, then run the collapse over a 325ms animation, so the collapse reads as intentional. Co-Authored-By: Claude Opus 4.8 (1M context) <noreply@anthropic.com> * feat(web): rename "Import server.json" to "Import from registry config" Rename the Add Servers menu entry and the modal header. Co-Authored-By: Claude Opus 4.8 (1M context) <noreply@anthropic.com> * feat(web): rename "Import config" to "Import client config" Rename the Add Servers menu entry and the modal header. Co-Authored-By: Claude Opus 4.8 (1M context) <noreply@anthropic.com> * refactor(web,core): move import orchestration into core helpers + web hooks Make the import logic reusable by CLI/TUI and keep the modals display-only: - core/mcp/import: add parseClientConfig (mcpServers→servers fallback), resolveServerId, selectServerJsonOption, and buildServerConfigForSelection, so the full import (parse → select → build → merge) is callable from any environment. - core/storage: extract the pure validateStoreId into a Node-free store-id module (store-io re-exports it) so the isomorphic import layer can validate ids without pulling Node deps into the browser bundle. - clients/web/hooks: useServerJsonImport and useImportClientConfig own all the wizard/parse/debounce/apply state; ServerImportConfigModal and ServerImportJsonModal are now thin display shells over the dumb panel. Co-Authored-By: Claude Opus 4.8 (1M context) <noreply@anthropic.com> * feat(web): rename "Import client config" to "Import from client config" Co-Authored-By: Claude Opus 4.8 (1M context) <noreply@anthropic.com> * feat(web): remove the Cancel button from the registry import modal The modal header X (and Escape) still dismiss it; drop the redundant Cancel button (and the panel onCancel prop). Co-Authored-By: Claude Opus 4.8 (1M context) <noreply@anthropic.com> * feat(web): hide validation results + name override until content is present In the registry import modal, the Validation Results section and the Server Name override field stay hidden until something has been pasted/loaded into the textarea. Co-Authored-By: Claude Opus 4.8 (1M context) <noreply@anthropic.com> * feat(web): make Validation Results a collapsible disclosure Wrap the registry import modal's validation results in a Mantine accordion disclosure (default open), matching the File Contents section. Co-Authored-By: Claude Opus 4.8 (1M context) <noreply@anthropic.com> * feat(web): Server Name disclosure with read-only derived name + override Make Server Name a collapsible disclosure containing a read-only "From configuration" field (the id derived from the server.json name) and the editable Override field. Co-Authored-By: Claude Opus 4.8 (1M context) <noreply@anthropic.com> * feat(web): scroll to and highlight a freshly-added server After a manual add/clone or an import (client config / registry), the new server's card scrolls into view and draws an animated border (Mantine Border Animate); clicking anywhere on the card dismisses it. - App tracks highlightedServerId; addServerHighlighted sets it (edits and conflict-overwrites don't). Threaded through InspectorView -> ServerListScreen -> ServerCard. - ServerCard scrolls into view on highlight and wraps in <BorderAnimate>; onClick clears the highlight. - Pin @gfazioli/mantine-border-animate@2.0.3 (Mantine 8 compatible; 2.0.4+ requires Mantine 9). Co-Authored-By: Claude Opus 4.8 (1M context) <noreply@anthropic.com> * fix(web): highlighted card fills its cell and its controls work on first click - The BorderAnimate wrapper is display:flex, so the card was shrinking to content width while the border spanned the cell. Stretch the card with w=100% (and the wrapper). - Always render BorderAnimate and toggle show/animate instead of conditionally wrapping: swapping the element type on clear remounted the card, swallowing the click that triggered it (e.g. the connect toggle fired clear but not connect, needing a second click). Verified: one click now connects + clears. Co-Authored-By: Claude Opus 4.8 (1M context) <noreply@anthropic.com> * fix(web,core): address review — OCI env, untrack fixture, rename validation - Untrack the stray inspector-v1-multi.server.json (accidentally committed) and gitignore root *.server.json fixtures. - core/mcp/import/serverJson: forward declared env vars into OCI containers via '-e KEY' docker args (they previously only set the docker CLI process env); add a test. Clarify buildServerConfig (destructure env out instead of spread-then-delete) and document value-vs-default env handling. - useImportClientConfig: validate 'rename' targets inline (invalid charset / collision with existing, additions, or other renames) and gate the Import button on canImport; surface the error on the field. Co-Authored-By: Claude Opus 4.8 (1M context) <noreply@anthropic.com> * feat(web): highlight all servers from a batch import, not just the last Track highlighted servers as a set of ids instead of one. addServerHighlighted accumulates each id (a multi-server client-config import highlights them all); opening an add/import modal starts a fresh batch. Clicking a card clears only that card's highlight; only the first highlighted card scrolls into view. Co-Authored-By: Claude Opus 4.8 (1M context) <noreply@anthropic.com> --------- Co-authored-by: Claude Opus 4.8 (1M context) <noreply@anthropic.com>
25 KiB
Inspector V2
This is an application for inspecting MCP servers. Has three incarnations, Web, TUI, and CLI.
Project Structure
inspector/
├── clients/
│ ├── web/ # Web client (Vite + React + Mantine)
│ │ ├── src/ # Browser source (React app, hooks, components)
│ │ ├── server/ # Node-only dev/prod backend wiring:
│ │ │ # vite-hono-plugin.ts (Hono middleware on the Vite dev server),
│ │ │ # server.ts (standalone Hono prod server),
│ │ │ # start-vite-dev-server.ts (in-process Vite starter for the launcher),
│ │ │ # web-server-config.ts (env parsing + initial-config payload + banner),
│ │ │ # sandbox-controller.ts (MCP Apps sandbox HTTP server),
│ │ │ # inject-auth-token.ts (embeds the API token into served index.html),
│ │ │ # vite-base-config.ts (shared optimizeDeps exclusions)
│ │ └── static/ # sandbox_proxy.html (served by sandbox-controller for MCP Apps tab)
│ ├── cli/ # CLI client (tsup bundle, @inspector/core alias)
│ ├── tui/ # TUI client (Ink + React, tsup bundle)
│ ├── launcher/ # Shared launcher (relative imports into sibling build/ outputs)
├── core/ # Shared core code (no package.json — consumed via the `@inspector/core` vite alias)
│ ├── auth/ # OAuth: state machine, providers, discovery, storage
│ │ ├── browser/ # Browser-side OAuth (sessionStorage, BrowserNavigation)
│ │ ├── node/ # Node-side OAuth (NodeOAuthStorage, OAuthCallbackServer)
│ │ └── remote/ # Remote OAuth storage (delegates to the remote server)
│ ├── json/ # JSON utilities and parameter/argument conversion
│ ├── logging/ # Silent pino logger singleton
│ ├── mcp/ # InspectorClient runtime + state stores
│ │ ├── import/ # Config import strategies (#1348): client-config parsers
│ │ │ # (Claude Desktop/Cursor/Cline/VS Code), registry
│ │ │ # server.json parser, strategy registry + well-known
│ │ │ # paths, strategy-agnostic merge. Pure/isomorphic;
│ │ │ # used by the web file-upload path + /api/import-source.
│ │ ├── node/ # Node stdio transport factory
│ │ ├── remote/ # Browser HTTP/SSE transport + remote logger/fetch
│ │ │ └── node/ # Hono-based remote server backend (used by remote/ above)
│ │ └── state/ # Zustand-style state stores consumed by core/react/
│ ├── react/ # React hooks over the state stores
│ └── storage/ # File and remote storage adapters (Zustand middleware)
├── test-servers/ # Composable MCP test servers + fixtures used by integration tests.
│ ├── src/ # TypeScript sources.
│ ├── build/ # Built JS (gitignored). Produced by `npm run test-servers:build`
│ │ # so integration tests can spawn the stdio server as a real
│ │ # subprocess via `node test-servers/build/test-server-stdio.js`.
│ └── tsconfig.json # tsc build config (NodeNext, outDir ./build).
│ # The Vite alias `@modelcontextprotocol/inspector-test-server`
│ # in clients/web/vite.config.ts points at build/index.js
│ # (not src/) so `getTestMcpServerPath()` returns a `.js` path.
│ # tsconfig.test.json keeps paths pointing at src for typecheck.
├── specification/ # Build specification
...
Development setup
v2 is not an npm workspace — each client under clients/* keeps its own package.json and node_modules (see the rationale in specification/v2_cli_tui_launcher.md). A single npm install at the repo root is still all you need: the root postinstall (scripts/install-clients.mjs) cascades npm install into clients/web, clients/cli, clients/tui, and clients/launcher.
- Fresh clone / first-time setup: run
npm installat the repo root. - After a pull that changes a client's dependencies: re-run
npm installat the root to re-sync every client (thepostinstallcascade handles it). - The cascade is dev-only: it exits early when the package is installed under
node_modules, and the published tarball ships only each client'sbuild/, so end users are unaffected. SetINSPECTOR_SKIP_CLIENT_INSTALL=1to skip it.
After installing, npm run build builds all clients. The launcher scripts (npm run web / web:dev) run the built launcher, so build first; for day-to-day web iteration use cd clients/web && npm run dev.
Repository & Project Board
- Repo: https://github.com/modelcontextprotocol/inspector.git
- Base Branches: v2/main, v1.5/main, main
- Project Boards:
Project Status and Direction
-
The main branch currently contains the legacy version of the Inspector, which we are accepting bug fixes and minor improvement PRs for.
-
The v1.5/main branch contains an intermediate version of the Inspector, where the shared logic between the three incarnations of the Inspector are extracted into a core subsystem with InspectorClient class as the common entry point. It also includes the TUI, a refactored CLI, and streamlined launcher.
-
The v2/main branch currently contains the new version of the web Inspector, composed of "dumb" components which accept data and callbacks as props and contain only display logic.
-
The InspectorClient from v1.5/main will be merged into v2/main, and wired up to the new web Inspector. The TUI and CLI will follow. Eventually when everything works on v2/main we will replace main with v2/main, eliminating the legacy implementations.
Web backend auth token
The dev/prod web backend protects every /api/* route with x-mcp-remote-auth: Bearer <MCP_INSPECTOR_API_TOKEN>. The browser recovers that token from three sources, in priority order (see App.tsx getAuthToken()):
window.__INSPECTOR_API_TOKEN__— injected intoindex.htmlon every page load by the backend (the dev Vite plugin viatransformIndexHtml, the prod Hono server on the/route), both routed throughclients/web/server/inject-auth-token.ts. This is what makes a bare-URL reload, a bookmark, or a clearedsessionStoragekeep working.?MCP_INSPECTOR_API_TOKEN=…query string — the URL the launcher banner prints; kept as a fallback for pasted full URLs.sessionStorage— backstop for navigations that land without either of the above.
Injection is a no-op when auth is disabled (DANGEROUSLY_OMIT_AUTH), and the global name is the shared INSPECTOR_API_TOKEN_GLOBAL constant in core/mcp/remote/constants.ts.
Maintenance Rules
Keep documentation files up to date
- When adding, removing, renaming, or changing the purpose of any file or folder, update the corresponding entry in the main README.md and/or the related clients/*/README.md
- When the structure of the project, the tech stack, or the developer setup changes, update appropriate README.md files with the details.
- When adding new commands, dependencies, or architectural patterns, update the relevant sections of appropriate README.md files as well.
- When rules for implementation and testing change, update this file AGENTS.md
Issue-driven Work Style
All work should be driven by items on the project board.
-
Before starting work, check the board for the relevant item.
-
Draft items vs. issues: Board items may be draft items (no issue number) or full GitHub issues. Before creating a new issue, always check if a matching draft item already exists on the board. If it does, convert it to an issue using
gh project item-editor create the issue and link it — never create a duplicate. -
Label by version. New issues and PRs must carry the label matching the target board / branch:
main→v1v1.5/main→v1.5v2/main→v2
Set the label at create time (
gh issue create --label v2 ...,gh pr create --label v2 ...) — don't rely on backfilling later, since unlabeled PRs are easy to miss when filtering by version. -
When work begins, create a feature branch and move the item to "In Progress".
-
When work is complete:
- Run format, lint, typecheck, build, and test — ensure all checks pass
- Open a PR against the matching base branch (
mainfor v1,v1.5/mainfor v1.5,v2/mainfor v2) and move the item to "In Review"
-
If new tasks are discovered or requested during development, create issues and add them to the board.
Always test new or modified code
- Ensure all code has corresponding tests
- Ensure test coverage for each file is at least 90%
- In unit tests that expect error output, suppress it from the console
- Run unit tests with
npm run test(ornpm run test:watchduring development) fromclients/web/ - Run CLI tests with
npm run testfromclients/cli/(builds test-servers + CLI bin first viapretest) - Run TUI tests with
npm run testfromclients/tui/ - The repo root has no aggregate
testscript — each client self-validates, so runnpm run validatefrom the root (all clients, fast) orcd clients/<name> && npm run validate(one client). Each client still exposes its owntest/test:coveragefor quick iteration. validateis fast: it runstest, nottest:coverage. The coverage gate (slower — adds v8 instrumentation, and for web the integration project) is a separate top-levelnpm run coverage(and per-clientcoverage:web/coverage:cli/coverage:tui/coverage:launcher, each delegating to that client'stest:coverage). Runnpm run coveragewhen you want the gate. CI does NOT runcoverage— the gate is local-only; CI runsvalidate(fast) plus the web integration suite (clients/webtest:integration, no coverage) so the integration paths are still exercised.- Each client's
test:coverageenforces a per-file gate: lines ≥ 90, statements ≥ 85, functions ≥ 80, branches ≥ 50 (CI enforces this gate). Branches is intentionally relaxed because Mantine portal/media-query branches are not exercisable under happy-dom; new business-logic branches should still be covered. - The same per-file gate is enforced for the CLI and TUI (#1484), not just web:
- CLI (
clients/cli): tests run in-process by importingrunCli()(see__tests__/helpers/cli-runner.ts) soclients/cli/srcis measured under v8 instrumentation. A thin out-of-process layer (__tests__/e2e.test.ts+scripts/smoke-cli.mjs) still spawns the built binary for the shebang/process.exitpaths;src/index.ts(binary bootstrap) is the only coverage exclusion.commanderuses.exitOverride()so a parse error throws instead of tearing down the test worker. - TUI (
clients/tui): the gate covers the non-React logic only —logger.ts,components/tabsConfig.ts, andutils/*(server resolution lives incore/and is measured by the web suite). The Ink components,App.tsx, andhooks/are an interim exclusion inclients/tui/vitest.config.tspending the renderer-based follow-up (#1501). When adding new non-React logic underclients/tui/src, it falls under the gate automatically — add tests for it.
- CLI (
- Run
npm run test:integration(also fromclients/web/) for the v1.5-ported InspectorClient + transport + auth integration suite. It runs under a separateintegrationvitest project in node env (no happy-dom) with 30s timeouts. The script buildstest-servers/first viatsc -p ../../test-servers --noCheckso the stdio MCP test server can be spawned as a real subprocess. CI runs it as its own step after unit tests. - Test files live alongside the source as
<Name>.test.tsx(or.test.tsfor non-React modules). v1.5-ported integration tests live underclients/web/src/test/integration/, mirroring thecore/source layout (mcp/,mcp/node/,mcp/remote/,auth/,auth/node/,storage/). Any test file under that folder is automatically picked up by theintegrationvitest project (node env, 30s timeouts) via the folder glob invite.config.ts— placement is the manifest, there is no enumeration to keep in sync. Tests outside the folder run in theunitproject (happy-dom). When adding a new test for, e.g.,core/mcp/remote/foo.ts, put it atsrc/test/integration/mcp/remote/foo.test.ts. - Use
renderWithMantinefromsrc/test/renderWithMantine.tsxto render components — it wraps inMantineProviderwith the project theme
Responding to Code Reviews
- When asked to respond to a code review of a PR,
- it is not necessary to implement all suggestions
- you are free to implement suggestions in a different way or to ignore if there is a good reason
- after making the changes, respond to each review comment with what was done (or why it was ignored)
Lint-fixed, Formatted code
- ALWAYS do
npm run formatbefore committing — it auto-fixes any Prettier issues.validaterunsformat:check(the non-fixing variant) and will fail in CI on any unformatted file, so always run the auto-fixer first rather than lettingformat:checkcatch it. - ALWAYS do
npm run validatebefore pushing any changes — from the repo root it chains the four per-client validations (validate:web→validate:cli→validate:tui→validate:launcher); each delegates to that client's ownnpm run validate=format:check+lint+build+testin its own folder (no coverage — fast). Every client is self-validating and the top level just chains them, building each client's bundle along the way (no cross-client build dependencies).- The one CLI nuance:
clients/cli's out-of-processe2e.test.tsspawns the built binary, so itstestbuilds first viapretest(test-servers:build && build). To avoid building it twice,clients/cli'svalidatefolds that in — it isformat:check && lint && testwith no separatebuildstep (the other clients, whose tests don't spawn their bundle, keep an explicitbuild).validate:web/validate:tui/validate:launcherare the uniformformat:check && lint && build && test. - Before pushing, also run
npm run coverage—validateis fast and does NOT enforce the per-file gate (or, for web, run the integration project);coveragedoes both. CI does not runcoverage(the gate is local-only); it runsvalidateplus a standalone webtest:integrationstep.
- The one CLI nuance:
smokeis a separate top-level target, NOT part ofvalidate. Run it (or the individualsmoke:*) after a build/validate:npm run validate && npm run smoke. It runssmoke:launcher(--helpdispatch) plus the prodsmoke:cli/smoke:tui/smoke:web, and contains no build commands — it assumes the cli/tui/launcher bundles already exist (a fullvalidatebuilds them;smoke:webbuildsclients/web/diston demand). CI runsvalidate, then the webtest:integrationstep, thensmoke. Storybook is the only CI step left out (see below).smoke:launcher(scripts/smoke-launcher.mjs) runs the built launcher with--help,--cli --help, and--tui --help, asserting each exits 0 and prints that mode's usage banner (which also proves the launcher resolved and loaded the right client build). It's the cheap dispatch check before the heavier prod smokes below.smoke:web(scripts/smoke-web.mjs) startsmcp-inspector --web(prod, no--dev) against the builtclients/web/distand assertsGET /serves the SPA (HTTP 200) with the injected__INSPECTOR_API_TOKEN__. Prod--webserves fromclients/web/dist, which ships in the published package but is absent in a fresh checkout — the runner builds it on demand (build:client=vite build) on first launch, or exits with an actionable error if that build can't run (seeclients/web/server/ensure-web-build.tsand the launcher README).--devruns Vite directly and never needsdist.smoke:cli(scripts/smoke-cli.mjs) drivesmcp-inspector --clithrough the built launcher against the bundled stdio test server via a temp--catalog: it assertstools/listreturns the server's tools (real connect over stdio), the default writable catalog is seeded empty on first run, a missing read-only--configerrors without seeding, and--catalog+--configis rejected.smoke:tui(scripts/smoke-tui.mjs) launchesmcp-inspector --tui --catalog <temp>and asserts the Ink app renders its first frame (the "MCP Servers" panel) within a timeout, then SIGTERMs it — a shallow boot/render check, not full interaction.smoke:tuiis local-only: it self-skips whenprocess.env.CIis set, because the Ink TUI needs a real TTY (raw mode) that headless CI lacks — so run it (vianpm run smoke) on your own machine before pushing. Both buildtest-servers/buildon demand if it's missing.- Also run
npm run test:storybookfromclients/web/before pushing — it executes every story'splayfunction in headless Chromium via@vitest/browser-playwright(~10s). CI runs this as a separate step (fromclients/web) aftervalidate; failures block merge. It is kept out ofvalidatebecause it needs the Playwright browser binary and is much slower than the unit suite. (There is no root-leveltest:storybookaggregate — run it in the web client.)
Typescript instructions
- Use TypeScript for all new code
- Follow TypeScript best practices and coding standards
- NEVER use 'any' as a type
- NEVER suppress error types (e.g., no-unused-vars, no-explicit-any) in the typescript or eslint configuration as a way of satisfying the linter or compiler.
- Utilize type annotations and interfaces to improve code clarity and maintainability
- Leverage TypeScript's type inference and static analysis features for better code quality and refactoring
- Use type guards and type assertions to handle potential type mismatches and ensure type safety
- Take advantage of TypeScript's advanced features like generics, type aliases, and conditional types to write more expressive and reusable code
- Regularly review and refactor TypeScript code to ensure it remains well-structured and adheres to evolving best practices
React instructions
- UI Components
- We are using the Mantine component library for UI.
- Instructions are at https://mantine.dev/llms.txt
- Avoid using div and other basic HTML elements for layout purposes.
- Prefer Mantine's Box, Group, and Stack components for layout.
- Use Mantine's theme and styling utilities to ensure a consistent and responsive design.
- NEVER use inline styles on a component.
- NEVER use raw hex values (
#ddd,#94a3b8, etc.) orrgba()literals for colors in component props or theme files. Use--inspector-*CSS custom properties defined inApp.css :root(e.g.,c: 'var(--inspector-text-primary)'). If no existing token fits, add one to:rootfirst. - NEVER add a CSS class to a Mantine component when the styles can instead be expressed as component props or a theme variant. CSS classes are a last resort.
- PREFER component props (via
.withProps()) to CSS for behavioral and visual styles. - PREFER defining styles as theme variants (via
Component.extend()insrc/theme/<Component>.ts) over CSS classes. Each Mantine component with custom variants has its own file insrc/theme/, exporting aTheme<Name>constant. The barrelsrc/theme/index.tsre-exports them all andtheme.tsimports from the barrel. Flat CSS properties (margin, padding, background, border, color, font-size, etc.) belong in the theme. Only pseudo-selectors, nested child selectors, keyframes, and native HTML element styles belong in App.css. - App.css must contain ONLY styles that cannot be expressed in the Mantine theme:
@keyframes, pseudo-selectors (:hover,:focus), cross-component hover relationships, nested child-element selectors for third-party HTML output (e.g. ReactMarkdown), and styles for native HTML elements (img,iframe). When refactoring a component, actively move any flat CSS properties out of App.css and into theme variants or.withProps()constants. - NEVER use inline code; instead extract to functions in the same file, exported or located in a shared location if immediately reusable.
- In a component's file, for sub-components:
- ALWAYS use Mantine components for layout and content, configured with props for styling and behavior.
- ALWAYS declare a meaningfully named subcomponent as a constant using
.withProps()if a component has two or more props. - NEVER use
Boxfor subcomponent constants —Boxdoes not support.withProps(). UseGroup,Stack,Flex,Text,Paper,UnstyledButton, orImageinstead. Pick the component that best matches the purpose:Paperfor bordered/surfaced containers,Textfor any text or content wrapper,Stack/Group/Flexfor layout. - NEVER use a CSS class on a subcomponent constant when the styles can be expressed as a Mantine theme variant instead. Define variants in
src/theme/<Component>.tsusingComponent.extend({ styles: (_theme, props) => { ... } })and reference them withvariant="variantName"on the component or in.withProps(). - CSS classes are ONLY acceptable on subcomponents for styles that cannot be expressed as flat CSS-in-JS properties in the theme — specifically: pseudo-selectors (
:hover,:focus), cross-component hover relationships (.parent:hover .child), nested child-element selectors (.wrapper p,.wrapper code),@keyframesdefinitions, and native HTML elements (img,iframe) that are not Mantine components. - When a theme variant needs a CSS class for nested/pseudo selectors, use
classNamesin the theme extension to auto-assign it — never addclassNamemanually in JSX for theme-styled components. - Example — subcomponent constant with
withProps:
const CardContent = Group.withProps({ flex: 1, align: 'flex-start', justify: 'space-between', wrap: 'nowrap', }); return <CardContent> ... </CardContent>- Example — theme variant with auto-assigned className for nested selectors:
// src/theme/Paper.ts export const ThemePaper = Paper.extend({ classNames: (_theme, props) => { if (props.variant === 'message') return { root: 'message' }; return {}; }, styles: (_theme, props) => { if (props.variant === 'message') { return { root: { padding: '1.5rem', borderRadius: 12 } }; } return { root: {} }; }, }), // Component.tsx const MessageContainer = Paper.withProps({ variant: 'message' });
- Theme files vs. Storybook element components
- Theme files (
src/theme/<Component>.ts) and element components (src/components/elements/) serve different purposes and both are needed. - Theme files customize every instance of a Mantine component app-wide — defaults (size, radius), custom variants, and global style overrides. They are applied automatically by
MantineProvider. - Element components add domain-specific semantics on top of Mantine primitives. For example,
AnnotationBadgemaps domain concepts (audience, destructive, longRun) to Mantine's styling primitives (color, variant). Storybook documents these domain components for designers and developers. - Element components MUST import from
@mantine/core, NOT fromsrc/theme/. The theme layer is applied transparently by the provider — elements do not need to know aboutTheme<Name>constants. - NEVER push domain-specific variant logic (e.g., annotation types, transport types) into theme files. Domain variants belong in the element component that owns those semantics. Theme files are for styling that applies to the Mantine primitive globally.
- Theme files (