Skip to content

Commit 82c32e8

Browse files
committed
refactor(mcp): replace print() with logging in setup scripts
Replace direct print() statements with Python's logging module in MCP setup and verification scripts for better configurability and production readiness. Changes: - setup_mcp.py: Convert 30+ print() calls to structured logging - verify_mcp.py: Convert 40+ print() calls to structured logging - mcp_server.py: Convert 4 print() calls to structured logging - Preserve colored CLI output using logging formatters - Maintain all functional behavior (refactor only) Benefits: - Configurable log levels (debug/info/warning/error) - Better observability in production environments - Cleaner programmatic usage (no stdout pollution) - Professional logging practices Fixes aden-hive#833
1 parent 0233065 commit 82c32e8

3 files changed

Lines changed: 137 additions & 86 deletions

File tree

core/setup_mcp.py

Lines changed: 62 additions & 47 deletions
Original file line numberDiff line numberDiff line change
@@ -6,11 +6,25 @@
66
"""
77

88
import json
9+
import logging
910
import os
1011
import subprocess
1112
import sys
1213
from pathlib import Path
1314

15+
# Configure logger
16+
logger = logging.getLogger(__name__)
17+
18+
19+
def setup_logger():
20+
"""Configure logger for CLI usage with colored output."""
21+
if not logger.handlers:
22+
handler = logging.StreamHandler(sys.stdout)
23+
formatter = logging.Formatter('%(message)s')
24+
handler.setFormatter(formatter)
25+
logger.addHandler(handler)
26+
logger.setLevel(logging.INFO)
27+
1428

1529
class Colors:
1630
"""ANSI color codes for terminal output."""
@@ -21,19 +35,19 @@ class Colors:
2135
NC = '\033[0m' # No Color
2236

2337

24-
def print_step(message: str, color: str = Colors.YELLOW):
25-
"""Print a colored step message."""
26-
print(f"{color}{message}{Colors.NC}")
38+
def log_step(message: str):
39+
"""Log a colored step message."""
40+
logger.info(f"{Colors.YELLOW}{message}{Colors.NC}")
2741

2842

29-
def print_success(message: str):
30-
"""Print a success message."""
31-
print(f"{Colors.GREEN}{message}{Colors.NC}")
43+
def log_success(message: str):
44+
"""Log a success message."""
45+
logger.info(f"{Colors.GREEN}{message}{Colors.NC}")
3246

3347

34-
def print_error(message: str):
35-
"""Print an error message."""
36-
print(f"{Colors.RED}{message}{Colors.NC}", file=sys.stderr)
48+
def log_error(message: str):
49+
"""Log an error message."""
50+
logger.error(f"{Colors.RED}{message}{Colors.NC}")
3751

3852

3953
def run_command(cmd: list, error_msg: str) -> bool:
@@ -42,53 +56,54 @@ def run_command(cmd: list, error_msg: str) -> bool:
4256
subprocess.run(cmd, check=True, capture_output=True, text=True)
4357
return True
4458
except subprocess.CalledProcessError as e:
45-
print_error(error_msg)
46-
print(f"Error output: {e.stderr}", file=sys.stderr)
59+
log_error(error_msg)
60+
logger.error(f"Error output: {e.stderr}")
4761
return False
4862

4963

5064
def main():
5165
"""Main setup function."""
52-
print("=== Aden Hive Framework MCP Server Setup ===")
53-
print()
66+
setup_logger()
67+
logger.info("=== Aden Hive Framework MCP Server Setup ===")
68+
logger.info("")
5469

5570
# Get script directory
5671
script_dir = Path(__file__).parent.absolute()
5772
os.chdir(script_dir)
5873

5974
# Step 1: Install framework package
60-
print_step("Step 1: Installing framework package...")
75+
log_step("Step 1: Installing framework package...")
6176
if not run_command(
6277
[sys.executable, "-m", "pip", "install", "-e", "."],
6378
"Failed to install framework package"
6479
):
6580
sys.exit(1)
66-
print_success("Framework package installed")
67-
print()
81+
log_success("Framework package installed")
82+
logger.info("")
6883

6984
# Step 2: Install MCP dependencies
70-
print_step("Step 2: Installing MCP dependencies...")
85+
log_step("Step 2: Installing MCP dependencies...")
7186
if not run_command(
7287
[sys.executable, "-m", "pip", "install", "mcp", "fastmcp"],
7388
"Failed to install MCP dependencies"
7489
):
7590
sys.exit(1)
76-
print_success("MCP dependencies installed")
77-
print()
91+
log_success("MCP dependencies installed")
92+
logger.info("")
7893

7994
# Step 3: Verify/create MCP configuration
80-
print_step("Step 3: Verifying MCP server configuration...")
95+
log_step("Step 3: Verifying MCP server configuration...")
8196
mcp_config_path = script_dir / ".mcp.json"
8297

8398
if mcp_config_path.exists():
84-
print_success("MCP configuration found at .mcp.json")
85-
print("Configuration:")
99+
log_success("MCP configuration found at .mcp.json")
100+
logger.info("Configuration:")
86101
with open(mcp_config_path) as f:
87102
config = json.load(f)
88-
print(json.dumps(config, indent=2))
103+
logger.info(json.dumps(config, indent=2))
89104
else:
90-
print_error("No .mcp.json found")
91-
print("Creating default MCP configuration...")
105+
log_error("No .mcp.json found")
106+
logger.info("Creating default MCP configuration...")
92107

93108
config = {
94109
"mcpServers": {
@@ -103,11 +118,11 @@ def main():
103118
with open(mcp_config_path, 'w') as f:
104119
json.dump(config, f, indent=2)
105120

106-
print_success("Created .mcp.json")
107-
print()
121+
log_success("Created .mcp.json")
122+
logger.info("")
108123

109124
# Step 4: Test MCP server
110-
print_step("Step 4: Testing MCP server...")
125+
log_step("Step 4: Testing MCP server...")
111126
try:
112127
# Try importing the MCP server module
113128
subprocess.run(
@@ -116,27 +131,27 @@ def main():
116131
capture_output=True,
117132
text=True
118133
)
119-
print_success("MCP server module verified")
134+
log_success("MCP server module verified")
120135
except subprocess.CalledProcessError as e:
121-
print_error("Failed to import MCP server module")
122-
print(f"Error: {e.stderr}", file=sys.stderr)
136+
log_error("Failed to import MCP server module")
137+
logger.error(f"Error: {e.stderr}")
123138
sys.exit(1)
124-
print()
139+
logger.info("")
125140

126141
# Success summary
127-
print(f"{Colors.GREEN}=== Setup Complete ==={Colors.NC}")
128-
print()
129-
print("The MCP server is now ready to use!")
130-
print()
131-
print(f"{Colors.BLUE}To start the MCP server manually:{Colors.NC}")
132-
print(" python -m framework.mcp.agent_builder_server")
133-
print()
134-
print(f"{Colors.BLUE}MCP Configuration location:{Colors.NC}")
135-
print(f" {mcp_config_path}")
136-
print()
137-
print(f"{Colors.BLUE}To use with Claude Desktop or other MCP clients,{Colors.NC}")
138-
print(f"{Colors.BLUE}add the following to your MCP client configuration:{Colors.NC}")
139-
print()
142+
logger.info(f"{Colors.GREEN}=== Setup Complete ==={Colors.NC}")
143+
logger.info("")
144+
logger.info("The MCP server is now ready to use!")
145+
logger.info("")
146+
logger.info(f"{Colors.BLUE}To start the MCP server manually:{Colors.NC}")
147+
logger.info(" python -m framework.mcp.agent_builder_server")
148+
logger.info("")
149+
logger.info(f"{Colors.BLUE}MCP Configuration location:{Colors.NC}")
150+
logger.info(f" {mcp_config_path}")
151+
logger.info("")
152+
logger.info(f"{Colors.BLUE}To use with Claude Desktop or other MCP clients,{Colors.NC}")
153+
logger.info(f"{Colors.BLUE}add the following to your MCP client configuration:{Colors.NC}")
154+
logger.info("")
140155

141156
example_config = {
142157
"mcpServers": {
@@ -147,8 +162,8 @@ def main():
147162
}
148163
}
149164
}
150-
print(json.dumps(example_config, indent=2))
151-
print()
165+
logger.info(json.dumps(example_config, indent=2))
166+
logger.info("")
152167

153168

154169
if __name__ == "__main__":

core/verify_mcp.py

Lines changed: 51 additions & 35 deletions
Original file line numberDiff line numberDiff line change
@@ -6,10 +6,24 @@
66
"""
77

88
import json
9+
import logging
910
import subprocess
1011
import sys
1112
from pathlib import Path
1213

14+
# Configure logger
15+
logger = logging.getLogger(__name__)
16+
17+
18+
def setup_logger():
19+
"""Configure logger for CLI usage."""
20+
if not logger.handlers:
21+
handler = logging.StreamHandler(sys.stdout)
22+
formatter = logging.Formatter('%(message)s')
23+
handler.setFormatter(formatter)
24+
logger.addHandler(handler)
25+
logger.setLevel(logging.INFO)
26+
1327

1428
class Colors:
1529
GREEN = '\033[0;32m'
@@ -21,29 +35,31 @@ class Colors:
2135

2236
def check(description: str) -> bool:
2337
"""Print check description and return a context manager for result."""
24-
print(f"Checking {description}...", end=" ")
38+
logger.info(f"Checking {description}... ", extra={'end': ''})
39+
sys.stdout.flush()
2540
return True
2641

2742

2843
def success(msg: str = "OK"):
29-
"""Print success message."""
30-
print(f"{Colors.GREEN}{msg}{Colors.NC}")
44+
"""Log success message."""
45+
logger.info(f"{Colors.GREEN}{msg}{Colors.NC}")
3146

3247

3348
def warning(msg: str):
34-
"""Print warning message."""
35-
print(f"{Colors.YELLOW}{msg}{Colors.NC}")
49+
"""Log warning message."""
50+
logger.warning(f"{Colors.YELLOW}{msg}{Colors.NC}")
3651

3752

3853
def error(msg: str):
39-
"""Print error message."""
40-
print(f"{Colors.RED}{msg}{Colors.NC}")
54+
"""Log error message."""
55+
logger.error(f"{Colors.RED}{msg}{Colors.NC}")
4156

4257

4358
def main():
4459
"""Run verification checks."""
45-
print("=== MCP Server Verification ===")
46-
print()
60+
setup_logger()
61+
logger.info("=== MCP Server Verification ===")
62+
logger.info("")
4763

4864
script_dir = Path(__file__).parent.absolute()
4965
all_checks_passed = True
@@ -61,7 +77,7 @@ def main():
6177
success(f"installed at {framework_path}")
6278
except subprocess.CalledProcessError:
6379
error("framework package not found")
64-
print(f" Run: pip install -e {script_dir}")
80+
logger.info(f" Run: pip install -e {script_dir}")
6581
all_checks_passed = False
6682

6783
# Check 2: MCP dependencies
@@ -79,7 +95,7 @@ def main():
7995

8096
if missing_deps:
8197
error(f"missing: {', '.join(missing_deps)}")
82-
print(f" Run: pip install {' '.join(missing_deps)}")
98+
logger.info(f" Run: pip install {' '.join(missing_deps)}")
8399
all_checks_passed = False
84100
else:
85101
success("all installed")
@@ -96,7 +112,7 @@ def main():
96112
success("loads successfully")
97113
except subprocess.CalledProcessError as e:
98114
error("failed to import")
99-
print(f" Error: {e.stderr}")
115+
logger.error(f" Error: {e.stderr}")
100116
all_checks_passed = False
101117

102118
# Check 4: MCP configuration file
@@ -110,9 +126,9 @@ def main():
110126
if "mcpServers" in config and "agent-builder" in config["mcpServers"]:
111127
server_config = config["mcpServers"]["agent-builder"]
112128
success("found and valid")
113-
print(f" Command: {server_config.get('command')}")
114-
print(f" Args: {' '.join(server_config.get('args', []))}")
115-
print(f" CWD: {server_config.get('cwd')}")
129+
logger.info(f" Command: {server_config.get('command')}")
130+
logger.info(f" Args: {' '.join(server_config.get('args', []))}")
131+
logger.info(f" CWD: {server_config.get('cwd')}")
116132
else:
117133
warning("exists but missing agent-builder config")
118134
all_checks_passed = False
@@ -121,8 +137,8 @@ def main():
121137
all_checks_passed = False
122138
else:
123139
warning("not found (optional)")
124-
print(f" Location would be: {mcp_config}")
125-
print(" Run setup_mcp.py to create it")
140+
logger.info(f" Location would be: {mcp_config}")
141+
logger.info(" Run setup_mcp.py to create it")
126142

127143
# Check 5: Framework modules
128144
check("core framework modules")
@@ -171,28 +187,28 @@ def main():
171187
warning("server startup slow (might be OK)")
172188
except subprocess.CalledProcessError as e:
173189
error("server failed to start")
174-
print(f" Error: {e.stderr}")
190+
logger.error(f" Error: {e.stderr}")
175191
all_checks_passed = False
176192

177-
print()
178-
print("=" * 40)
193+
logger.info("")
194+
logger.info("=" * 40)
179195
if all_checks_passed:
180-
print(f"{Colors.GREEN}✓ All checks passed!{Colors.NC}")
181-
print()
182-
print("Your MCP server is ready to use.")
183-
print()
184-
print(f"{Colors.BLUE}To start the server:{Colors.NC}")
185-
print(" python -m framework.mcp.agent_builder_server")
186-
print()
187-
print(f"{Colors.BLUE}To use with Claude Desktop:{Colors.NC}")
188-
print(" Add the configuration from .mcp.json to your")
189-
print(" Claude Desktop MCP settings")
196+
logger.info(f"{Colors.GREEN}✓ All checks passed!{Colors.NC}")
197+
logger.info("")
198+
logger.info("Your MCP server is ready to use.")
199+
logger.info("")
200+
logger.info(f"{Colors.BLUE}To start the server:{Colors.NC}")
201+
logger.info(" python -m framework.mcp.agent_builder_server")
202+
logger.info("")
203+
logger.info(f"{Colors.BLUE}To use with Claude Desktop:{Colors.NC}")
204+
logger.info(" Add the configuration from .mcp.json to your")
205+
logger.info(" Claude Desktop MCP settings")
190206
else:
191-
print(f"{Colors.RED}✗ Some checks failed{Colors.NC}")
192-
print()
193-
print("To fix issues, run:")
194-
print(f" python {script_dir / 'setup_mcp.py'}")
195-
print()
207+
logger.info(f"{Colors.RED}✗ Some checks failed{Colors.NC}")
208+
logger.info("")
209+
logger.info("To fix issues, run:")
210+
logger.info(f" python {script_dir / 'setup_mcp.py'}")
211+
logger.info("")
196212

197213

198214
if __name__ == "__main__":

0 commit comments

Comments
 (0)