File size: 6,443 Bytes
7bedc79
 
 
 
 
 
0fc6e34
7bedc79
 
 
 
0fc6e34
7bedc79
 
 
 
031fd6d
7bedc79
031fd6d
7bedc79
031fd6d
7bedc79
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
031fd6d
 
7bedc79
 
 
 
 
 
 
 
 
0fc6e34
7bedc79
0fc6e34
7bedc79
0fc6e34
7bedc79
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
import { McpServer } from "@modelcontextprotocol/sdk/server/mcp.js";
import { StdioServerTransport } from "@modelcontextprotocol/sdk/server/stdio.js";
import { z } from "zod";
import { readFileSync, existsSync, readdirSync, statSync, mkdirSync, writeFileSync } from "node:fs";
import { resolve, join, dirname } from "node:path";
import { parsers } from "../parsers/index.js";
import { dedupeRules } from "../core/dedupe.js";
import { generateConfig, outputFileFor } from "../migrator/generate.js";
import { detectDriftEntries } from "../drift/detect.js";
import { generateReport, formatReport } from "../checker/engine.js";
import type { Rule, AgentKind } from "../core/types.js";
import { findAgentFiles } from "../core/files.js";


function collectRules(root: string): Array<{ agent: string; rules: Rule[]; files: string[] }> {
  const results: Array<{ agent: string; rules: Rule[]; files: string[] }> = [];
  const seenFiles = new Set<string>();
  for (const [agentName, parser] of Object.entries(parsers)) {
    const files = findAgentFiles(root, agentName).filter((f) => !seenFiles.has(f));
    if (files.length === 0) continue;
    files.forEach((f) => seenFiles.add(f));
    const rules: Rule[] = [];
    for (const file of files) {
      rules.push(...parser.parse(readFileSync(file, "utf-8"), file));
    }
    results.push({ agent: agentName, rules, files });
  }
  return results;
}

export function createMcpServer(): McpServer {
  const server = new McpServer({
    name: "agentlens",
    version: "0.1.0",
  });

  // === scan ===
  server.tool(
    "agentlens_scan",
    "Scan the project for AI agent config files (CLAUDE.md, .cursor/rules, AGENTS.md etc.) and summarize rules found",
    {
      path: z.string().optional().describe("Project root path (defaults to cwd)"),
    },
    async ({ path }) => {
      const root = resolve(path ?? process.cwd());
      const results = collectRules(root);

      if (results.length === 0) {
        return {
          content: [{ type: "text", text: `No agent configs found in ${root}. Supported: claude (CLAUDE.md), cursor (.cursor/rules), codex (AGENTS.md)` }],
        };
      }

      const lines: string[] = [`Agent config scan for ${root}:\n`];
      for (const r of results) {
        const cats = new Map<string, number>();
        for (const rule of r.rules) cats.set(rule.category, (cats.get(rule.category) ?? 0) + 1);
        const catStr = [...cats.entries()].map(([c, n]) => `${c}(${n})`).join(", ");
        lines.push(`${r.agent.toUpperCase()}: ${r.rules.length} rules from ${r.files.length} file(s) [${catStr}]`);
      }

      return { content: [{ type: "text", text: lines.join("\n") }] };
    }
  );

  // === move ===
  server.tool(
    "agentlens_move",
    "Migrate agent config rules from one format to another (e.g., CLAUDE.md → .cursor/rules/)",
    {
      from: z.enum(["claude", "cursor", "codex", "windsurf", "copilot", "dsh", "workbuddy", "zcode", "mimo"]).describe("Source agent format"),
      to: z.enum(["claude", "cursor", "codex", "windsurf", "copilot", "dsh", "workbuddy", "zcode", "mimo"]).describe("Target agent format"),
      path: z.string().optional().describe("Project root path"),
      output: z.string().optional().describe("Custom output file path"),
    },
    async ({ from, to, path, output }) => {
      const root = resolve(path ?? process.cwd());
      const parser = parsers[from];
      if (!parser) return { content: [{ type: "text", text: `Unknown agent: ${from}` }] };

      const files = findAgentFiles(root, from);
      const parsed: Rule[] = [];
      for (const file of files) {
        parsed.push(...parser.parse(readFileSync(file, "utf-8"), file));
      }
      const rules = dedupeRules(parsed);

      if (rules.length === 0) {
        return { content: [{ type: "text", text: `No ${from} rules found in ${root}` }] };
      }

      const content = generateConfig(rules, to as AgentKind);
      const outPath = output ? resolve(root, output) : resolve(root, outputFileFor(to as AgentKind));
      mkdirSync(dirname(outPath), { recursive: true });
      writeFileSync(outPath, content, "utf-8");

      return {
        content: [{
          type: "text",
          text: `Migrated ${rules.length} rules from ${from} to ${to}\nOutput: ${outPath}\n\nPreview:\n${content.slice(0, 500)}`,
        }],
      };
    }
  );

  // === drift ===
  server.tool(
    "agentlens_drift",
    "Detect config drift across agent rule files (similar rules with different wording)",
    {
      path: z.string().optional().describe("Project root path"),
    },
    async ({ path }) => {
      const root = resolve(path ?? process.cwd());
      const results = collectRules(root);
      const allRules = results.flatMap((r) => r.rules);

      if (allRules.length === 0) {
        return { content: [{ type: "text", text: "No agent rules found to compare." }] };
      }

      const drifts = detectDriftEntries(allRules);
      if (drifts.length === 0) {
        return { content: [{ type: "text", text: `No config drift detected across ${allRules.length} rules.` }] };
      }

      const lines = [`Found ${drifts.length} drift issue(s):\n`];
      for (const d of drifts) {
        lines.push(`[${d.type}] ${d.description}`);
      }
      return { content: [{ type: "text", text: lines.join("\n\n") }] };
    }
  );

  // === check ===
  server.tool(
    "agentlens_check",
    "Run adversarial QA on code — checks for security issues, correctness bugs, and style problems",
    {
      code: z.string().describe("Code content to analyze"),
      filename: z.string().optional().describe("Filename (for language detection)"),
    },
    async ({ code, filename }) => {
      const ext = filename?.split(".").pop()?.toLowerCase();
      const langMap: Record<string, string> = {
        ts: "typescript", tsx: "typescript", js: "javascript", jsx: "javascript",
        py: "python", go: "go", rs: "rust", java: "java",
      };
      const language = ext ? langMap[ext] : undefined;

      const report = generateReport([{ path: filename ?? "input", content: code, language }]);
      return { content: [{ type: "text", text: formatReport(report) }] };
    }
  );

  return server;
}

export async function startMcpServer(): Promise<void> {
  const server = createMcpServer();
  const transport = new StdioServerTransport();
  await server.connect(transport);
  console.error("AgentLens MCP server running on stdio");
}