Skip to content

Commit 9d39c09

Browse files
authored
Merge pull request aden-hive#973 from AryanyAI/refactor/logging-mcp-scripts
refactor(mcp): replace print() with logging in setup scripts
2 parents 6acdb65 + 407816d commit 9d39c09

3 files changed

Lines changed: 140 additions & 92 deletions

File tree

core/setup_mcp.py

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

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

15+
logger = logging.getLogger(__name__)
16+
17+
18+
def setup_logger():
19+
"""Configure logger for CLI usage with colored output."""
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+
1427

1528
class Colors:
1629
"""ANSI color codes for terminal output."""
@@ -22,19 +35,19 @@ class Colors:
2235
NC = "\033[0m" # No Color
2336

2437

25-
def print_step(message: str, color: str = Colors.YELLOW):
26-
"""Print a colored step message."""
27-
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}")
2841

2942

30-
def print_success(message: str):
31-
"""Print a success message."""
32-
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}")
3346

3447

35-
def print_error(message: str):
36-
"""Print an error message."""
37-
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}")
3851

3952

4053
def run_command(cmd: list, error_msg: str) -> bool:
@@ -43,52 +56,53 @@ def run_command(cmd: list, error_msg: str) -> bool:
4356
subprocess.run(cmd, check=True, capture_output=True, text=True)
4457
return True
4558
except subprocess.CalledProcessError as e:
46-
print_error(error_msg)
47-
print(f"Error output: {e.stderr}", file=sys.stderr)
59+
log_error(error_msg)
60+
logger.error(f"Error output: {e.stderr}")
4861
return False
4962

5063

5164
def main():
5265
"""Main setup function."""
53-
print("=== Aden Hive Framework MCP Server Setup ===")
54-
print()
66+
setup_logger()
67+
logger.info("=== Aden Hive Framework MCP Server Setup ===")
68+
logger.info("")
5569

5670
# Get script directory
5771
script_dir = Path(__file__).parent.absolute()
5872
os.chdir(script_dir)
5973

6074
# Step 1: Install framework package
61-
print_step("Step 1: Installing framework package...")
75+
log_step("Step 1: Installing framework package...")
6276
if not run_command(
6377
[sys.executable, "-m", "pip", "install", "-e", "."], "Failed to install framework package"
6478
):
6579
sys.exit(1)
66-
print_success("Framework package installed")
67-
print()
80+
log_success("Framework package installed")
81+
logger.info("")
6882

6983
# Step 2: Install MCP dependencies
70-
print_step("Step 2: Installing MCP dependencies...")
84+
log_step("Step 2: Installing MCP dependencies...")
7185
if not run_command(
7286
[sys.executable, "-m", "pip", "install", "mcp", "fastmcp"],
7387
"Failed to install MCP dependencies",
7488
):
7589
sys.exit(1)
76-
print_success("MCP dependencies installed")
77-
print()
90+
log_success("MCP dependencies installed")
91+
logger.info("")
7892

7993
# Step 3: Verify/create MCP configuration
80-
print_step("Step 3: Verifying MCP server configuration...")
94+
log_step("Step 3: Verifying MCP server configuration...")
8195
mcp_config_path = script_dir / ".mcp.json"
8296

8397
if mcp_config_path.exists():
84-
print_success("MCP configuration found at .mcp.json")
85-
print("Configuration:")
98+
log_success("MCP configuration found at .mcp.json")
99+
logger.info("Configuration:")
86100
with open(mcp_config_path) as f:
87101
config = json.load(f)
88-
print(json.dumps(config, indent=2))
102+
logger.info(json.dumps(config, indent=2))
89103
else:
90-
print_error("No .mcp.json found")
91-
print("Creating default MCP configuration...")
104+
log_error("No .mcp.json found")
105+
logger.info("Creating default MCP configuration...")
92106

93107
config = {
94108
"mcpServers": {
@@ -103,11 +117,11 @@ def main():
103117
with open(mcp_config_path, "w") as f:
104118
json.dump(config, f, indent=2)
105119

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

109123
# Step 4: Test MCP server
110-
print_step("Step 4: Testing MCP server...")
124+
log_step("Step 4: Testing MCP server...")
111125
try:
112126
# Try importing the MCP server module
113127
subprocess.run(
@@ -116,27 +130,27 @@ def main():
116130
capture_output=True,
117131
text=True,
118132
)
119-
print_success("MCP server module verified")
133+
log_success("MCP server module verified")
120134
except subprocess.CalledProcessError as e:
121-
print_error("Failed to import MCP server module")
122-
print(f"Error: {e.stderr}", file=sys.stderr)
135+
log_error("Failed to import MCP server module")
136+
logger.error(f"Error: {e.stderr}")
123137
sys.exit(1)
124-
print()
138+
logger.info("")
125139

126140
# 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()
141+
logger.info(f"{Colors.GREEN}=== Setup Complete ==={Colors.NC}")
142+
logger.info("")
143+
logger.info("The MCP server is now ready to use!")
144+
logger.info("")
145+
logger.info(f"{Colors.BLUE}To start the MCP server manually:{Colors.NC}")
146+
logger.info(" python -m framework.mcp.agent_builder_server")
147+
logger.info("")
148+
logger.info(f"{Colors.BLUE}MCP Configuration location:{Colors.NC}")
149+
logger.info(f" {mcp_config_path}")
150+
logger.info("")
151+
logger.info(f"{Colors.BLUE}To use with Claude Desktop or other MCP clients,{Colors.NC}")
152+
logger.info(f"{Colors.BLUE}add the following to your MCP client configuration:{Colors.NC}")
153+
logger.info("")
140154

141155
example_config = {
142156
"mcpServers": {
@@ -147,8 +161,8 @@ def main():
147161
}
148162
}
149163
}
150-
print(json.dumps(example_config, indent=2))
151-
print()
164+
logger.info(json.dumps(example_config, indent=2))
165+
logger.info("")
152166

153167

154168
if __name__ == "__main__":

core/verify_mcp.py

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

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

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

1427
class Colors:
1528
GREEN = "\033[0;32m"
@@ -21,29 +34,31 @@ class Colors:
2134

2235
def check(description: str) -> bool:
2336
"""Print check description and return a context manager for result."""
24-
print(f"Checking {description}...", end=" ")
37+
logger.info(f"Checking {description}... ", extra={"end": ""})
38+
sys.stdout.flush()
2539
return True
2640

2741

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

3246

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

3751

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

4256

4357
def main():
4458
"""Run verification checks."""
45-
print("=== MCP Server Verification ===")
46-
print()
59+
setup_logger()
60+
logger.info("=== MCP Server Verification ===")
61+
logger.info("")
4762

4863
script_dir = Path(__file__).parent.absolute()
4964
all_checks_passed = True
@@ -61,7 +76,7 @@ def main():
6176
success(f"installed at {framework_path}")
6277
except subprocess.CalledProcessError:
6378
error("framework package not found")
64-
print(f" Run: pip install -e {script_dir}")
79+
logger.info(f" Run: pip install -e {script_dir}")
6580
all_checks_passed = False
6681

6782
# Check 2: MCP dependencies
@@ -75,7 +90,7 @@ def main():
7590

7691
if missing_deps:
7792
error(f"missing: {', '.join(missing_deps)}")
78-
print(f" Run: pip install {' '.join(missing_deps)}")
93+
logger.info(f" Run: pip install {' '.join(missing_deps)}")
7994
all_checks_passed = False
8095
else:
8196
success("all installed")
@@ -92,7 +107,7 @@ def main():
92107
success("loads successfully")
93108
except subprocess.CalledProcessError as e:
94109
error("failed to import")
95-
print(f" Error: {e.stderr}")
110+
logger.error(f" Error: {e.stderr}")
96111
all_checks_passed = False
97112

98113
# Check 4: MCP configuration file
@@ -106,9 +121,9 @@ def main():
106121
if "mcpServers" in config and "agent-builder" in config["mcpServers"]:
107122
server_config = config["mcpServers"]["agent-builder"]
108123
success("found and valid")
109-
print(f" Command: {server_config.get('command')}")
110-
print(f" Args: {' '.join(server_config.get('args', []))}")
111-
print(f" CWD: {server_config.get('cwd')}")
124+
logger.info(f" Command: {server_config.get('command')}")
125+
logger.info(f" Args: {' '.join(server_config.get('args', []))}")
126+
logger.info(f" CWD: {server_config.get('cwd')}")
112127
else:
113128
warning("exists but missing agent-builder config")
114129
all_checks_passed = False
@@ -117,8 +132,8 @@ def main():
117132
all_checks_passed = False
118133
else:
119134
warning("not found (optional)")
120-
print(f" Location would be: {mcp_config}")
121-
print(" Run setup_mcp.py to create it")
135+
logger.info(f" Location would be: {mcp_config}")
136+
logger.info(" Run setup_mcp.py to create it")
122137

123138
# Check 5: Framework modules
124139
check("core framework modules")
@@ -168,28 +183,28 @@ def main():
168183
warning("server startup slow (might be OK)")
169184
except subprocess.CalledProcessError as e:
170185
error("server failed to start")
171-
print(f" Error: {e.stderr}")
186+
logger.error(f" Error: {e.stderr}")
172187
all_checks_passed = False
173188

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

194209

195210
if __name__ == "__main__":

0 commit comments

Comments
 (0)