-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathserver.py
More file actions
1395 lines (1079 loc) · 47.7 KB
/
server.py
File metadata and controls
1395 lines (1079 loc) · 47.7 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
"""
BotWithUs MCP Server
Bridges Claude Code to the game pipe server via msgpack over named pipes.
The game must be running with agentcpp injected.
Each game instance creates a pipe at \\\\.\\pipe\\BotWithUs_{PID}.
Use --pid to target a specific instance, or omit to auto-discover.
"""
import sys
import struct
import json
import argparse
import ctypes
import threading
from typing import Optional
import msgpack
import win32file
import win32pipe
import pywintypes
from mcp.server.fastmcp import FastMCP
mcp = FastMCP("botwithus", log_level="ERROR")
PIPE_PREFIX = "BotWithUs_"
MAX_BODY_SIZE = 16 * 1024 * 1024
def discover_game_pipes() -> list[dict]:
"""Find all running BotWithUs pipe instances. Returns list of {pid, pipe_name}."""
import os
results = []
try:
pipe_dir = r"\\.\pipe"
for name in os.listdir(pipe_dir):
if name.startswith(PIPE_PREFIX):
pid_str = name[len(PIPE_PREFIX):]
try:
pid = int(pid_str)
results.append({"pid": pid, "pipe_name": f"\\\\.\\pipe\\{name}"})
except ValueError:
continue
except OSError:
pass
return results
def get_pipe_name(pid: Optional[int] = None) -> str:
"""Get pipe name for a specific PID, or auto-discover the first available instance."""
if pid is not None:
return f"\\\\.\\pipe\\{PIPE_PREFIX}{pid}"
instances = discover_game_pipes()
if not instances:
raise ConnectionError(
"No BotWithUs game instances found. Is the game running with agentcpp injected?"
)
if len(instances) == 1:
return instances[0]["pipe_name"]
pids = [str(i["pid"]) for i in instances]
raise ConnectionError(
f"Multiple game instances found (PIDs: {', '.join(pids)}). "
f"Use --pid to specify which instance to connect to."
)
class PipeClient:
def __init__(self, pipe_name: str):
self._pipe_name = pipe_name
self._handle = None
self._lock = threading.Lock()
self._request_id = 0
def connect(self):
if self._handle is not None:
return
try:
self._handle = win32file.CreateFile(
self._pipe_name,
win32file.GENERIC_READ | win32file.GENERIC_WRITE,
0, None,
win32file.OPEN_EXISTING,
0, None,
)
win32pipe.SetNamedPipeHandleState(
self._handle, win32pipe.PIPE_READMODE_BYTE, None, None
)
except pywintypes.error as e:
self._handle = None
raise ConnectionError(
f"Cannot connect to game pipe ({self._pipe_name}). "
f"Is the game running with agentcpp injected? ({e})"
)
def disconnect(self):
if self._handle is not None:
try:
win32file.CloseHandle(self._handle)
except Exception:
pass
self._handle = None
def _send(self, data: dict):
body = msgpack.packb(data, use_bin_type=True)
header = struct.pack("<I", len(body))
win32file.WriteFile(self._handle, header + body)
def _recv(self) -> dict:
_, header = win32file.ReadFile(self._handle, 4)
if len(header) < 4:
raise ConnectionError("Pipe closed (incomplete header)")
body_len = struct.unpack("<I", header)[0]
if body_len == 0 or body_len > MAX_BODY_SIZE:
raise ConnectionError(f"Invalid body length: {body_len}")
chunks = []
remaining = body_len
while remaining > 0:
_, chunk = win32file.ReadFile(self._handle, remaining)
if not chunk:
raise ConnectionError("Pipe closed during body read")
chunks.append(chunk)
remaining -= len(chunk)
body = b"".join(chunks)
return msgpack.unpackb(body, raw=False, unicode_errors='replace')
def call(self, method: str, params: Optional[dict] = None) -> object:
with self._lock:
self.connect()
self._request_id += 1
req_id = self._request_id
msg = {"method": method, "id": req_id}
if params:
msg["params"] = params
try:
self._send(msg)
while True:
resp = self._recv()
if "event" in resp:
continue
if resp.get("id") == req_id:
if "error" in resp:
raise Exception(f"RPC error: {resp['error']}")
return resp.get("result")
except (pywintypes.error, ConnectionError, OSError):
self.disconnect()
raise
pipe: Optional[PipeClient] = None
def rpc(method: str, **params):
if pipe is None:
raise ConnectionError("PipeClient not initialized. Server startup failed.")
return pipe.call(method, params if params else None)
# ── Connection ────────────────────────────────────────────────────────
@mcp.tool()
def ping() -> dict:
"""Ping the game pipe server. Returns {"pong": true} if connected."""
return rpc("rpc.ping")
@mcp.tool()
def list_methods() -> list:
"""List all RPC methods registered on the game pipe server."""
return rpc("rpc.list_methods")
# ── Entity Queries ────────────────────────────────────────────────────
@mcp.tool()
def query_npcs(
radius: Optional[int] = None,
tile_x: int = 0, tile_y: int = 0,
plane: int = -1,
type_id: int = -1,
name_pattern: Optional[str] = None,
match_type: str = "contains",
case_sensitive: bool = False,
visible_only: bool = False,
in_combat: bool = False,
not_in_combat: bool = False,
option_pattern: Optional[str] = None,
option_match_type: str = "contains",
sort_by_distance: bool = False,
max_results: int = 0,
) -> list:
"""Query NPCs in the game world.
Returns list of NPCs with handle, server_index, type_id, tile_x, tile_y, name, etc.
Use handle with get_entity_info/get_entity_health for details.
Args:
radius: Max distance in tiles from (tile_x, tile_y). Omit for no spatial filter.
tile_x: Center X tile for radius/distance sorting.
tile_y: Center Y tile for radius/distance sorting.
plane: Filter to specific game plane (-1 = any).
type_id: Filter by NPC type ID (-1 = any).
name_pattern: Filter by name string.
match_type: How to match name: exact, prefix, suffix, contains, regex.
visible_only: Only return visible NPCs.
in_combat: Only NPCs currently in combat.
not_in_combat: Only NPCs not in combat.
option_pattern: Filter by right-click option text (e.g. "Talk-to", "Attack").
option_match_type: How to match option: exact, prefix, suffix, contains, regex.
sort_by_distance: Sort results by distance from tile_x/tile_y.
max_results: Limit number of results (0 = unlimited).
"""
p = {"type": "npc"}
if radius is not None:
p["radius"] = radius
if tile_x: p["tile_x"] = tile_x
if tile_y: p["tile_y"] = tile_y
if plane >= 0: p["plane"] = plane
if type_id >= 0: p["type_id"] = type_id
if name_pattern: p["name_pattern"] = name_pattern
if match_type != "contains": p["match_type"] = match_type
if case_sensitive: p["case_sensitive"] = True
if visible_only: p["visible_only"] = True
if in_combat: p["in_combat"] = True
if not_in_combat: p["not_in_combat"] = True
if option_pattern: p["option_pattern"] = option_pattern
if option_match_type != "contains": p["option_match_type"] = option_match_type
if sort_by_distance: p["sort_by_distance"] = True
if max_results > 0: p["max_results"] = max_results
return rpc("query_entities", **p)
@mcp.tool()
def query_players(
radius: Optional[int] = None,
tile_x: int = 0, tile_y: int = 0,
plane: int = -1,
name_pattern: Optional[str] = None,
match_type: str = "contains",
in_combat: bool = False,
sort_by_distance: bool = False,
max_results: int = 0,
) -> list:
"""Query players in the game world.
Returns list of players with handle, server_index, type_id, tile_x, tile_y, name, etc.
Args:
radius: Max distance in tiles from (tile_x, tile_y).
tile_x: Center X tile for radius/distance sorting.
tile_y: Center Y tile for radius/distance sorting.
plane: Filter to specific game plane (-1 = any).
name_pattern: Filter by player name.
match_type: How to match name: exact, prefix, suffix, contains, regex.
in_combat: Only players currently in combat.
sort_by_distance: Sort results by distance from tile_x/tile_y.
max_results: Limit number of results (0 = unlimited).
"""
p = {"type": "player"}
if radius is not None:
p["radius"] = radius
if tile_x: p["tile_x"] = tile_x
if tile_y: p["tile_y"] = tile_y
if plane >= 0: p["plane"] = plane
if name_pattern: p["name_pattern"] = name_pattern
if match_type != "contains": p["match_type"] = match_type
if in_combat: p["in_combat"] = True
if sort_by_distance: p["sort_by_distance"] = True
if max_results > 0: p["max_results"] = max_results
return rpc("query_entities", **p)
@mcp.tool()
def query_locations(
radius: Optional[int] = None,
tile_x: int = 0, tile_y: int = 0,
plane: int = -1,
type_id: int = -1,
name_pattern: Optional[str] = None,
match_type: str = "contains",
option_pattern: Optional[str] = None,
option_match_type: str = "contains",
sort_by_distance: bool = False,
max_results: int = 0,
) -> list:
"""Query game objects/locations (doors, trees, rocks, etc.) in the game world.
Returns list with handle, type_id, tile_x, tile_y, name, options, name_hash.
Args:
radius: Max distance in tiles from (tile_x, tile_y).
tile_x: Center X tile for radius/distance sorting.
tile_y: Center Y tile for radius/distance sorting.
plane: Filter to specific game plane (-1 = any).
type_id: Filter by location type ID (-1 = any).
name_pattern: Filter by name string.
match_type: How to match name: exact, prefix, suffix, contains, regex.
option_pattern: Filter by right-click option text (e.g. "Chop down", "Mine").
option_match_type: How to match option: exact, prefix, suffix, contains, regex.
sort_by_distance: Sort results by distance from tile_x/tile_y.
max_results: Limit number of results (0 = unlimited).
"""
p = {"type": "location"}
if radius is not None:
p["radius"] = radius
if tile_x: p["tile_x"] = tile_x
if tile_y: p["tile_y"] = tile_y
if plane >= 0: p["plane"] = plane
if type_id >= 0: p["type_id"] = type_id
if name_pattern: p["name_pattern"] = name_pattern
if match_type != "contains": p["match_type"] = match_type
if option_pattern: p["option_pattern"] = option_pattern
if option_match_type != "contains": p["option_match_type"] = option_match_type
if sort_by_distance: p["sort_by_distance"] = True
if max_results > 0: p["max_results"] = max_results
return rpc("query_entities", **p)
@mcp.tool()
def query_ground_items(
radius: Optional[int] = None,
tile_x: int = 0, tile_y: int = 0,
plane: int = -1,
sort_by_distance: bool = False,
max_results: int = 0,
) -> list:
"""Query ground items (dropped items on the floor).
Returns list with handle, tile_x, tile_y, and items array [{item_id, quantity}, ...].
Args:
radius: Max distance in tiles from (tile_x, tile_y).
tile_x: Center X tile for radius/distance sorting.
tile_y: Center Y tile for radius/distance sorting.
plane: Filter to specific game plane (-1 = any).
sort_by_distance: Sort results by distance from tile_x/tile_y.
max_results: Limit number of results (0 = unlimited).
"""
p = {}
if radius is not None:
p["radius"] = radius
if tile_x: p["tile_x"] = tile_x
if tile_y: p["tile_y"] = tile_y
if plane >= 0: p["plane"] = plane
if sort_by_distance: p["sort_by_distance"] = True
if max_results > 0: p["max_results"] = max_results
return rpc("query_ground_items", **p)
@mcp.tool()
def query_entities(
type: str,
radius: Optional[int] = None,
tile_x: int = 0, tile_y: int = 0,
plane: int = -1,
type_id: int = -1,
name_pattern: Optional[str] = None,
match_type: str = "contains",
case_sensitive: bool = False,
visible_only: bool = False,
moving_only: bool = False,
stationary_only: bool = False,
in_combat: bool = False,
not_in_combat: bool = False,
option_pattern: Optional[str] = None,
option_match_type: str = "contains",
sort_by_distance: bool = False,
max_results: int = 0,
) -> list:
"""Generic entity query. Prefer query_npcs/query_players/query_locations for typed queries.
Args:
type: Entity type - "npc", "player", "location", or "obj_stack".
radius: Max distance in tiles from (tile_x, tile_y).
tile_x: Center X tile for radius/distance sorting.
tile_y: Center Y tile for radius/distance sorting.
plane: Filter to specific game plane (-1 = any).
type_id: Filter by entity type ID (-1 = any).
name_pattern: Filter by name string.
match_type: How to match name: exact, prefix, suffix, contains, regex.
case_sensitive: Case sensitive name matching.
visible_only: Only visible entities.
moving_only: Only moving entities.
stationary_only: Only stationary entities.
in_combat: Only entities in combat.
not_in_combat: Only entities not in combat.
option_pattern: Filter by right-click option text (NPC/location only).
option_match_type: How to match option: exact, prefix, suffix, contains, regex.
sort_by_distance: Sort by distance from tile_x/tile_y.
max_results: Limit results (0 = unlimited).
"""
p = {"type": type}
if radius is not None: p["radius"] = radius
if tile_x: p["tile_x"] = tile_x
if tile_y: p["tile_y"] = tile_y
if plane >= 0: p["plane"] = plane
if type_id >= 0: p["type_id"] = type_id
if name_pattern: p["name_pattern"] = name_pattern
if match_type != "contains": p["match_type"] = match_type
if case_sensitive: p["case_sensitive"] = True
if visible_only: p["visible_only"] = True
if moving_only: p["moving_only"] = True
if stationary_only: p["stationary_only"] = True
if in_combat: p["in_combat"] = True
if not_in_combat: p["not_in_combat"] = True
if option_pattern: p["option_pattern"] = option_pattern
if option_match_type != "contains": p["option_match_type"] = option_match_type
if sort_by_distance: p["sort_by_distance"] = True
if max_results > 0: p["max_results"] = max_results
return rpc("query_entities", **p)
# ── Entity Details ────────────────────────────────────────────────────
@mcp.tool()
def get_entity_info(handle: int) -> dict:
"""Get full info for an NPC or player by handle.
Returns: handle, server_index, type_id, tile_x, tile_y, tile_z, name, name_hash,
is_moving, is_hidden, animation_id, stance_id, health, max_health, following_index,
overhead_text, combat_level.
"""
return rpc("get_entity_info", handle=handle)
@mcp.tool()
def get_entity_name(handle: int) -> dict:
"""Get the name of an entity by handle. Returns {"name": "..."}."""
return rpc("get_entity_name", handle=handle)
@mcp.tool()
def get_entity_health(handle: int) -> dict:
"""Get current and max health of an entity. Returns {"health": int, "max_health": int}."""
return rpc("get_entity_health", handle=handle)
@mcp.tool()
def get_entity_position(handle: int) -> dict:
"""Get tile position of an entity. Returns {"tile_x": int, "tile_y": int, "plane": int}."""
return rpc("get_entity_position", handle=handle)
@mcp.tool()
def get_entity_animation(handle: int) -> dict:
"""Get current animation ID of an entity. Returns {"animation_id": int}."""
return rpc("get_entity_animation", handle=handle)
@mcp.tool()
def is_entity_valid(handle: int) -> dict:
"""Check if an entity handle is still valid. Returns {"valid": bool}."""
return rpc("is_entity_valid", handle=handle)
@mcp.tool()
def get_entity_hitmarks(handle: int) -> list:
"""Get active hitmarks (damage splats) on an entity. Returns [{damage, type, cycle}, ...]."""
return rpc("get_entity_hitmarks", handle=handle)
@mcp.tool()
def get_animation_length(animation_id: int) -> dict:
"""Get the byte length of an animation archive. Returns {"length": int} (-1 if not found)."""
return rpc("get_animation_length", animation_id=animation_id)
# ── Projectiles, Spot Anims, Hint Arrows ──────────────────────────────
@mcp.tool()
def query_projectiles(
projectile_id: int = -1,
plane: int = -1,
max_results: int = 0,
) -> list:
"""Query active projectiles in the game world.
Returns list with handle, projectile_id, start_x/y, end_x/y, plane,
target_index, source_index, start_cycle, end_cycle.
Args:
projectile_id: Filter by projectile ID (-1 = any).
plane: Filter by plane (-1 = any).
max_results: Limit results (0 = unlimited).
"""
p = {}
if projectile_id >= 0: p["projectile_id"] = projectile_id
if plane >= 0: p["plane"] = plane
if max_results > 0: p["max_results"] = max_results
return rpc("query_projectiles", **p)
@mcp.tool()
def query_spot_anims(
anim_id: int = -1,
plane: int = -1,
max_results: int = 0,
) -> list:
"""Query active spot animations (graphic effects at locations).
Returns list with handle, anim_id, tile_x, tile_y, tile_z.
Args:
anim_id: Filter by animation ID (-1 = any).
plane: Filter by plane (-1 = any).
max_results: Limit results (0 = unlimited).
"""
p = {}
if anim_id >= 0: p["anim_id"] = anim_id
if plane >= 0: p["plane"] = plane
if max_results > 0: p["max_results"] = max_results
return rpc("query_spot_anims", **p)
@mcp.tool()
def query_hint_arrows(max_results: int = 0) -> list:
"""Query active hint arrows (tutorial/quest indicators).
Returns list with handle, type, tile_x, tile_y, tile_z, target_index.
Args:
max_results: Limit results (0 = unlimited).
"""
p = {}
if max_results > 0: p["max_results"] = max_results
return rpc("query_hint_arrows", **p)
# ── Worlds ────────────────────────────────────────────────────────────
@mcp.tool()
def query_worlds(include_activity: bool = False) -> list:
"""Query available game worlds.
Returns list with world_id, properties, population, ping.
Optionally includes activity string.
Args:
include_activity: Include the world's activity description string.
"""
p = {}
if include_activity: p["include_activity"] = True
return rpc("query_worlds", **p)
@mcp.tool()
def get_current_world() -> dict:
"""Get the current world ID. Returns {"world_id": int} (-1 if not logged in)."""
return rpc("get_current_world")
@mcp.tool()
def compute_name_hash(name: str) -> dict:
"""Compute the name hash for a string. Useful for name_hash entity filtering.
Args:
name: The name string to hash.
"""
return rpc("compute_name_hash", name=name)
# ── Components / UI ──────────────────────────────────────────────────
@mcp.tool()
def query_components(
interface_id: int = -1,
item_id: int = -1,
sprite_id: int = -1,
type: int = -1,
text_pattern: Optional[str] = None,
match_type: str = "contains",
case_sensitive: bool = False,
option_pattern: Optional[str] = None,
visible_only: bool = False,
max_results: int = 0,
) -> list:
"""Query UI components (interface elements like buttons, text, items).
Returns list with handle, interface_id, component_id, sub_component_id,
type, item_id, item_count, sprite_id.
Args:
interface_id: Filter to specific interface (-1 = any).
item_id: Filter by item ID shown in component (-1 = any).
sprite_id: Filter by sprite ID (-1 = any).
type: Filter by component type byte (-1 = any).
text_pattern: Filter by text content.
match_type: How to match text: exact, contains, regex.
case_sensitive: Case sensitive text matching.
option_pattern: Filter by right-click option text.
visible_only: Only visible components.
max_results: Limit results (0 = unlimited).
"""
p = {}
if interface_id >= 0: p["interface_id"] = interface_id
if item_id >= 0: p["item_id"] = item_id
if sprite_id >= 0: p["sprite_id"] = sprite_id
if type >= 0: p["type"] = type
if text_pattern: p["text_pattern"] = text_pattern
if match_type != "contains": p["match_type"] = match_type
if case_sensitive: p["case_sensitive"] = True
if option_pattern: p["option_pattern"] = option_pattern
if visible_only: p["visible_only"] = True
if max_results > 0: p["max_results"] = max_results
return rpc("query_components", **p)
@mcp.tool()
def is_component_valid(interface_id: int, component_id: int, sub_component_id: int = -1) -> dict:
"""Check if a UI component exists and is valid.
Args:
interface_id: Interface ID.
component_id: Component ID within the interface.
sub_component_id: Sub-component ID (-1 for top-level).
"""
return rpc("is_component_valid",
interface_id=interface_id, component_id=component_id, sub_component_id=sub_component_id)
@mcp.tool()
def get_component_text(interface_id: int, component_id: int) -> dict:
"""Get the text content of a UI component. Returns {"text": str|null}."""
return rpc("get_component_text", interface_id=interface_id, component_id=component_id)
@mcp.tool()
def get_component_item(interface_id: int, component_id: int, sub_component_id: int = -1) -> dict:
"""Get item shown in a UI component. Returns {"item_id": int, "count": int}."""
return rpc("get_component_item",
interface_id=interface_id, component_id=component_id, sub_component_id=sub_component_id)
@mcp.tool()
def get_component_position(interface_id: int, component_id: int) -> dict:
"""Get screen position and size of a UI component. Returns {x, y, width, height}."""
return rpc("get_component_position", interface_id=interface_id, component_id=component_id)
@mcp.tool()
def get_component_options(interface_id: int, component_id: int) -> list:
"""Get right-click menu options of a UI component. Returns list of option strings."""
return rpc("get_component_options", interface_id=interface_id, component_id=component_id)
@mcp.tool()
def get_component_sprite_id(interface_id: int, component_id: int) -> dict:
"""Get the sprite ID of a UI component. Returns {"sprite_id": int} (-1 if none)."""
return rpc("get_component_sprite_id", interface_id=interface_id, component_id=component_id)
@mcp.tool()
def get_component_type(interface_id: int, component_id: int) -> dict:
"""Get the type of a UI component. Returns {"type": int, "type_name": str}."""
return rpc("get_component_type", interface_id=interface_id, component_id=component_id)
@mcp.tool()
def get_component_children(interface_id: int, component_id: int) -> list:
"""Get child sub-components of a UI component.
Returns list with handle, interface_id, component_id, sub_component_id,
type, item_id, item_count, sprite_id.
"""
return rpc("get_component_children", interface_id=interface_id, component_id=component_id)
@mcp.tool()
def get_open_interfaces() -> list:
"""Get all currently open interfaces. Returns [{parent_hash, interface_id}, ...]."""
return rpc("get_open_interfaces")
@mcp.tool()
def is_interface_open(interface_id: int) -> dict:
"""Check if a specific interface is currently open. Returns {"open": bool}."""
return rpc("is_interface_open", interface_id=interface_id)
# ── Inventory / Items ─────────────────────────────────────────────────
@mcp.tool()
def query_inventories() -> list:
"""List all active inventories. Returns [{inventory_id, item_count, capacity}, ...]."""
return rpc("query_inventories")
@mcp.tool()
def query_inventory_items(
inventory_id: int = -1,
item_id: int = -1,
min_quantity: int = 0,
non_empty: bool = True,
max_results: int = 0,
) -> list:
"""Query items in inventories.
Returns list with handle, item_id, quantity, slot.
Args:
inventory_id: Filter to specific inventory (-1 = all).
item_id: Filter by item ID (-1 = any).
min_quantity: Minimum quantity filter (0 = no filter).
non_empty: Exclude empty slots (default true).
max_results: Limit results (0 = unlimited).
"""
p = {}
if inventory_id >= 0: p["inventory_id"] = inventory_id
if item_id >= 0: p["item_id"] = item_id
if min_quantity > 0: p["min_quantity"] = min_quantity
if not non_empty: p["non_empty"] = False
if max_results > 0: p["max_results"] = max_results
return rpc("query_inventory_items", **p)
@mcp.tool()
def get_inventory_item(inventory_id: int, slot: int) -> dict:
"""Get a specific inventory item by slot. Returns {handle, item_id, quantity, slot}."""
return rpc("get_inventory_item", inventory_id=inventory_id, slot=slot)
@mcp.tool()
def get_item_vars(inventory_id: int, slot: int) -> list:
"""Get item variables for an item in a specific slot. Returns [{var_id, value}, ...]."""
return rpc("get_item_vars", inventory_id=inventory_id, slot=slot)
@mcp.tool()
def get_item_var_value(inventory_id: int, slot: int, var_id: int) -> dict:
"""Get a specific item variable value. Returns {"value": int}."""
return rpc("get_item_var_value", inventory_id=inventory_id, slot=slot, var_id=var_id)
# ── Player Stats ──────────────────────────────────────────────────────
@mcp.tool()
def get_player_stats() -> list:
"""Get all player skill stats. Returns [{skill_id, level, boosted_level, max_level, xp}, ...]."""
return rpc("get_player_stats")
@mcp.tool()
def get_player_stat(skill_id: int) -> dict:
"""Get a specific skill stat. Returns {skill_id, level, boosted_level, max_level, xp}."""
return rpc("get_player_stat", skill_id=skill_id)
# ── Chat ──────────────────────────────────────────────────────────────
@mcp.tool()
def query_chat_history(message_type: int = -1, max_results: int = 50) -> list:
"""Query chat message history.
Returns [{index, message_type, text, player_name}, ...].
Args:
message_type: Filter by message type (-1 = all).
max_results: Max messages to return (default 50).
"""
p = {}
if message_type >= 0: p["message_type"] = message_type
if max_results != 50: p["max_results"] = max_results
return rpc("query_chat_history", **p)
# ── Vars ──────────────────────────────────────────────────────────────
@mcp.tool()
def get_varp(var_id: int) -> dict:
"""Get a player variable (varp) value. Returns {"value": int}."""
return rpc("get_varp", var_id=var_id)
@mcp.tool()
def get_varbit(varbit_id: int) -> dict:
"""Get a varbit value. Returns {"value": int}."""
return rpc("get_varbit", varbit_id=varbit_id)
@mcp.tool()
def get_varc_int(varc_id: int) -> dict:
"""Get a client variable (varc) integer value. Returns {"value": int}."""
return rpc("get_varc_int", varc_id=varc_id)
@mcp.tool()
def get_varc_string(varc_id: int) -> dict:
"""Get a client variable (varc) string value. Returns {"value": str}."""
return rpc("get_varc_string", varc_id=varc_id)
@mcp.tool()
def query_varbits(varbit_ids: list[int]) -> list:
"""Get multiple varbit values at once. Returns [{varbit_id, value}, ...].
Args:
varbit_ids: List of varbit IDs to query.
"""
return rpc("query_varbits", varbit_ids=varbit_ids)
# ── Cache ─────────────────────────────────────────────────────────────
@mcp.tool()
def get_cache_file(index_id: int, archive_id: int, file_id: int = 0) -> dict:
"""Read a file from the game cache. Returns {"data": bytes, "size": int}.
Args:
index_id: Cache index ID.
archive_id: Archive ID within the index.
file_id: File ID within the archive (default 0).
"""
return rpc("get_cache_file", index_id=index_id, archive_id=archive_id, file_id=file_id)
@mcp.tool()
def get_cache_file_count(index_id: int, archive_id: int = 0, shift: int = 0) -> dict:
"""Get number of files in a cache index/archive. Returns {"count": int}.
Args:
index_id: Cache index ID.
archive_id: Archive ID (default 0).
shift: Bit shift for addressing (default 0).
"""
return rpc("get_cache_file_count", index_id=index_id, archive_id=archive_id, shift=shift)
# ── Config Type Lookups ──────────────────────────────────────────────
@mcp.tool()
def get_item_type(id: int) -> dict:
"""Get item definition by ID. Returns name, options, price, equipment slot, stackability, etc.
Args:
id: Item type ID.
"""
return rpc("get_item_type", id=id)
@mcp.tool()
def get_npc_type(id: int) -> dict:
"""Get NPC definition by ID. Returns name, options, combat level, transforms, etc.
Args:
id: NPC type ID.
"""
return rpc("get_npc_type", id=id)
@mcp.tool()
def get_location_type(id: int) -> dict:
"""Get location/object definition by ID. Returns name, options, size, interaction type, etc.
Args:
id: Location type ID.
"""
return rpc("get_location_type", id=id)
@mcp.tool()
def get_enum_type(id: int) -> dict:
"""Get enum (key-value mapping) definition by ID. Enums map inputs to outputs (e.g. skill IDs to names).
Returns id, input/output type IDs, default values, and entries map.
Args:
id: Enum type ID.
"""
return rpc("get_enum_type", id=id)
@mcp.tool()
def get_struct_type(id: int) -> dict:
"""Get struct definition by ID. Structs are parameter bags (key-value pairs of int/string).
Returns id and params map.
Args:
id: Struct type ID.
"""
return rpc("get_struct_type", id=id)
@mcp.tool()
def get_sequence_type(id: int) -> dict:
"""Get animation sequence definition by ID. Returns frame data, priority, loop info, hand items, etc.
Args:
id: Animation sequence (anim) ID.
"""
return rpc("get_sequence_type", id=id)
@mcp.tool()
def get_quest_type(id: int) -> dict:
"""Get quest definition by ID. Returns name, difficulty, requirements, progress tracking vars, etc.
Args:
id: Quest type ID.
"""
return rpc("get_quest_type", id=id)
# ── Action Queue (read-only) ─────────────────────────────────────────
@mcp.tool()
def get_action_queue_size() -> dict:
"""Get the number of actions currently queued. Returns {"size": int}."""
return rpc("get_action_queue_size")
@mcp.tool()
def get_action_history(max_results: int = 50, action_id_filter: int = -1) -> list:
"""Get recent action history (newest first).
Returns [{action_id, param1, param2, param3, timestamp, delta}, ...].
Args:
max_results: Max entries to return (default 50).
action_id_filter: Filter to specific action ID (-1 = all).
"""
p = {}
if max_results != 50: p["max_results"] = max_results
if action_id_filter >= 0: p["action_id_filter"] = action_id_filter
return rpc("get_action_history", **p)
@mcp.tool()
def get_last_action_time() -> dict:
"""Get timestamp of the last action. Returns {"timestamp": value}."""
return rpc("get_last_action_time")
@mcp.tool()
def are_actions_blocked() -> dict:
"""Check if action processing is currently blocked. Returns {"blocked": bool}."""
return rpc("are_actions_blocked")
# ── Game State ────────────────────────────────────────────────────────
@mcp.tool()
def get_account_info() -> dict:
"""Get account information for the current client session.
Returns: client_type (0=jagex, 1=steam), client_state, session_id,
ip_hash, jx_display_name (from launcher), jx_character_id,
display_name (in-game, null if not logged in), is_member,
server_index, logged_in, login_progress, login_status.
"""
return rpc("get_account_info")
@mcp.tool()
def get_local_player() -> dict:
"""Get the local player's info (position, name, combat level, health, animation, etc.).
Returns: server_index, name, tile_x, tile_y, plane, is_member, is_moving,
animation_id, stance_id, health, max_health, combat_level, overhead_text,
target_index, target_type.
"""
return rpc("get_local_player")
@mcp.tool()
def get_game_cycle() -> dict:
"""Get the current game tick counter. Returns {"cycle": int}."""
return rpc("get_game_cycle")
@mcp.tool()
def get_login_state() -> dict:
"""Get the current login state. Returns {"state": int, "login_progress": int, "login_status": int}."""
return rpc("get_login_state")
@mcp.tool()
def get_mini_menu() -> list:
"""Get the current right-click menu entries.
Returns list of [{option_text, action_id, type_id, item_id, param1, param2, param3}, ...].
"""
return rpc("get_mini_menu")
@mcp.tool()