Skip to main content
Glama
README.md

# React MCP (Model Context Protocol) Frontend Server

> A powerful Orchestration Core that enables AI agents to interact with React applications, enforcing Feature-Sliced Design (FSD) conventions through the Model Context Protocol.

## Overview
The **MCP React Frontend Server** is a Model Context Protocol (MCP) implementation designed to act as an Orchestration Core and Architectural Hub for React/Next.js applications. It enforces Feature-Sliced Design (FSD) boundaries, semantic naming conventions, and project-specific constraints. The server interacts with MCP clients (like IDEs or agents) to validate code architecture, prevent structural entropy, and scaffold standardized FSD entities through deterministic rules rather than ephemeral prompts.

<div align="center">
  <img src="./public/logo.png" alt="MCP React Frontend Logo" width="500" style="border-radius: 16px;" />
</div>

## MCP Capabilities

### Tools

1. **`analyze_project`**
   - **Description**: Analyze project files for FSD violations and naming conventions.
   - **Input**:
     - `files` (*array*): File paths (relative to project root) as strings or `{ path, imports }` objects. FSD layer / private-import checks run only when imports are known.
     - `codeSnippets` (*array of objects, optional*): Objects containing `fileName` and `content` for deep linter analysis; imports are extracted from the content automatically.
   - **Output**: JSON containing `status` (SUCCESS/ERROR), `summary` (total errors/warnings), `violations` array, `recommendations` array and optional `notes` (e.g. when FSD import checks were skipped).
   - **Behavior**: Delegates import analysis to `FsdAgent` and code snippet analysis to `LinterAgent`. The combined violations are processed by `RecommenderAgent` to generate actionable fixes.

2. **`get_rules`**
   - **Description**: Get project rules (fsd, naming, linter, structure, styles, patterns).
   - **Input**: `domain` (*optional*), `pattern` (*optional*), `includeDocs` (*boolean, optional*) — inline referenced markdown docs.
   - **Output**: JSON object detailing the project rules. `template` / `relatedDocs` fields are rule doc ids.
   - **Behavior**: Fetches configurations from `RulesProvider`.

3. **`get_pattern_doc`**
   - **Description**: Get a rule/pattern markdown doc (examples, prohibitions, anti-patterns) by id.
   - **Input**: `id` (*optional*) — without it returns the list of available docs.
   - **Output**: Markdown text of the doc.

4. **`scaffold_entity`**
   - **Description**: Generate a standardized FSD entity structure with API, types, schema, and converters.
   - **Input**:
     - `name` (*string*): The name of the entity.
     - `path` (*string*): The target directory path (relative to `src/entities`).
   - **Output**: Text message confirming the creation of the architecture.
   - **Behavior**: Generates folders (`api/`, `types/`, `schema/`, `converters/`, `ui/`) and boilerplate files including RTK Query services, Zod schemas, data converters, and a public API index.

### Resources

- **`rules://docs/{id}`** (`text/markdown`): every rule/pattern doc from `src/entities/rules/config/**/*.md`. Docs are embedded at build time into `rule-docs.generated.ts` — run `npm run rules:docs` after editing any rules `*.md` (also runs automatically in `dev` / `build`).

## Architecture
The application is built on top of the **Next.js App Router** and the `@modelcontextprotocol/sdk`.

### Main Modules
- **`mcp-server.ts`**: The factory that creates the `McpServer` instance, registers tools, and bridges MCP SDK with internal logic.
- **`Agents`**:
  - `FsdAgent`: Responsible for cross-import checking and FSD semantic layer isolation constraints.
  - `LinterAgent`: Checks AST or string content against naming and structural rules.
  - `RecommenderAgent`: Generates mitigation steps for detected violations.
- **Transport**: `src/app/api/mcp/route.ts` — stateless Streamable HTTP (`WebStandardStreamableHTTPServerTransport`, JSON responses). Only `POST` (and CORS `OPTIONS`) is served; `GET`/`DELETE` answer `405` because there are no sessions or server-sent streams. The legacy SSE transport (protocol 2024-11-05) was removed: MCP Inspector and `mcp-remote` speak Streamable HTTP.

### Data Flow
1. **Request**: MCP Client connects via `/api/mcp`. Next.js routes the request.
2. **Processing**: The HTTP transport translates the request into the `McpServer`. For tool calls, the specific agent (`FsdAgent`, `LinterAgent`) is invoked.
3. **Response**: Analysis results are aggregated, serialized to JSON and wrapped in an MCP content block.

### External Dependencies
- `@modelcontextprotocol/sdk`: Core MCP logic.
- `next` / `react`: Driving the API routes and web interface.
- `zod`: Schema validation.

## Usage

Clients connect over stdio (local script) or Streamable HTTP (`/api/mcp`).

### Connecting to MCP Clients (e.g., Antigravity)

Add the following to your `mcp_config.json` manually:

#### 1. Local Stdio (Recommended)

Fastest and most stable for development. Uses the local script directly.

```json
{
  "mcpServers": {
    "mcp-react-frontend-local": {
      "command": "npx",
      "args": ["-y", "tsx", "scripts/mcp-stdio.ts"],
      "cwd": "D://<path_to_project_root>"
    }
  }
}
```

#### 2. Local HTTP

Connects over HTTP to a running server on `localhost:3000`. Requires `mcp-remote`.

```json
{
  "mcpServers": {
    "mcp-react-frontend-http": {
      "command": "npx",
      "args": ["-y", "mcp-remote", "http://localhost:3000/api/mcp"]
    }
  }
}
```

#### 3. Remote

Production (Vercel):

```json
{
  "mcpServers": {
    "mcp-react-frontend-remote": {
      "command": "npx",
      "args": ["-y", "mcp-remote", "https://orchestrator.damir-karimov.com/api/mcp"]
    }
  }
}
```

Fallback (Render):

> [!IMPORTANT]
> Initial connection can take **up to 60 seconds** due to server "warm-up" (cold start).

```json
{
  "mcpServers": {
    "mcp-react-frontend-remote-fallback": {
      "command": "npx",
      "args": ["-y", "mcp-remote", "https://mcp-react-frontend.onrender.com/api/mcp"]
    }
  }
}
```


### Supported Rules & Patterns Scope
The MCP server enforces a highly deterministic, strict architectural contract defined in `src/entities/rules/config/domains/*.json` and `src/entities/rules/config/patterns/*.json` (aggregated by `RulesProvider`). The validation scope guarantees structural integrity across the following domains:

**1. Feature-Sliced Design (FSD) Topology**
- **Unidirectional Dependency Flow**: Strictly validates import boundaries across `app` → `pages` → `widgets` → `features` → `entities` → `shared`.
- **Cross-Layer Isolation**: Detects and prohibits private cross-imports, enforcing mandatory barrel-export (`index.ts`) usage.

**2. Semantic Naming & Typing Contracts**
- **Pattern Enforcement**: Mandates `kebab-case` for file systems.
- **Type Prefixing/Suffixing**: Validates strict prefixes (`I` for interfaces, `T` for types, `ENUM_` for enums) and DTO backend suffixes (`*Backend`, `-backend.interface.ts`).
- **Framework Awareness**: Intelligently excludes Next.js App Router reserved files (`page`, `layout`, etc.) and React hooks (`use*`) from generic naming constraints.

**3. Structural Integrity & Boilerplate Constraints**
- **Entity Anatomy**: Rejects FSD entities missing mandatory internal sub-modules (`api`, `types`, `schema`, `converters`, `ui`).
- **File Fingerprinting**: Validates extension semantics (`*.schema.ts`, `*.converters.ts`, `*.service.ts`).

**4. Code Quality & Safety (Linter)**
- **Runtime Safety**: Hard bans on `console.*` usage and `any` types.
- **TypeScript Strictness**: Prohibits native TypeScript `enum` usage (forcing object/const maps) and mandates strict typing.

**5. UI & Design Token Constraints**
- **Atomic Styling**: Documents the recommended Tailwind utility families (`allowedUtilityPrefixes`: colors via tokens, spacing/sizing via the scale, no arbitrary values). This is guidance for generated code, not a linter check.
- **Color Palette Isolation**: Strictly forbids raw Tailwind color primitives (e.g., `slate`, `red`, `blue`, `emerald`) and static `white`/`black` utilities, forcing the application to use semantic CSS variables and design tokens.
- **Tailwind v4**: Tokens live in `src/shared/styles/{globals,variables,theme}.css` (`@theme`, `@theme inline`, `@custom-variant dark`); no `tailwind.config.ts`.
- **Class Merging**: Mandates the `cn` utility wrapper for dynamic class composition.

**6. Implementation Protocol Validation**
- **RTK Query**: Validates API code-splitting via `injectEndpoints`, centralized tags, and base queries.
- **DTO Converters**: Requires symmetric data transformation with operation-specific names (`mapOrdersToFrontend`, `mapCreateEntityToBackend`, pattern `map*ToFrontend|ToBackend`) between network boundaries and domain models. Shared list contract: `IPaginationRequest` / `IPaginationResponse`.
- **Zod Schemas**: Validates payload schema definitions against strongly typed `i18n` localization keys.
- **Mocking (MSW)**: Ensures mock handlers are properly registered and isolated.
- **Error Boundaries**: Validates the presence of `ErrorBoundary` wrappers and `withErrorBoundary` HOCs on dynamic or volatile UI components.
- **Theme Segregation**: Controls the usage of `ThemeProvider` and `useTheme` hooks for stable DOM synchronization.


## Configuration
- **Environment Variables** (read only in `src/shared/config/env/env.config.ts`; copy `.env.example` to `.env.local`). Required ones fail the build with a clear message when missing — set them on Vercel and Render too:
  - `NEXT_PUBLIC_APP_URL` (required) — canonical site URL for canonical/hreflang, sitemap, Open Graph and JSON-LD. Any other host (vercel.app, onrender.com, previews, localhost) gets `X-Robots-Tag: noindex`.
  - `NEXT_PUBLIC_CONTACT_EMAIL`, `NEXT_PUBLIC_CONTACT_TELEGRAM`, `NEXT_PUBLIC_CONTACT_LINKEDIN`, `NEXT_PUBLIC_CONTACT_GITHUB` (required) — author contacts on the Creator page; the GitHub username also builds the repository link.
  - `NEXT_PUBLIC_GTM_ID` — Google Tag Manager container; empty disables it. Fires on the canonical host only.
  - `GOOGLE_SITE_VERIFICATION`, `YANDEX_VERIFICATION` — verification meta tags; empty — no tag.
- **Configs**: Handled internally by `RulesProvider` (FSD constraints).
- **Secrets**: Not defined in code.

## Local Development

```bash
# 1. Install dependencies (.npmrc sets legacy-peer-deps: @vercel/analytics has an
#    optional @sveltejs/kit peer that needs Vite 8, while vitest 3 pins Vite 7)
npm install

# 2. Build the project (TypeScript, Prettier check and Next.js build — does not modify files)
npm run build

# Tests: unit (vitest) and e2e against a production build (Playwright, JS disabled + axe)
npm test
npx playwright install chromium   # once
npm run test:e2e

# 3. Start the application
npm run dev
# Server will be available at http://localhost:3000
```
*Requirements*: Node.js 18+ (inferred from Next 14+), npm.

## Limitations
- **Hardcoding**: The scaffold tool implicitly hardcodes the `src/entities/` prefix for generating files.
- **Validation Constraints**: There is no authentication (CORS `*`); anyone with network access can call the tools. Inputs are bounded instead: request bodies are capped at 1 MB (`413`) and `analyze_project` limits files, snippets and snippet length (`src/features/mcp/lib/analyze-project.ts`).
- **Rate limiting**: In-memory limits are meaningless on serverless instances. Configure a Vercel Firewall rate-limit rule for `/api/*` in the project dashboard.