@dhvanilpansuriya/code-niyam 1.0.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/README.md ADDED
@@ -0,0 +1,56 @@
1
+ # Code-Niyam MCP Server
2
+
3
+ An industrial-grade Model Context Protocol (MCP) server for strict enforcement of UI consistency and architectural patterns.
4
+
5
+ ## ๐Ÿš€ Overview
6
+
7
+ **Code-Niyam** enables AI assistants to strictly follow your project's design tokens and coding conventions. Instead of giving the model vague instructions, you use MCP tools to inject high-density, formatted system prompts directly into the model's context.
8
+
9
+ ## โœจ Features
10
+
11
+ - **Strict UI Enforcement**: Inject design tokens (HSL, spacing, grid) into every session.
12
+ - **Architectural Guardian**: Ensure the model follows your specific coding patterns (Functional vs Class-based, Naming, etc.).
13
+ - **Business Context Injection**: Help the model understand the high-level flow of your project.
14
+ - **Template System**: Manage all rules in clean Markdown (`src/templates/*.md`).
15
+ - **Industrial Standards**: Built with TypeScript, Zod, and Vitest.
16
+
17
+ ## ๐Ÿ› ๏ธ Installation
18
+
19
+ 1. Clone the repository.
20
+ 2. Install dependencies:
21
+ ```bash
22
+ npm install
23
+ ```
24
+ 3. Build the project:
25
+ ```bash
26
+ npm run build
27
+ ```
28
+
29
+ ## ๐Ÿ“– Usage
30
+
31
+ ### Connecting to AI Clients (Cursor, Claude Desktop, etc.)
32
+
33
+ Add the following command to your MCP configuration:
34
+ ```bash
35
+ node d:/Work/MCP/bin/index.js
36
+ ```
37
+
38
+ ### Available Tools
39
+
40
+ - `get_ui_rules`: Injects the UI design system prompts.
41
+ - `get_code_patterns`: Injects architectural and coding convention prompts.
42
+ - `get_project_flow`: Injects business logic and high-level context.
43
+
44
+ ## ๐Ÿงช Testing
45
+
46
+ Run the test suite using Vitest:
47
+ ```bash
48
+ npm test
49
+ ```
50
+
51
+ ## ๐Ÿ“ Customization
52
+
53
+ To change your project's rules, simply edit the Markdown files in the `src/templates/` directory. The MCP server reads these files live on every tool call.
54
+
55
+ ---
56
+ Built with โค๏ธ for High-Speed Developer Workflows.
@@ -0,0 +1,2 @@
1
+ import { ToolHandler } from "./types.js";
2
+ export declare const codePatternsHandler: ToolHandler;
@@ -0,0 +1,15 @@
1
+ import { loadTemplate } from "../utils/template-loader.js";
2
+ export const codePatternsHandler = {
3
+ name: "get_code_patterns",
4
+ description: "Get strict architectural and coding pattern rules.",
5
+ inputSchema: {
6
+ type: "object",
7
+ properties: {},
8
+ },
9
+ handle: async () => {
10
+ const content = await loadTemplate("code_patterns");
11
+ return {
12
+ content: [{ type: "text", text: content }],
13
+ };
14
+ },
15
+ };
@@ -0,0 +1,2 @@
1
+ import { ToolHandler } from "./types.js";
2
+ export declare const projectFlowHandler: ToolHandler;
@@ -0,0 +1,15 @@
1
+ import { loadTemplate } from "../utils/template-loader.js";
2
+ export const projectFlowHandler = {
3
+ name: "get_project_flow",
4
+ description: "Get high-level project flow and business context rules.",
5
+ inputSchema: {
6
+ type: "object",
7
+ properties: {},
8
+ },
9
+ handle: async () => {
10
+ const content = await loadTemplate("project_flow");
11
+ return {
12
+ content: [{ type: "text", text: content }],
13
+ };
14
+ },
15
+ };
@@ -0,0 +1,11 @@
1
+ export interface ToolHandler {
2
+ name: string;
3
+ description: string;
4
+ inputSchema: any;
5
+ handle: (params: any) => Promise<{
6
+ content: Array<{
7
+ type: "text";
8
+ text: string;
9
+ }>;
10
+ }>;
11
+ }
@@ -0,0 +1 @@
1
+ export {};
@@ -0,0 +1,2 @@
1
+ import { ToolHandler } from "./types.js";
2
+ export declare const uiRulesHandler: ToolHandler;
@@ -0,0 +1,15 @@
1
+ import { loadTemplate } from "../utils/template-loader.js";
2
+ export const uiRulesHandler = {
3
+ name: "get_ui_rules",
4
+ description: "Get strict UI consistency and design system rules.",
5
+ inputSchema: {
6
+ type: "object",
7
+ properties: {},
8
+ },
9
+ handle: async () => {
10
+ const content = await loadTemplate("ui_rules");
11
+ return {
12
+ content: [{ type: "text", text: content }],
13
+ };
14
+ },
15
+ };
package/bin/index.d.ts ADDED
@@ -0,0 +1 @@
1
+ export {};
package/bin/index.js ADDED
@@ -0,0 +1,70 @@
1
+ import { Server } from "@modelcontextprotocol/sdk/server/index.js";
2
+ import { StdioServerTransport } from "@modelcontextprotocol/sdk/server/stdio.js";
3
+ import { CallToolRequestSchema, ListToolsRequestSchema, } from "@modelcontextprotocol/sdk/types.js";
4
+ import { logger } from "./utils/logger.js";
5
+ import { uiRulesHandler } from "./handlers/ui-rules.js";
6
+ import { codePatternsHandler } from "./handlers/code-patterns.js";
7
+ import { projectFlowHandler } from "./handlers/project-flow.js";
8
+ /**
9
+ * Industrial MCP Server: Context-Guard
10
+ */
11
+ class ContextGuardServer {
12
+ server;
13
+ handlers = new Map();
14
+ constructor() {
15
+ this.server = new Server({
16
+ name: "code-niyam",
17
+ version: "1.0.0",
18
+ }, {
19
+ capabilities: {
20
+ tools: {},
21
+ },
22
+ });
23
+ // Register Handlers
24
+ this.registerHandler(uiRulesHandler);
25
+ this.registerHandler(codePatternsHandler);
26
+ this.registerHandler(projectFlowHandler);
27
+ this.server.onerror = (error) => logger.error("[MCP Error]", error);
28
+ this.setupHandlers();
29
+ }
30
+ registerHandler(handler) {
31
+ this.handlers.set(handler.name, handler);
32
+ }
33
+ setupHandlers() {
34
+ // List available tools
35
+ this.server.setRequestHandler(ListToolsRequestSchema, async () => ({
36
+ tools: Array.from(this.handlers.values()).map((h) => ({
37
+ name: h.name,
38
+ description: h.description,
39
+ inputSchema: h.inputSchema,
40
+ })),
41
+ }));
42
+ // Handle tool execution
43
+ this.server.setRequestHandler(CallToolRequestSchema, async (request) => {
44
+ const { name, arguments: args } = request.params;
45
+ logger.info(`Executing tool: ${name}`);
46
+ const handler = this.handlers.get(name);
47
+ if (!handler) {
48
+ logger.warn(`Tool not found: ${name}`);
49
+ throw new Error(`Tool unknown: ${name}`);
50
+ }
51
+ try {
52
+ return await handler.handle(args);
53
+ }
54
+ catch (error) {
55
+ logger.error(`Error in tool ${name}:`, error);
56
+ throw error;
57
+ }
58
+ });
59
+ }
60
+ async run() {
61
+ const transport = new StdioServerTransport();
62
+ await this.server.connect(transport);
63
+ logger.info("Context-Guard MCP Server running on stdio");
64
+ }
65
+ }
66
+ const server = new ContextGuardServer();
67
+ server.run().catch((err) => {
68
+ logger.error("Fatal server error:", err);
69
+ process.exit(1);
70
+ });
@@ -0,0 +1,9 @@
1
+ /**
2
+ * Simple structured logger for MCP.
3
+ * Always logs to stderr because stdio is used for JSON-RPC.
4
+ */
5
+ export declare const logger: {
6
+ info: (message: string, meta?: any) => void;
7
+ error: (message: string, error?: any) => void;
8
+ warn: (message: string, meta?: any) => void;
9
+ };
@@ -0,0 +1,23 @@
1
+ /**
2
+ * Simple structured logger for MCP.
3
+ * Always logs to stderr because stdio is used for JSON-RPC.
4
+ */
5
+ export const logger = {
6
+ info: (message, meta) => {
7
+ const output = JSON.stringify({ level: "info", message, ...meta });
8
+ console.error(output);
9
+ },
10
+ error: (message, error) => {
11
+ const output = JSON.stringify({
12
+ level: "error",
13
+ message,
14
+ error: error instanceof Error ? error.message : error,
15
+ stack: error instanceof Error ? error.stack : undefined,
16
+ });
17
+ console.error(output);
18
+ },
19
+ warn: (message, meta) => {
20
+ const output = JSON.stringify({ level: "warn", message, ...meta });
21
+ console.error(output);
22
+ },
23
+ };
@@ -0,0 +1,6 @@
1
+ /**
2
+ * Loads a markdown template from the src/templates directory.
3
+ * @param templateName The name of the template file (without extension).
4
+ * @returns The content of the template.
5
+ */
6
+ export declare function loadTemplate(templateName: string): Promise<string>;
@@ -0,0 +1,23 @@
1
+ import { readFile } from "fs/promises";
2
+ import { join, dirname } from "path";
3
+ import { fileURLToPath } from "url";
4
+ const __dirname = dirname(fileURLToPath(import.meta.url));
5
+ const TEMPLATES_DIR = join(__dirname, "..", "templates");
6
+ /**
7
+ * Loads a markdown template from the src/templates directory.
8
+ * @param templateName The name of the template file (without extension).
9
+ * @returns The content of the template.
10
+ */
11
+ export async function loadTemplate(templateName) {
12
+ const filePath = join(TEMPLATES_DIR, `${templateName}.md`);
13
+ try {
14
+ return await readFile(filePath, "utf-8");
15
+ }
16
+ catch (error) {
17
+ // Avoid logging errors during tests for expected failures
18
+ if (process.env.NODE_ENV !== "test") {
19
+ console.error(`Failed to load template ${templateName}:`, error);
20
+ }
21
+ return `### Error\nTemplate ${templateName} not found.`;
22
+ }
23
+ }
package/package.json ADDED
@@ -0,0 +1,34 @@
1
+ {
2
+ "name": "@dhvanilpansuriya/code-niyam",
3
+ "version": "1.0.0",
4
+ "description": "Industrial-grade MCP server for strict context and UI rule enforcement.",
5
+ "type": "module",
6
+ "main": "bin/index.js",
7
+ "bin": {
8
+ "code-niyam": "bin/index.js"
9
+ },
10
+ "files": [
11
+ "bin",
12
+ "src/templates"
13
+ ],
14
+ "scripts": {
15
+ "build": "tsc",
16
+ "watch": "tsc -w",
17
+ "start": "node bin/index.js",
18
+ "dev": "ts-node src/index.ts",
19
+ "lint": "eslint src --ext .ts",
20
+ "test": "vitest run"
21
+ },
22
+ "dependencies": {
23
+ "@modelcontextprotocol/sdk": "^1.6.0",
24
+ "zod": "^3.24.2"
25
+ },
26
+ "devDependencies": {
27
+ "@types/node": "^22.13.10",
28
+ "typescript": "^5.8.2",
29
+ "ts-node": "^10.9.2",
30
+ "eslint": "^9.22.0",
31
+ "vitest": "^3.0.8",
32
+ "prettier": "^3.5.3"
33
+ }
34
+ }
@@ -0,0 +1,22 @@
1
+ ### !! STRICT_FOLLOW_INSTRUCTION !!
2
+ You are now in **ARCHITECTURAL GUARDIAN MODE**. Your primary objective is to ensure the codebase remains clean, predictable, and scalable.
3
+
4
+ #### 1. Coding Standards
5
+ - **Functional First**: Use functional components and pure functions. Avoid classes unless absolutely necessary for state management.
6
+ - **Explicit Types**: No `any` types. Strictly define interfaces or types for all function signatures and data structures.
7
+ - **Naming**:
8
+ - Components: `PascalCase`
9
+ - Functions/Variables: `camelCase`
10
+ - Constants: `SCREAMING_SNAKE_CASE`
11
+
12
+ #### 2. Error Handling
13
+ - Use structured error responses.
14
+ - Never swallow errors; always log them with context using the project's logging utility.
15
+ - Use `try/catch` blocks at the boundary of external interactions (APIs, DBs).
16
+
17
+ #### 3. Module Structure
18
+ - Keep logic in `src/handlers` and utilities in `src/utils`.
19
+ - Export only what is necessary using explicit `export` statements.
20
+
21
+ ---
22
+ *Consistency is the key to velocity.*
@@ -0,0 +1,17 @@
1
+ ### !! STRICT_FOLLOW_INSTRUCTION !!
2
+ You are now in **PROJECT LOGIC MODE**. Your primary objective is to maintain consistency with the high-level business goals and technical flow.
3
+
4
+ #### 1. Project Overview
5
+ - **Goal**: Build a high-speed, contextual MCP server for design consistency.
6
+ - **Audience**: Developers looking to reduce "context-swapping" debt.
7
+
8
+ #### 2. Key Flows
9
+ - **Rule Injection**: Every task must begin by identifying which "Guardian" (UI, Architecture, or Flow) is relevant.
10
+ - **Prompt Precedence**: Static rules in this MCP take precedence over general LLM knowledge.
11
+
12
+ #### 3. Success Metrics
13
+ - **Coding Speed**: Minimal back-and-forth for design corrections.
14
+ - **Consistency**: 100% adherence to HSL tokens and 4px grids.
15
+
16
+ ---
17
+ *Stay aligned with the mission.*
@@ -0,0 +1,20 @@
1
+ ### !! STRICT_FOLLOW_INSTRUCTION !!
2
+ You are now in **UI CONSISTENCY MODE**. Your primary objective is to maintain pixel-perfect adherence to the project's design system.
3
+
4
+ #### 1. Color Palette (HSL)
5
+ - **Background**: `hsl(220, 15%, 10%)` (Deep Space)
6
+ - **Surface**: `hsl(220, 15%, 15%)` (Steel Gray)
7
+ - **Primary**: `hsl(250, 70%, 60%)` (Electric Purple)
8
+ - **Text-Base**: `hsl(0, 0%, 95%)`
9
+
10
+ #### 2. Layout & Spacing
11
+ - **Grid**: Use a 12-column flex or grid system.
12
+ - **Spacing Scale**: 4px base (4, 8, 12, 16, 24, 32, 48, 64).
13
+ - **Rounding**: `rounded-xl` (12px) for cards, `rounded-full` for buttons.
14
+
15
+ #### 3. Component Usage
16
+ - Prefer **Radix UI** primitives and **Lucide React** icons.
17
+ - Avoid hardcoded hex codes; always use CSS variables or Tailwind tokens.
18
+
19
+ ---
20
+ *Failure to follow these rules will result in a visual debt warning.*