Python MCP Server
Python MCP-Server zur Code-Graph-Extraktion
Dieser MCP-Server (Model Context Protocol) bietet Tools zum Extrahieren und Analysieren von Python-Codestrukturen mit Schwerpunkt auf Import-/Exportbeziehungen zwischen Dateien. Es handelt sich um eine leichtgewichtige Implementierung, die kein Agentensystem benötigt und sich daher problemlos in jede Python-Anwendung integrieren lässt.
Merkmale
Code Relationship Discovery : Analysieren Sie Importbeziehungen zwischen Python-Dateien
Intelligente Code-Extraktion : Extrahieren Sie nur die relevantesten Codeabschnitte, um innerhalb der Token-Grenzen zu bleiben
Verzeichniskontext : Fügen Sie Dateien aus demselben Verzeichnis ein, um einen besseren Kontext bereitzustellen
Einbeziehung der Dokumentation : Fügen Sie immer README.md-Dateien (oder Varianten) ein, um die Projektdokumentation bereitzustellen
LLM-freundliche Formatierung : Formatieren Sie Code mit den richtigen Metadaten für Sprachmodelle
MCP-Protokollunterstützung : Vollständig kompatibel mit dem Model Context Protocol JSON-RPC-Standard
Related MCP server: CodeAnalysis MCP Server
Das get_python_code Tool
Der Server stellt ein leistungsstarkes Tool zur Codeextraktion bereit, das:
Analysiert eine Python-Zieldatei und erkennt alle importierten Module, Klassen und Funktionen
Gibt den vollständigen Code der Zieldatei zurück
Enthält Code für alle referenzierten Objekte aus anderen Dateien
Fügt zusätzliche Kontextdateien aus demselben Verzeichnis hinzu
Beachtet Token-Grenzen, um eine Überlastung der Sprachmodelle zu vermeiden
Installation
# Clone the repository
git clone https://github.com/yourusername/python-mcp-new.git
cd python-mcp-new
# Create a virtual environment
python -m venv venv
source venv/bin/activate # On Windows, use: venv\Scripts\activate
# Install dependencies
pip install -r requirements.txtUmgebungsvariablen
Erstellen Sie eine .env Datei basierend auf dem bereitgestellten .env.example :
# Token limit for extraction
TOKEN_LIMIT=8000Verwendung
Konfigurieren für MCP-Clients
Um diesen MCP-Server für die Verwendung in MCP-kompatiblen Clients (wie Codeium Windsurf) zu konfigurieren, fügen Sie der MCP-Konfigurationsdatei Ihres Clients die folgende Konfiguration hinzu:
{
"mcpServers": {
"python-code-explorer": {
"command": "python",
"args": [
"/path/to/python-mcp-new/server.py"
],
"env": {
"TOKEN_LIMIT": "8000"
}
}
}
}Ersetzen Sie /path/to/python-mcp-new/server.py durch den absoluten Pfad zur Datei server.py auf Ihrem System.
Sie können die Umgebungsvariablen auch anpassen:
TOKEN_LIMIT: Maximales Token-Limit für die Codeextraktion (Standard: 8000)
Anwendungsbeispiele
Direkter Funktionsaufruf
from agent import get_python_code
# Get Python code structure for a specific file
result = get_python_code(
target_file="/home/user/project/main.py",
root_repo_path="/home/user/project" # Optional, defaults to target file directory
)
# Process the result
target_file = result["target_file"]
print(f"Main file: {target_file['file_path']}")
print(f"Docstring: {target_file['docstring']}")
# Display related files
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']}")
# See if we're close to the token limit
print(f"Token usage: {result['token_count']}/{result['token_limit']}")Beispielantwort (direkter Funktionsaufruf)
{
"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
}Verwenden des MCP-Protokolls
Auflisten der verfügbaren Tools
from agent import handle_mcp_request
import json
# List available tools
list_request = {
"jsonrpc": "2.0",
"id": 1,
"method": "tools/list"
}
response = handle_mcp_request(list_request)
print(json.dumps(response, indent=2))Beispielantwort (Tools/Liste)
{
"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"]
}
}
]
}
}Aufrufen des Tools get_python_code
from agent import handle_mcp_request
import json
# Call the get_python_code tool
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))Beispielantwort (Tools/Aufruf)
{
"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
}
}Fehlerbehandlung
from agent import handle_mcp_request
# Call with invalid file path
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))Beispiel für eine Fehlerantwort
{
"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
}
}Testen
Führen Sie die Tests aus, um die Funktionalität zu überprüfen:
python -m unittest discover testsSchlüsselkomponenten
agent.py : Enthält die Funktion
get_python_codeund benutzerdefinierte MCP-Protokollhandlercode_grapher.py : Implementiert die
CodeGrapherKlasse für die Python-Codeanalyseserver.py : Vollständige MCP-Serverimplementierung mit dem MCP Python SDK
run_server.py : CLI-Tool zum Ausführen des MCP-Servers
Beispiele/ : Beispielskripte, die die Verwendung des MCP-Servers und -Clients zeigen
tests/ : Umfassende Testfälle für alle Funktionen
Details zum Antwortformat
Das Tool get_python_code gibt ein strukturiertes JSON-Objekt mit den folgenden Feldern zurück:
Feld | Typ | Beschreibung |
| Objekt | Informationen zur Ziel-Python-Datei |
| Array | Liste der von der Zieldatei importierten Objekte |
| Array | Zusätzliche Kontextdateien aus demselben Verzeichnis |
| Nummer | Gesamtzahl der in der Antwort enthaltenen Dateien |
| Nummer | Ungefähre Anzahl der Token im gesamten enthaltenen Code |
| Nummer | Maximales Token-Limit für die Extraktion konfiguriert |
Zieldateiobjekt
Feld | Typ | Beschreibung |
| Zeichenfolge | Relativer Pfad zur Datei vom Repository-Stamm |
| Zeichenfolge | Vollständiger Quellcode der Datei |
| Zeichenfolge | Immer "Ziel" |
| Zeichenfolge | Docstring auf Modulebene, falls verfügbar |
Referenziertes Dateiobjekt
Feld | Typ | Beschreibung |
| Zeichenfolge | Relativer Pfad zur Datei |
| Zeichenfolge | Name des importierten Objekts (Klasse, Funktion usw.) |
| Zeichenfolge | Typ des Objekts („Klasse“, „Funktion“ usw.) |
| Zeichenfolge | Quellcode des spezifischen Objekts |
| Zeichenfolge | Docstring des Objekts, falls verfügbar |
| Boolesch | Ob der Code aufgrund von Token-Limits gekürzt wurde |
Zusätzliches Dateiobjekt
Feld | Typ | Beschreibung |
| Zeichenfolge | Relativer Pfad zur Datei |
| Zeichenfolge | Vollständiger Quellcode der Datei |
| Zeichenfolge | Art der Beziehung (z. B. „related_by_directory“) |
| Zeichenfolge | Docstring auf Modulebene, falls verfügbar |
Verwenden des MCP SDK-Servers
Dieses Projekt umfasst nun einen voll funktionsfähigen Model Context Protocol (MCP)-Server, der mit dem offiziellen Python MCP SDK erstellt wurde. Der Server stellt unsere Codeextraktionsfunktionalität standardisiert bereit und kann mit jedem MCP-Client, einschließlich Claude Desktop, verwendet werden.
Starten des Servers
# Start the server with default settings
python run_server.py
# Specify a custom name
python run_server.py --name "My Code Explorer"
# Use a specific .env file
python run_server.py --env-file .env.productionVerwenden des MCP-Entwicklungsmodus
Wenn das MCP SDK installiert ist, können Sie den Server mithilfe der MCP-CLI im Entwicklungsmodus ausführen:
# Install the MCP CLI
pip install "mcp[cli]"
# Start the server in development mode with the Inspector UI
mcp dev server.pyDadurch wird der MCP Inspector gestartet, eine Weboberfläche zum Testen und Debuggen Ihres Servers.
Claude Desktop Integration
Sie können den Server in Claude Desktop installieren, um direkt von Claude aus auf Ihre Code-Explorationstools zuzugreifen:
# Install the server in Claude Desktop
mcp install server.py
# With custom configuration
mcp install server.py --name "Python Code Explorer" -f .envBenutzerdefinierte Serverbereitstellung
Für benutzerdefinierte Bereitstellungen können Sie den MCP-Server direkt verwenden:
from server import mcp
# Configure the server
mcp.name = "Custom Code Explorer"
# Run the server
mcp.run()Verwenden des MCP-Clients
Sie können das MCP Python SDK verwenden, um programmgesteuert eine Verbindung zum Server herzustellen. Siehe das bereitgestellte Beispiel in examples/mcp_client_example.py :
from mcp.client import Client, Transport
# Connect to the server
client = Client(Transport.subprocess(["python", "server.py"]))
client.initialize()
# List available tools
for tool in client.tools:
print(f"Tool: {tool.name}")
# Use the get_code tool
result = client.tools.get_code(target_file="path/to/your/file.py")
print(f"Found {len(result['referenced_files'])} referenced files")
# Clean up
client.shutdown()Führen Sie das Beispiel aus:
python examples/mcp_client_example.py [optional_target_file.py]Hinzufügen zusätzlicher Tools
Sie können dem MCP-Server zusätzliche Tools hinzufügen, indem Sie Funktionen mit dem Dekorator @mcp.tool() in server.py dekorieren:
@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()]Sie können auch Ressourcenendpunkte hinzufügen, um Daten direkt bereitzustellen:
@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 statsModellkontextprotokollintegration
Dieses Projekt berücksichtigt den Model Context Protocol (MCP)-Standard vollständig und bietet zwei Implementierungsoptionen:
Native MCP-Integration : Die ursprüngliche Implementierung in
agent.pybietet eine direkte JSON-RPC-Schnittstelle, die mit MCP kompatibel ist.MCP SDK-Integration : Die neue Implementierung in
server.pynutzt das offizielle MCP Python SDK für eine robustere und funktionsreichere Erfahrung.
Vorteile der MCP-Integration
Standardisierte Schnittstelle : Macht Ihre Tools jedem MCP-kompatiblen Client verfügbar
Verbesserte Sicherheit : Integriertes Berechtigungsmodell und Ressourcenkontrollen
Bessere LLM-Integration : Nahtlose Integration mit Claude Desktop und anderen LLM-Plattformen
Verbesserte Entwicklererfahrung : Umfassende Tools wie der MCP Inspector
MCP-Protokollversion
Diese Implementierung unterstützt das MCP-Protokoll Version 0.7.0.
Weitere Informationen zu MCP finden Sie in der offiziellen Dokumentation .
This server cannot be installed
Maintenance
Related MCP Servers
- AlicenseBqualityFmaintenanceA Model Context Protocol server that enables LLMs to read, search, and analyze code files with advanced caching and real-time file watching capabilities.61339MIT
- FlicenseDqualityDmaintenanceA comprehensive Model Context Protocol server for advanced code analysis that provides tools for syntax analysis, dependency visualization, and AI-assisted development workflow support.287

CodeAlive MCPofficial
AlicenseNot gradedqualityAmaintenanceA Model Context Protocol server that enhances AI agents by providing deep semantic understanding of codebases, enabling more intelligent interactions through advanced code search and contextual awareness.88MIT- AlicenseNot gradedqualityDmaintenanceA Model Context Protocol server that analyzes application codebases with real-time file watching, providing AI assistants like Claude with deep insights into project structure, code patterns, and architecture.MIT
Related MCP Connectors
A comprehensive Model Context Protocol (MCP) server that enables AI assistants to interact with yo…
A Model Context Protocol server for Wix AI tools
Deterministic context layer for your codebase: change impact, blast radius, answers with receipts.
Appeared in Searches
- A guide to Python dependency resolution and package management
- A tool for analyzing Python repository structure and code relationships
- AI tools for debugging Python code
- A tool or method for searching a codebase and providing relevant context
- A search for information about Vetctorcode or related content
Latest Blog Posts
- Who's Calling? MCP Hosts Are an Identity Blind Spot (And the Spec Knows It)By Om-Shree-0709 on .mcpAgent IdentityOAuth 2.1
- Your AI Chatbot Just Exposed Your CEO's Salary to an InternBy Om-Shree-0709 on .Agent IdentityMCP SecurityOAuth Delegation
- Why MCP Servers Need Execution Sandboxing (And Why Your Current Stack Isn't Enough)By Om-Shree-0709 on .Agentic AiPrompt InjectionWebAssembly
MCP directory API
We provide all the information about MCP servers via our MCP API.
curl -X GET 'https://glama.ai/api/mcp/v1/servers/hesiod-au/python-mcp'
If you have feedback or need assistance with the MCP directory API, please join our Discord server