Repository navigation
Expand file tree
/
Copy pathmcpserver.lua
More file actions
2293 lines (2070 loc) · 69.6 KB
/
Copy pathmcpserver.lua
File metadata and controls
2293 lines (2070 loc) · 69.6 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
--[[
Cheat Engine Model Context Protocol (MCP) Server
Pure Cheat Engine Lua implementation (no external dependencies, no Python)
Implements Model Context Protocol (MCP) specification version 2024-11-05.
Supports dual transports:
1. HTTP / Server-Sent Events (SSE): for Claude Desktop, Cursor, and web clients (http://127.0.0.1:20000/sse)
2. Raw TCP line-delimited JSON-RPC stream: for direct socket clients, CLI bridges, and stdio-to-tcp proxies
]]
local jsonparser = require 'json'
-- Global server table
MCPServer = MCPServer or {}
MCPServer.version = "1.0.0"
MCPServer.protocolVersion = "2024-11-05"
MCPServer.port = 20000
MCPServer.localhostOnly = true
MCPServer.autoStart = false
MCPServer.running = false
MCPServer.serverTerminated = false
MCPServer.serverSocket = nil
MCPServer.serverThread = nil
MCPServer.heartbeatThread = nil
MCPServer.clients = {}
MCPServer.sseSessions = {}
MCPServer.tools = {}
MCPServer.scanners = {}
MCPServer.watchpoints = {}
MCPServer.lockCS = createCriticalSection()
-------------------------------------------------------------------------------
-- Helper Functions
-------------------------------------------------------------------------------
local function makeArray(t)
t = t or {}
setmetatable(t, {isArray = true})
return t
end
local function runOnMainThread(fn)
if inMainThread and inMainThread() then
return fn()
else
return synchronize(fn)
end
end
local function safeHex(addr)
if addr == nil then return "0" end
if type(addr) == "number" then
return string.format("0x%X", addr)
end
return tostring(addr)
end
local function resolveAddress(addr)
if addr == nil then return nil end
if type(addr) == "number" then return addr end
local str = tostring(addr):trim()
local a = getAddressSafe(str)
if a then return a end
-- Try tonumber with hex
if str:sub(1, 2) == "0x" or str:sub(1, 2) == "0X" then
return tonumber(str:sub(3), 16)
end
return tonumber(str, 16) or tonumber(str)
end
local function byteTableToHexString(bytes)
if not bytes or #bytes == 0 then return "" end
local parts = {}
for i = 1, #bytes do
parts[i] = string.format("%02X", bytes[i])
end
return table.concat(parts, " ")
end
local function hexStringToByteTable(hexStr)
local bytes = {}
-- Remove 0x prefix if any, spaces, dashes, commas
local clean = hexStr:gsub("0[xX]", ""):gsub("[%s%-,]", "")
for i = 1, #clean, 2 do
local b = tonumber(clean:sub(i, i + 1), 16)
if b then
table.insert(bytes, b)
end
end
return bytes
end
local function generateSessionId()
local template = "xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx"
math.randomseed(os.time() + (os.clock() * 1000000 % 100000))
return string.gsub(template, "[xy]", function(c)
local v = (c == "x") and math.random(0, 0xf) or math.random(8, 0xb)
return string.format("%x", v)
end)
end
local function detectConfiguredPort()
local home = os.getenv("HOME") or os.getenv("USERPROFILE")
if home then
local path = home .. "/.gemini/config/mcp_config.json"
local f = io.open(path, "r")
if f then
local content = f:read("*a")
f:close()
if content then
local p = content:match("http://127%.0%.0%.1:(%d+)/sse") or content:match("http://localhost:(%d+)/sse")
if p and tonumber(p) then
return tonumber(p)
end
end
end
end
return nil
end
local function updateAntigravityConfig(port)
local home = os.getenv("HOME") or os.getenv("USERPROFILE")
if not home then return false end
local dir = home .. "/.gemini/config"
local path = dir .. "/mcp_config.json"
local ok, res = pcall(function()
local cfg = {
mcpServers = {
cheatengine = {
serverUrl = string.format("http://127.0.0.1:%d/sse", port)
}
}
}
local f = io.open(path, "r")
if f then
local content = f:read("*a")
f:close()
if content and content:trim() ~= "" then
local decOk, existing = pcall(jsonparser.decode, content)
if decOk and type(existing) == "table" then
existing.mcpServers = existing.mcpServers or {}
existing.mcpServers.cheatengine = existing.mcpServers.cheatengine or {}
existing.mcpServers.cheatengine.serverUrl = string.format("http://127.0.0.1:%d/sse", port)
cfg = existing
end
end
end
local fOut = io.open(path, "w")
if fOut then
fOut:write(jsonparser.encode(cfg))
fOut:close()
return true
end
return false
end)
return ok and res
end
-------------------------------------------------------------------------------
-- Tool Registration & Dynamic AITools Bridge
-------------------------------------------------------------------------------
function MCPServer.registerTool(name, description, properties, required, func)
if not name or name == "" then
error("Tool name cannot be empty")
end
local cleanProps = {}
if properties then
for k, v in pairs(properties) do
local p = {}
for pk, pv in pairs(v) do
if pk == "type" and type(pv) == "string" then
p[pk] = pv:lower() -- JSON Schema requires lowercase (string, integer, etc.)
else
p[pk] = pv
end
end
cleanProps[k] = p
end
end
local req = {}
if required then
for _, r in ipairs(required) do
table.insert(req, r)
end
end
makeArray(req)
MCPServer.tools[name] = {
name = name,
description = description or "",
inputSchema = {
type = "object",
properties = cleanProps,
required = req
},
func = func
}
end
function MCPServer.importAIToolsBridge()
if _G.aitools and type(_G.aitools) == "table" then
for name, t in pairs(_G.aitools) do
if MCPServer.tools[name] == nil and t.functionToCall then
local props = {}
if t.parameters and t.parameters.properties then
for pk, pv in pairs(t.parameters.properties) do
local p = {}
for field, val in pairs(pv) do
if field == "type" and type(val) == "string" then
p[field] = val:lower()
else
p[field] = val
end
end
props[pk] = p
end
end
local req = {}
if t.parameters and t.parameters.required then
for _, r in ipairs(t.parameters.required) do
table.insert(req, r)
end
end
makeArray(req)
MCPServer.tools[name] = {
name = name,
description = t.description or "",
inputSchema = {
type = "object",
properties = props,
required = req
},
func = function(args)
return t.functionToCall(args)
end
}
end
end
end
end
-------------------------------------------------------------------------------
-- Built-in Cheat Engine Tools
-------------------------------------------------------------------------------
-- 1. get_opened_process
MCPServer.registerTool(
"get_opened_process",
"Returns information about the currently opened target process in Cheat Engine.",
{},
{},
function(args)
local pid = getOpenedProcessID()
local procName = process
local is64 = targetIs64Bit and targetIs64Bit() or false
local isArm = targetIsArm and targetIsArm() or false
local isX86 = targetIsX86 and targetIsX86() or true
return {
processID = pid,
processName = procName or (pid ~= 0 and ("PID " .. pid) or nil),
isOpened = (pid ~= 0 and pid ~= nil),
is64Bit = is64,
architecture = isArm and "arm" or (isX86 and "x86" or "unknown")
}
end
)
-- 2. open_process
MCPServer.registerTool(
"open_process",
"Opens / attaches Cheat Engine to a target process by name or PID.",
{
process = { type = "string", description = "The name of the executable (e.g. 'game.exe') or the integer Process ID." }
},
{ "process" },
function(args)
local target = args.process
local pid = tonumber(target)
if pid then
openProcess(pid)
else
openProcess(tostring(target))
end
local curPid = getOpenedProcessID()
if curPid ~= 0 and curPid ~= nil then
return { success = true, processID = curPid, processName = process }
else
return { success = false, error = "Failed to open process: " .. tostring(target) }
end
end
)
-- 3. get_process_list
MCPServer.registerTool(
"get_process_list",
"Lists currently running processes on the system with their Process IDs and names.",
{
filter = { type = "string", description = "Optional filter substring to search for in process names." }
},
{},
function(args)
local filter = args.filter and tostring(args.filter):lower() or nil
local pl = getProcesslist()
local result = {}
if pl then
for pid, name in pairs(pl) do
if not filter or tostring(name):lower():find(filter, 1, true) then
table.insert(result, { pid = pid, name = name })
end
end
end
table.sort(result, function(a, b) return a.name:lower() < b.name:lower() end)
makeArray(result)
return { processes = result, count = #result }
end
)
-- 4. pause_process / unpause_process
MCPServer.registerTool("pause_process", "Freezes / pauses the target process execution.", {}, {}, function(args)
pause()
return { status = "paused" }
end)
MCPServer.registerTool("unpause_process", "Resumes / unpauses the target process execution.", {}, {}, function(args)
unpause()
return { status = "resumed" }
end)
-- 5. read_memory
MCPServer.registerTool(
"read_memory",
"Reads a typed value (byte, int16, int32, int64, float, double, pointer, string) from an address or expression.",
{
address = { type = "string", description = "Target memory address or expression (e.g. '0x12345678', 'game.exe+0x1000', '[0x1234]+0x10')." },
type = {
type = "string",
description = "Variable data type: 'byte', 'int16', 'int32', 'int64', 'float', 'double', 'pointer', 'string'.",
enum = { "byte", "int16", "int32", "int64", "float", "double", "pointer", "string" }
},
length = { type = "integer", description = "For 'string' type: maximum number of characters to read (default: 50)." },
is_wide = { type = "boolean", description = "For 'string' type: set true for wide UTF-16 string (default: false)." }
},
{ "address", "type" },
function(args)
local addr = resolveAddress(args.address)
if not addr then
return { error = "Cannot resolve address: " .. tostring(args.address) }
end
local t = (args.type or "int32"):lower()
local val = nil
if t == "byte" then
val = readByte(addr)
elseif t == "int16" or t == "word" or t == "short" then
val = readSmallInteger(addr)
elseif t == "int32" or t == "int" or t == "dword" then
val = readInteger(addr)
elseif t == "int64" or t == "qword" then
local qw = readQword(addr)
val = qw and string.format("0x%X", qw) or nil
elseif t == "float" or t == "single" then
val = readFloat(addr)
elseif t == "double" then
val = readDouble(addr)
elseif t == "pointer" then
local ptr = readPointer(addr)
val = ptr and string.format("0x%X", ptr) or nil
elseif t == "string" then
local len = tonumber(args.length) or 50
local isWide = args.is_wide or false
val = readString(addr, len, isWide)
else
return { error = "Unsupported type: " .. tostring(t) }
end
if val == nil then
return { error = "Memory unreadable at address " .. safeHex(addr), address = safeHex(addr) }
end
return {
address = safeHex(addr),
type = t,
value = val
}
end
)
-- 6. read_bytes
MCPServer.registerTool(
"read_bytes",
"Reads a sequence of raw bytes from a memory address or expression.",
{
address = { type = "string", description = "Address or expression to start reading from." },
count = { type = "integer", description = "Number of bytes to read." }
},
{ "address", "count" },
function(args)
local addr = resolveAddress(args.address)
if not addr then return { error = "Invalid address: " .. tostring(args.address) } end
local count = tonumber(args.count) or 16
if count <= 0 or count > 65536 then
return { error = "Count out of range (1-65536)" }
end
local bytes = readBytes(addr, count, true)
if not bytes then
return { error = "Failed to read memory at " .. safeHex(addr) }
end
makeArray(bytes)
return {
address = safeHex(addr),
count = #bytes,
hex = byteTableToHexString(bytes),
bytes = bytes
}
end
)
-- 7. write_memory
MCPServer.registerTool(
"write_memory",
"Writes a typed value (byte, int16, int32, int64, float, double, pointer, string) to a memory address.",
{
address = { type = "string", description = "Target memory address or expression." },
type = {
type = "string",
description = "Variable data type: 'byte', 'int16', 'int32', 'int64', 'float', 'double', 'pointer', 'string'.",
enum = { "byte", "int16", "int32", "int64", "float", "double", "pointer", "string" }
},
value = { type = "string", description = "Value to write (formatted appropriately for the type)." },
is_wide = { type = "boolean", description = "For 'string' type: set true for wide UTF-16 string." }
},
{ "address", "type", "value" },
function(args)
local addr = resolveAddress(args.address)
if not addr then return { error = "Invalid address: " .. tostring(args.address) } end
local t = (args.type or "int32"):lower()
local valStr = tostring(args.value)
local ok = false
if t == "byte" then
ok = writeByte(addr, tonumber(valStr))
elseif t == "int16" or t == "word" or t == "short" then
ok = writeSmallInteger(addr, tonumber(valStr))
elseif t == "int32" or t == "int" or t == "dword" then
ok = writeInteger(addr, tonumber(valStr))
elseif t == "int64" or t == "qword" then
local n = tonumber(valStr) or tonumber(valStr, 16)
ok = writeQword(addr, n)
elseif t == "float" or t == "single" then
ok = writeFloat(addr, tonumber(valStr))
elseif t == "double" then
ok = writeDouble(addr, tonumber(valStr))
elseif t == "pointer" then
local ptr = resolveAddress(valStr)
ok = writePointer(addr, ptr)
elseif t == "string" then
local isWide = args.is_wide or false
ok = writeString(addr, valStr, isWide)
else
return { error = "Unsupported type: " .. tostring(t) }
end
if ok then
return { success = true, address = safeHex(addr), type = t, value = valStr }
else
return { success = false, error = "Write failed at " .. safeHex(addr) }
end
end
)
-- 8. write_bytes
MCPServer.registerTool(
"write_bytes",
"Writes raw bytes to a memory address. Bytes can be a hex string ('90 90 90') or array of integers.",
{
address = { type = "string", description = "Target memory address or expression." },
bytes = { type = "string", description = "Hexadecimal byte string (e.g. '90 90 90' or '909090')." }
},
{ "address", "bytes" },
function(args)
local addr = resolveAddress(args.address)
if not addr then return { error = "Invalid address: " .. tostring(args.address) } end
local byteTable
if type(args.bytes) == "table" then
byteTable = args.bytes
else
byteTable = hexStringToByteTable(tostring(args.bytes))
end
if #byteTable == 0 then
return { error = "No valid bytes provided" }
end
local ok = writeBytes(addr, byteTable)
if ok then
return { success = true, address = safeHex(addr), count = #byteTable, hex = byteTableToHexString(byteTable) }
else
return { success = false, error = "Failed to write bytes at " .. safeHex(addr) }
end
end
)
-- 9. resolve_pointer_chain
MCPServer.registerTool(
"resolve_pointer_chain",
"Resolves a multilevel pointer chain: base address + list of offsets.",
{
base_address = { type = "string", description = "Base address or module expression (e.g. 'game.exe+0x1234')." },
offsets = {
type = "array",
items = { type = "string" },
description = "List of offsets to dereference (e.g. ['0x10', '0x20', '0x8'])."
}
},
{ "base_address", "offsets" },
function(args)
local cur = resolveAddress(args.base_address)
if not cur then return { error = "Invalid base address: " .. tostring(args.base_address) } end
local steps = {}
table.insert(steps, { step = 0, address = safeHex(cur), description = "Base Address" })
local offsets = args.offsets or {}
for i = 1, #offsets do
local offStr = tostring(offsets[i]):trim()
local off = tonumber(offStr, 16) or tonumber(offStr) or 0
local ptr = readPointer(cur)
if ptr == nil or ptr == 0 then
return {
error = "Null or invalid pointer at step " .. i .. " (address: " .. safeHex(cur) .. ")",
steps = steps,
resolvedAtStep = i - 1
}
end
cur = ptr + off
table.insert(steps, {
step = i,
pointerValue = safeHex(ptr),
offset = safeHex(off),
targetAddress = safeHex(cur)
})
end
makeArray(steps)
return {
success = true,
finalAddress = safeHex(cur),
steps = steps
}
end
)
-- 10. create_scan / refine_scan / get_scan_results / free_scan
local varTypeMap = {
byte = vtByte,
word = vtWord,
["2bytes"] = vtWord,
dword = vtDword,
["4bytes"] = vtDword,
qword = vtQword,
["8bytes"] = vtQword,
float = vtSingle,
single = vtSingle,
double = vtDouble,
string = vtString,
bytearray = vtByteArray,
aob = vtByteArray,
all = vtAll
}
local scanOptionMap = {
exact = soExactValue,
bigger = soBiggerThan,
smaller = soSmallerThan,
between = soValueBetween,
unknown = soUnknownValue,
increased = soIncreasedValue,
decreased = soDecreasedValue,
changed = soChanged,
unchanged = soUnchanged,
increased_by = soIncreasedValueBy,
decreased_by = soDecreasedValueBy
}
MCPServer.registerTool(
"create_scan",
"Starts a new memory scan in the target process. Returns a scan_id for refining or reading results.",
{
value = { type = "string", description = "Value to scan for (omit or empty for unknown initial value scan)." },
value2 = { type = "string", description = "Secondary value for 'between' scan." },
var_type = {
type = "string",
description = "Type: 'byte', '2bytes', '4bytes', '8bytes', 'float', 'double', 'string', 'bytearray', 'all'.",
default = "4bytes"
},
scan_option = {
type = "string",
description = "Option: 'exact', 'bigger', 'smaller', 'between', 'unknown'.",
default = "exact"
},
start_address = { type = "string", description = "Start address (default: 0)." },
stop_address = { type = "string", description = "Stop address (default: 0x7FFFFFFFFFFFFFFF)." }
},
{},
function(args)
local ms = createMemScan()
if not ms then return { error = "Failed to create memory scanner" } end
local vt = varTypeMap[(args.var_type or "4bytes"):lower()] or vtDword
local so = scanOptionMap[(args.scan_option or "exact"):lower()] or soExactValue
local startAddr = args.start_address and resolveAddress(args.start_address) or 0
local stopAddr = args.stop_address and resolveAddress(args.stop_address) or 0x7FFFFFFFFFFFFFFF
local val = args.value and tostring(args.value) or ""
local val2 = args.value2 and tostring(args.value2) or ""
if (args.scan_option or ""):lower() == "unknown" or val == "" then
so = soUnknownValue
end
ms.firstScan(so, vt, rtRounded, val, val2, startAddr, stopAddr, "+W-C", fsmNotAligned, "4", true, false, false, false)
ms.waitTillDone()
local scanId = #MCPServer.scanners + 1
MCPServer.scanners[scanId] = { memScan = ms, varType = vt }
local fl = createFoundList(ms)
fl.initialize()
local count = fl.Count
local samples = {}
local sampleCount = math.min(count, 10)
for i = 0, sampleCount - 1 do
table.insert(samples, { address = fl.Address[i], value = fl.Value[i] })
end
fl.deinitialize()
fl.destroy()
makeArray(samples)
return {
scan_id = scanId,
found_count = count,
sample_results = samples
}
end
)
MCPServer.registerTool(
"refine_scan",
"Filters / refines an existing memory scan with next scan criteria.",
{
scan_id = { type = "integer", description = "Scan ID returned from create_scan." },
scan_option = {
type = "string",
description = "'exact', 'increased', 'decreased', 'changed', 'unchanged', 'bigger', 'smaller', 'between', 'increased_by', 'decreased_by'."
},
value = { type = "string", description = "Value to scan for." },
value2 = { type = "string", description = "Secondary value for 'between'." }
},
{ "scan_id", "scan_option" },
function(args)
local item = MCPServer.scanners[args.scan_id]
if not item or not item.memScan then
return { error = "Invalid scan_id: " .. tostring(args.scan_id) }
end
local ms = item.memScan
local so = scanOptionMap[(args.scan_option or "exact"):lower()] or soExactValue
local val = args.value and tostring(args.value) or ""
local val2 = args.value2 and tostring(args.value2) or ""
ms.nextScan(so, rtRounded, nil, val, val2, false, false, false, false, false, false)
ms.waitTillDone()
local fl = createFoundList(ms)
fl.initialize()
local count = fl.Count
local samples = {}
local sampleCount = math.min(count, 10)
for i = 0, sampleCount - 1 do
table.insert(samples, { address = fl.Address[i], value = fl.Value[i] })
end
fl.deinitialize()
fl.destroy()
makeArray(samples)
return {
scan_id = args.scan_id,
found_count = count,
sample_results = samples
}
end
)
MCPServer.registerTool(
"get_scan_results",
"Retrieves found addresses and values from a completed memory scan.",
{
scan_id = { type = "integer", description = "Scan ID." },
start_index = { type = "integer", description = "Start index (default 0)." },
count = { type = "integer", description = "Max results to return (default 50, max 500)." }
},
{ "scan_id" },
function(args)
local item = MCPServer.scanners[args.scan_id]
if not item or not item.memScan then
return { error = "Invalid scan_id: " .. tostring(args.scan_id) }
end
local ms = item.memScan
local fl = createFoundList(ms)
fl.initialize()
local total = fl.Count
local startIndex = tonumber(args.start_index) or 0
local maxCount = math.min(tonumber(args.count) or 50, 500)
local results = {}
for i = startIndex, math.min(startIndex + maxCount - 1, total - 1) do
table.insert(results, { index = i, address = fl.Address[i], value = fl.Value[i] })
end
fl.deinitialize()
fl.destroy()
makeArray(results)
return {
scan_id = args.scan_id,
total_count = total,
returned_count = #results,
results = results
}
end
)
MCPServer.registerTool(
"free_scan",
"Frees and cleans up a memory scan object.",
{
scan_id = { type = "integer", description = "Scan ID to free." }
},
{ "scan_id" },
function(args)
local item = MCPServer.scanners[args.scan_id]
if item and item.memScan then
item.memScan.destroy()
MCPServer.scanners[args.scan_id] = nil
return { success = true }
end
return { error = "Scan not found" }
end
)
-- 11. Disassembly & Assembly
MCPServer.registerTool(
"disassemble",
"Disassembles instructions at a given memory address or expression.",
{
address = { type = "string", description = "Starting address or symbol expression." },
count = { type = "integer", description = "Number of instructions to disassemble (default 10, max 100)." }
},
{ "address" },
function(args)
local addr = resolveAddress(args.address)
if not addr then return { error = "Invalid address: " .. tostring(args.address) } end
local count = math.min(tonumber(args.count) or 10, 100)
local instructions = {}
local cur = addr
local d = createDisassembler()
d.showSymbols = true
d.showModules = true
for i = 1, count do
local s = d.disassemble(cur)
local lastData = d.LastDisassembleData
local size = #lastData.bytes
local hexBytes = byteTableToHexString(lastData.bytes)
table.insert(instructions, {
address = safeHex(cur),
addressString = getNameFromAddress(cur, true, true, false),
bytes = hexBytes,
opcode = lastData.opcode,
parameters = lastData.parameters,
full = lastData.opcode .. " " .. lastData.parameters,
size = size
})
cur = cur + (size > 0 and size or 1)
end
d.destroy()
makeArray(instructions)
return {
start_address = safeHex(addr),
count = #instructions,
instructions = instructions
}
end
)
MCPServer.registerTool(
"assemble",
"Assembles an instruction string. If address is provided, writes it to memory.",
{
instruction = { type = "string", description = "Assembly instruction (e.g. 'nop', 'mov eax, 1')." },
address = { type = "string", description = "Optional target address to assemble at and write to." }
},
{ "instruction" },
function(args)
local addr = args.address and resolveAddress(args.address) or nil
local byteTable = assemble(args.instruction, addr)
if not byteTable or #byteTable == 0 then
return { error = "Failed to assemble: " .. tostring(args.instruction) }
end
makeArray(byteTable)
return {
success = true,
instruction = args.instruction,
address = addr and safeHex(addr) or nil,
bytes = byteTable,
hex = byteTableToHexString(byteTable)
}
end
)
MCPServer.registerTool(
"auto_assemble",
"Executes a Cheat Engine Auto Assembler (AA) script. Supports hooks, code caves, allocs, and symbol registrations.",
{
script = { type = "string", description = "Auto Assembler script content." }
},
{ "script" },
function(args)
local ok, disableInfo, warnings = autoAssemble(args.script)
if ok then
return {
success = true,
warnings = warnings
}
else
return {
success = false,
error = tostring(disableInfo)
}
end
end
)
MCPServer.registerTool(
"check_auto_assemble_syntax",
"Checks the syntax of an Auto Assembler script without executing it.",
{
script = { type = "string", description = "Auto Assembler script content." }
},
{ "script" },
function(args)
local ok, err = autoAssembleCheck(args.script, true, false)
return {
valid = ok,
error = not ok and tostring(err) or nil
}
end
)
-- 12. Modules & Symbols
MCPServer.registerTool(
"enum_modules",
"Lists all loaded modules (DLLs/executables) in the target process with base address and size.",
{},
{},
function(args)
local mods = enumModules()
local result = {}
if mods then
for i, m in ipairs(mods) do
table.insert(result, {
name = m.Name,
address = safeHex(m.Address),
size = m.Size or 0,
path = m.PathToFile
})
end
end
makeArray(result)
return { modules = result, count = #result }
end
)
MCPServer.registerTool(
"resolve_symbol",
"Resolves a symbol or expression to its memory address (e.g. 'kernel32.dll!CreateFileW', 'game.exe+0x1000').",
{
symbol = { type = "string", description = "Symbol name or expression." }
},
{ "symbol" },
function(args)
local addr = getAddressSafe(args.symbol)
if addr then
return {
symbol = args.symbol,
address = safeHex(addr),
decimal = addr
}
else
return { error = "Unable to resolve symbol: " .. tostring(args.symbol) }
end
end
)
MCPServer.registerTool(
"get_symbol_from_address",
"Retrieves symbolic or module+offset name for a memory address.",
{
address = { type = "string", description = "Memory address to inspect." }
},
{ "address" },
function(args)
local addr = resolveAddress(args.address)
if not addr then return { error = "Invalid address: " .. tostring(args.address) } end
local name = getNameFromAddress(addr, true, true, false)
return {
address = safeHex(addr),
name = name
}
end
)
MCPServer.registerTool(
"get_function_range",
"Estimates the start and end address of the function enclosing the given address.",
{
address = { type = "string", description = "Address within the function." }
},
{ "address" },
function(args)
local addr = resolveAddress(args.address)
if not addr then return { error = "Invalid address: " .. tostring(args.address) } end
local startAddr, stopAddr = getFunctionRange(addr)
if startAddr and stopAddr then
return {
address = safeHex(addr),
start = safeHex(startAddr),
["stop"] = safeHex(stopAddr),
size = stopAddr - startAddr
}
else
return { error = "Could not determine function range for " .. safeHex(addr) }
end
end
)
-- 13. Address List / Cheat Table Records
MCPServer.registerTool(
"get_address_list",
"Retrieves all records from Cheat Engine's address list (the cheat table).",
{},
{},
function(args)
local al = getAddressList()
local records = {}
for i = 0, al.Count - 1 do
local mr = al.MemoryRecord[i]
table.insert(records, {
id = mr.ID,
description = mr.Description,
address = mr.AddressString,
currentAddress = safeHex(mr.CurrentAddress),
varType = mr.VarType,
value = mr.Value,
active = mr.Active,
isScript = (mr.VarType == "vtAutoAssembler")
})
end
makeArray(records)
return { count = #records, records = records }
end
)
MCPServer.registerTool(
"create_memory_record",
"Creates a new record in Cheat Engine's address list (cheat table).",
{
description = { type = "string", description = "Description / label for the entry." },