我们将构建一个名为 "Context Mapper" 的系统。
目标:
- 创建一个模拟的复杂项目结构(包含你的“层级化地图”)。
- 开发一个 MCP Server,它能接受一个文件路径,自动向上递归查找所有的
.guide.md,并将它们合并成一份“完美上下文”喂给 Claude。
我们分三个阶段完成:造地图(模拟项目) -> 造工具(MCP Server) -> 连接与实战。
第一阶段:造地图(模拟一个 Rust 交易系统)
首先,我们需要一个测试靶子。假设这是你正在开发的 Rust 股票交易项目。
打开终端(Cursor 或 VS Code),在一个空白处执行以下命令,创建目录结构和说明文件:
Bash
# 1. 创建项目根目录
mkdir my-trading-bot
cd my-trading-bot
# 2. 创建各级目录
mkdir -p src/strategy
mkdir -p src/ui
# 3. 【根目录】总司令说明 (.guide.md)
echo "# 全局架构说明
- 项目类型: Rust 量化交易系统
- 核心库: actix-web, tokio, polars
- 编码规范: 必须使用 async/await,错误处理使用 anyhow。" > .guide.md
# 4. 【Strategy 层】策略模块说明
echo "# 策略模块说明 (Strategy)
- 职责: 负责计算买卖信号
- 限制: 计算延迟必须低于 5ms
- 核心文件: signal.rs" > src/strategy/.guide.md
# 5. 【UI 层】界面模块说明
echo "# UI 模块说明 (Frontend)
- 技术栈: Tauri + React
- 风格: 暗黑模式,模仿 Bloomberg 终端" > src/ui/.guide.md
# 6. 创建一些假代码文件(用于测试)
touch src/strategy/signal.rs
touch src/ui/chart.tsx
现在的结构:
Plaintext
my-trading-bot/
├── .guide.md <-- 全局规则
└── src/
├── strategy/
│ ├── .guide.md <-- 策略规则
│ └── signal.rs <-- 你正在写的文件
└── ui/
├── .guide.md <-- UI 规则
└── chart.tsx
第二阶段:造工具(开发 MCP Server)
现在我们要写那个“智能助手”,它负责帮你读这些 MD 文件。
退出刚才的目录,新建一个文件夹专门放 MCP 代码:
Bash
cd ..
mkdir context-mapper-mcp
cd context-mapper-mcp
# 初始化 Node 项目
npm init -y
npm install @modelcontextprotocol/sdk zod
npm install -D typescript @types/node ts-node
npx tsc --init
修改 tsconfig.json (确保 outDir 是 dist, rootDir 是 src):
JSON
{
"compilerOptions": {
"target": "ES2022",
"module": "NodeNext",
"moduleResolution": "NodeNext",
"outDir": "./dist",
"rootDir": "./src",
"strict": true,
"esModuleInterop": true
}
}
核心代码 src/index.ts (这是核心逻辑:给定一个路径,不停往上找 .guide.md)
TypeScript
import { McpServer } from "@modelcontextprotocol/sdk/server/mcp.js";
import { StdioServerTransport } from "@modelcontextprotocol/sdk/server/stdio.js";
import { z } from "zod";
import * as fs from "fs";
import * as path from "path";
// 创建 Server
const server = new McpServer({
name: "context-mapper",
version: "1.0.0",
});
// 辅助函数:向上递归查找所有的 .guide.md
function findGuideFiles(startPath: string): string[] {
const guides: string[] = [];
let currentDir = startPath;
// 如果传入的是文件,先取其目录
if (fs.existsSync(startPath) && fs.statSync(startPath).isFile()) {
currentDir = path.dirname(startPath);
}
// 循环向上查找,直到根目录
while (true) {
const guidePath = path.join(currentDir, ".guide.md");
if (fs.existsSync(guidePath)) {
// 把找到的内容放在数组开头(这样最上层的会在最前面,或者你可以反过来)
// 这里我们要:最上层(根目录)在最前,最底层(当前目录)在最后
// 所以我们用 unshift 插入到头部?
// 不,我们先 push 进去,是 [子, 父, 爷],最后 reverse 变成 [爷, 父, 子] 比较符合人类逻辑
const content = fs.readFileSync(guidePath, "utf-8");
const header = `\n--- Context from: ${currentDir} ---\n`;
guides.push(header + content);
}
const parentDir = path.dirname(currentDir);
// 如果到达系统根目录,停止
if (parentDir === currentDir) break;
currentDir = parentDir;
}
// 反转数组,让根目录的说明排在最前面
return guides.reverse();
}
// 注册工具
server.tool(
"get_hierarchical_context",
{
target_path: z.string().describe("你要编辑的文件的绝对路径,例如 /Users/me/project/src/ui/button.tsx")
},
async ({ target_path }) => {
try {
if (!fs.existsSync(target_path)) {
return { content: [{ type: "text", text: `错误: 路径不存在 ${target_path}` }] };
}
const contextParts = findGuideFiles(target_path);
if (contextParts.length === 0) {
return { content: [{ type: "text", text: "在该路径的上级目录中没有找到 .guide.md 文件。" }] };
}
const fullContext = contextParts.join("\n");
return {
content: [{
type: "text",
text: `已为你加载层级化上下文:\n${fullContext}\n\n(请根据以上架构规范编写代码)`
}],
};
} catch (error: any) { // Type assertion for error
return { content: [{ type: "text", text: `读取失败: ${error.message}` }] };
}
}
);
async function main() {
const transport = new StdioServerTransport();
await server.connect(transport);
console.error("Context Mapper MCP Server running...");
}
main().catch((error) => {
console.error("Fatal error:", error);
process.exit(1);
});
编译代码: 在 package.json 添加 build 并运行:
JSON
"scripts": { "build": "tsc && node dist/index.js" }
运行一次 npm run build 确保生成了 dist/index.js。
第三阶段: 使用官方调试工具 (MCP Inspector) —— 【最推荐,无需账号】
这是开发者测试 MCP Server 最直接的方式。你不需要登录任何账号,不需要 API Key,它直接在本地运行一个网页界面,让你模拟调用工具。
怎么做:
-
保持在你的
context-mapper-mcp项目目录下。 -
在终端运行以下命令(注意替换你的入口文件路径):
Bash
npx @modelcontextprotocol/inspector node dist/index.js
他就相当于一个MCP Client (inspector)
在 VS Code 中使用 (最推荐,稳如老狗)
VS Code 原生不带 MCP 界面,但有一个开源神级插件叫 Cline (前身叫 Claude Dev),它不仅支持 MCP,还能换各种模型(DeepSeek, Gemini, OpenAI)。
1. 安装插件
- 打开 VS Code。
- 点击左侧扩展图标(积木块)。
- 搜索并安装 "Cline" (图标是一个黑底白线条的机器人/几何图形)。
2. 配置 MCP
- 安装好后,点击左侧边栏的 Cline 图标打开对话框。
- 点击对话框顶部的 数据库按钮 。
- 在菜单中找到 "MCP Servers" 。
- 点击右边的链接/按钮(通常叫 "Edit MCP Settings" 或是一个 📄 图标),这会打开一个 JSON 配置文件。
3. 填入配置
把下面的代码填进去(注意替换为你之前的真实路径):
JSON
{
"mcpServers": {
"context-mapper": {
"command": "node",
"args": [
"/Users/xx/xx/MCP/Skill/context-mapper-mcp/dist/index.js"
]
}
}
}
4. 见证奇迹
-
保存文件。
-
回到 Cline 对话框,你会看到一个绿色的插头图标或者提示 "Connected to context-mapper"。
-
直接在对话框里输入:
“读取一下 /Users/xx/my-trading-bot/src/strategy/signal.rs 的层级上下文,帮我优化一下代码”
-
Cline 会自动请求权限(点击 "Always Allow"),然后调用你的工具。
可以看到他读到了每个层级的制定的规则 提示词
最后创建出来代码
trea中一样也是配置mcpserver 然后在
用就行