返回市场
代码解析器-mcp

代码解析器-mcp

作者:BillDuke136 星标更新:2025-03-04

项目介绍

Code Explainer MCP

一个作为MCP(模型上下文协议)服务器的Cloudflare Worker,用于代码解释。它分析并解释代码,提供全面的结构和功能分解。

License

功能

  • 架构图:生成ASCII图,展示整体结构、组件之间的关系以及数据流。
  • 核心功能分析:基于模式识别,确定并解释代码的主要目的。
  • 组件分解:列出所有主要类和函数,并简要描述它们的角色。
  • 多语言支持:分析多种编程语言的代码,包括JavaScript、TypeScript、Python、Java、C#等。
  • JSDoc/文档字符串识别:提取并利用代码中的现有文档。
  • 安全API:使用Bearer令牌认证来保护您的端点。

工作原理

Code Explainer 使用以下组合技术分析源代码:

  1. 模式识别:识别代码结构和常见模式。
  2. 关系分析:映射组件之间的依赖关系。
  3. 文档提取:优先考虑现有的文档注释。
  4. 架构可视化:创建代码结构的ASCII图。
  5. 组件描述:提供函数和类的语义描述。

所有处理都在Cloudflare Worker中进行,没有外部依赖。

安装

先决条件

  • Node.js(版本12或更高)
  • Wrangler(Cloudflare Workers CLI)
  • 一个Cloudflare账户

设置

  1. 克隆此仓库:

    git clone https://github.com/BillDuke13/code-explainer-mcp.git
    cd code-explainer-mcp
    
  2. 安装依赖项:

    npm install
    
  3. 配置您的密钥:

    • 编辑 wrangler.jsonc 并将 YOUR_SECRET_KEY_HERE 替换为您选择的密钥,或者
    • 使用Cloudflare密钥(推荐用于生产环境):
      wrangler secret put SHARED_SECRET
      
  4. 部署到Cloudflare Workers:

    npm run deploy
    

使用方法

API端点

向您的worker URL发送POST请求,请求体如下所示的JSON:

{
  "method": "explainCode",
  "params": ["your code here", "programming language"]
}

在请求头中包含授权信息,使用您的密钥:

Authorization: Bearer YOUR_SECRET_KEY_HERE

响应格式

响应将是一个包含代码分析结果的JSON对象:

{
  "result": "# 代码分析:JavaScript代码\n\n## 架构图\n...\n\n## 核心功能\n..."
}

示例用法

JavaScript(浏览器)

async function explainCode(code, language) {
  const response = await fetch('https://your-worker-url.workers.dev', {
    method: 'POST',
    headers: {
      'Content-Type': 'application/json',
      'Authorization': 'Bearer YOUR_SECRET_KEY_HERE',
    },
    body: JSON.stringify({
      method: "explainCode",
      params: [code, language]
    }),
  });
  
  if (!response.ok) {
    throw new Error(`HTTP错误!状态码:${response.status}`);
  }
  
  const data = await response.json();
  return data.result;
}

// 示例用法
const jsCode = `function add(a, b) { return a + b; }`;
explainCode(jsCode, "javascript")
  .then(explanation => console.log(explanation))
  .catch(error => console.error('错误:', error));

Python(Requests)

import requests
import json

def explain_code(code, language, api_url, secret_key):
    headers = {
        'Content-Type': 'application/json',
        'Authorization': f'Bearer {secret_key}'
    }
    
    payload = {
        'method': 'explainCode',
        'params': [code, language]
    }
    
    response = requests.post(api_url, headers=headers, json=payload)
    response.raise_for_status()
    
    return response.json()['result']

# 示例用法
code = "def hello(): print('Hello, world!')"
explanation = explain_code(code, "python", "https://your-worker-url.workers.dev", "YOUR_SECRET_KEY_HERE")
print(explanation)

Node.js(Axios)

const axios = require('axios');

async function explainCode(code, language) {
  try {
    const response = await axios.post('https://your-worker-url.workers.dev', {
      method: 'explainCode',
      params: [code, language]
    }, {
      headers: {
        'Content-Type': 'application/json',
        'Authorization': 'Bearer YOUR_SECRET_KEY_HERE'
      }
    });
    
    return response.data.result;
  } catch (error) {
    console.error('错误:', error.response ? error.response.data : error.message);
    throw error;
  }
}

// 示例用法
const codeToAnalyze = `
class Person {
  constructor(name) {
    this.name = name;
  }
  
  sayHello() {
    return \`Hello, my name is \${this.name}\`;
  }
}
`;

explainCode(codeToAnalyze, 'javascript')
  .then(explanation => console.log(explanation))
  .catch(err => console.error('无法解释代码:', err));

本地开发

  1. 克隆仓库并安装依赖项:

    git clone https://github.com/BillDuke13/code-explainer-mcp.git
    cd code-explainer-mcp
    npm install
    
  2. 运行开发服务器:

    wrangler dev
    
  3. 在本地测试端点:

    curl -X POST http://localhost:8787 \
      -H "Content-Type: application/json" \
      -H "Authorization: Bearer YOUR_SECRET_KEY_HERE" \
      -d '{"method":"explainCode","params":["function hello() { return \"Hello World\"; }","javascript"]}'
    

开发指南

  • 遵循TypeScript最佳实践
  • 对复杂逻辑添加注释
  • 更新公共API更改的文档
  • 为新功能添加测试

安全性

  • API使用Bearer令牌认证进行保护
  • 使用环境密钥存储生产环境中的共享密钥
  • 不要在版本控制中提交实际的密钥
  • 推荐在生产部署中实施速率限制

许可证

本项目根据Apache许可证2.0版发布 - 详情见LICENSE文件。