-
-
Notifications
You must be signed in to change notification settings - Fork 39
Expand file tree
/
Copy pathapktool_mcp_server.py
More file actions
1856 lines (1548 loc) · 69.4 KB
/
apktool_mcp_server.py
File metadata and controls
1856 lines (1548 loc) · 69.4 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
# /// script
# requires-python = ">=3.10"
# dependencies = [ "fastmcp", "logging", "argparse" ]
# ///
"""
Copyright (c) 2025 apktool mcp server developer(s) (https://github.com/zinja-coder/apktool-mcp-server)
See the file 'LICENSE' for copying permission
"""
import logging
import subprocess
import os
import shutil
import argparse
import json
import time
import xml.etree.ElementTree as ET
from typing import List, Union, Dict, Optional, Callable, Any
from fastmcp import FastMCP
# Set up logging configuration
logger = logging.getLogger()
logger.setLevel(logging.INFO)
# Console handler for logging to the console
console_handler = logging.StreamHandler()
console_handler.setLevel(logging.INFO)
console_handler.setFormatter(logging.Formatter('%(asctime)s - %(levelname)s - %(message)s'))
logger.addHandler(console_handler)
# Parse arguments
parser = argparse.ArgumentParser("APKTool MCP Server")
parser.add_argument("--http", help="Serve MCP Server over HTTP stream.", action="store_true", default=False)
parser.add_argument("--port", help="Specify the port number for --http to serve on. (default:8652)", default=8652, type=int)
parser.add_argument("--workspace", help="Specify workspace directory for APK projects", default="apktool_mcp_server_workspace", type=str)
parser.add_argument("--timeout", help="Default timeout for APKTool commands in seconds", default=300, type=int)
args = parser.parse_args()
# Initialize the MCP server
mcp = FastMCP("APKTool-MCP Server with Advanced Features")
# Current workspace for decoded APK projects
WORKSPACE_DIR = os.environ.get("APKTOOL_WORKSPACE", args.workspace)
DEFAULT_TIMEOUT = args.timeout
# Ensure workspace directory exists
os.makedirs(WORKSPACE_DIR, exist_ok=True)
class PaginationUtils:
"""Utility class for handling pagination across different MCP tools"""
# Configuration constants
DEFAULT_PAGE_SIZE = 100
MAX_PAGE_SIZE = 10000
MAX_OFFSET = 1000000
@staticmethod
def validate_pagination_params(offset: int, count: int) -> tuple[int, int]:
"""Validate and normalize pagination parameters"""
offset = max(0, min(offset, PaginationUtils.MAX_OFFSET))
count = max(0, min(count, PaginationUtils.MAX_PAGE_SIZE))
return offset, count
@staticmethod
def handle_pagination(
items: List[Any],
offset: int = 0,
count: int = 0,
data_type: str = "paginated-list",
items_key: str = "items",
item_transformer: Optional[Callable[[Any], Any]] = None
) -> Dict[str, Any]:
"""
Generic pagination handler for list data
Args:
items: List of items to paginate
offset: Starting offset
count: Number of items to return (0 means use default)
data_type: Type identifier for the response
items_key: Key name for items in response
item_transformer: Optional function to transform items
Returns:
Paginated response dictionary
"""
if items is None:
items = []
total_items = len(items)
# Validate parameters
offset, count = PaginationUtils.validate_pagination_params(offset, count)
# Determine effective limit
if count == 0:
effective_limit = min(PaginationUtils.DEFAULT_PAGE_SIZE, max(0, total_items - offset))
else:
effective_limit = min(count, max(0, total_items - offset))
# Calculate bounds
start_index = min(offset, total_items)
end_index = min(start_index + effective_limit, total_items)
has_more = end_index < total_items
# Extract and transform paginated subset
paginated_items = items[start_index:end_index]
if item_transformer:
paginated_items = [item_transformer(item) for item in paginated_items]
# Build response
result = {
"type": data_type,
items_key: paginated_items,
"pagination": {
"total": total_items,
"offset": offset,
"limit": effective_limit,
"count": len(paginated_items),
"has_more": has_more
}
}
# Add navigation helpers
if has_more:
result["pagination"]["next_offset"] = end_index
if offset > 0:
prev_offset = max(0, offset - effective_limit)
result["pagination"]["prev_offset"] = prev_offset
# Page calculations
if effective_limit > 0:
current_page = (offset // effective_limit) + 1
total_pages = (total_items + effective_limit - 1) // effective_limit
result["pagination"]["current_page"] = current_page
result["pagination"]["total_pages"] = total_pages
result["pagination"]["page_size"] = effective_limit
return result
class ValidationUtils:
"""Utility class for input validation"""
@staticmethod
def validate_path(path: str, must_exist: bool = True) -> Dict[str, Union[bool, str]]:
"""Validate file/directory path"""
if not path or not isinstance(path, str):
return {"valid": False, "error": "Path cannot be empty"}
if must_exist and not os.path.exists(path):
return {"valid": False, "error": f"Path does not exist: {path}"}
return {"valid": True}
@staticmethod
def validate_workspace_path(path: str, workspace_dir: str) -> Dict[str, Union[bool, str]]:
"""Validate that a path resolves within the workspace directory.
Prevents path traversal attacks (CWE-22) by ensuring the resolved
path is contained within WORKSPACE_DIR.
Args:
path: The path to validate
workspace_dir: The workspace directory to validate against
Returns:
Dictionary with 'valid' boolean and optional 'error' message
"""
if not path or not isinstance(path, str):
return {"valid": False, "error": "Path cannot be empty"}
real_path = os.path.realpath(path)
real_workspace = os.path.realpath(workspace_dir)
# Ensure the path is within the workspace (use os.sep to prevent
# prefix-matching against sibling directories, e.g.
# /workspace_evil matching /workspace)
if not (real_path == real_workspace or real_path.startswith(real_workspace + os.sep)):
return {
"valid": False,
"error": f"Path must be within the workspace directory ({real_workspace}). "
f"Resolved path: {real_path}"
}
return {"valid": True}
@staticmethod
def validate_class_name(class_name: str) -> Dict[str, Union[bool, str]]:
"""Validate Java class name format"""
if not class_name or not isinstance(class_name, str):
return {"valid": False, "error": "Class name cannot be empty"}
if not class_name.replace('.', '').replace('_', '').replace('$', '').isalnum():
return {"valid": False, "error": "Invalid class name format"}
return {"valid": True}
@staticmethod
def validate_search_pattern(pattern: str) -> Dict[str, Union[bool, str]]:
"""Validate search pattern"""
if not pattern or not isinstance(pattern, str):
return {"valid": False, "error": "Search pattern cannot be empty"}
if len(pattern) > 1000:
return {"valid": False, "error": "Search pattern too long (max 1000 characters)"}
return {"valid": True}
# Enhanced command runner with better error handling
def run_command(command: List[str], timeout: int = DEFAULT_TIMEOUT, cwd: Optional[str] = None) -> Dict[str, Union[str, int, bool]]:
"""Enhanced command runner with comprehensive error handling"""
try:
logger.info(f"Running command: {' '.join(command)}")
# Input validation
if not command or not all(isinstance(arg, str) for arg in command):
return {
"success": False,
"error": "Invalid command format"
}
result = subprocess.run(
command,
stdout=subprocess.PIPE,
stderr=subprocess.PIPE,
text=True,
check=True,
timeout=timeout,
cwd=cwd
)
logger.info(f"Command completed successfully with return code {result.returncode}")
return {
"success": True,
"stdout": result.stdout,
"stderr": result.stderr,
"returncode": result.returncode,
"command": " ".join(command)
}
except subprocess.CalledProcessError as e:
logger.error(f"Command failed with return code {e.returncode}: {e.stderr}")
return {
"success": False,
"stdout": e.stdout or "",
"stderr": e.stderr or "",
"returncode": e.returncode,
"error": f"Command failed with return code {e.returncode}",
"command": " ".join(command)
}
except subprocess.TimeoutExpired as e:
logger.error(f"Command timed out after {timeout} seconds")
return {
"success": False,
"error": f"Command timed out after {timeout} seconds",
"command": " ".join(command)
}
except FileNotFoundError:
return {
"success": False,
"error": "APKTool not found. Please ensure APKTool is installed and in PATH"
}
except Exception as e:
logger.error(f"Unexpected error running command: {str(e)}")
return {
"success": False,
"error": f"Unexpected error: {str(e)}",
"command": " ".join(command)
}
# Health check functionality
@mcp.tool()
async def health_check() -> Dict:
"""
Check the health status of the APKTool MCP server and APKTool installation.
Returns:
Dictionary containing server status and APKTool availability
"""
try:
# Check APKTool installation
apktool_result = run_command(["apktool", "--version"], timeout=10)
result = {
"server_status": "running",
"workspace_dir": WORKSPACE_DIR,
"workspace_exists": os.path.exists(WORKSPACE_DIR),
"apktool_available": apktool_result["success"],
"timestamp": time.time()
}
if apktool_result["success"]:
result["apktool_version"] = apktool_result["stdout"].strip()
else:
result["apktool_error"] = apktool_result["error"]
logger.info("APKTool MCP Server: Health check completed")
return result
except Exception as e:
logger.error(f"Health check error: {str(e)}")
return {
"server_status": "error",
"error": str(e),
"timestamp": time.time()
}
# Enhanced MCP Tools with validation and better error handling
@mcp.tool()
async def decode_apk(
apk_path: str,
force: bool = True,
no_res: bool = False,
no_src: bool = False,
output_dir: Optional[str] = None,
timeout: int = DEFAULT_TIMEOUT
) -> Dict:
"""
Decode an APK file using APKTool with comprehensive validation and error handling.
Args:
apk_path: Path to the APK file to decode
force: Force delete destination directory if it exists
no_res: Do not decode resources
no_src: Do not decode sources
output_dir: Custom output directory (optional)
timeout: Command timeout in seconds
Returns:
Dictionary with operation results including validation details
"""
# Input validation
path_validation = ValidationUtils.validate_path(apk_path, must_exist=True)
if not path_validation["valid"]:
return {"success": False, "error": path_validation["error"]}
if not apk_path.lower().endswith(('.apk', '.xapk')):
return {"success": False, "error": "File must have .apk or .xapk extension"}
# Determine output directory
if output_dir is None:
apk_name = os.path.basename(apk_path).rsplit('.', 1)[0]
output_dir = os.path.join(WORKSPACE_DIR, apk_name)
# Validate output_dir is within WORKSPACE_DIR to prevent path traversal (CWE-22)
workspace_validation = ValidationUtils.validate_workspace_path(output_dir, WORKSPACE_DIR)
if not workspace_validation["valid"]:
return {"success": False, "error": workspace_validation["error"]}
# Build command
command = ["apktool", "d", apk_path, "-o", output_dir]
if force:
command.append("-f")
if no_res:
command.append("-r")
if no_src:
command.append("-s")
result = run_command(command, timeout=timeout)
if result["success"]:
# Additional validation - check if output directory was created
if os.path.exists(output_dir):
result["output_dir"] = output_dir
result["workspace"] = WORKSPACE_DIR
# Get basic project info
manifest_path = os.path.join(output_dir, "AndroidManifest.xml")
apktool_yml_path = os.path.join(output_dir, "apktool.yml")
result["has_manifest"] = os.path.exists(manifest_path)
result["has_apktool_yml"] = os.path.exists(apktool_yml_path)
else:
result["warning"] = "Decode reported success but output directory not found"
return result
@mcp.tool()
async def build_apk(
project_dir: str,
output_apk: Optional[str] = None,
debug: bool = True,
force_all: bool = False,
timeout: int = DEFAULT_TIMEOUT
) -> Dict:
"""
Build an APK file from a decoded APKTool project with enhanced validation.
Args:
project_dir: Path to the APKTool project directory
output_apk: Optional output APK path
debug: Build with debugging info
force_all: Force rebuild all files
timeout: Command timeout in seconds
Returns:
Dictionary with operation results and build information
"""
# Input validation
path_validation = ValidationUtils.validate_path(project_dir, must_exist=True)
if not path_validation["valid"]:
return {"success": False, "error": path_validation["error"]}
# Validate project_dir is within WORKSPACE_DIR to prevent path traversal (CWE-22)
workspace_validation = ValidationUtils.validate_workspace_path(project_dir, WORKSPACE_DIR)
if not workspace_validation["valid"]:
return {"success": False, "error": workspace_validation["error"]}
if not os.path.isdir(project_dir):
return {"success": False, "error": f"Project path is not a directory: {project_dir}"}
# Check for required files
apktool_yml = os.path.join(project_dir, "apktool.yml")
manifest_xml = os.path.join(project_dir, "AndroidManifest.xml")
if not os.path.exists(apktool_yml):
return {"success": False, "error": "apktool.yml not found. Is this a valid APKTool project?"}
if not os.path.exists(manifest_xml):
return {"success": False, "error": "AndroidManifest.xml not found. Is this a valid APKTool project?"}
# Build command
command = ["apktool", "b", project_dir]
if debug:
command.append("-d")
if force_all:
command.append("-f")
if output_apk:
# Validate output_apk is within WORKSPACE_DIR to prevent path traversal (CWE-22)
workspace_validation = ValidationUtils.validate_workspace_path(output_apk, WORKSPACE_DIR)
if not workspace_validation["valid"]:
return {"success": False, "error": workspace_validation["error"]}
command.extend(["-o", output_apk])
result = run_command(command, timeout=timeout)
if result["success"]:
# Determine built APK path
if not output_apk:
output_apk = os.path.join(project_dir, "dist", os.path.basename(project_dir) + ".apk")
if os.path.exists(output_apk):
result["apk_path"] = output_apk
result["apk_size"] = os.path.getsize(output_apk)
else:
result["warning"] = f"Build succeeded but APK not found at expected path: {output_apk}"
return result
@mcp.tool()
async def get_manifest(project_dir: str) -> Dict:
"""
Get the AndroidManifest.xml content from a decoded APK project with validation.
Args:
project_dir: Path to the APKTool project directory
Returns:
Dictionary with manifest content, metadata, and validation results
"""
# Input validation
path_validation = ValidationUtils.validate_path(project_dir, must_exist=True)
if not path_validation["valid"]:
return {"success": False, "error": path_validation["error"]}
# Validate project_dir is within WORKSPACE_DIR to prevent path traversal (CWE-22)
workspace_validation = ValidationUtils.validate_workspace_path(project_dir, WORKSPACE_DIR)
if not workspace_validation["valid"]:
return {"success": False, "error": workspace_validation["error"]}
manifest_path = os.path.join(project_dir, "AndroidManifest.xml")
if not os.path.exists(manifest_path):
return {
"success": False,
"error": f"AndroidManifest.xml not found in {project_dir}",
"expected_path": manifest_path
}
try:
with open(manifest_path, 'r', encoding="utf-8") as f:
content = f.read()
result = {
"success": True,
"manifest": content,
"path": manifest_path,
"size": os.path.getsize(manifest_path),
"encoding": "utf-8"
}
return result
except Exception as e:
logger.error(f"Error reading manifest: {str(e)}")
return {
"success": False,
"error": f"Failed to read AndroidManifest.xml: {str(e)}",
"path": manifest_path
}
@mcp.tool()
async def get_apktool_yml(project_dir: str) -> Dict:
"""
Get apktool.yml information from a decoded APK project with validation.
Args:
project_dir: Path to APKTool project directory
Returns:
Dictionary with apktool.yml content, metadata, and validation results
"""
# Input validation
path_validation = ValidationUtils.validate_path(project_dir, must_exist=True)
if not path_validation["valid"]:
return {"success": False, "error": path_validation["error"]}
# Validate project_dir is within WORKSPACE_DIR to prevent path traversal (CWE-22)
workspace_validation = ValidationUtils.validate_workspace_path(project_dir, WORKSPACE_DIR)
if not workspace_validation["valid"]:
return {"success": False, "error": workspace_validation["error"]}
yml_path = os.path.join(project_dir, "apktool.yml")
if not os.path.exists(yml_path):
return {
"success": False,
"error": f"apktool.yml not found in {project_dir}",
"expected_path": yml_path
}
try:
with open(yml_path, 'r', encoding="utf-8") as f:
content = f.read()
result = {
"success": True,
"content": content,
"path": yml_path,
"size": os.path.getsize(yml_path),
"encoding": "utf-8"
}
return result
except Exception as e:
logger.error(f"Error reading apktool.yml: {str(e)}")
return {
"success": False,
"error": f"Failed to read apktool.yml: {str(e)}",
"path": yml_path
}
@mcp.tool()
async def list_smali_directories(project_dir: str) -> Dict:
"""
List all smali directories in a project with enhanced metadata.
Args:
project_dir: Path to the APKTool project directory
Returns:
Dictionary with list of smali directories and metadata
"""
# Input validation
path_validation = ValidationUtils.validate_path(project_dir, must_exist=True)
if not path_validation["valid"]:
return {"success": False, "error": path_validation["error"]}
# Validate project_dir is within WORKSPACE_DIR to prevent path traversal (CWE-22)
workspace_validation = ValidationUtils.validate_workspace_path(project_dir, WORKSPACE_DIR)
if not workspace_validation["valid"]:
return {"success": False, "error": workspace_validation["error"]}
try:
smali_dirs = []
for d in os.listdir(project_dir):
dir_path = os.path.join(project_dir, d)
if d.startswith("smali") and os.path.isdir(dir_path):
# Count files in smali directory
file_count = 0
try:
for root, _, files in os.walk(dir_path):
file_count += len([f for f in files if f.endswith('.smali')])
except Exception as e:
logger.warning(f"Error counting files in {dir_path}: {e}")
file_count = 0
smali_dirs.append({
"name": d,
"path": dir_path,
"smali_file_count": file_count
})
return {
"success": True,
"smali_dirs": smali_dirs,
"count": len(smali_dirs)
}
except Exception as e:
logger.error(f"Error listing smali directories: {str(e)}")
return {
"success": False,
"error": f"Failed to list smali directories: {str(e)}"
}
@mcp.tool()
async def list_smali_files(
project_dir: str,
smali_dir: str = "smali",
package_prefix: Optional[str] = None,
offset: int = 0,
count: int = 0
) -> Dict:
"""
List smali files with pagination support and enhanced filtering.
Args:
project_dir: Path to the APKTool project directory
smali_dir: Which smali directory to use (smali, smali_classes2, etc.)
package_prefix: Optional package prefix to filter by (e.g., "com.example")
offset: Starting offset for pagination
count: Number of items to return (0 means use default)
Returns:
Paginated dictionary with list of smali files and metadata
"""
# Input validation
path_validation = ValidationUtils.validate_path(project_dir, must_exist=True)
if not path_validation["valid"]:
return {"success": False, "error": path_validation["error"]}
# Validate project_dir is within WORKSPACE_DIR to prevent path traversal (CWE-22)
workspace_validation = ValidationUtils.validate_workspace_path(project_dir, WORKSPACE_DIR)
if not workspace_validation["valid"]:
return {"success": False, "error": workspace_validation["error"]}
smali_path = os.path.join(project_dir, smali_dir)
# Validate smali_dir doesn't escape project_dir via traversal (CWE-22)
real_smali_path = os.path.realpath(smali_path)
real_project_dir = os.path.realpath(project_dir)
if not real_smali_path.startswith(real_project_dir + os.sep):
return {"success": False, "error": "smali_dir must not contain path traversal components"}
if not os.path.exists(smali_path):
# Get available smali directories
try:
smali_dirs = [d for d in os.listdir(project_dir)
if d.startswith("smali") and os.path.isdir(os.path.join(project_dir, d))]
except Exception:
smali_dirs = []
return {
"success": False,
"error": f"Smali directory not found: {smali_path}",
"available_dirs": smali_dirs
}
try:
smali_files = []
search_root = smali_path
# Handle package filtering
if package_prefix:
# Validate package name format
if not package_prefix.replace('.', '').replace('_', '').replace('$', '').isalnum():
return {"success": False, "error": "Invalid package prefix format"}
package_path = os.path.join(smali_path, package_prefix.replace('.', os.path.sep))
if not os.path.exists(package_path):
return {
"success": False,
"error": f"Package not found: {package_prefix}",
"expected_path": package_path
}
search_root = package_path
# Recursively find all .smali files
for root, _, files in os.walk(search_root):
for file in files:
if file.endswith(".smali"):
file_path = os.path.join(root, file)
rel_path = os.path.relpath(file_path, smali_path)
class_name = rel_path.replace(os.path.sep, '.').replace('.smali', '')
smali_files.append({
"class_name": class_name,
"file_path": file_path,
"rel_path": rel_path,
"size": os.path.getsize(file_path)
})
# Sort by class name for consistent results
smali_files.sort(key=lambda x: x["class_name"])
# Apply pagination
paginated_result = PaginationUtils.handle_pagination(
items=smali_files,
offset=offset,
count=count,
data_type="smali-files",
items_key="smali_files"
)
# Add metadata
paginated_result["success"] = True
paginated_result["smali_dir"] = smali_dir
paginated_result["package_prefix"] = package_prefix
paginated_result["search_root"] = search_root
return paginated_result
except Exception as e:
logger.error(f"Error listing smali files: {str(e)}")
return {
"success": False,
"error": f"Failed to list smali files: {str(e)}"
}
@mcp.tool()
async def get_smali_file(project_dir: str, class_name: str) -> Dict:
"""
Get content of a specific smali file by class name with validation.
Args:
project_dir: Path to the APKTool project directory
class_name: Full class name (e.g., com.example.MyClass)
Returns:
Dictionary with smali file content and metadata
"""
# Input validation
path_validation = ValidationUtils.validate_path(project_dir, must_exist=True)
if not path_validation["valid"]:
return {"success": False, "error": path_validation["error"]}
# Validate project_dir is within WORKSPACE_DIR to prevent path traversal (CWE-22)
workspace_validation = ValidationUtils.validate_workspace_path(project_dir, WORKSPACE_DIR)
if not workspace_validation["valid"]:
return {"success": False, "error": workspace_validation["error"]}
class_validation = ValidationUtils.validate_class_name(class_name)
if not class_validation["valid"]:
return {"success": False, "error": class_validation["error"]}
try:
# Look for the class in all smali directories
smali_dirs = [d for d in os.listdir(project_dir)
if d.startswith("smali") and os.path.isdir(os.path.join(project_dir, d))]
for smali_dir in smali_dirs:
file_path = os.path.join(
project_dir,
smali_dir,
class_name.replace('.', os.path.sep) + '.smali'
)
if os.path.exists(file_path):
with open(file_path, 'r', encoding="utf-8") as f:
content = f.read()
return {
"success": True,
"content": content,
"file_path": file_path,
"smali_dir": smali_dir,
"size": os.path.getsize(file_path),
"class_name": class_name,
"encoding": "utf-8"
}
return {
"success": False,
"error": f"Smali file not found for class: {class_name}",
"searched_dirs": smali_dirs
}
except Exception as e:
logger.error(f"Error getting smali file: {str(e)}")
return {
"success": False,
"error": f"Failed to get smali file: {str(e)}"
}
@mcp.tool()
async def modify_smali_file(
project_dir: str,
class_name: str,
new_content: str,
create_backup: bool = True
) -> Dict:
"""
Modify smali file content with validation and backup support.
Args:
project_dir: Path to the APKTool project directory
class_name: Full class name (e.g., com.example.MyClass)
new_content: New content for the smali file
create_backup: Whether to create a backup of the original file
Returns:
Dictionary with operation results and metadata
"""
# Input validation
path_validation = ValidationUtils.validate_path(project_dir, must_exist=True)
if not path_validation["valid"]:
return {"success": False, "error": path_validation["error"]}
# Validate project_dir is within WORKSPACE_DIR to prevent path traversal (CWE-22)
workspace_validation = ValidationUtils.validate_workspace_path(project_dir, WORKSPACE_DIR)
if not workspace_validation["valid"]:
return {"success": False, "error": workspace_validation["error"]}
class_validation = ValidationUtils.validate_class_name(class_name)
if not class_validation["valid"]:
return {"success": False, "error": class_validation["error"]}
try:
# Find the smali file
smali_dirs = [d for d in os.listdir(project_dir)
if d.startswith("smali") and os.path.isdir(os.path.join(project_dir, d))]
file_path = None
for smali_dir in smali_dirs:
test_path = os.path.join(
project_dir,
smali_dir,
class_name.replace('.', os.path.sep) + '.smali'
)
if os.path.exists(test_path):
file_path = test_path
break
if not file_path:
return {
"success": False,
"error": f"Smali file not found for class: {class_name}",
"searched_dirs": smali_dirs
}
# Get original content size
original_size = os.path.getsize(file_path)
# Create backup if requested
backup_path = None
if create_backup:
backup_path = f"{file_path}.bak.{int(time.time())}"
shutil.copy2(file_path, backup_path)
# Write new content
with open(file_path, 'w', encoding='utf-8') as f:
f.write(new_content)
return {
"success": True,
"message": f"Successfully modified {file_path}",
"file_path": file_path,
"backup_path": backup_path,
"class_name": class_name,
"original_size": original_size,
"new_size": len(new_content),
"backup_created": backup_path is not None
}
except Exception as e:
logger.error(f"Error modifying smali file: {str(e)}")
return {
"success": False,
"error": f"Failed to modify smali file: {str(e)}"
}
@mcp.tool()
async def list_resources(
project_dir: str,
resource_type: Optional[str] = None,
offset: int = 0,
count: int = 0
) -> Dict:
"""
List resources with pagination support and enhanced metadata.
Args:
project_dir: Path to the APKTool project directory
resource_type: Optional resource type to filter by (e.g., "layout", "drawable")
offset: Starting offset for pagination
count: Number of items to return (0 means use default)
Returns:
Paginated dictionary with list of resources and metadata
"""
# Input validation
path_validation = ValidationUtils.validate_path(project_dir, must_exist=True)
if not path_validation["valid"]:
return {"success": False, "error": path_validation["error"]}
# Validate project_dir is within WORKSPACE_DIR to prevent path traversal (CWE-22)
workspace_validation = ValidationUtils.validate_workspace_path(project_dir, WORKSPACE_DIR)
if not workspace_validation["valid"]:
return {"success": False, "error": workspace_validation["error"]}
res_path = os.path.join(project_dir, "res")
if not os.path.exists(res_path):
return {
"success": False,
"error": f"Resources directory not found: {res_path}"
}
try:
if resource_type:
# List resources of specific type
type_path = os.path.join(res_path, resource_type)
if not os.path.exists(type_path):
# Get available resource types
resource_types = [
d for d in os.listdir(res_path)
if os.path.isdir(os.path.join(res_path, d))
]
return {
"success": False,
"error": f"Resource type directory not found: {resource_type}",
"available_types": resource_types
}
resources = []
for item in os.listdir(type_path):
item_path = os.path.join(type_path, item)
if os.path.isfile(item_path):
resources.append({
"name": item,
"path": item_path,
"size": os.path.getsize(item_path),
"type": resource_type,
"extension": os.path.splitext(item)[1],
"modified_time": os.path.getmtime(item_path)
})
# Sort by name
resources.sort(key=lambda x: x["name"])
# Apply pagination
paginated_result = PaginationUtils.handle_pagination(
items=resources,
offset=offset,
count=count,
data_type="resources",
items_key="resources"
)
paginated_result["success"] = True
paginated_result["resource_type"] = resource_type
paginated_result["resource_path"] = type_path
return paginated_result
else:
# List all resource types with counts
resource_types = []
for item in os.listdir(res_path):
type_path = os.path.join(res_path, item)
if os.path.isdir(type_path):
try:
files = [f for f in os.listdir(type_path) if os.path.isfile(os.path.join(type_path, f))]
resource_count = len(files)
# Calculate total size
total_size = 0
for f in files:
try:
total_size += os.path.getsize(os.path.join(type_path, f))
except:
pass
resource_types.append({
"type": item,
"path": type_path,
"count": resource_count,
"total_size": total_size
})
except Exception as e:
logger.warning(f"Error processing resource type {item}: {e}")
resource_types.append({
"type": item,
"path": type_path,
"count": 0,
"total_size": 0,
"error": str(e)
})
# Sort by type name
resource_types.sort(key=lambda x: x["type"])
# Apply pagination
paginated_result = PaginationUtils.handle_pagination(