agentlens / src /mcp /server.ts
hongcoding's picture
feat: DSH bot-instruction parser + dedupe + DSH panel project picker
0fc6e34 verified
Raw History Blame Contribute Delete
6.44 kB
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");
}