canonical-theme-mcp-server

v1.0.4
@luis-neira/canonical-theme-mcp-server Checked 3 days ago Published 4 months ago

An MCP server that returns focused, exact slices of a project's canonical Mantine theme.

An MCP server that reads a project's canonical Mantine theme by file path and returns focused, exact source slices. The caller does not need to load the whole theme or send its contents through the MCP request. match_canonical_theme_values and resolve_canonical_theme_paths run in opposite directions. Use the first when you hold a raw design value and do not know where it lives in the theme; use the second when you already hold a theme reference and need the value it resolves to. Every tool returns evidence.

Summary extracted from the README.

canonical-theme-mcp-server

An MCP server that reads a project's canonical Mantine theme by file path and returns focused, exact source slices. The caller does not need to load the whole theme or send its contents through the MCP request.

The server has four tools:

Tool Description
match_canonical_theme_values Return every exact canonical-theme match for each supplied raw value, optionally grouped by CSS-property compatibility.
get_canonical_shadow_candidates Return every configured canonical shadow without ranking or recommending a candidate.
get_canonical_component_overrides Return an exact override or no-override result for each supplied Mantine component.
resolve_canonical_theme_paths Resolve a theme path or CSS variable to its exact value and source evidence.

match_canonical_theme_values and resolve_canonical_theme_paths run in opposite directions. Use the first when you hold a raw design value and do not know where it lives in the theme; use the second when you already hold a theme reference and need the value it resolves to.

Every tool returns evidence. None of them ranks matches, discards them, or chooses among them — that judgement belongs to the caller.

How it works

The theme is read as TypeScript source and analysed as an abstract syntax tree. The server never imports, executes, or evaluates the theme file.

It uses the TypeScript compiler API to produce a single SourceFile via ts.createSourceFile. There is no ts.Program and no type checker: the server looks only at syntax within one file. That keeps it fast and dependency-free, and it is why the parser ships inside this package rather than borrowing the application's TypeScript installation or requiring the application to have node_modules.

The pipeline

A request moves through four stages.

  1. Load (src/canonical-theme-file.ts) — resolve and vet the file before reading it: absolute path, a confirmed project root, a regular file, under 2 MB, and carrying the @canonical-theme marker. When the root came from the client or the environment, the file must also sit inside it after realpath. Returns { path, text }. This module imports no TypeScript API at all; it is the single door through which every tool reads from disk.

    Those two root sources come from src/project-roots.ts, which asks the client and falls back to CANONICAL_THEME_PROJECT_ROOT. Both arrive over the client connection or the server configuration rather than as tool arguments, so a caller can name any filePath it likes but cannot widen the boundary that contains it. The third source, derivation from filePath itself, is the exception — see What the boundary does and does not guarantee.

  2. Parse (src/theme-slicer.ts) — build the SourceFile, index every top-level const, function, and class by name, then locate the sole createTheme(...) call and resolve its argument to an object literal.

  3. Index — walk the known theme sections and flatten every reachable scalar into a list of { value, themePath, source, startLine, endLine } records, attaching the Mantine prop value and CSS variable each binding generates (colors.blue[5] → blue.5 and var(--mantine-color-blue-5)).

  4. Answer — filter that index for the requested values, or slice the shadows / components sections directly.

What the resolver follows

Theme values are frequently written indirectly. Within the single file, the resolver follows:

  • local const references, including chains, with cycle guards;
  • property access (TOKENS.spacing.md) and element access (SIZES[2], TOKENS["md"]);
  • template literals, when every interpolated span itself resolves;
  • string, numeric, boolean, and signed numeric literals;
  • wrappers that do not change the value — parentheses, as, satisfies, type assertions, and non-null assertions.

colorsTuple(...) is special-cased: a uniform tuple yields one representative shade-9 binding rather than ten identical entries. Ordinary palettes keep every repeated value as its own match.

The two directions therefore treat a uniform tuple differently, by design. match_canonical_theme_values collapses it to shade 9 so one colour does not return ten duplicate matches. resolve_canonical_theme_paths expands from it, so colors.brand[3] resolves to the tuple's colour — which is what Mantine does at runtime — and marks the result uniform with evidence at the colorsTuple call.

Anything the resolver cannot follow statically is simply not indexed. It is never guessed at, and never partially reported.

Indexed sections

Only these theme sections are walked:

black, white, colors, primaryColor, primaryShade, fontFamily, fontFamilyMonospace, headings, fontSizes, lineHeights, radius, defaultRadius, shadows, spacing, breakpoints, other

A value that appears anywhere else — including inside components — is not matched by match_canonical_theme_values.

Component overrides

components is handled separately. An override is returned as a verbatim source slice rather than being interpreted, so Button.extend({ ... }) comes back as written. Any local declarations the override references are collected and returned alongside it, so the caller sees the whole picture without reading the file.

Each override also reports themeReferences: the complete canonical theme paths the override reads, gathered from the override expression and from the local declarations it depends on.

{ "name": "Button", "status": "override", "source": "Button: Button.extend({ ... })",
  "themeReferences": ["theme.colors.primaryTextColor[9]", "theme.spacing.md"] }

Only complete paths are returned — theme.colors is dropped when theme.colors.primaryTextColor[9] is also present. Entries are deduplicated and ordered by source encounter. They are accepted verbatim by resolve_canonical_theme_paths, so a caller never needs to read paths out of the source text. The list is evidence of what the override reads; it says nothing about which references matter for a given styling decision.

references and themeReferences are different things: the first names local declarations in the theme file, the second names canonical theme paths.

Refusing to guess

Where a spread makes a fact unprovable, the tool errors instead of asserting something it cannot demonstrate. A spread in components means absence cannot be proven, so no-override is never claimed; a spread in shadows means the candidate list cannot be shown to be complete. This is the same principle as the tools not ranking matches: the server reports only what the source shows.

CSS-property compatibility

src/css-property-sections.ts maps a CSS property to the theme sections that could sensibly supply it — padding to spacing, box-shadow to shadows, and so on. It is pure string logic with no AST dependency. It only groups matches; nothing is discarded.

Requirements

  • Node.js 22 or newer.
  • The client declares at least one root, the server configuration sets CANONICAL_THEME_PROJECT_ROOT, or an ancestor of filePath holds a package.json or .git.
  • filePath is absolute and resolves to a regular file. When the root comes from the client or CANONICAL_THEME_PROJECT_ROOT, filePath must also stay inside it, including after resolving symlinks.
  • The theme file is at most 2 MB and contains @canonical-theme at the start of its own comment line. The marker regex is line-anchored, so a marker trailing after code on the same line does not match.

Theme file constraints

The file must satisfy these, or the tool returns an error:

Constraint Error when violated
Exactly one createTheme(...) call Expected exactly one createTheme(...) call; found N.
Its argument is an object literal, or a local constant resolving to one The createTheme(...) argument must be an object literal…
A theme section is declared at most once — checked per operation, only for the sections it inspects The canonical theme defines <name> more than once.
shadows / components resolve to object literals The theme <name> value must be an object literal…
No spread in shadows when listing candidates Cannot return every shadow candidate…
No spread in components when proving absence Cannot prove that <name> has no override…

MCP configuration

Every filePath must resolve inside a project root. The server asks the client for its roots over the MCP roots capability, so most clients need no per-project configuration:

{
  "mcpServers": {
    "canonical-theme": {
      "command": "npx",
      "args": ["-y", "@luis-neira/canonical-theme-mcp-server@latest"]
    }
  }
}

Clients that do not implement roots may name the root explicitly. This is a fallback: it is used only when the client declares no roots.

{
  "mcpServers": {
    "canonical-theme": {
      "command": "npx",
      "args": ["-y", "@luis-neira/canonical-theme-mcp-server@latest"],
      "env": {
        "CANONICAL_THEME_PROJECT_ROOT": "/absolute/path/to/project"
      }
    }
  }
}

When neither supplies a root, the root is derived from filePath: the nearest ancestor directory holding a package.json or .git. The walk stops at the home directory, which is checked before the marker, so a package.json sitting directly in $HOME never becomes a root. The filesystem root is not excluded the same way — it is probed like any other ancestor, so a marked / would be returned. If no marked ancestor exists, the request is refused.

What the boundary does and does not guarantee

Roots are resolved in order — declared by the client, then CANONICAL_THEME_PROJECT_ROOT, then derived from filePath. The first source that supplies a root wins; they are not merged.

The first two are boundaries in the real sense. They arrive over the client connection or the server configuration, never as a tool argument, so a caller can name any filePath it likes and the containment check can still reject it.

Derivation is different, and the difference is worth stating plainly. A root derived from filePath contains that file by construction, so containment becomes a tautology rather than a check. On that path the real gate is the @canonical-theme marker together with the requirement that the file parse to exactly one createTheme(...) call. Arbitrary files stay unreadable: an SSH key or an .env satisfies neither condition. What derivation does permit is reading a canonical theme belonging to a different project on the same machine.

Supply a client root or CANONICAL_THEME_PROJECT_ROOT where that matters. Derivation exists so that the common case needs no per-project configuration.

Tool inputs

Match raw design values against the canonical theme:

{
  "filePath": "/absolute/path/to/project/src/designSystemTheme.ts",
  "values": [
    { "id": "background", "value": "#F7F6FD", "cssProperty": "background-color" },
    { "id": "icon-size", "value": "40px", "cssProperty": "width" }
  ]
}

cssProperty is optional and accepts kebab-case or camelCase. When present, the result separates compatibleMatches from otherExactMatches using the theme section appropriate for that property. Both groups remain exact source evidence; the server does not rank, discard, or choose among them. Without cssProperty, the result retains the original matches array.

If and only if exact matching reports no match for a boxShadow value, retrieve the unranked canonical shadow candidates:

{
  "filePath": "/absolute/path/to/project/src/designSystemTheme.ts"
}

Retrieve component overrides for the initial frozen tree or only newly added components:

{
  "filePath": "/absolute/path/to/project/src/designSystemTheme.ts",
  "components": ["Paper", "Group", "Button"]
}

Resolve a theme reference back to its value:

{
  "filePath": "/absolute/path/to/project/src/designSystemTheme.ts",
  "paths": ["colors.primaryTextColor[9]", "var(--mantine-spacing-md)"]
}

Each path returns exactly one result. A leading theme. is stripped and .9 is read as [9], but only as a fallback after an exact match fails, so a literal numeric key always wins. Statuses are exact, not-indexed (the section is never walked, such as anything under components), or no-match. A no-match that is a prefix of indexed paths reports them in prefixOf.

Two facts are disclosed rather than hidden. A shade of a uniform colorsTuple palette resolves with uniform: true and cites the tuple call, so a caller can still tell a repeated colour from ten distinct ones. A duplicated key resolves to the later declaration — the one ECMAScript uses — with shadowed: true and the losing declaration in shadowedSource.

All results report the resolved canonical-theme path.

The results include:

  • one exact or no-match result for every requested raw value;
  • every exact theme path and any generated prop value or CSS variable for each match;
  • compact source evidence and line numbers for each match;
  • an exact override or explicit no-override result for every requested component;
  • local declarations attached to a component that references them.

Development

npm install
npm run ci

npm run ci runs the build, a Biome format check, and the test suite.

Source layout

Module Responsibility
src/index.ts Entry point; starts the server.
src/server.ts Registers the three MCP tools and their Zod input schemas.
src/project-roots.ts Resolves project roots from the client, falling back to the environment.
src/canonical-theme-file.ts Path containment, size cap, and marker check. No TypeScript API.
src/css-property-sections.ts CSS property → theme section map. Pure string logic.
src/theme-slicer.ts AST parsing, value indexing, and the three tool implementations.

Source files import each other with .ts specifiers; rewriteRelativeImportExtensions rewrites them to .js on build, so the same paths work when tests run the TypeScript directly.

The server uses the official MCP TypeScript SDK and communicates over stdio.