-
Notifications
You must be signed in to change notification settings - Fork 2k
Expand file tree
/
Copy pathcode_implementation_server.py
More file actions
1517 lines (1273 loc) · 51 KB
/
code_implementation_server.py
File metadata and controls
1517 lines (1273 loc) · 51 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
#!/usr/bin/env python3
"""
Code Implementation MCP Server
This MCP server provides core functions needed for paper code reproduction:
1. File read/write operations
2. Code execution and testing
3. Code search and analysis
4. Iterative improvement support
Usage:
python tools/code_implementation_server.py
"""
import os
import subprocess
import json
import sys
import io
from pathlib import Path
import re
from typing import Dict, Any, List
import tempfile
import shutil
import logging
from datetime import datetime
# Set standard output encoding to UTF-8
if sys.stdout.encoding != "utf-8":
try:
if hasattr(sys.stdout, "reconfigure"):
sys.stdout.reconfigure(encoding="utf-8")
sys.stderr.reconfigure(encoding="utf-8")
else:
sys.stdout = io.TextIOWrapper(sys.stdout.detach(), encoding="utf-8")
sys.stderr = io.TextIOWrapper(sys.stderr.detach(), encoding="utf-8")
except Exception as e:
print(f"Warning: Could not set UTF-8 encoding: {e}")
# Import MCP related modules
from mcp.server.fastmcp import FastMCP
# Setup logging
logging.basicConfig(level=logging.INFO)
logger = logging.getLogger(__name__)
# Create FastMCP server instance
mcp = FastMCP("code-implementation-server")
# Global variables: workspace directory and operation history
WORKSPACE_DIR = None
OPERATION_HISTORY = []
CURRENT_FILES = {}
def initialize_workspace(workspace_dir: str = None):
"""
Initialize workspace
By default, the workspace will be set by the workflow via the set_workspace tool to:
{plan_file_parent}/generate_code
Args:
workspace_dir: Optional workspace directory path
"""
global WORKSPACE_DIR
if workspace_dir is None:
# Default to generate_code directory under current directory, but don't create immediately
# This default value will be overridden by workflow via set_workspace tool
WORKSPACE_DIR = Path.cwd() / "generate_code"
# logger.info(f"Workspace initialized (default value, will be overridden by workflow): {WORKSPACE_DIR}")
# logger.info("Note: Actual workspace will be set by workflow via set_workspace tool to {plan_file_parent}/generate_code")
else:
WORKSPACE_DIR = Path(workspace_dir).resolve()
# Only create when explicitly specified
WORKSPACE_DIR.mkdir(parents=True, exist_ok=True)
logger.info(f"Workspace initialized: {WORKSPACE_DIR}")
def ensure_workspace_exists():
"""Ensure workspace directory exists"""
global WORKSPACE_DIR
if WORKSPACE_DIR is None:
initialize_workspace()
# Create workspace directory (if it doesn't exist)
if not WORKSPACE_DIR.exists():
WORKSPACE_DIR.mkdir(parents=True, exist_ok=True)
logger.info(f"Workspace directory created: {WORKSPACE_DIR}")
def validate_path(path: str) -> Path:
"""Validate if path is within workspace"""
if WORKSPACE_DIR is None:
initialize_workspace()
full_path = (WORKSPACE_DIR / path).resolve()
if not str(full_path).startswith(str(WORKSPACE_DIR)):
raise ValueError(f"Path {path} is outside workspace scope")
return full_path
def log_operation(action: str, details: Dict[str, Any]):
"""Log operation history"""
OPERATION_HISTORY.append(
{"timestamp": datetime.now().isoformat(), "action": action, "details": details}
)
# ==================== File Operation Tools ====================
@mcp.tool()
async def read_file(
file_path: str, start_line: int = None, end_line: int = None
) -> str:
"""
Read file content, supports specifying line number range
Args:
file_path: File path, relative to workspace
start_line: Starting line number (1-based, optional)
end_line: Ending line number (1-based, optional)
Returns:
JSON string of file content or error message
"""
try:
full_path = validate_path(file_path)
if not full_path.exists():
result = {"status": "error", "message": f"File does not exist: {file_path}"}
log_operation(
"read_file_error", {"file_path": file_path, "error": "file_not_found"}
)
return json.dumps(result, ensure_ascii=False, indent=2)
with open(full_path, "r", encoding="utf-8") as f:
lines = f.readlines()
# 处理行号范围
if start_line is not None or end_line is not None:
start_idx = (start_line - 1) if start_line else 0
end_idx = end_line if end_line else len(lines)
lines = lines[start_idx:end_idx]
content = "".join(lines)
result = {
"status": "success",
"content": content,
"file_path": file_path,
"total_lines": len(lines),
"size_bytes": len(content.encode("utf-8")),
}
log_operation(
"read_file",
{
"file_path": file_path,
"start_line": start_line,
"end_line": end_line,
"lines_read": len(lines),
},
)
return json.dumps(result, ensure_ascii=False, indent=2)
except Exception as e:
result = {
"status": "error",
"message": f"Failed to read file: {str(e)}",
"file_path": file_path,
}
log_operation("read_file_error", {"file_path": file_path, "error": str(e)})
return json.dumps(result, ensure_ascii=False, indent=2)
@mcp.tool()
async def read_multiple_files(file_requests: str, max_files: int = 5) -> str:
"""
Read multiple files in a single operation (for batch reading)
Args:
file_requests: JSON string with file requests, e.g.,
'{"file1.py": {}, "file2.py": {"start_line": 1, "end_line": 10}}'
or simple array: '["file1.py", "file2.py"]'
max_files: Maximum number of files to read in one operation (default: 5)
Returns:
JSON string of operation results for all files
"""
try:
# Parse the file requests
try:
requests_data = json.loads(file_requests)
except json.JSONDecodeError as e:
return json.dumps(
{
"status": "error",
"message": f"Invalid JSON format for file_requests: {str(e)}",
"operation_type": "multi_file",
"timestamp": datetime.now().isoformat(),
},
ensure_ascii=False,
indent=2,
)
# Normalize requests format
if isinstance(requests_data, list):
# Convert simple array to dict format
normalized_requests = {file_path: {} for file_path in requests_data}
elif isinstance(requests_data, dict):
normalized_requests = requests_data
else:
return json.dumps(
{
"status": "error",
"message": "file_requests must be a JSON object or array",
"operation_type": "multi_file",
"timestamp": datetime.now().isoformat(),
},
ensure_ascii=False,
indent=2,
)
# Validate input
if len(normalized_requests) == 0:
return json.dumps(
{
"status": "error",
"message": "No files provided for reading",
"operation_type": "multi_file",
"timestamp": datetime.now().isoformat(),
},
ensure_ascii=False,
indent=2,
)
if len(normalized_requests) > max_files:
return json.dumps(
{
"status": "error",
"message": f"Too many files provided ({len(normalized_requests)}), maximum is {max_files}",
"operation_type": "multi_file",
"timestamp": datetime.now().isoformat(),
},
ensure_ascii=False,
indent=2,
)
# Process each file
results = {
"status": "success",
"message": f"Successfully processed {len(normalized_requests)} files",
"operation_type": "multi_file",
"timestamp": datetime.now().isoformat(),
"files_processed": len(normalized_requests),
"files": {},
"summary": {
"successful": 0,
"failed": 0,
"total_size_bytes": 0,
"total_lines": 0,
"files_not_found": 0,
},
}
# Process each file individually
for file_path, options in normalized_requests.items():
try:
full_path = validate_path(file_path)
start_line = options.get("start_line")
end_line = options.get("end_line")
if not full_path.exists():
results["files"][file_path] = {
"status": "error",
"message": f"File does not exist: {file_path}",
"file_path": file_path,
"content": "",
"total_lines": 0,
"size_bytes": 0,
"start_line": start_line,
"end_line": end_line,
}
results["summary"]["failed"] += 1
results["summary"]["files_not_found"] += 1
continue
with open(full_path, "r", encoding="utf-8") as f:
lines = f.readlines()
# Handle line range
original_line_count = len(lines)
if start_line is not None or end_line is not None:
start_idx = (start_line - 1) if start_line else 0
end_idx = end_line if end_line else len(lines)
lines = lines[start_idx:end_idx]
content = "".join(lines)
size_bytes = len(content.encode("utf-8"))
lines_count = len(lines)
# Record individual file result
results["files"][file_path] = {
"status": "success",
"message": f"File read successfully: {file_path}",
"file_path": file_path,
"content": content,
"total_lines": lines_count,
"original_total_lines": original_line_count,
"size_bytes": size_bytes,
"start_line": start_line,
"end_line": end_line,
"line_range_applied": start_line is not None
or end_line is not None,
}
# Update summary
results["summary"]["successful"] += 1
results["summary"]["total_size_bytes"] += size_bytes
results["summary"]["total_lines"] += lines_count
# Log individual file operation
log_operation(
"read_file_multi",
{
"file_path": file_path,
"start_line": start_line,
"end_line": end_line,
"lines_read": lines_count,
"size_bytes": size_bytes,
"batch_operation": True,
},
)
except Exception as file_error:
# Record individual file error
results["files"][file_path] = {
"status": "error",
"message": f"Failed to read file: {str(file_error)}",
"file_path": file_path,
"content": "",
"total_lines": 0,
"size_bytes": 0,
"start_line": options.get("start_line"),
"end_line": options.get("end_line"),
}
results["summary"]["failed"] += 1
# Log individual file error
log_operation(
"read_file_multi_error",
{
"file_path": file_path,
"error": str(file_error),
"batch_operation": True,
},
)
# Determine overall status
if results["summary"]["failed"] > 0:
if results["summary"]["successful"] > 0:
results["status"] = "partial_success"
results["message"] = (
f"Read {results['summary']['successful']} files successfully, {results['summary']['failed']} failed"
)
else:
results["status"] = "failed"
results["message"] = (
f"All {results['summary']['failed']} files failed to read"
)
# Log overall operation
log_operation(
"read_multiple_files",
{
"files_count": len(normalized_requests),
"successful": results["summary"]["successful"],
"failed": results["summary"]["failed"],
"total_size_bytes": results["summary"]["total_size_bytes"],
"status": results["status"],
},
)
return json.dumps(results, ensure_ascii=False, indent=2)
except Exception as e:
result = {
"status": "error",
"message": f"Failed to read multiple files: {str(e)}",
"operation_type": "multi_file",
"timestamp": datetime.now().isoformat(),
"files_processed": 0,
}
log_operation("read_multiple_files_error", {"error": str(e)})
return json.dumps(result, ensure_ascii=False, indent=2)
@mcp.tool()
async def write_file(
file_path: str, content: str, create_dirs: bool = True, create_backup: bool = False
) -> str:
"""
Write content to file
Args:
file_path: File path, relative to workspace
content: Content to write to file
create_dirs: Whether to create directories if they don't exist
create_backup: Whether to create backup file if file already exists
Returns:
JSON string of operation result
"""
try:
full_path = validate_path(file_path)
# Create directories (if needed)
if create_dirs:
full_path.parent.mkdir(parents=True, exist_ok=True)
# Backup existing file (only when explicitly requested)
backup_created = False
if full_path.exists() and create_backup:
backup_path = full_path.with_suffix(full_path.suffix + ".backup")
shutil.copy2(full_path, backup_path)
backup_created = True
# Write file
with open(full_path, "w", encoding="utf-8") as f:
f.write(content)
# Update current file record
CURRENT_FILES[file_path] = {
"last_modified": datetime.now().isoformat(),
"size_bytes": len(content.encode("utf-8")),
"lines": len(content.split("\n")),
}
result = {
"status": "success",
"message": f"File written successfully: {file_path}",
"file_path": file_path,
"size_bytes": len(content.encode("utf-8")),
"lines_written": len(content.split("\n")),
"backup_created": backup_created,
}
log_operation(
"write_file",
{
"file_path": file_path,
"size_bytes": len(content.encode("utf-8")),
"lines": len(content.split("\n")),
"backup_created": backup_created,
},
)
return json.dumps(result, ensure_ascii=False, indent=2)
except Exception as e:
result = {
"status": "error",
"message": f"Failed to write file: {str(e)}",
"file_path": file_path,
}
log_operation("write_file_error", {"file_path": file_path, "error": str(e)})
return json.dumps(result, ensure_ascii=False, indent=2)
@mcp.tool()
async def write_multiple_files(
file_implementations: str,
create_dirs: bool = True,
create_backup: bool = False,
max_files: int = 5,
) -> str:
"""
Write multiple files in a single operation (for batch implementation)
Args:
file_implementations: JSON string mapping file paths to content, e.g.,
'{"file1.py": "content1", "file2.py": "content2"}'
create_dirs: Whether to create directories if they don't exist
create_backup: Whether to create backup files if they already exist
max_files: Maximum number of files to write in one operation (default: 5)
Returns:
JSON string of operation results for all files
"""
try:
# Parse the file implementations
try:
files_dict = json.loads(file_implementations)
except json.JSONDecodeError as e:
return json.dumps(
{
"status": "error",
"message": f"Invalid JSON format for file_implementations: {str(e)}",
"operation_type": "multi_file",
"timestamp": datetime.now().isoformat(),
},
ensure_ascii=False,
indent=2,
)
# Validate input
if not isinstance(files_dict, dict):
return json.dumps(
{
"status": "error",
"message": "file_implementations must be a JSON object mapping file paths to content",
"operation_type": "multi_file",
"timestamp": datetime.now().isoformat(),
},
ensure_ascii=False,
indent=2,
)
if len(files_dict) == 0:
return json.dumps(
{
"status": "error",
"message": "No files provided for writing",
"operation_type": "multi_file",
"timestamp": datetime.now().isoformat(),
},
ensure_ascii=False,
indent=2,
)
if len(files_dict) > max_files:
return json.dumps(
{
"status": "error",
"message": f"Too many files provided ({len(files_dict)}), maximum is {max_files}",
"operation_type": "multi_file",
"timestamp": datetime.now().isoformat(),
},
ensure_ascii=False,
indent=2,
)
# Process each file
results = {
"status": "success",
"message": f"Successfully processed {len(files_dict)} files",
"operation_type": "multi_file",
"timestamp": datetime.now().isoformat(),
"files_processed": len(files_dict),
"files": {},
"summary": {
"successful": 0,
"failed": 0,
"total_size_bytes": 0,
"total_lines": 0,
"backups_created": 0,
},
}
# Process each file individually
for file_path, content in files_dict.items():
try:
full_path = validate_path(file_path)
# Create directories (if needed)
if create_dirs:
full_path.parent.mkdir(parents=True, exist_ok=True)
# Backup existing file (only when explicitly requested)
backup_created = False
if full_path.exists() and create_backup:
backup_path = full_path.with_suffix(full_path.suffix + ".backup")
shutil.copy2(full_path, backup_path)
backup_created = True
results["summary"]["backups_created"] += 1
# Write file
with open(full_path, "w", encoding="utf-8") as f:
f.write(content)
# Calculate file metrics
size_bytes = len(content.encode("utf-8"))
lines_count = len(content.split("\n"))
# Update current file record
CURRENT_FILES[file_path] = {
"last_modified": datetime.now().isoformat(),
"size_bytes": size_bytes,
"lines": lines_count,
}
# Record individual file result
results["files"][file_path] = {
"status": "success",
"message": f"File written successfully: {file_path}",
"size_bytes": size_bytes,
"lines_written": lines_count,
"backup_created": backup_created,
}
# Update summary
results["summary"]["successful"] += 1
results["summary"]["total_size_bytes"] += size_bytes
results["summary"]["total_lines"] += lines_count
# Log individual file operation
log_operation(
"write_file_multi",
{
"file_path": file_path,
"size_bytes": size_bytes,
"lines": lines_count,
"backup_created": backup_created,
"batch_operation": True,
},
)
except Exception as file_error:
# Record individual file error
results["files"][file_path] = {
"status": "error",
"message": f"Failed to write file: {str(file_error)}",
"size_bytes": 0,
"lines_written": 0,
"backup_created": False,
}
results["summary"]["failed"] += 1
# Log individual file error
log_operation(
"write_file_multi_error",
{
"file_path": file_path,
"error": str(file_error),
"batch_operation": True,
},
)
# Determine overall status
if results["summary"]["failed"] > 0:
if results["summary"]["successful"] > 0:
results["status"] = "partial_success"
results["message"] = (
f"Processed {results['summary']['successful']} files successfully, {results['summary']['failed']} failed"
)
else:
results["status"] = "failed"
results["message"] = (
f"All {results['summary']['failed']} files failed to write"
)
# Log overall operation
log_operation(
"write_multiple_files",
{
"files_count": len(files_dict),
"successful": results["summary"]["successful"],
"failed": results["summary"]["failed"],
"total_size_bytes": results["summary"]["total_size_bytes"],
"status": results["status"],
},
)
return json.dumps(results, ensure_ascii=False, indent=2)
except Exception as e:
result = {
"status": "error",
"message": f"Failed to write multiple files: {str(e)}",
"operation_type": "multi_file",
"timestamp": datetime.now().isoformat(),
"files_processed": 0,
}
log_operation("write_multiple_files_error", {"error": str(e)})
return json.dumps(result, ensure_ascii=False, indent=2)
# ==================== Code Execution Tools ====================
@mcp.tool()
async def execute_python(code: str, timeout: int = 30) -> str:
"""
Execute Python code and return output
Args:
code: Python code to execute
timeout: Timeout in seconds
Returns:
JSON string of execution result
"""
try:
# Create temporary file
with tempfile.NamedTemporaryFile(
mode="w", suffix=".py", delete=False, encoding="utf-8"
) as f:
f.write(code)
temp_file = f.name
try:
# Ensure workspace directory exists
ensure_workspace_exists()
# Execute Python code
result = subprocess.run(
[sys.executable, temp_file],
cwd=WORKSPACE_DIR,
capture_output=True,
text=True,
timeout=timeout,
encoding="utf-8",
)
execution_result = {
"status": "success" if result.returncode == 0 else "error",
"return_code": result.returncode,
"stdout": result.stdout,
"stderr": result.stderr,
"timeout": timeout,
}
if result.returncode != 0:
execution_result["message"] = "Python code execution failed"
else:
execution_result["message"] = "Python code execution successful"
log_operation(
"execute_python",
{
"return_code": result.returncode,
"stdout_length": len(result.stdout),
"stderr_length": len(result.stderr),
},
)
return json.dumps(execution_result, ensure_ascii=False, indent=2)
finally:
# Clean up temporary file
os.unlink(temp_file)
except subprocess.TimeoutExpired:
result = {
"status": "error",
"message": f"Python code execution timeout ({timeout}秒)",
"timeout": timeout,
}
log_operation("execute_python_timeout", {"timeout": timeout})
return json.dumps(result, ensure_ascii=False, indent=2)
except Exception as e:
result = {
"status": "error",
"message": f"Python code execution failed: {str(e)}",
}
log_operation("execute_python_error", {"error": str(e)})
return json.dumps(result, ensure_ascii=False, indent=2)
@mcp.tool()
async def execute_bash(command: str, timeout: int = 30) -> str:
"""
Execute bash command
Args:
command: Bash command to execute
timeout: Timeout in seconds
Returns:
JSON string of execution result
"""
try:
# 安全检查:禁止危险命令
dangerous_commands = ["rm -rf", "sudo", "chmod 777", "mkfs", "dd if="]
if any(dangerous in command.lower() for dangerous in dangerous_commands):
result = {
"status": "error",
"message": f"Dangerous command execution prohibited: {command}",
}
log_operation(
"execute_bash_blocked",
{"command": command, "reason": "dangerous_command"},
)
return json.dumps(result, ensure_ascii=False, indent=2)
# Ensure workspace directory exists
ensure_workspace_exists()
# Execute command
result = subprocess.run(
command,
shell=True,
cwd=WORKSPACE_DIR,
capture_output=True,
text=True,
timeout=timeout,
encoding="utf-8",
)
execution_result = {
"status": "success" if result.returncode == 0 else "error",
"return_code": result.returncode,
"stdout": result.stdout,
"stderr": result.stderr,
"command": command,
"timeout": timeout,
}
if result.returncode != 0:
execution_result["message"] = "Bash command execution failed"
else:
execution_result["message"] = "Bash command execution successful"
log_operation(
"execute_bash",
{
"command": command,
"return_code": result.returncode,
"stdout_length": len(result.stdout),
"stderr_length": len(result.stderr),
},
)
return json.dumps(execution_result, ensure_ascii=False, indent=2)
except subprocess.TimeoutExpired:
result = {
"status": "error",
"message": f"Bash command execution timeout ({timeout} seconds)",
"command": command,
"timeout": timeout,
}
log_operation("execute_bash_timeout", {"command": command, "timeout": timeout})
return json.dumps(result, ensure_ascii=False, indent=2)
except Exception as e:
result = {
"status": "error",
"message": f"Failed to execute bash command: {str(e)}",
"command": command,
}
log_operation("execute_bash_error", {"command": command, "error": str(e)})
return json.dumps(result, ensure_ascii=False, indent=2)
@mcp.tool()
async def read_code_mem(file_paths: List[str]) -> str:
"""
Check if file summaries exist in implement_code_summary.md for multiple files
Args:
file_paths: List of file paths to check for summary information in implement_code_summary.md
Returns:
Summary information for all requested files if available
"""
try:
if not file_paths or not isinstance(file_paths, list):
result = {
"status": "error",
"message": "file_paths parameter is required and must be a list",
}
log_operation(
"read_code_mem_error", {"error": "missing_or_invalid_file_paths"}
)
return json.dumps(result, ensure_ascii=False, indent=2)
# Remove duplicates while preserving order
unique_file_paths = list(dict.fromkeys(file_paths))
# Ensure workspace exists
ensure_workspace_exists()
# Look for implement_code_summary.md in the workspace
current_path = Path(WORKSPACE_DIR)
summary_file_path = current_path.parent / "implement_code_summary.md"
if not summary_file_path.exists():
result = {
"status": "no_summary",
"file_paths": unique_file_paths,
"message": "No summary file found.",
"results": [],
}
log_operation(
"read_code_mem",
{"file_paths": unique_file_paths, "status": "no_summary_file"},
)
return json.dumps(result, ensure_ascii=False, indent=2)
# Read the summary file
with open(summary_file_path, "r", encoding="utf-8") as f:
summary_content = f.read()
if not summary_content.strip():
result = {
"status": "no_summary",
"file_paths": unique_file_paths,
"message": "Summary file is empty.",
"results": [],
}
log_operation(
"read_code_mem",
{"file_paths": unique_file_paths, "status": "empty_summary"},
)
return json.dumps(result, ensure_ascii=False, indent=2)
# Process each file path and collect results
results = []
summaries_found = 0
for file_path in unique_file_paths:
# Extract file-specific section from summary
file_section = _extract_file_section_from_summary(
summary_content, file_path
)
if file_section:
file_result = {
"file_path": file_path,
"status": "summary_found",
"summary_content": file_section,
"message": f"Summary information found for {file_path}",
}
summaries_found += 1
else:
file_result = {
"file_path": file_path,
"status": "no_summary",
"summary_content": None,
"message": f"No summary found for {file_path}",
}
results.append(file_result)
# Determine overall status
if summaries_found == len(unique_file_paths):
overall_status = "all_summaries_found"
elif summaries_found > 0:
overall_status = "partial_summaries_found"
else:
overall_status = "no_summaries_found"
result = {
"status": overall_status,
"file_paths": unique_file_paths,
"total_requested": len(unique_file_paths),
"summaries_found": summaries_found,
"message": f"Found summaries for {summaries_found}/{len(unique_file_paths)} files",
"results": results,
}
log_operation(
"read_code_mem",
{
"file_paths": unique_file_paths,
"status": overall_status,
"total_requested": len(unique_file_paths),
"summaries_found": summaries_found,
},
)
return json.dumps(result, ensure_ascii=False, indent=2)
except Exception as e:
result = {
"status": "error",
"message": f"Failed to check code memory: {str(e)}",
"file_paths": file_paths
if isinstance(file_paths, list)
else [str(file_paths)],
"results": [],
}
log_operation(
"read_code_mem_error", {"file_paths": file_paths, "error": str(e)}
)
return json.dumps(result, ensure_ascii=False, indent=2)
def _extract_file_section_from_summary(
summary_content: str, target_file_path: str
) -> str:
"""
Extract the specific section for a file from the summary content
Args:
summary_content: Full summary content
target_file_path: Path of the target file
Returns:
File-specific section or None if not found
"""
import re