-
Notifications
You must be signed in to change notification settings - Fork 11
Expand file tree
/
Copy pathindex.ts
More file actions
334 lines (303 loc) · 10.2 KB
/
Copy pathindex.ts
File metadata and controls
334 lines (303 loc) · 10.2 KB
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
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
#!/usr/bin/env node
import { McpServer } from "@modelcontextprotocol/sdk/server/mcp.js";
import { StdioServerTransport } from "@modelcontextprotocol/sdk/server/stdio.js";
import { exec } from "child_process";
import { existsSync, promises as fs } from "fs";
import * as path from "path";
import { promisify } from "util";
import { z } from "zod";
import * as gitignoreParser from "gitignore-parser";
const execPromise = promisify(exec);
// 默认黑名单,当.gitignore不存在时使用
const folderBlackList = [
"node_modules",
".codelf",
".git",
".idea",
".vscode",
"dist",
"build",
"out",
"target",
"bin",
"obj",
".next",
"coverage",
"__pycache__",
".DS_Store",
"tmp",
"temp",
"logs",
".cache",
".github",
".gitlab",
"vendor",
];
const forceBlackList = [".git", ".codelf", ".vscode", ".idea"];
const GET_PROJECT_TEMPLATE = `
This is the current project details, include project structure, dev attentions, and other important information:
{{S}}
Keep in mind:
1. after you finish modifying code to stisfy user requirements, you have to call 'update-project-info' which help you ensure the document remains up to date.
2. follow the response of 'update-project-info' to update .codelf/*.md files.
`;
// 用于解析.gitignore文件的函数
async function parseGitignore(
rootPath: string,
targetPath: string
): Promise<boolean | null> {
const gitignorePath = path.join(rootPath, ".gitignore");
// 检查.gitignore文件是否存在
if (!existsSync(gitignorePath)) {
return null;
}
try {
// 读取.gitignore文件内容
const content = await fs.readFile(gitignorePath, "utf-8");
// 使用gitignore-parser的compile方法解析.gitignore内容
const gitignore = gitignoreParser.compile(content);
// 使用denies方法检查路径是否被拒绝(被忽略)
return gitignore.denies(targetPath);
} catch (error) {
console.error("Error parsing .gitignore:", error);
return null;
}
}
// Create server instance
const server = new McpServer({
name: "codelf-mcp-server",
version: "0.0.1",
description:
"Enables AI agents to better understand and modify code. Highly recommended for use under all circumstances",
});
// define project info context info tools
server.tool(
"get-project-info",
`Complete the project details and points to note.
its very important for LLM/Agent edit code. the more you konw, the more you can do.
its very useful for cursor or windsurf no martter in agent or edit mode.
**Highly recommended for use under all circumstances**.
`,
{
rootPath: z.string().describe(
`The root path of the project,
C:/User/name/codeProject in windows
/usr/name/codeProject/ in macos/linux`
),
},
async ({ rootPath }) => {
const content = await fs
.readdir(path.join(rootPath, ".codelf"))
.then(async (files) => {
const mdFiles = files.filter((f) => f.endsWith(".md"));
const contents = await Promise.all(
mdFiles.map(async (file) => {
// ignore files start with "_", like _changelog.md
if (file.startsWith("_")) {
return "";
}
const content = await fs.readFile(
path.join(rootPath, ".codelf", file),
"utf-8"
);
const name = path.basename(file, ".md");
return `<${name}>\n\n${content}\n\n</${name}>\n`;
})
);
return GET_PROJECT_TEMPLATE.replace("{{S}}", contents.join("\n"));
})
.catch(() => "");
return {
content: [
{
type: "text",
text: content,
},
],
};
}
);
server.tool(
"update-project-info",
"when you have finished modifying code to stisfy user requirements, you have to update .codelf/*.md files. This tool help you ensure the document remains up to date.",
{
rootPath: z.string().describe(
`The root path of the project,
"C:/User/name/codeProject" in windows
"/usr/name/codeProject/" in macos/linux`
),
},
async ({ rootPath }) => {
return {
content: [
{
type: "text",
text: `[ATTENTION] Next step you must do:
** Read files .codelf/project.md and .codelf/changelog.md and update them base on the changes you have just done.**
`,
},
],
};
}
);
server.tool(
"init-codelf",
`Initialize .codelf directory and files. which can help llm better understand your project.
After init .codelf directory and files, you should:
1. every file in .codelf directory is a markdown file, you can read them and update them.
2. you have to follow the instructions in .codelf/*.md files and update them.
`,
{
rootPath: z.string().describe(
`The root path of the project,
"C:/User/name/codeProject" in windows
"/usr/name/codeProject/" in macos/linux`
),
},
async ({ rootPath }) => {
try {
await fs.mkdir(path.join(rootPath, ".codelf"), { recursive: true });
// 检查目标目录是否为空
const files = await fs.readdir(path.join(rootPath, ".codelf"));
if (files.length === 0) {
// 目录为空,执行 git clone
const { stdout, stderr } = await execPromise(
`git clone https://github.com/Disdjj/codelf-template ${path.join(
rootPath,
".codelf"
)}`
);
// remove .git folder
await fs.rm(path.join(rootPath, ".codelf", ".git"), {
recursive: true,
});
const fileTree = await getFileTree(rootPath);
// append filetree to .codelf/project.md
await fs.appendFile(
path.join(rootPath, ".codelf", "project.md"),
`\n\`\`\`\n${fileTree}\n\`\`\`\n`
);
return {
content: [
{
type: "text",
text: `Successfully initialized .codelf directory with template.\nOutput: ${stdout}\n${
stderr ? `Error: ${stderr}` : ""
}`,
},
{
type: "text",
text: `[Attention]\n
Next step you should do:\n
1. every file in .codelf directory is a markdown file, you can read them and update them.
2. you have to follow the instructions in .codelf/*.md files and update them.
3. before you finish edit .codelf/*.md files, do not use update-project-info/get-project-info.
4. after you finish edit .codelf/*.md files, just stop.
`,
},
],
};
} else {
// 目录不为空,提示用户
return {
content: [
{
type: "text",
text: "The .codelf directory already exists and is not empty. Please remove or empty it before initializing.",
},
],
};
}
} catch (error) {
return {
content: [
{
type: "text",
text: `Failed to initialize .codelf directory: ${
error instanceof Error ? error.message : String(error)
}`,
},
],
};
}
}
);
async function getFileTree(rootPath: string): Promise<string> {
const indent = " ";
// 递归处理单个路径(目录或文件)
const processEntry = async (entryPath: string, displayName: string, prefix: string, relativePath: string): Promise<string[]> => {
const stat = await fs.stat(entryPath).catch(() => null);
const lines: string[] = [];
if (stat && stat.isDirectory()) {
lines.push(`${prefix}- ${displayName}`);
const entries = await fs.readdir(entryPath, { withFileTypes: true });
for (const entry of entries) {
if (entry.isDirectory() && forceBlackList.includes(entry.name)) continue;
const entryRelativePath = path.join(relativePath, entry.name).replace(/\\/g, "/");
const subPath = path.join(entryPath, entry.name);
lines.push(...(await processEntry(subPath, entry.name, prefix + indent, entryRelativePath)));
}
} else if (stat && stat.isFile()) {
lines.push(`${prefix}- ${displayName}`);
}
return lines;
};
const buildTree = async (
dir: string,
prefix: string,
relativePath: string = ""
): Promise<string[]> => {
const codelfPath = path.join(rootPath, ".codelf.config");
const result: string[] = [];
const existsCodelfFile = existsSync(codelfPath) && !(await fs.stat(codelfPath)).isDirectory();
if (existsCodelfFile && dir === rootPath) {
// 读取 .codelf.config 文件内容
const content = await fs.readFile(codelfPath, "utf-8");
const lines = content
.split(/\r?\n/)
.map((l) => l.trim())
.filter((l) => l && !l.startsWith("#"));
if (lines.length) {
for (const line of lines) {
const entryPath = path.join(rootPath, line);
result.push(...(await processEntry(entryPath, line, prefix, line.replace(/\\/g, "/"))));
}
return result;
}
}
// 原有递归逻辑
const entries = await fs.readdir(dir, { withFileTypes: true });
for (const entry of entries) {
if (entry.isDirectory() && forceBlackList.includes(entry.name)) {
continue;
}
// 尝试解析.gitignore文件
// 如果.gitignore存在且解析成功,使用其规则;否则使用默认黑名单
const entryRelativePath = path
.join(relativePath, entry.name)
.replace(/\\/g, "/");
const isIgnore = await parseGitignore(rootPath, entryRelativePath);
// 使用.gitignore规则或默认黑名单进行过滤
const shouldIgnore =
typeof isIgnore === "boolean"
? isIgnore
: folderBlackList.includes(entry.name);
if (!shouldIgnore) {
const entryPath = path.join(dir, entry.name);
result.push(...(await processEntry(entryPath, entry.name, prefix, entryRelativePath)));
}
}
return result;
};
const result = await buildTree(rootPath, "", "");
return ["root", ...result].join("\n");
}
async function main() {
const transport = new StdioServerTransport();
await server.connect(transport);
console.log("MCP Server running on stdio");
}
main().catch((error) => {
console.error("Fatal error in main():", error);
process.exit(1);
});