Python MCP Server

Python MCP Server

一个模型上下文协议服务器,用于提取和分析 Python 代码结构,重点关注文件之间的导入/导出关系,以帮助 LLM 理解代码上下文。 (Simplified version, emphasizing clarity and common usage:) 一个模型上下文协议服务器,它提取并分析 Python 代码结构,特别是文件之间的导入/导出关系,从而帮助 LLM 理解代码上下文。

Category
访问服务器

README

用于代码图提取的 Python MCP 服务器

此 MCP(模型上下文协议)服务器提供用于提取和分析 Python 代码结构的工具,重点关注文件之间的导入/导出关系。 这是一个轻量级的实现,不需要代理系统,因此可以轻松集成到任何 Python 应用程序中。

特性

  • 代码关系发现:分析 Python 文件之间的导入关系
  • 智能代码提取:仅提取最相关的代码段,以保持在令牌限制内
  • 目录上下文:包含来自同一目录的文件,以提供更好的上下文
  • 文档包含:始终包含 README.md 文件(或变体),以提供项目文档
  • LLM 友好格式:使用适当的元数据格式化代码,以便用于语言模型
  • MCP 协议支持:完全兼容模型上下文协议 JSON-RPC 标准

get_python_code 工具

该服务器公开了一个强大的代码提取工具,该工具:

  • 分析目标 Python 文件并发现所有导入的模块、类和函数
  • 返回目标文件的完整代码
  • 包含来自其他文件的所有引用对象的代码
  • 从同一目录添加其他上下文文件
  • 遵守令牌限制,以避免使语言模型不堪重负

安装

# 克隆存储库
git clone https://github.com/yourusername/python-mcp-new.git
cd python-mcp-new

# 创建一个虚拟环境
python -m venv venv
source venv/bin/activate  # 在 Windows 上,使用:venv\Scripts\activate

# 安装依赖项
pip install -r requirements.txt

环境变量

基于提供的 .env.example 创建一个 .env 文件:

# 提取的令牌限制
TOKEN_LIMIT=8000

用法

为 MCP 客户端配置

要配置此 MCP 服务器以用于 MCP 兼容的客户端(如 Codeium Windsurf),请将以下配置添加到客户端的 MCP 配置文件:

{
  "mcpServers": {
    "python-code-explorer": {
      "command": "python",
      "args": [
        "/path/to/python-mcp-new/server.py"
      ],
      "env": {
        "TOKEN_LIMIT": "8000"
      }
    }
  }
}

/path/to/python-mcp-new/server.py 替换为系统上 server.py 文件的绝对路径。

您还可以自定义环境变量:

  • TOKEN_LIMIT:代码提取的最大令牌限制(默认值:8000)

用法示例

直接函数调用

from agent import get_python_code

# 获取特定文件的 Python 代码结构
result = get_python_code(
    target_file="/home/user/project/main.py",
    root_repo_path="/home/user/project"  # 可选,默认为目标文件目录
)

# 处理结果
target_file = result["target_file"]
print(f"Main file: {target_file['file_path']}")
print(f"Docstring: {target_file['docstring']}")

# 显示相关文件
for ref_file in result["referenced_files"]:
    print(f"Related file: {ref_file['file_path']}")
    print(f"Object: {ref_file['object_name']}")
    print(f"Type: {ref_file['object_type']}")

# 查看是否接近令牌限制
print(f"Token usage: {result['token_count']}/{result['token_limit']}")

示例响应(直接函数调用)

{
    "target_file": {
        "file_path": "main.py",
        "code": "import os\nimport sys\nfrom utils.helpers import format_output\n\ndef main():\n    args = sys.argv[1:]\n    if not args:\n        print('No arguments provided')\n        return\n    \n    result = format_output(args[0])\n    print(result)\n\nif __name__ == '__main__':\n    main()",
        "type": "target",
        "docstring": ""
    },
    "referenced_files": [
        {
            "file_path": "utils/helpers.py",
            "object_name": "format_output",
            "object_type": "function",
            "code": "def format_output(text):\n    \"\"\"Format the input text for display.\"\"\"\n    if not text:\n        return ''\n    return f'Output: {text.upper()}'\n",
            "docstring": "Format the input text for display.",
            "truncated": false
        }
    ],
    "additional_files": [
        {
            "file_path": "config.py",
            "code": "# Configuration settings\n\nDEBUG = True\nVERSION = '1.0.0'\nMAX_RETRIES = 3\n",
            "type": "related_by_directory",
            "docstring": "Configuration settings for the application."
        }
    ],
    "total_files": 3,
    "token_count": 450,
    "token_limit": 8000
}

使用 MCP 协议

列出可用工具

from agent import handle_mcp_request
import json

# 列出可用工具
list_request = {
    "jsonrpc": "2.0",
    "id": 1,
    "method": "tools/list"
}

response = handle_mcp_request(list_request)
print(json.dumps(response, indent=2))

示例响应 (tools/list)

{
  "jsonrpc": "2.0",
  "id": 1,
  "result": {
    "tools": [
      {
        "name": "get_python_code",
        "description": "Return the code of a target Python file and related files based on import/export proximity.",
        "inputSchema": {
          "type": "object",
          "properties": {
            "target_file": {
              "type": "string",
              "description": "Path to the Python file to analyze."
            },
            "root_repo_path": {
              "type": "string",
              "description": "Root directory of the repository. If not provided, the directory of the target file will be used."
            }
          },
          "required": ["target_file"]
        }
      }
    ]
  }
}

调用 get_python_code 工具

from agent import handle_mcp_request
import json

# 调用 get_python_code 工具
tool_request = {
    "jsonrpc": "2.0",
    "id": 2,
    "method": "tools/call",
    "params": {
        "name": "get_python_code",
        "arguments": {
            "target_file": "/home/user/project/main.py",
            "root_repo_path": "/home/user/project"  # Optional
        }
    }
}

response = handle_mcp_request(tool_request)
print(json.dumps(response, indent=2))

示例响应 (tools/call)

{
  "jsonrpc": "2.0",
  "id": 2,
  "result": {
    "content": [
      {
        "type": "text",
        "text": "Python code analysis for /home/user/project/main.py"
      },
      {
        "type": "resource",
        "resource": {
          "uri": "resource://python-code/main.py",
          "mimeType": "application/json",
          "data": {
            "target_file": {
              "file_path": "main.py",
              "code": "import os\nimport sys\nfrom utils.helpers import format_output\n\ndef main():\n    args = sys.argv[1:]\n    if not args:\n        print('No arguments provided')\n        return\n    \n    result = format_output(args[0])\n    print(result)\n\nif __name__ == '__main__':\n    main()",
              "type": "target",
              "docstring": ""
            },
            "referenced_files": [
              {
                "file_path": "utils/helpers.py",
                "object_name": "format_output",
                "object_type": "function",
                "code": "def format_output(text):\n    \"\"\"Format the input text for display.\"\"\"\n    if not text:\n        return ''\n    return f'Output: {text.upper()}'\n",
                "docstring": "Format the input text for display.",
                "truncated": false
              }
            ],
            "additional_files": [
              {
                "file_path": "config.py",
                "code": "# Configuration settings\n\nDEBUG = True\nVERSION = '1.0.0'\nMAX_RETRIES = 3\n",
                "type": "related_by_directory",
                "docstring": "Configuration settings for the application."
              }
            ],
            "total_files": 3,
            "token_count": 450,
            "token_limit": 8000
          }
        }
      }
    ],
    "isError": false
  }
}

处理错误

from agent import handle_mcp_request

# 使用无效文件路径调用
faulty_request = {
    "jsonrpc": "2.0",
    "id": 3,
    "method": "tools/call",
    "params": {
        "name": "get_python_code",
        "arguments": {
            "target_file": "/path/to/nonexistent.py"
        }
    }
}

response = handle_mcp_request(faulty_request)
print(json.dumps(response, indent=2))

示例错误响应

{
  "jsonrpc": "2.0",
  "id": 3,
  "result": {
    "content": [
      {
        "type": "text",
        "text": "Error processing Python code: No such file or directory: '/path/to/nonexistent.py'"
      }
    ],
    "isError": true
  }
}

测试

运行测试以验证功能:

python -m unittest discover tests

主要组件

  • agent.py:包含 get_python_code 函数和自定义 MCP 协议处理程序
  • code_grapher.py:实现用于 Python 代码分析的 CodeGrapher
  • server.py:使用 MCP Python SDK 的完整 MCP 服务器实现
  • run_server.py:用于运行 MCP 服务器的 CLI 工具
  • examples/:显示如何使用 MCP 服务器和客户端的示例脚本
  • tests/:所有功能的综合测试用例

响应格式详细信息

get_python_code 工具返回一个结构化的 JSON 对象,其中包含以下字段:

字段 类型 描述
target_file 对象 有关目标 Python 文件的信息
referenced_files 数组 目标文件导入的对象列表
additional_files 数组 来自同一目录的其他上下文文件
total_files 数字 响应中包含的文件总数
token_count 数字 所有包含的代码中令牌的近似计数
token_limit 数字 为提取配置的最大令牌限制

目标文件对象

字段 类型 描述
file_path 字符串 从存储库根目录到文件的相对路径
code 字符串 文件的完整源代码
type 字符串 始终为 "target"
docstring 字符串 如果可用,则为模块级文档字符串

引用文件对象

字段 类型 描述
file_path 字符串 文件的相对路径
object_name 字符串 导入对象的名称(类、函数等)
object_type 字符串 对象的类型(“类”、“函数”等)
code 字符串 特定对象的源代码
docstring 字符串 如果可用,则为对象的文档字符串
truncated 布尔值 代码是否由于令牌限制而被截断

附加文件对象

字段 类型 描述
file_path 字符串 文件的相对路径
code 字符串 文件的完整源代码
type 字符串 关系类型(例如,“related_by_directory”)
docstring 字符串 如果可用,则为模块级文档字符串

使用 MCP SDK 服务器

该项目现在包含一个功能齐全的模型上下文协议 (MCP) 服务器,该服务器使用官方 Python MCP SDK 构建。 该服务器以标准化方式公开我们的代码提取功能,该功能可以与任何 MCP 客户端(包括 Claude Desktop)一起使用。

启动服务器

# 使用默认设置启动服务器
python run_server.py

# 指定自定义名称
python run_server.py --name "My Code Explorer"

# 使用特定的 .env 文件
python run_server.py --env-file .env.production

使用 MCP 开发模式

安装 MCP SDK 后,您可以使用 MCP CLI 在开发模式下运行服务器:

# 安装 MCP CLI
pip install "mcp[cli]"

# 在开发模式下使用 Inspector UI 启动服务器
mcp dev server.py

这将启动 MCP Inspector,这是一个用于测试和调试服务器的 Web 界面。

Claude Desktop 集成

您可以将服务器安装到 Claude Desktop 中,以直接从 Claude 访问您的代码浏览工具:

# 在 Claude Desktop 中安装服务器
mcp install server.py

# 使用自定义配置
mcp install server.py --name "Python Code Explorer" -f .env

自定义服务器部署

对于自定义部署,您可以直接使用 MCP 服务器:

from server import mcp

# 配置服务器
mcp.name = "Custom Code Explorer"

# 运行服务器
mcp.run()

使用 MCP 客户端

您可以使用 MCP Python SDK 以编程方式连接到服务器。 请参阅 examples/mcp_client_example.py 中提供的示例:

from mcp.client import Client, Transport

# 连接到服务器
client = Client(Transport.subprocess(["python", "server.py"]))
client.initialize()

# 列出可用工具
for tool in client.tools:
    print(f"Tool: {tool.name}")

# 使用 get_code 工具
result = client.tools.get_code(target_file="path/to/your/file.py")
print(f"Found {len(result['referenced_files'])} referenced files")

# 清理
client.shutdown()

运行示例:

python examples/mcp_client_example.py [optional_target_file.py]

添加其他工具

您可以通过使用 server.py 中的 @mcp.tool() 装饰器装饰函数来向 MCP 服务器添加其他工具:

@mcp.tool()
def analyze_imports(target_file: str) -> Dict[str, Any]:
    """Analyze all imports in a Python file."""
    # Implementation code here
    return {
        "file": target_file,
        "imports": [],  # List of imports found
        "analysis": ""  # Analysis of the imports
    }
    
@mcp.tool()
def find_python_files(directory: str, pattern: str = "*.py") -> list[str]:
    """Find Python files matching a pattern in a directory."""
    from pathlib import Path
    return [str(p) for p in Path(directory).glob(pattern) if p.is_file()]

您还可以添加资源端点以直接提供数据:

@mcp.resource("python_stats://{directory}")
def get_stats(directory: str) -> Dict[str, Any]:
    """Get statistics about Python files in a directory."""
    from pathlib import Path
    stats = {
        "directory": directory,
        "file_count": 0,
        "total_lines": 0,
        "average_lines": 0
    }
    
    files = list(Path(directory).glob("**/*.py"))
    stats["file_count"] = len(files)
    
    if files:
        total_lines = 0
        for file in files:
            with open(file, "r") as f:
                total_lines += len(f.readlines())
        stats["total_lines"] = total_lines
        stats["average_lines"] = total_lines / len(files)
    
    return stats

模型上下文协议集成

该项目完全拥抱模型上下文协议 (MCP) 标准,提供两种实现选项:

  1. 原生 MCP 集成agent.py 中的原始实现提供了一个直接的 JSON-RPC 接口,该接口与 MCP 兼容。

  2. MCP SDK 集成server.py 中的新实现利用官方 MCP Python SDK 获得更强大和功能丰富的体验。

MCP 集成的优势

  • 标准化接口:使您的工具可用于任何 MCP 兼容的客户端
  • 增强的安全性:内置的权限模型和资源控制
  • 更好的 LLM 集成:与 Claude Desktop 和其他 LLM 平台无缝集成
  • 改进的开发者体验:全面的工具,如 MCP Inspector

MCP 协议版本

此实现支持 MCP 协议版本 0.7.0。

有关 MCP 的更多信息,请参阅 官方文档

推荐服务器

Baidu Map

Baidu Map

百度地图核心API现已全面兼容MCP协议,是国内首家兼容MCP协议的地图服务商。

官方
精选
JavaScript
Playwright MCP Server

Playwright MCP Server

一个模型上下文协议服务器,它使大型语言模型能够通过结构化的可访问性快照与网页进行交互,而无需视觉模型或屏幕截图。

官方
精选
TypeScript
Magic Component Platform (MCP)

Magic Component Platform (MCP)

一个由人工智能驱动的工具,可以从自然语言描述生成现代化的用户界面组件,并与流行的集成开发环境(IDE)集成,从而简化用户界面开发流程。

官方
精选
本地
TypeScript
Audiense Insights MCP Server

Audiense Insights MCP Server

通过模型上下文协议启用与 Audiense Insights 账户的交互,从而促进营销洞察和受众数据的提取和分析,包括人口统计信息、行为和影响者互动。

官方
精选
本地
TypeScript
VeyraX

VeyraX

一个单一的 MCP 工具,连接你所有喜爱的工具:Gmail、日历以及其他 40 多个工具。

官方
精选
本地
graphlit-mcp-server

graphlit-mcp-server

模型上下文协议 (MCP) 服务器实现了 MCP 客户端与 Graphlit 服务之间的集成。 除了网络爬取之外,还可以将任何内容(从 Slack 到 Gmail 再到播客订阅源)导入到 Graphlit 项目中,然后从 MCP 客户端检索相关内容。

官方
精选
TypeScript
Kagi MCP Server

Kagi MCP Server

一个 MCP 服务器,集成了 Kagi 搜索功能和 Claude AI,使 Claude 能够在回答需要最新信息的问题时执行实时网络搜索。

官方
精选
Python
e2b-mcp-server

e2b-mcp-server

使用 MCP 通过 e2b 运行代码。

官方
精选
Neon MCP Server

Neon MCP Server

用于与 Neon 管理 API 和数据库交互的 MCP 服务器

官方
精选
Exa MCP Server

Exa MCP Server

模型上下文协议(MCP)服务器允许像 Claude 这样的 AI 助手使用 Exa AI 搜索 API 进行网络搜索。这种设置允许 AI 模型以安全和受控的方式获取实时的网络信息。

官方
精选