Skip to main content
Glama

gmod-mcp

ExtReMLapin/gmod-mcp MCP server

MCP conformance tests


The GMod MCP server that runs inside the game: Lua in every realm, maps, console, errors, screenshots, hook tracing, test clients and long-running jobs, straight from inside the game.

TIP

Quick start (Claude Code, Windows)

1. In Claude Code, run:

/plugin marketplace add ExtReMLapin/gmod-mcp
/plugin install gmod-mcp@gmod-mcp

2. Restart Claude Code.

3. Ask Claude: set up gmod-mcp

That's it. Claude installs the module in your game (it asks first) and starts Garry's Mod with -mcp.

4. Turn on updates (recommended): /plugin → Marketplaces → gmod-mcp → Enable auto-update. Claude Code keeps auto-update off for marketplaces other than Anthropic's, and no claude plugin subcommand turns it on. See Updates.

Other MCP clients, Linux or a dedicated server: see Install. Tested with Claude Code 2.1.325.

An MCP server that lives inside Garry's Mod. Drop one native module into your game and an AI coding agent (Claude Code or any MCP client) can run Lua in the menu, client and server realms, load maps, read the console and errors, inspect and edit the world, take screenshots, trace hooks and look up the documentation — on your own machine.

  • Self-contained: one DLL, one small Lua file and a small block in menu.lua (see What gets modified). With Claude Code, the plugin brings the module and adds a small bridge that Claude Code starts by itself. No Python, no Node, nothing to run yourself.

  • Local only: listens on 127.0.0.1 with a bearer token, refuses pages from other sites, inactive unless the game is started with -mcp.

  • Safe by default: never touches the client realm while you are connected to someone else's server.

Related MCP server: gmod-mcp

Contents

Install

You need Garry's Mod with the 64-bit binaries (the default on current Steam builds: bin\win64\gmod.exe, or gmod_win64.exe at the root of the game folder on older installs). Two ways: the Claude Code plugin (the Quick start at the top of this page), or by hand for any other MCP client.

Claude Code plugin

The repository is also a Claude Code plugin marketplace. In Claude Code:

/plugin marketplace add ExtReMLapin/gmod-mcp
/plugin install gmod-mcp@gmod-mcp

From a shell: claude plugin marketplace add ExtReMLapin/gmod-mcp, then claude plugin install gmod-mcp@gmod-mcp. Restart Claude Code, then ask Claude set up gmod-mcp: its skill copies the two files into the game (after asking you) and starts the game with -mcp. Claude Code stays connected while the game is closed: the tools say so, Claude starts the game again instead of giving up, and they work again as soon as it is up, no reconnection needed. Updates: see Updates.

The plugin holds:

  • the gmod MCP server: gmod-mcp-bridge, a small stdio program Claude Code starts by itself. It relays to the game, stays connected while the game is closed (tools then answer game_not_running), and tells Claude Code when the game is back. It reads the token from its file, so nothing secret lands in Claude Code's settings;

  • the module of the same version, for the game (Windows and Linux binaries);

  • one skill: how to install or update the module, find the game folder, start the game with -mcp, run several games, set up a dedicated server. It asks before touching the game folder and never restarts a game you just closed.

Each release publishes the plugin as one zip (gmod-mcp-plugin.zip, pinned by its SHA-256 in the marketplace), so the repository holds no binaries.

If you added the server by hand earlier (claude mcp add ... gmod), the plugin does not replace that entry: both stay and every tool is listed twice. Remove the old one with claude mcp remove gmod (add -s user if you added it with --scope user; an entry added without a scope only exists in the folder where you ran the command).

Right after the install, Claude Code may say "1 userConfig option not yet set": that is the option that turns the feedback offers on or off, which is on by default. Nothing to do.

Remove the plugin with /plugin uninstall gmod-mcp@gmod-mcp.

By hand, 1. Garry's Mod side (drag and drop)

  1. Download gmod-mcp-win64.zip (Windows) or gmod-mcp-linux64.zip (a Linux dedicated server) from the latest release.

  2. Open it. Everything sits in a top folder, gmod-mcp-win64/ (or gmod-mcp-linux64/): drag the garrysmod folder from inside it onto your game folder (…\steamapps\common\GarrysMod, the one that already contains a garrysmod folder). Accept the merge. That adds two files: garrysmod/lua/bin/gmsv_mcpagent_win64.dll and garrysmod/lua/autorun/server/mcpagent_boot.lua.

  3. In Steam: Garry's Mod → Properties → Launch options, add:

    -mcp

    Recommended, so the game keeps running at full speed in the background: -mcp -windowed +engine_no_focus_sleep 0 +snd_mute_losefocus 0

  4. Start the game and load any map once (Start new game). The module installs its main-menu loader by itself; from then on it starts at the main menu every time. The console says [mcpagent] main-menu loader installed ….

By hand, 2. MCP client side

Open the game console (~) and type:

mcpagent_setup

It prints the exact setup for your machine, token included. For Claude Code without the plugin, paste this in a terminal (--scope user makes it available in every folder; without it the entry only exists in the folder where you ran the command):

claude mcp add --scope user --transport http gmod http://127.0.0.1:27080/mcp --header "Authorization: Bearer <token>"

Restart Claude Code. That's it. The same output also shows a .mcp.json snippet for other MCP clients (Streamable HTTP + bearer token). The token is created once in %APPDATA%\gmod-mcp\token (Linux: $XDG_CONFIG_HOME/gmod-mcp/token, ~/.config/gmod-mcp/token by default), never changes, and is only printed when you ask for it — keep it private.

Without the plugin, Claude Code only connects if the game is already running when it starts; otherwise use /mcp, Reconnect, once the game is up. The plugin avoids that. Other MCP clients can do the same with gmod-mcp-bridge from the release zip, a stdio server that stays up while the game is closed.

Each release also attaches gmod-mcp.mcpb, the same bridge (Windows and Linux x86-64) as an MCP Bundle, and is listed in the official MCP Registry as io.github.ExtReMLapin/gmod-mcp: MCP clients that install from the registry or open .mcpb files can use it. It is only the bridge: the game still needs the module from step 1 above, and the game still has to run with -mcp.

Dedicated server

Same zip (gmod-mcp-linux64.zip for a Linux server), same drag and drop of its garrysmod folder into the server's folder (the one that holds garrysmod and the server binary), and start the server with -mcp. Only the server realm exists in that mode. The module is 64-bit: start srcds_win64.exe (Linux: srcds_run_x64). On Linux the default branch of the dedicated server has no 64-bit binary: install it with +app_update 4020 -beta x86-64.

Linux server branches:

  • x86-64 works on Ubuntu 22.04 (glibc 2.35, where it was tested) and newer.

  • dev (64-bit srcds_linux64) needs glibc 2.38 and GLIBCXX_3.4.32 (Ubuntu 24.04 or newer): the server binary itself does not start on older systems, with or without the module.

  • The public (default) branch is 32-bit only. The module is 64-bit and is not loaded there; the server starts normally, without gmod-mcp and without a crash.

game_quit on a dedicated server: the engine blocks the console quit from server Lua, so on Linux the module ends the process itself with SIGTERM (the server's own clean shutdown) half a second after it answered. On a Windows dedicated server there is no such path and game_quit answers the error blocked (stop the server from its console, or use game_terminate, which kills it at once). game_terminate works the same on both systems.

mcpagent_setup works in the server console too. The plugin and the bridge reach a server running on your machine like a game: a server alone takes port 27080; next to a client game, use instances_list and pass instance (see Several games at once). The plugin's skill can also set a server up for you.

Updates

  • What updates by itself. With auto-update on (/plugin → Marketplaces → gmod-mcp → Enable auto-update), Claude Code updates the plugin a few minutes after a session starts; the new version runs from the next start of Claude Code (or after /reload-plugins). Claude Code keeps it off for third-party marketplaces and no claude plugin subcommand turns it on: use that menu.

  • By hand, in a shell:

    claude plugin marketplace update gmod-mcp
    claude plugin update gmod-mcp@gmod-mcp

    then restart Claude Code (or /reload-plugins). The first command matters: Claude Code compares with its local copy of the marketplace, and without refreshing it plugin update answers "already at the latest version".

  • What is in the plugin: the bridge Claude Code talks to, the skill, and a copy of the module for the game.

  • What does not update by itself: the module loaded by the game (garrysmod/lua/bin/gmsv_mcpagent_*.dll). After a plugin update, quit Garry's Mod and ask Claude update gmod-mcp: the skill copies the new module into the game. Until then, tool results carry a warning that names both versions: the bridge learns the module's version when the game first answers, so it shows from a moment after that, and the server instructions carry it too.

  • Without the plugin: quit the game (it keeps the DLL locked), download the new zip from the releases and overwrite the two files. The version warning is a feature of the bridge, so only the plugin gives it.

  • What the commands download: /plugin marketplace add clones this repository (to read its .claude-plugin/marketplace.json); /plugin install and updates download only the release zip of that version (gmod-mcp-plugin.zip, checked against its SHA-256), not the source code.

Feedback from agents

Agents using gmod-mcp are asked (server instructions, guide, skill) to note the frictions they meet with it and, at the end of a task, to offer you to report the ones that cost real time or a feature. If you agree, they draft the issue in English with no secrets, paths, project names or code, look for duplicates, and file it with gh when it is installed and signed in (otherwise they give you a prefilled link: one click). Issues carry the agent-feedback label.

To turn the offers off, set the plugin option feedback_offers (on by default) to false: /plugin configure gmod-mcp@gmod-mcp in Claude Code, or in a shell:

echo '{"feedback_offers": "false"}' | claude plugin configure gmod-mcp@gmod-mcp --values-stdin

Then restart Claude Code.

Comparison with other servers

As of 2026-11-14, gmod-mcp covers the most capabilities of the 22 Garry's Mod MCP servers we compared. Code read, nothing executed · method & full table

Repos: ExtReMLapin/gmod-mcp · AmyJeanes/GMod-MCP-Server · Sycatle/gmod-mcp · TomDotBat/gmcl_mcp · Pollux12/vscode-gmod-glua-ls · Celant/GmodMCP · Earu/GTerm · mathis1M/gmod-mcp · 14 more

Tools

Area

Tools

Session

status, map_list, map_load, disconnect, game_quit, game_terminate, wait_for, wait_frames

Lua

lua_exec, lua_exec_file, lua_reload (run an addon file again from the disk, in its realms), lua_check (syntax and globals of a snippet, file or whole addon, without running it), lua_job (long work spread over frames, with progress; async: true with lua_job_status / lua_job_cancel), lua_inspect, lua_function_source (is a running function the code on disk?), lua_mount (this game loads Lua from your worktree first), lua_file_write / _read / _list / _delete, tests_run (GLuaTest format)

Hooks

hook_list, hook_trace, perf_hook_cost

Console

console_exec (a 1; b 2 runs two commands like the console; an unknown command is an error; convars it sets are read back), console_read, console_wait (block until N lines match, e.g. the end of a batch), console_buffer, convar_get, convar_set, concommand_list

Errors

errors_since, errors_clear (Lua errors from all three realms, with stack)

World

ents_find, ent_info, ent_spawn, ent_remove, ent_fire, players_list, player_set, bots_add, trace, trace_through (every surface crossed, with thickness and material)

Rendering

screenshot (works at the main menu, in a dialog and on a loading screen too, on Windows), screenshot_from (arbitrary camera), debug_draw, debug_clear

UI input

ui_click (click or scroll at a pixel of a screenshot), ui_key (keys and text; characters outside the machine's ANSI code page are refused, the engine would alter them): dialogs, Derma and menu buttons that have no console command. Windows test clients only; posted to the game's own window, your real mouse and focus are untouched

Sound

sound_emit, sound_trace

Performance

perf_snapshot

Documentation

api_search (what really exists in each realm), wiki_search, wiki_page (wiki.facepunch.com, cached)

Events

events_wait (long-poll: map_loaded, lua_error, main_thread_stalled…), reports_read / reports_channels / reports_clear (fed by mcpagent.report() from your scripts)

Instances

instances_list; with the plugin (Windows): instances_launch (1 to 8 test clients), instances_close, instance_select (the session's default instance)

Besides tools, the server offers:

  • Prompts (slash commands in Claude Code): write-lua-job, debug-errors, run-tests, check-map, with completion of map names, realms and test files.

  • Resources: the agent guide (mcpagent://guide), gmod://errors and gmod://console (subscribable: the client is told when they change), and the templates gmod://wiki/{page} and gmod://lua/{path}.

  • Progress and cancellation: long tools report progress while they run, and stop when the client cancels. Long operations (map_load, long waits, long jobs) run as background MCP Tasks for clients that support them.

  • Confirmation: changing a convar saved in your config.cfg asks you first (when the client supports it).

Long-running Lua jobs

lua_exec runs code in one go, and the game is frozen while it runs. For anything longer, lua_job runs the script as a coroutine resumed once per frame. The script talks back through a job object, and its progress shows up in Claude Code while it runs:

local props = 0
local all = ents.GetAll()
for i, ent in ipairs(all) do
    if ent:GetClass() == "prop_physics" then props = props + 1 end
    if i % 100 == 0 then job:progress(i, #all, props .. " props so far") end
    job:step()  -- hands control back to the game once this frame's time slice is used
end
return { props = props }

Also available: job:sleep(seconds), job:frames(n), job:wait(fn, timeout), job:report(value) for intermediate results, job:dt() (real seconds since the last resume; FrameTime() on the server is the tick step, not that interval), job:call(realm, code) (runs a chunk in the other realm of the instance and returns its values, so one job can move the player on the server and check what the client sees), and args (also job.args) for the call's arguments. async: true returns at once with a job id (lua_job_status, lua_job_cancel), and fresh_env: true keeps the script's globals out of the game's _G. The agent learns this protocol from the tool description and the write-lua-job prompt.

Testing a branch: the mounted Lua folder

Every game process loads the addons from the same garrysmod/addons/ folder, so an agent that works in a git worktree of an addon cannot test its branch in one test client without changing the folder every other client (and your own game) uses. The mounted folder solves this per process: lua_mount {path: "D:/dev/my-addon-wt"} (or instances_launch {lua_mount: "D:/dev/my-addon-wt"} for a new test client) makes that one game look for Lua files in the worktree before every addon. include(), autorun files and AddCSLuaFile then get the branch's files, at every map load, and the other games keep the installed addon.

instances_launch {count: 1, owner: "fork-a", lua_mount: "D:/dev/my-addon-wt", map: "gm_construct"}
lua_function_source {realm: "server", expr: "MyAddon.Update"}   -> source: the worktree's file
  • path is the addon's root (the folder that contains lua/) or its lua/ folder, absolute. Its gamemodes/ folder is overlaid too (materials, sounds and models are not: see the table below).

  • The path must be ASCII-only: the game's file system lists a folder with non-ASCII characters but loads none of its files, so lua_mount refuses it. Use an ASCII junction instead (mklink /J C:\dev\my-addon "D:\Développement\my-addon").

  • It applies to files loaded from then on. Code that already runs is not run again: after lua_mount, call map_load. instances_launch {lua_mount} sets it before the first map, so nothing more is needed there.

  • lua_mount {} shows the current mounted folder and the engine's Lua search paths; lua_mount {path: null} removes it (from the next map load).

  • The engine caches Lua files by name and file time; lua_mount empties that cache when it changes (so an addon file and its worktree copy with the same name and time cannot be mixed up). Example: the worktree D:/dev/my-addon-wt of the addon installed as garrysmod/addons/my_addon, mounted with lua_mount {path: "D:/dev/my-addon-wt"} then map_load:

File on disk

What this game does with it

D:/dev/my-addon-wt/lua/autorun/my_addon.lua

runs as autorun/my_addon.lua (instead of the installed one)

D:/dev/my-addon-wt/lua/my_addon/core.lua

what include("my_addon/core.lua") loads

D:/dev/my-addon-wt/lua/my_addon/new.lua (only in the branch)

found by include("my_addon/new.lua")

garrysmod/addons/my_addon/lua/my_addon/old.lua (deleted in the branch)

still loaded from the installed addon

D:/dev/my-addon-wt/gamemodes/<gm>/...

gamemode files

materials/, sound/, models/, anything else

not mounted

  • What sees the mounted folder (checked in game): autorun files, include(), AddCSLuaFile (the client gets the folder's copy), the console's lua_openscript / lua_openscript_cl, file.Read / file.Find with "LUA", and gmod-mcp's lua_exec_file, lua_job {path}, lua_check, lua_reload and lua_function_source, which look in the same order as the engine. Not affected: materials, sounds, models, data/.

  • A file of the folder hides the installed addon's file with the same Lua path; files only in the game are still loaded, including a file your branch deleted.

  • The engine names the folder's files from the folder's root: debug.getinfo(f).source is @lua/my_addon/x.lua, not @addons/my_addon/lua/my_addon/x.lua.

  • No autorefresh: status.lua_mount.stale_files lists the folder's files that changed since each realm loaded them; lua_reload {mounted_changed: true} runs them again (or lua_reload {path} for one file, or map_load), then lua_function_source to check that the running function is the file's. A reload re-runs the file: it does not undo hooks or entities the old copy created. map_load warns when the folder changed during the load, and empties the engine's Lua file cache first.

  • Which copy ran: lua_function_source and lua_inspect on a function return from_mount and the real disk path (@lua/x.lua is the same name for the folder's copy and an installed one). It is recorded when the folder was put in front of the realm's Lua path, not guessed from the name.

  • Windows game clients only for now: not on Linux (the engine's filesystem interface is not verified there) nor on a dedicated server (its filesystem interface is not reachable the same way).

  • How it works: the engine's own search paths (IFileSystem::AddSearchPath at the head of the Lua path IDs), put back in front at every map start; see docs/REVERSE.md. Nothing is written to the game folder.

How it works

A Garry's Mod process runs up to three Lua states: menu (always there), client and server (created when a map loads, destroyed when it unloads). The module is loaded once per process, in the menu state, and drives the other two, re-injecting its small Lua runtime each time a map loads.

flowchart LR
    agent["AI agent<br/>(Claude Code)"] -- "MCP over HTTP<br/>127.0.0.1:27080" --> http

    subgraph game["the 64-bit game (one process)"]
        direction TB
        subgraph dll["gmsv_mcpagent (native module, loaded once)"]
            http["HTTP / MCP server<br/>(network thread)"] -- "job queue" --> pump["pump<br/>(main thread, every frame)"]
        end
        pump --> menu["menu state<br/>always present"]
        pump --> client["client state<br/>after a map loads"]
        pump --> server["server state<br/>singleplayer / listen"]
    end

All Lua runs on the game's main thread; the network thread only queues work, so a frozen game can still be inspected (status) and killed (game_terminate).

With the plugin, Claude Code does not talk to the game directly: it starts gmod-mcp-bridge (stdio) and the bridge relays every message to the game over that same HTTP connection. The bridge listens on nothing, answers while the game is closed (every tool listed, calls saying the game is not running), tells Claude Code when the game is back, and holds the tools that must work without a game: instances_launch, instances_close, instance_select.

Several games at once

Each game process (a client, a dedicated server…) has its own MCP server on its own port: 27080, then 27081, 27082… Nothing is shared between processes except a directory.

flowchart LR
    agent["AI agent"] --> coord["client game<br/>:27080 (holds the base port)"]
    coord -- "relay: instance=srcds-…" --> srcds["dedicated server<br/>:27081"]
    srcds -. "heartbeat every 2 s" .-> coord
  • The process holding the base port also acts as a directory and relay: instances_list shows every running game, and any tool accepts an instance argument to target another game. So Claude Code needs a single entry.

  • With one game running, nothing changes: no instance needed. With several, calls without instance are refused with ambiguous_instance (listing the ids) instead of guessing, and every answer says which game produced it (answered_by).

  • A game that crashes is told apart from one that quit: calls to it answer client_crashed (server_crashed for a dedicated server) with the name of the crash dump in crashes/ (when one was written) and the exit code, and instances_list shows it as crashed for an hour. The coordinator decides from the game's own goodbye at shutdown, a game_quit/game_terminate sent through it, a dump written just before the process ended, and its exit code. A process killed from outside with no dump looks like a crash with exit code 1. A call in flight to a game that dies is answered at once, and the answer carries the free memory of the machine (out of memory is a likely cause).

  • A game that is hung is flagged: instances_list gives stalled_s (seconds its main thread has been blocked) and fps_low_s (seconds under 10 fps), and the state becomes hung after 60 s (180 s during a map load) with the advice to close and relaunch; a call to a frozen process fails with instance_hung after 30 s without heartbeat. instances_launch checks the free commit and RAM first and refuses with low_memory (the figures, how many clients run) when they cannot hold the clients; ignore_low_memory: true overrides it.

  • If the game holding the base port exits, the others keep running; within a few seconds one of them takes the base port over and the rest register with it.

Several clients can run side by side too. With the Claude Code plugin, the instances_launch tool starts 1 to 8 test clients (small, frame-capped, on a private desktop, Windows for now), instances_close closes them (by id, pid or owner label), and instance_select sets the default instance of a session. Its description gives the measured cost: about 1.5 GB of RAM and a fifth of a CPU core per client. Sub-agents of one Claude Code session share that session: each one labels its clients with owner and closes only those. The label travels with the game (command line and heartbeat), so instances_list shows it on every instance and instances_close {owner} still finds clients started with keep: true by an earlier session; it never closes a game that is not one of our test clients.

Starting a game makes every other running Garry's Mod release its GPU resources for 2-10 s, and a map load ending in that window crashes that game (engine bug, Facepunch garrysmod-issues#7137). The bridge therefore makes instances_launch and map_load wait for each other (every session of the user shares the lock; waited_s / waited_reason in the result, errors map_load_in_progress / launch_in_progress when the wait would exceed timeout_s), and instances_launch {map} loads its maps after a 15 s settle delay; at most 2 maps load at a time across all sessions (a third map_load or launch load waits, map_load_in_progress at the timeout). It also sees map loads it did not start (console map, Lua, a script talking to the game: every game reports loading in instances_list), instances_launch waits for them too and map_load lists them (other_games_loading). It cannot hold back a game you start by hand, nor a console or Lua map load started while a launch is creating its processes: do not do those while other games load or launch. Right after a game starts, the other games can be unreachable for 15-18 s (instance_unreachable): wait and retry. Best order: launch all clients in one instances_launch, then work. GMOD_MCP_FP7137_WORKAROUND=0 turns the wait off. The game that holds the base port is the coordinator (instances_list shows it): when it ends, another game takes the role over in about 3 s and calls with instance answer the retryable coordinator_changing meanwhile (the bridge retries for 10 s); instances_close says when it closed the coordinator.

The clients start on a private Windows desktop (desktop: "private", the default; Windows only). What makes your own game freeze and glitch when a test client starts is the new game's broadcast, which only reaches the windows of its own desktop: a client on another desktop of the same window station never finds your game, so your game is not disturbed at all (measured: no video-memory drop, no blocked main thread). One desktop per bridge session, created at the first launch and closed once its last client is gone. What it changes: the clients have no window and no taskbar button (close them with instances_close, not by hand), they never take your focus (no -mcp_return_focus), and they are silent by default (-nosound; pass sound: true for sound tests, as SoundDuration of ADPCM WAV files differs without sound). ui_click, ui_key and screenshot still work (the module posts window messages inside the game's own process, and the screenshot is the engine's own capture). desktop: "shared" starts them on your desktop as before (visible window, the foreground handed back to you). The clients of one session share their desktop, so they still disturb each other: the waits above still apply. Games started by hand are not on it: they are covered by the waits only.

The clients share the game folder with your own game, including data/, cfg/ and the cookies (sv.db/cl.db): a test that writes there changes your game too, and nothing in the module redirects or hides those writes (it does not replace any of the game's file.* functions, so an addon that checks them sees the real ones). An addon that caches into data/ does it in the first seconds after the map loads (and an addon whose cache format changed may delete the old cache there), before commands can switch it off: its convars do not exist yet. Switch its writes off with early_lua, and clean up after the test.

early_lua runs your Lua in the client and server realms of each client before any addon's file, to set what an addon reads before its first write (an addon's convars and globals do not exist when commands run): set its own switch, hook a function, wrap a call. The module writes it into a small autorun file that it mounts in front of every addon, so it replaces nothing in the game. A Lua error in it is printed to the console, not raised. status shows early_lua (mounted, and error when the mount was refused: the code then does not run). The temporary folder of that file is removed by instances_close and at the end of the session; a client killed together with its bridge leaves it behind and the next launch removes folders nothing touched for three days.

Archived convars changed through commands, launch_args or fps_max are given back to your value from cfg/config.cfg before a clean quit, like the options the tool sets itself (the module restores those that exist and are archived at that moment; the list is fixed at launch, so a convar an addon creates later and that you set from console_exec is not restored). instances_close kills the process: nothing is written then.

Before a launch the bridge compares the module in the game folder (lua/bin) with the one the plugin ships: an older one refuses the launch with module_outdated and the update steps (ignore_outdated_module: true starts anyway), and instances_list / the game_not_running error show module_outdated while no game runs.

Test clients leave your video settings alone. Garry's Mod normally saves the window size it was started with as its video setting (resolution, anti-aliasing, ... in the registry). instances_launch starts its clients with -dxlevel 95, the level the engine keeps on current hardware: with that option the engine neither reads nor writes those settings, so your own resolution is still there at your next start. (Clients that older versions of gmod-mcp started could overwrite it: if your game opens small, set the resolution again in the video options. Clients you start by hand with -w/-h still save their size: add -dxlevel 95 to avoid it.)

Test clients leave your frame cap and focus options alone. instances_launch starts its clients with +fps_max 20 (30 for the normal preset), +fps_max_nofocus and +snd_mute_losefocus 0. Those convars are saved into cfg/config.cfg when a game quits cleanly, and your own game reads the same file: a test client that quit would have left your fps_max at 20. The clients now carry -mcp_test_client, and before one quits cleanly (game_quit, a quit sent through console_exec, the main menu's Quit button, the window's close button) the module sets each of these convars back to the value your config.cfg has at that moment, or to the convar's default when the file has no line for it. Not covered: a quit typed by hand in a test client's console. instances_close kills the process, which saves nothing. (A client that older versions started and then quit may have changed fps_max in your config: check it in the options.)

Frame cap, extra options and startup commands for test clients. instances_launch takes a few options for what the presets do not cover (they are checked before anything starts; a refused one is invalid_params naming it):

instances_launch {count: 1, fps_max: 300, fps_max_nofocus: 0,
                  commands: ["snd_mute_losefocus 0", "cl_showfps 1"],
                  launch_args: ["-noborder"], map: "gm_construct"}
  • fps_max and fps_max_nofocus (integers, 0 = no cap, otherwise 10 to 1000) replace the preset's frame cap (fps_max_nofocus follows fps_max when only that one is given). The result says what the clients run at (fps_max, fps_max_nofocus, fps_note).

  • commands are console commands run on each client once it answers, before the map loads, in order; instances[].commands says how each went. quit/exit, connect/retry/redirect/connect_lobby (gmod-mcp never connects to a server) and map changes (map, changelevel, load: use map) are refused.

  • launch_args are extra engine command-line tokens, one per array element (["+cl_showfps", "1"], a word without spaces, quotes or ;). Refused: what gmod-mcp sets itself (-multirun, -mcp*, -w, -h, -width, -height, the window-mode options, -dxlevel, -condebug, -game), +connect and +map. The options are listed on the Valve Developer Community, Command line options (and the Garry's Mod wiki for the GMod-specific ones); console commands and convars are listed by api_search and concommand_list.

The archived convars these options change (fps_max, a +convar token, a command such as cl_showfps 1 or toggle snd_mute_losefocus) are given back to your value before a clean quit, exactly like the built-in ones above (the bridge lists their names to the module with -mcp_restore_convars; this needs the module of the same release, an older one restores only the four it knew). A convar changed by exec of a cfg file is not tracked.

Code Mode (Claude Code)

Claude Code's experimental Code Mode lets the model write JavaScript that calls the tools (await tools["mcp__plugin_gmod-mcp_gmod__status"]({})). gmod-mcp works with it:

  • A result arrives as a string, the JSON of structuredContent: JSON.parse it (and accept an object too, a later Claude Code version may pass one).

  • An error throws, and e.detail is the parsed error {"error": {code, message, details, next_call?}}: the text of every error is exactly that JSON object, also the ones the bridge answers itself (game_not_running, port_conflict...) and when the plugin and the module have different versions (the warning is a field of that object, version_warning).

  • A long call (map_load, a wait of 15 s or more) is answered synchronously when it comes from a script (Claude Code marks those calls), so await map_load(...) returns the real result. Outside Code Mode, a client that supports MCP tasks gets map_load as a background task: set GMOD_MCP_TASKS=off (see Configuration) to turn that off for every client.

  • At most 10 calls run in parallel in a script. Map loads and launches are still one at a time (the FP7137 lock), so parallel map_load calls queue.

Configuration

Launch option

Effect

-mcp

Required. Without it the module prints one line and does nothing (and never touches any file).

-mcpport <n>

Base port, 1 to 65000 (default 27080; anything else falls back to it). The module tries the base port, then the 15 next ones, and refuses to start if none is free.

The bridge only talks to the base port. If you changed it with -mcpport, tell the bridge the same number: with the plugin, set the GMOD_MCP_PORT environment variable for Claude Code (--port <n> is for running gmod-mcp-bridge yourself, in another MCP client's configuration). It also matters when another program already holds port 27080: the game then takes the next free port (its console line [mcpagent] active: ... http://127.0.0.1:<port>/mcp says which) and the bridge does not look there. Free port 27080, or start the game with -mcpport <free port> and set GMOD_MCP_PORT to that port. The bridge recognises the situation: gmod-mcp signs every answer with an X-Gmod-Mcp header, so a port that answers without it is held by another program, and the tools then answer port_conflict (not game_not_running), naming the port, how to find the program (Get-NetTCPConnection -LocalPort 27080 on Windows, ss -ltnp on Linux) and, when it finds one on the next ports, the GMOD_MCP_PORT value to use.

Environment variable

Effect

GMOD_MCP_TASKS

auto (default): with a client that supports the MCP Tasks extension (2026-07-28), the game answers map_load and waits of 15 s or more with a background task, except for calls made by a Claude Code Code Mode script, which are answered in place. off: never, for any client. Set it in the environment of Claude Code (the bridge then does not forward the extension to the game) or of the game (the module reads it too). A client that asks for a task itself (the older 2025-11-25 form) still gets one.

Scratch Lua files for the agent go to garrysmod/lua/mcpagent_tmp/ (status gives the absolute path); errors and tracebacks then point at the real file.

Security

  • Binds to 127.0.0.1 only. Every request needs the bearer token; a browser Origin other than a local one (localhost, 127.0.0.1, [::1]) is refused, and the Host header must be loopback with the right port (DNS rebinding). The bridge opens no port at all.

  • The only outbound traffic is HTTPS GET requests to wiki.facepunch.com, through the game's own HTTP client.

  • Client realm lock. Running Lua in the client state bypasses sv_allowcslua, like a cheat would. The module refuses to touch the client realm unless the server runs on your own machine: the game hosts it (singleplayer, listen server), or its address is loopback or exactly one of this machine's own network addresses (a local dedicated server). On any other server, even on your LAN, nothing is injected into the client, client calls fail with client_locked and status says why. This cannot be disabled.

  • console_exec refuses connect/redirect to servers that are not on this machine (including after a ;). A connect must also be alone on its line: echo x; connect ... is refused, because the engine crashes on it while a map is loaded. convar_set refuses archived convars (they would end up in your config.cfg) unless asked explicitly.

What gets modified in your game folder

  • The two files from the zip.

  • garrysmod/lua/menu/menu.lua: Garry's Mod has no plugin folder for the main menu, so the module appends a small block between -- MCPAGENT BEGIN and -- MCPAGENT END (the original is saved once as menu.lua.mcpagent.bak). The block is written to be harmless: everything runs inside pcall, an obviously broken or empty DLL is skipped instead of triggering a Windows error dialog, and if a load ever crashes the game, the next start skips the module and tells you why. The file is only written when the game runs with -mcp, and only if the result compiles.

  • Steam "Verify integrity of game files" will report menu.lua as modified and restore the original — that is expected. Game updates do the same. The block comes back by itself the next time you play with -mcp and load a map.

  • garrysmod/data/mcpagent/ (wiki cache) and garrysmod/lua/mcpagent_tmp/ (agent scratch files).

  • With instances_launch {early_lua}: a small gmod-mcp-early/<token> folder in your temp folder, outside the game folder. It is removed when the client is closed, and the next launch removes the ones that are three days old.

Uninstall

  1. Keep -mcp in the launch options for now: mcpagent_uninstall only exists while the module is loaded. Start the game, and at the main menu type in the console: mcpagent_uninstall. It removes the block from menu.lua, which is then byte-identical to the original.

  2. Quit the game, then remove -mcp from the Steam launch options.

  3. Delete garrysmod/lua/bin/gmsv_mcpagent_win64.dll (Linux: gmsv_mcpagent_linux64.dll), garrysmod/lua/autorun/server/mcpagent_boot.lua and the backup garrysmod/lua/menu/menu.lua.mcpagent.bak.

  4. Optionally delete garrysmod/data/mcpagent, garrysmod/lua/mcpagent_tmp and the token folder (%APPDATA%\gmod-mcp, Linux: ~/.config/gmod-mcp).

  5. With the plugin: /plugin uninstall gmod-mcp@gmod-mcp, then claude plugin marketplace remove gmod-mcp. A server added by hand: claude mcp remove gmod.

Limitations

  • Tested on Windows x64 (game and dedicated server) and in a Linux x64 dedicated server. The Linux client game has not been tested. instances_launch is Windows only.

  • The very first start needs one map load (to install the main-menu loader).

  • Without a loaded map, screenshot runs the engine's own jpeg command: the engine writes a file in garrysmod/screenshots/, the module reads exactly the file the engine names in its console and deletes it (nothing else is touched). It works while other windows cover the game, but not while the game is minimized or frozen (capture_timeout). The image is the engine's JPEG at the game's screen size and quality: no HUD choice, no w/h, no PNG, no crop/scale. screenshot_from and the render source need a loaded map.

  • An image is never returned above 8 MB encoded (a client drops the connection above 16 MB per message): a too big png comes back as a JPEG (size_capped: true) or fails with result_too_large. screenshot {crop, scale} crops and enlarges a small region (a HUD icon).

  • hook_trace adds a temporary hook: if another hook returns a value first, that call is not seen.

  • The Garry's Mod dedicated server ignores packets from 127.0.0.1: to join a local dedicated server, connect to this machine's LAN address (the client lock recognizes it as local).

  • Lua errors raised by code run through lua_exec are returned to the caller, not reported by errors_since.

  • A lua_job dies with its realm: loading a map ends the jobs running in the client and server states.

  • Progress and cancellation do not cross instances: a call relayed to another game reports neither.

  • MCP logging, sampling and roots (deprecated in the 2026-07-28 specification) are not implemented.

Building from source

Requirements: CMake 3.24+, a C++17 compiler (MSVC 2022 or GCC 11+), internet access at configure time (dependencies are fetched and verified by SHA-256).

cmake -S . -B build -DCMAKE_BUILD_TYPE=Release
cmake --build build --config Release

The output in build/ is the module, gmsv_mcpagent_win64.dll (or _linux64.dll), and the bridge, gmod-mcp-bridge; loader/mcpagent_boot.lua is the autorun file. The build also runs gmod-mcp-snapshot, which writes the module's tool descriptions into the bridge (served while the game has never answered).

Tests without a game: python tests/bridge/test_bridge.py <bridge> (a fake game server covers the protocol and the odd cases) and python tests/protocol/check_constants.py (protocol constants against the official schema). CI runs both on Windows and Linux. The test matrix is in docs/TESTS.md; notes on the engine interfaces used are in docs/REVERSE.md.

License

MIT — see LICENSE and THIRD_PARTY_NOTICES.md. Not affiliated with Facepunch Studios or Valve.

Available Tools

65 tools
bots_addAdd botsA

bots_add(n, name?). Adds n bots in the server realm (player.CreateNextBot), named _. Bots need free player slots: in singleplayer (map_load maxplayers 1) there are none, so load the map with e.g. maxplayers: 4 first; otherwise error no_slots. Bots do not survive a map load (map_load removes them: add them again after it; checked live). Result: {added: [entity summaries], count}. Needs a loaded map (map_load): the server and client realms do not exist at the main menu.

Inputs: n (required), name, instance. Returns: next, note, added, count, +6 more

concommand_listList commandsA
Read-only

concommand_list(realm?, engine?, filter?). Lists console commands. Always: the Lua commands of realm (concommand.Add, name matches filter as a case-insensitive substring). With a filter and engine: true (default): also the engine's commands and convars whose name or help text matches, parsed from the console command find <filter>. Result: {lua_commands, realm, engine_commands?, engine_convars?}. Example: {"filter": "sv_"}.

Inputs: realm, engine, filter, instance. Returns: next, note, realm, warning, +8 more

console_bufferConsole buffer capacityA
Idempotent

console_buffer(capacity?). Reads or sets how many console lines this game keeps for console_read, console_wait and console_exec (default 20000; lowering it drops the oldest lines at once). Without capacity: just reads it. Result: {capacity, cursor (the current console position)}.

Inputs: capacity, instance. Returns: next, note, cursor, warning, +6 more

console_execRun a console commandA
Destructive

console_exec(cmd, realm?, connect_timeout_s?, regex?, wait_frames?). Runs a console command line from a realm (menu: RunConsoleCommand; server: game.ConsoleCommand; client: RunConsoleCommand, with automatic fallback to the engine if the command is blocked from Lua). Like the engine console, ';' and line breaks outside quotes separate commands: 'a 1; b 2' runs a then b (statements lists them). Waits a few frames then returns the console lines printed meanwhile (gmod-mcp's own log lines left out; the console is shared, so filter with regex). An unknown command or convar is an error (unknown_command), not a silent no-op. For every convar it set or named, convars gives the value read back (value, number, and a warning for FCVAR_ARCHIVE convars, which land in the user's config and are shared by every instance). killserver on a game that hosts a map first leaves it like disconnect (left_game_first: true): run in game it can crash the engine. Example: {"cmd": "sv_gravity 600"}. convar_set refuses archived convars unless persist: true.

Inputs: cmd (required), realm, regex, instance, +2 more. Returns: cmd, via, next, note, +15 more

console_readRead the consoleA
Read-only

console_read(cursor?, limit?, regex?). Reads this game's console output: everything printed by the engine and by Lua in every realm (print, Msg, MsgN, MsgC, errors), one entry per line, kept in a ring buffer (20000 lines by default, see console_buffer) that survives map changes. Without cursor: the last limit lines (matching regex). With cursor: the lines from that point on; pass next_cursor to the next call to read only new lines. Result: {lines: [{seq, t (s since module start), level: message|warning|assert|error|log, text}], next_cursor, lost (lines dropped before you read them), oldest, capture (spew, logging, condebug or none: none = nothing is captured)}. To block until a line appears, use console_wait. Example: {"regex": "^\[ERROR\]", "limit": 50}.

Inputs: limit, regex, cursor, instance. Returns: lost, next, note, lines, +9 more

console_waitWait for console linesA
Read-only

console_wait(regex, timeout_s?, count?, cursor?). Blocks until count console lines matching regex are printed (from cursor, default: now), e.g. the end line of a test batch: {regex: "^BATCH DONE", count: 4, timeout_s: 900}. Returns the matching lines and next_cursor (just after the last one used: pass it to the next wait so nothing printed in between is missed). Reports progress; error timeout (with the lines found so far). Lines come from every realm and the engine (print, Msg, engine messages). Can run as an MCP task.

Inputs: regex (required), count, cursor, instance, +1 more. Returns: lost, next, note, lines, +9 more

convar_getRead a convarA
Read-only

convar_get(name, realm?). Value (string as the engine stores it), number (the value as a number when it is one: compare this, since the same value can read "0.0" or "0.000000"), default, help text, flags (raw and decoded as flag_names), min/max of a convar, and archived: true when changing it is saved into cfg/config.cfg (shared with the user's game and every instance); archived_from says flags or config.cfg, in_config_cfg whether config.cfg lists it (test clients only). Do not use ConVar:IsFlagSet(FCVAR_ARCHIVE) from Lua for this: it can be false for an archived convar (CreateClientConVar with save). A convar created this session and not saved yet shows archived: false. FCVAR_PROTECTED convars have their value masked.

Inputs: name (required), realm, instance. Returns: max, min, via, help, +19 more

convar_setSet a convarA
Idempotent

convar_set(name, value, realm?, persist?). Sets a convar from a realm (RunConsoleCommand; server realm: game.ConsoleCommand), waits 3 frames and reads it back. When the value did not take from Lua (some convars, e.g. volume_sfx, ignore Lua) it retries through the engine console (client mode). Convars with FCVAR_ARCHIVE are saved into the user's cfg/config.cfg when the game quits and are shared by every game of this folder: they are refused unless persist: true (your MCP client may then ask the user). Result: the convar as convar_get reads it, plus previous and via (lua or engine). Errors: not_found, protected (FCVAR_PROTECTED), archived, set_refused (cheat without sv_cheats, wrong realm, blocked command). Example: {"name": "sv_gravity", "value": 300, "realm": "server"}.

Inputs: name (required), value (required), realm, persist, +1 more. Returns: max, min, via, help, +19 more

debug_clearClear debug primitivesA
Idempotent

debug_clear(). Client only (unsupported on srcds). Removes every primitive drawn by debug_draw (client realm). Result: {cleared: count}.

Inputs: instance. Returns: next, note, cleared, warning, +5 more

debug_drawDraw debug primitivesA

debug_draw(primitives, duration?). Client only (unsupported on srcds: it draws in the client realm, a dedicated server has none). Draws 3D lines, arrows (a line with a head at to), wireframe boxes, wireframe spheres and text in the game world, in the client realm (a map must be loaded), visible on screen and in screenshot/screenshot_from. They add up across calls and expire after duration seconds of game time (0 = until debug_clear or the next map). Nothing changes in the game itself. Result: {added, active, expire_in_s}. Example: {"primitives": [{"type": "line", "from": [0, 0, 64], "to": [500, 0, 64], "color": [0, 255, 0]}, {"type": "sphere", "pos": [500, 0, 64], "radius": 16}, {"type": "box", "min": [-32, -32, 0], "max": [32, 32, 72]}, {"type": "text", "pos": [0, 0, 100], "text": "spawn"}], "duration": 30}.

Inputs: primitives (required), duration, instance. Returns: next, note, added, active, +7 more

disconnectReturn to main menuA
DestructiveIdempotent

disconnect(timeout_s?). Leaves the current map for the main menu (console disconnect) and waits until the client and server realms are gone; their Lua states are destroyed. Client only (unsupported on srcds). Result: {disconnected, was_in_game, duration_s, realms}. Errors: busy (a map_load runs), timeout.

Inputs: instance, timeout_s. Returns: next, note, realms, warning, +8 more

ent_fireFire an entity inputA
Destructive

ent_fire(id, input, delay?, param?). Sends a map I/O input to an entity in the server realm (Entity:Fire(input, param, delay)), e.g. Open, Close, Toggle, Lock on a door, or Kill. Returns at once ({fired, id, param, delay}): the effect happens on a later frame (after delay seconds), so check it with ent_info or wait_for. An input the entity does not know is ignored silently: no error, and nothing in the console (checked live), so always check the effect. Example: {"id": 57, "input": "Open"}. Needs a loaded map (map_load): the server and client realms do not exist at the main menu.

Inputs: id (required), input (required), delay, param, +1 more. Returns: id, next, note, delay, +8 more

ent_infoEntity detailsA
Read-only

ent_info(id, realm?, depth?, limit?). Details of one entity by index (id 0 = the world). Result: id, class, model, name, nick, pos, ang, valid, velocity, health, max_health, solid, movetype, collision_group (raw engine enums), obb {mins, maxs} (local bounds), parent and owner (entity ids or null), nw_vars (SetNW* values), table (the entity's Lua table, cut at depth/limit), and in the server realm keyvalues (map/engine keyvalues) and, for classes containing "door", door {m_eDoorState, m_toggle_state, state: closed|opening|open|closing|ajar}. transmit tells what Lua can know about the entity reaching the client: server realm {always_sent, in_pvs_of: [player ids whose PVS holds it], note}, client realm {on_client, dormant: out of the PVS}. An entity that is not on the client answers not_found there: ask both realms. Error not_found for an invalid id. Example: {"id": 57}. Needs a loaded map (map_load): the server and client realms do not exist at the main menu.

Inputs: id (required), depth, limit, realm, +1 more. Returns: id, ang, obb, pos, +26 more

ent_removeRemove an entityA
Destructive

ent_remove(id). Removes an entity by index in the server realm (Entity:Remove, effective at once). Players and the world are refused (forbidden); an invalid id gives not_found. Result: {removed: id}. Needs a loaded map (map_load): the server and client realms do not exist at the main menu.

Inputs: id (required), instance. Returns: next, note, removed, warning, +5 more

ents_findFind entitiesA
Read-only

ents_find(realm?, class?, limit?, model?, near?, radius?). Lists entities, filtered by class, model and/or distance (all filters combine; none = every entity). class and model are case-insensitive globs where * matches anything ("prop_*", "door", "models/props_c17/"). near + radius keep the entities whose position is within radius of near (ents.FindInSphere), sorted nearest first, each with distance. Result: {entities: [{id, class, model, name (targetname, if any), nick (players), pos [x,y,z], ang [p,y,r], distance?}], count (all matches), truncated (count > limit)}. id is the entity index: pass it to ent_info, ent_fire, ent_remove (a clientside-only entity, ClientsideModel and the like, has id -1: no tool can address it, see note; use lua_exec in the client realm). A number the game cannot hold (NaN, infinity) reads null. Server realm by default; the client realm only sees networked entities (and no targetnames). Example: {"class": "func_door", "near": [0, 0, 64], "radius": 1024, "limit": 10}. Needs a loaded map (map_load): the server and client realms do not exist at the main menu.

Inputs: near, class, limit, model, +3 more. Returns: next, note, count, warning, +7 more

ent_spawnSpawn an entityA

ent_spawn(class, ang?, freeze?, keyvalues?, model?, pos?). Creates an entity in the server realm, in this order: ents.Create(class), SetModel, SetPos, SetAngles, SetKeyValue for each keyvalue (values sent as strings), Spawn, Activate, then freeze. It stays until removed or the map changes. Result: the entity summary {id, class, model, name, pos, ang}. Error invalid_class if the class does not exist. Example: {"class": "prop_physics", "model": "models/props_c17/oildrum001.mdl", "pos": [0, 0, 100], "freeze": true}. Needs a loaded map (map_load): the server and client realms do not exist at the main menu.

Inputs: class (required), ang, pos, model, +3 more. Returns: id, ang, pos, name, +12 more

errors_clearClear errorsA
DestructiveIdempotent

errors_clear(). Forgets the errors kept so far (errors_since then starts empty); cursors keep growing, so an old cursor stays valid. Result: {cleared, next_cursor}.

Inputs: instance. Returns: next, note, cleared, warning, +6 more

errors_sinceRead Lua errorsA
Read-only

errors_since(realm?, cursor?, exclude_pattern?, exclude_source?, group_by?, limit?, pattern?, since_map_load?, ...). Lua errors of every realm of this game, as the game reports them (client mode: the menu's OnLuaError hook; srcds: parsed from the console). The game reports each distinct error as it happens. Cursor: 0 = from the oldest kept error; pass next_cursor to read only new ones. The last 2000 are kept and survive map loads: each error carries map_load (a number that grows with every map load) and map; since_map_load: true keeps only the current map's errors, including those raised while it loaded. Result: {errors: [{seq, realm, message, stack: [{file, line, function}], addon, addon_id, time, map_load, map, hook?}], next_cursor, lost, map_load, map, warnings?}. A game that several agents share, or a stuck loop, fills it with errors that are not yours or all the same: group_by: "message" returns one entry per message and source, {groups: [{message, source, count, first_seq, first_time, last_seq, last_time, realms, map, stack, hook?, addon}], groups_total, next_cursor, lost, map_load, map} instead, most frequent first; source / exclude_source keep or drop the errors raised under a file prefix (e.g. "lua/my_addon/client/"), pattern / exclude_pattern a regex on the message. warnings (only when there is something to say): errors_dropped (lost > 0: the oldest errors were dropped before you read them) and repeated_errors (most of the list is one message: group it). hook: the hook that raised it, when lua_exec / lua_job's hook guard removed or watched it. Example: {"cursor": 0, "since_map_load": true, "group_by": "message", "source": "lua/my_addon/"}.

Inputs: limit, realm, cursor, source, +6 more. Returns: map, lost, next, note, +11 more

events_waitWait for eventsA
Read-only

events_wait(timeout_s?, cursor?, limit?, types?). Waits for events of this game instance and returns AS SOON AS one of the wanted types arrives (all that arrived, up to limit), or after timeout_s with timed_out: true. Types: menu_ready, runtime_injected, realm_up, realm_down, realm_ready, map_loaded, disconnected, disconnect_reason, connection_failed, main_thread_stalled, main_thread_resumed, lua_error, runtime_error, report (a mcpagent.report value), focus_released, user: (sent by game code with mcpagent.event(type, data)). Without cursor it waits for events from now on; pass the returned next_cursor to the next call so nothing is missed in between. The instance keeps the last 5000 events (lost > 0 = some were dropped before you read them). Result: {events: [{seq, time (s since module start), type, data}], next_cursor, lost, timed_out}. Example: {"types": ["map_loaded", "lua_error"], "timeout_s": 60}.

Inputs: limit, types, cursor, instance, +1 more. Returns: lost, next, note, events, +8 more

game_quitQuit the game cleanlyA
Destructive

game_quit(). Asks the game to quit cleanly (console quit): it saves its config (cfg/config.cfg, video settings) and exits; the MCP server of this instance goes away with it. For test clients started by instances_launch, prefer instances_close (it kills the process: nothing is saved, and the exit is short); game_quit is safe on them too: before quitting, the module gives the archived convars their command line changed (fps_max, fps_max_nofocus, snd_mute_losefocus, and those named by instances_launch commands or launch_args) the user's values from cfg/config.cfg, or their defaults when the file has no line. On a dedicated server the console quit is blocked from server Lua: on Linux the module then ends the process itself with SIGTERM (the server's own clean shutdown, half a second after the answer); where that is not possible (Windows srcds) the error is blocked and nothing quits. Result: {quitting: true}; on the coordinator while other instances live, also coordinator_moved: true, remaining_instances and a warning (they elect a new coordinator).

Inputs: instance. Returns: next, note, warning, quitting, +5 more

game_terminateKill the game immediatelyA
Destructive

game_terminate(delay_ms?). Kills this game process at once (no config saved, no clean shutdown), from the network thread, so it works even when the game is frozen (infinite loop, status main_thread_stalled). The answer {terminating, pid, main_thread_stalled, last_tick_age_s} is sent first, then the process ends after delay_ms. With instance, the coordinator relays it to that game. Never use it on the user's own game unless they ask.

Inputs: delay_ms, instance. Returns: pid, next, note, warning, +8 more

hook_listList hooksA
Read-only

hook_list(realm?, name?, added_by?, event?). Hooks registered with hook.Add in a realm (hook.GetTable), with where each function was defined. Without event: every event (large; name keeps the hooks whose identifier contains it, e.g. to check that one was removed). Result: {hooks: {: [{id, source (file), line, what, added_by?, chunk?, added_at?}]}, count, now}, and with event: event, known (false = no hook and no gamemode function for that name: probably a typo) and gamemode_function (source of GAMEMODE:, or null). Example: {"realm": "client", "event": "Think"}. Which hooks the tools left on the game: a hook that lua_exec, lua_exec_file, lua_reload or lua_job added through hook.Add while its chunk ran (or during a job's resumes) carries added_by (that tool), chunk (the chunk name) and added_at (SysTime() of the realm when it was added; now in the result is the same clock, so now - added_at is its age in seconds). added_by: "mcp" keeps only those hooks (or name one tool), combinable with name and event: {"added_by": "mcp"} answers "what did the tools leave on this game?". Only a hook still registered with the function the tool added (or its guard wrapper) is reported: one the addon replaced since is not. Not seen: a hook added later by a callback or a timer the chunk left behind. The list is kept per realm, bounded (500 hooks) and starts empty at every map load. Remove a leftover with hook.Remove(event, id) in lua_exec.

Inputs: name, event, realm, added_by, +1 more. Returns: now, next, note, count, +10 more

hook_traceTrace a hookA
Read-only

hook_trace(event, realm?, depth?, duration_s?, max_calls?). Records the calls of a hook event for duration_s (or until max_calls), with each call's arguments serialized (entities as {__type, id, class...}), through a temporary hook.Add that returns nothing (game behaviour unchanged), removed at the end. Waits the whole duration (progress reported; MCP task possible). Result: {event, calls: [{t (seconds since start), args: [...]}], recorded, total_calls (also those past max_calls), capped, duration_s, tracer_removed}. Not seen: calls that a hook running before it stopped by returning a value. Error realm_lost if the map changes meanwhile. Example: {"realm": "server", "event": "PlayerSay", "duration_s": 10}.

Inputs: event (required), depth, realm, instance, +2 more. Returns: next, note, calls, event, +11 more

instances_closeClose test clientsA
Destructive

instances_close(all?, instances?, owner?, pids?). Closes clients this session started with instances_launch, at once and without writing their config, by instance id, by pid (also for a client that never answered, e.g. gmod-mcp did not load in it) or by owner label. By id, pid or all, only this bridge session's clients: other games (the user's own, another session's) are refused, close those only if the user asks, with game_terminate. By owner label it also closes keep: true test clients of an earlier session (a bridge restarted, another agent) that carry that label (instances_list shows it as owner; closed[i].launched_by_other_session is true), but never a game that is not a test client or one without the tag. Sub-agents of one Claude Code session share it: all: true closes their clients too. The selectors add up (instances, pids, owner). Result: {closed: [{pid, instance?, owner?}], already_gone?: [{pid, instance?, owner?}] (processes that had ended before the call: nothing was closed), refused?: [ids, pids or "owner:" not started by this session or already closed], why_refused?}; an error (code refused, the same fields beside it) only when nothing was closed. Closing the client that is the coordinator (the game on the base port, see instances_list: role, coordinator_warning) while other games live moves that role: the answer says so (closed[i].was_coordinator, coordinator_moved_to, warning) and calls of other agents answer coordinator_changing for a few seconds. Example: {"owner": "fork-a"}.

Inputs: all, pids, owner, instances.

instance_selectSet the default instanceA
Idempotent

instance_select(instance). Makes instance this session's default: tool calls without an instance argument go to it (useful with several games running, where they would otherwise be refused as ambiguous). null clears it. Lasts until the session ends. Do not use it with sub-agents: they all share this session, so a default set by one applies to every other's calls too (they would act on its game). Pass instance on every call instead. Result: {default_instance, previous}. An id that instances_list does not show is refused (unknown_instance, the default stays); when the list cannot be read the id is accepted with a warning.

Inputs: instance (required).

instances_launchLaunch test clientsA

instances_launch(timeout_s?, allow_shadow?, commands?, count?, desktop?, early_lua?, fps_max?, fps_max_nofocus?, ...). Starts 1 to 8 extra Garry's Mod clients for tests, and works while no game runs (the first one then becomes the main instance). Each starts with -multirun, gmod-mcp on, a small window and a frame cap, on a private Windows desktop (below), waits until it answers, then loads map through map_load (never +map: a game loading a map in the background can grab the mouse). Returns their instance ids and pids: pass an id as instance on every call. DEFAULTS that change what your test sees: (1) desktop private: no window, never the focus, close only with instances_close; (2) silent: -nosound, so the sound engine answers differently (SoundDuration of an ADPCM WAV 0.49 s instead of 1.24 s): pass sound: true for any test that touches sound; (3) test clients share the user's real data/, cfg and cookies: switch an addon's writes off with early_lua, clean up after the test; (4) an installed module older than the plugin's is refused (module_outdated). Without keep: true they end with this bridge session (when it ends, the clients it started are closed, also when the bridge is killed: they run in a job object that dies with it); with keep: true they outlive it, and a later session closes them by owner (below) or by pid / game_terminate. Close them earlier with instances_close (at once) or game_quit (a clean quit, see the convar note below). Sub-agents of one Claude Code session share this bridge: give each one's clients an owner label and close them with instances_close {owner}, never {all: true}, which would close the other sub-agents' clients too. The owner label goes to the game (-mcp_owner) and back in its heartbeat: instances_list shows owner on every instance whichever bridge session launched it, and instances_close {owner} also closes keep: true test clients of an EARLIER session that carry that label (only test clients started by instances_launch, never the user's own game or an instance without the tag). The game is found through Steam; pass game_dir (the folder holding gmod_win64.exe or bin/win64/gmod.exe) if it is elsewhere. Windows only for now. Presets: 'light' (default: 640x360, 20 fps; for most tests, NOT for performance measurements: the 20 fps cap hides per-frame cost) and 'normal' (640x360, 30 fps; for rendering checks, screenshots and frame-time sensitive tests). Desktop (Windows): by default each client runs on a private Windows desktop of this bridge session (desktop: "private"; result desktop, desktop_name). A starting game makes every game on ITS desktop release and restore its GPU resources (the user's own game freezes about 10 s and its render targets are rebuilt empty); a client on another desktop never finds the user's windows, so the user's game is not disturbed. Consequences: the client has no visible window and no taskbar button (nothing to close by hand: instances_close), it never takes the user's focus, and sound is OFF unless you pass sound: true (nobody sees it, and its audio would still reach the speakers). ui_click, ui_key and screenshot still work (posted window messages and the engine's own capture: no real input and no screen grab). Clients of one session share that desktop, so they still disturb each other as described below. desktop: "shared" starts them on the user's desktop (visible window, the foreground handed back to the user's window): use it only to look at the window. If the private desktop cannot be created the call fails with launch_failed and starts nothing: pass desktop: shared. Before starting anything the module installed in the game folder (lua/bin) is compared with the one this plugin ships: an older one is refused with module_outdated and the update steps (a client would run it and only say so afterwards), unless ignore_outdated_module: true. instances_list and the game_not_running error show module_outdated while no game runs. Pass-through options (checked before anything starts; a refused one is invalid_params naming it): fps_max and fps_max_nofocus (integers: 0 = no cap, or 10 to 1000) replace the preset's frame cap (fps_max_nofocus follows fps_max when only that one is given): timing-sensitive tests give different verdicts at 20, 45 and 300 fps, and perf measurements need more than 30. commands: console commands run on each client once it answers, before map loads, one at a time in order, e.g. ["fps_max 300", "snd_mute_losefocus 0"] (a ; splits a line as in the console); refused: quit and exit (close with instances_close), connect, retry, redirect and connect_lobby (gmod-mcp never connects to a server) and map changes (map, changelevel, load: use map). Each result is in instances[i].commands [{cmd, ok, error?}]; a command that fails makes the call isError, the others still run. launch_args: extra engine command-line tokens, one per array element (a printable ASCII word without spaces, quotes or ;), e.g. ["-noborder", "+cl_showfps", "1"]; a +name value token runs a console command at startup. Refused: what gmod-mcp sets itself (-multirun, -mcp*, -w, -h, -width, -height and the window-mode options, -dxlevel, -condebug, -game), +connect and the other connecting or map-loading commands. -nosound is the same as sound: false. Archived convars changed this way (fps_max, a +convar token, a command such as cl_showfps 1 or toggle snd_mute_losefocus) are given back to the user's value before a clean quit like the frame cap (needs the module of this release in the game folder: an older module restores only fps_max, fps_max_nofocus, engine_no_focus_sleep and snd_mute_losefocus; a convar changed by exec of a cfg file is not tracked). Where the options are listed: command-line options, Valve Developer Community "Command line options" (https://developer.valvesoftware.com/wiki/Command_line_options) and, for the GMod-specific ones, the Garry's Mod wiki (wiki_search "command line"); console commands and convars: api_search and concommand_list on a running client. All clients share the game folder with the user's own game: same addons, cfg, data/ and cookies (sv.db/cl.db). A test that writes cookies, data files or archived convars changes the user's game too: clean up after it. An addon that caches into data/ (or deletes its cache when its format changes) does it in the first seconds after the map loads, before you can switch it off (commands run before the addon's convars exist): nothing isolates your data/ from a test client, so pass early_lua (Issue #20), Lua that runs in each client's client and server realms before any addon's file (set the addon's own switch off, hook or wrap something before its first write). The module writes it into an autorun file it mounts in front of the addons, so it replaces nothing in the game; if it cannot mount it, the code does not run (status of the client: early_lua.mounted false, early_lua.error says why). A Lua error in it is printed to the console, not raised. Its temporary folder is removed by instances_close and when the session ends; a client killed with its bridge leaves it and the next launch removes folders nothing touched for three days. The frame cap and the focus options these clients start with (fps_max, fps_max_nofocus, snd_mute_losefocus) are archived convars: the module gives each one the user's value from cfg/config.cfg (its default when the file has no line) before the client quits cleanly (game_quit, console quit, the Quit button, the window's close button; not a quit the user types by hand in that client's console), so none of them leaks into the user's config. The same holds for archived convars changed through commands, launch_args or fps_max (the module restores the ones that exist and are archived at quit); a convar an addon creates later and that you set from console_exec or convar_set is NOT restored (the list is fixed at launch). Closing with instances_close kills the process and writes nothing. Video settings: the clients start with -dxlevel 95, so the engine neither reads nor writes the user's stored video mode (resolution, anti-aliasing): the user's own game keeps its resolution. Measured cost per client on gm_construct (16-core PC, the game and its 4 browser subprocesses): light about 19% of one core, 1.55 GB of commit (virtual memory) and 1.2 GB of RAM; normal 24% and the same memory. Eight clients: about 1.5 cores and 12 GB. Memory is the limit, not CPU: a machine out of commit makes every game crash (0xC000041D, no dump), so before starting anything this call checks the free commit and free RAM and refuses with the error low_memory {details: free_commit_mb, free_ram_mb, running_clients (all sessions: the registered instances, this bridge's clients and every process of the game's executable, so clients another session started that have not registered yet count), registered_clients, game_processes, per_client_mb, count, needed_commit_mb, needed_ram_mb} when they do not cover the clients asked for (1.6 GB of commit each plus 1 GB for the rest of the machine, 1.2 GB of RAM each); nothing is started then. Close clients you no longer use (instances_close), start fewer, or pass ignore_low_memory: true to start anyway. The frame cap is what saves CPU (30 to 20 fps: -20%); sound: false saves about 12% more. Window size barely matters, and a client narrower than 640 pixels crashes while loading a map (integer division by zero in client.dll at client Lua startup: seen at 480x270 and 320x240; it only survived with the HUD turned off). -textmode and lower graphics settings were measured: no real gain (and graphics settings would be saved into the user's own), so neither is offered. Result: {instances: [{instance, pid, port, owner?, commands? [{cmd, ok, error?}], early_lua? (true), map? (or map: null + map_error)}], game_dir, found_by, preset, keep, desktop, desktop_name?, desktop_note?, sound, module?, fps_max, fps_max_nofocus, fps_note, launch_args?, lua_mount}. If they do not all answer within timeout_s: error timeout with silent_pids (started but never answered: close them with instances_close {pids}) and answered [{instance, pid}]. A client that crashed during startup or its map load is reported as client_crashed (startup: the whole call's error; map load: that client's map_error), with the minidump file name in details.dump (for a human) and exit_code: launch a replacement. With count > 1 the other clients of the call are not closed when one dies at startup: the error lists the ones still running in details.still_running [{pid, state: answering or still starting, instance?}] and a top-level warning; close them (instances_close) or use them. When the clients started but a map, a startup command or the lua_mount did not work, the call is isError with the whole result above plus error {code: launch_incomplete, message}. Example: {"count": 2, "map": "gm_construct", "owner": "fork-a"}, then pass each returned instance id as instance. Starting a game makes every other running Garry's Mod release its GPU resources for 2-10 s, and a map load that ends in that window crashes that game (engine bug, Facepunch garrysmod-issues #7137). So the bridge serialises the launches and map loads that go through it, from any session: this call first waits while any game loads a map, and with map the maps load after a 15 s settle delay, 2 at a time across every session (a map_load of another session counts). "Any game" includes loads the bridge did not start (console map, changelevel, Lua RunConsoleCommand, a script talking to the game): every game reports when it is loading a map (instances_list loading), and waited_reason then starts with map_load_outside_bridge. A call that waited reports waited_s and waited_reason (and progress when your client sent a progress token). If the wait would exceed timeout_s it fails with error map_load_in_progress and starts nothing: retry later, or with a larger timeout_s. Not covered: a game started by hand (not by this call) and a load that begins while a launch is already creating its processes (only launches and map_load calls of the bridge wait, a load started by other means is never held back). A client that is frozen (instances_list state unresponsive or hung: suspended, crash dialog, a load that never ends) keeps a new client from registering (engine FP7137 handshake), so a launch beside it ends with 0 of N clients answered: before starting anything this call refuses with peer_unhealthy {details.unhealthy: [{instance, pid, state}]}, naming the way out (instances_close {pids} for a client this session started, game_terminate {instance} for any), unless ignore_unhealthy: true; a timeout also names the stuck peers it saw meanwhile (details.unhealthy_peers). When a program that is not gmod-mcp holds the base port (port_conflict, see status), the launch is refused up front with the fix (GMOD_MCP_PORT) and nothing is started: the clients would register on the next port, where this bridge cannot see them. Right after a game starts, the other games can be unreachable for 15-18 s (instance_unreachable or timeouts): expected, wait and retry; it is not a dead game (client_crashed is the signal for a dead one). Order: launch all the clients you need in ONE call (with map, they load 2 at a time after the settle delay), then work. Do not interleave launches with map loads, yours or another session's.

Inputs: map, keep, count, owner, +16 more.

instances_listList instancesA
Read-only

instances_list(include_crashed?, owner?). Known gmod-mcp instances (this one, and on the coordinator every registered member): id, mode (client/srcds), port, pid, map, realms (client true = the client is in game), role, heartbeat age and health: agent_version, uptime_s, fps (over the last 3 s), main_thread_stalled, stalled_s (seconds the main thread has been blocked, 0 when it ticks), silent_s (seconds since its last heartbeat, 0 for this game: it grows for a frozen one, state "unresponsive", and is the number the instance_hung error gives; heartbeat_age_s is the same figure unrounded), fps_low_s (seconds the frame rate has stayed under 10 fps, 0 when fine or while the game loads: measurements taken meanwhile are suspect), loading (true while a map load is in progress, whatever started it: console, Lua, map_load, which counts from its first moment, while it still waits for the menu and the engine has not started the load; sent at once when it starts and ends; it ends when the server state that started it is gone, e.g. a disconnect right after map, and a load whose loading screen has been down for 30 s no longer counts; a loading screen with nothing behind it for 12 s (no server or client realm, not connected, no load starting: the engine's stuck state after map then disconnect at once) is not a load: loading is false and the entry carries loading_stuck: true, and map_load clears it (disconnect does not); status reports the same flags), lua_errors (count since start; errors_since for the details). The instance with role "coordinator" (also named by coordinator_id) holds the directory: when it ends, another takes over within about a second, and during the hand-over coordinator_changing: true (calls with instance answer the retryable error coordinator_changing, with retry_after_s). Instances whose process ended are removed, except those that crashed: they stay an hour with state "crashed" and crash {dump (crashes/*.mdmp file name or null), exit_code, evidence}; relaunch with instances_launch, the dump is for a human. States: "running" (live); "hung" (main thread blocked for 60 s, 180 s during a map load, or no heartbeat for that long while the process lives: a load that never ends, an infinite loop, a crash dialog; it will not recover: the note says to close it with instances_close {pids} or game_terminate {instance} and relaunch, and what was measured on it since is void); "unresponsive" (no heartbeat for 10 s but the process lives: busy or frozen, becomes hung after the limit); "crashed". A call in flight to an instance that dies is answered at once with client_crashed / server_crashed, and one whose process is frozen with no heartbeat for 30 s with instance_hung. Any tool accepts an instance argument: the coordinator relays the call to that instance. Through the plugin's bridge, entries also carry the owner label given to instances_launch (sent by the game itself, so it shows for every instance whichever bridge session launched it) and test_client (true for clients started by instances_launch), owner filters on it, desktop (private or shared) and launched_by_this_session on the clients this session launched, and launched_not_answering lists the clients it launched that never answered (close them with instances_close {pids}); with no game running the list is empty, with a note. include_crashed: false leaves the crashed entries out (they stay known: a call to one still answers client_crashed) and says how many in crashed_hidden.

Inputs: owner, include_crashed. Returns: next, note, warning, warnings, +7 more

lua_checkCheck Lua without running itA
Read-only

lua_check(realm?, code?, path?, globals?, limit?). Compiles Lua with the game's own parser (GLua syntax: !=, &&, ||, !, //, /* /, continue) and runs nothing. code, or path: a file or a whole folder (every .lua under it, e.g. an addon), absolute or relative to the game folder or lua/mcpagent_tmp/. Returns ok, errors [{file, line, message}] (one per file: the parser stops at the first error), and from the bytecode: unknown_globals (globals read but neither defined in the checked files nor present in the realm: typos, missing includes, wrong realm) and globals_written (every global assignment, e.g. a forgotten local). Unknown globals depend on the realm: pick the one the code runs in ('client'/'server' need a map; 'menu' lacks most game functions). ENT, SWEP, GM, EFFECT and TOOL are never reported. Result: {ok, realm, checked (files), errors: [{file, line, message}], unknown_globals: [{name, file, line}], globals_written: [{name, file, line}], truncated? (lists cut at limit), notes?}. In a test file (a tests/, test/ or spec/ folder, test_.lua, *_test.lua, *_spec.lua) expect is known, so tests_run files do not drown the list; other unknown globals there are still reported. Errors: realm_unavailable, not_found. Example: {"realm": "server", "path": "addons/my_addon/lua"}.

Inputs: code, path, limit, realm, +2 more. Returns: ok, next, note, path, +13 more

lua_execExecute LuaA
Destructive

lua_exec(code, realm?, timeout_s?, budget?, chunkname?, depth?, fields?, hook_guard?, limit?, ...). Executes Lua code in a realm under xpcall + debug.traceback, at full speed (the LuaJIT compiler is left on; no time limit unless budget: a budget installs a count hook, which makes LuaJIT interpret, so never time or benchmark code under one). Returns all serialized return values (values, n), captured print/Msg/MsgN/MsgC (output), duration_ms, chunk_bytes, chunkname and the realm's generation (it changes on every map load: compare it with map_load's result to know which state ran the code). Values come back whole: nothing is cut unless you pass depth, limit or max_string, and then the result says truncated: . A value too big to send (over a million values or 64 MiB of strings) fails with result_too_large; a whole _G is about 4.5 MB: return only what you need. Non-JSON types: {__type: Vector|Angle|Color|Entity|function|cycle|...}. Example: {"realm": "server", "code": "return #player.GetAll(), game.GetMap()"} -> {values: [1, "gm_construct"], n: 2, output: "", duration_ms, chunk_bytes, chunkname, generation}. Errors: lua_syntax_error, lua_error (with traceback), budget_exceeded, main_thread_timeout, result_too_large, realm_unavailable, client_locked. compile_ms is the time to compile the code, duration_ms the time to run it (a file that only defines functions runs in a few microseconds: that is not an empty run). include() only resolves paths under lua/ (for any other file it loads nothing and returns no value; the error only goes to the game console): then the result has include_failed and a warning; lua_exec_file with an absolute path loads a file from anywhere. Code that is already in a file: lua_exec_file (or lua_job {path}), not its content pasted here. Some convars cannot be set from Lua (RunConsoleCommand is refused for protected ones, e.g. volume_sfx, fps_max, silently): when the code calls RunConsoleCommand with such a command the result lists it in blocked_console_commands with a warning (only RunConsoleCommand calls made by this code while it runs are seen; a command refused for another reason, e.g. a cheat convar, is not): use convar_set or console_exec, then read the value back. Hooks: a hook this code adds with hook.Add is wrapped by the hook guard (see hook_guard) and listed by hook_list with added_by "lua_exec": hook.GetTable()[event][id] is then the guard's wrapper, not your function (mcpagent.unwrap(fn) gives your function back); only lua_exec {code} and lua_job wrap, lua_exec_file and lua_reload register hooks exactly as the game would. A temporary hook is yours to remove: hook_list {added_by: "mcp"} lists what the tools left on the game.

Inputs: code (required), depth, limit, realm, +7 more. Returns: n, file, next, note, +23 more

lua_exec_fileExecute a Lua fileA
Destructive

lua_exec_file(path, realm?, timeout_s?, assign_to?, budget?, chunkname?, depth?, fields?, hook_guard?, ...). Like lua_exec but reads the code from a file on the game's disk (with a mounted Lua folder, see lua_mount, a relative path finds its files first, like the engine). The chunk is named after the real path (e.g. @lua/mcpagent_tmp/test.lua) for actionable errors and tracebacks, or chunkname (e.g. the addon-relative name of a file from your git worktree). Prefer it to pasting a file into lua_exec's code: it saves the tokens of the file on every call. With fields, only the test's verdict comes back. Example: {"realm": "server", "path": "tests/check_doors.lua", "fields": ["pass", "fails"]} (relative: lua/mcpagent_tmp/tests/check_doors.lua first). Which file ran: the result has file (the real path), from_mount (true: the lua_mount folder's copy) and other_matches (other files the same relative path fits: they did NOT run; the first match wins: lua/mcpagent_tmp/, then the mounted folder, then the game folder, then lua/, gamemodes/, addons/*/lua/). A data file outside lua/ (fixtures under tests/ of a worktree, which file.Read(..., "LUA") cannot reach even when the worktree is mounted): give its absolute path and assign_to, e.g. {"path": "D:/dev/my-addon-wt/tests/fixtures/walls.lua", "assign_to": "WALLS"}; the file ends with return { ... } and later calls read WALLS. compile_ms / duration_ms say how long compiling and running took. include() of a file outside lua/ loads nothing and returns nothing (the error goes only to the game console) (see include_failed in the result): this tool with an absolute path is the way to load it. Hooks: the file's hooks are registered exactly as the game would, unwrapped (hook.GetTable() holds the file's own functions), unless you pass hook_guard above 0 (then they are the guard's wrappers). hook_list names them with added_by "lua_exec_file".

Inputs: path (required), depth, limit, realm, +8 more. Returns: n, file, next, note, +23 more

lua_file_deleteDelete a temporary Lua fileA
Destructive

lua_file_delete(name). Deletes one file of the game's lua/mcpagent_tmp/ folder (code it defined keeps running). Result: {deleted}. Error not_found.

Inputs: name (required), instance. Returns: next, note, deleted, warning, +5 more

lua_file_listList temporary Lua filesA
Read-only

lua_file_list(). Lists every file under the game's lua/mcpagent_tmp/ folder, subfolders included. Result: {dir (absolute), files: [paths relative to dir, sorted]}.

Inputs: instance. Returns: dir, next, note, files, +6 more

lua_file_readRead a temporary Lua fileA
Read-only

lua_file_read(name). Reads a file of the game's lua/mcpagent_tmp/ folder. Result: {path, content}. Error not_found.

Inputs: name (required), instance. Returns: next, note, path, content, +6 more

lua_file_writeWrite a temporary Lua fileA
DestructiveIdempotent

lua_file_write(name, content). Writes (or overwrites) a file in the game's lua/mcpagent_tmp/ folder, creating subfolders. Useful when you do not share the game's disk; if you do, write there directly. Run it with lua_exec_file {path: name}; from game code it is include("mcpagent_tmp/"). Result: {path (absolute), bytes, exec_path}.

Inputs: name (required), content (required), instance. Returns: next, note, path, bytes, +7 more

lua_function_sourceIs this function the code on disk?A
Destructive

lua_function_source(expr, realm?). Tells where a function was defined and whether the game runs the current code of that file: its bytecode is compared with the file compiled again from disk, in the same realm. Use it before trusting a test result after an edit (a map that was not reloaded, a file the client got from the server, another copy of the addon). Pick the realm the function lives in (default menu in client mode, server on srcds: addon code is usually in 'server' or 'client'). The file is found like the engine does (mounted Lua folder first, then lua/, gamemodes/, addons). Result: {source ("@" as the engine names it), linedefined, lastlinedefined, file/disk (absolute; the copy this realm ran), from_mount (true: it came from the mounted Lua folder, recorded when the folder was put in front of the realm's Lua path; false: the installed copy), mount_has_file, provenance (mount_in_place_at_load | reloaded_from_mount | installed | not_on_disk | no_file), file_age_s, matches_disk: true (same code) | false (edited since it was loaded, or another copy) | null (no file: code from lua_exec/RunString, or only inside a .gma), line_on_disk (where it starts now), note}. Example: {"realm": "server", "expr": "MyAddon.Update"}.

Inputs: expr (required), realm, instance. Returns: disk, file, next, note, +17 more

lua_inspectInspect a Lua valueA
Destructive

lua_inspect(expr, realm?, depth?, limit?). Evaluates an expression in a realm (it runs: keep it side-effect free; 2 s time limit) and describes the value. Result: {type, value (serialized to depth; 0 = summary only), and for a table: count, keys: [{key, key_type, type}] up to limit, truncated; metatable?: {type, name (MetaName), keys, methods (functions of __index)}}; for a function also {source, linedefined, lastlinedefined, from_mount, disk, mount_has_file, provenance} (see lua_function_source). Use it to discover an API or a structure; use lua_exec to compute something. Example: {"realm": "server", "expr": "FindMetaTable("Player")", "depth": 0, "limit": 300}.

Inputs: expr (required), depth, limit, realm, +1 more. Returns: disk, keys, next, note, +19 more

lua_jobRun a long Lua jobA
Destructive

lua_job(realm?, code?, path?, timeout_s?, args?, async?, chunkname?, depth?, ...). Runs a Lua script as a coroutine resumed once per frame, so long work (scans, batches of traces, multi-second tests) does not freeze the game and reports progress while it runs. The script MUST cooperate through the job object (global inside the chunk, also its first argument):

  • job:progress(done, total, message) or job:progress(message): forwarded to the client as MCP progress (and as the task status when run as a task).

  • job:step(): call it inside long loops; it yields only when this frame's time slice (slice_ms, default 8 ms) is used up.

  • job:yield() / job:frames(n) / job:sleep(seconds) / job:wait(fn, timeout): resume on a later frame.

  • job:report(value [, channel]): intermediate result, returned at the end and readable live with reports_read (channel "job:"). Each report is bounded: depth 8, 5000 entries per table, strings of 1 MiB (an item the serializer cannot take, over 20000 values, becomes a {__type="report_too_large"} marker); a cut part is marked truncated and counted in reports_truncated. At most 1000 reports are kept (more are counted in reports_dropped), 32 MiB of strings in all: put big data in the returned values or a file instead.

  • args (a global, same table as job.args): the args object of this call. job:elapsed(): seconds since start.

  • job:dt(): real seconds since this job was last resumed (since the start on the first resume). Use it for movement per frame: ply:SetPos(a + dir * speed * job:dt()). FrameTime() on the server is the engine's tick step, not the interval between two resumes (a job runs once per client frame): do not use it to scale a step.

  • job:call(realm, code [, {budget, depth, limit, max_string}]): runs the chunk in ANOTHER realm of this instance ("server", "client" or "menu") right now and returns its values, like lua_exec there (what it prints goes into the job's output as "[client] ..."). It never yields, so one job can drive both sides: a server job moves the player, waits a frame, then asks the client what it sees: local pos = job:call("client", "return LocalPlayer():GetPos()"). To wait for something over there: job:wait(function() return job:call("client", "return cond") end, 10). Values come back as JSON: a Vector, Angle or Color is a real one again, an Entity is {__type="Entity", id, class} (not an entity), a function or userdata a description; strings are valid UTF-8 text, not binary; a nil inside a table is dropped (field) or a null placeholder (array item). Budget (default 10 s) stops a runaway chunk. Failure raises {code, message}: realm_unavailable (no map yet, srcds has only the server, the realm was re-created by a map change: retry, or catch it with pcall), runtime_unavailable (that state is still initializing: retry), client_locked, lua_syntax_error, lua_error, budget_exceeded, result_too_large, invalid_params (your own realm). Do not synchronise two jobs through files in data/: use one job and job:call.

  • return value, ... ends the job: the values are the tool result. Realm: server by default (a map must be loaded); menu always exists in client mode. The code is code, or path (a file, found like lua_exec_file finds it). By default the call waits for the end and returns {job_id, values, n, reports, output (printed text), frames, resumes, cpu_ms, elapsed_s, generation, truncated?, concurrent_jobs?}; timeout_s (default 300) cancels a job that is still running. Errors: lua_syntax_error, lua_error (with traceback, reports and output so far), realm_reset (the map changed: the job died with its Lua state), cancelled, timeout. With timeout_s of 15 or more the call runs as a background task (when the client supports tasks): the result is then delivered ONCE, by the task notification, and the job is forgotten. A later lua_job_status {id} does not give it again: it answers not_found with details.delivered_at ("result already delivered") as long as the Lua state lives; the job did not get lost. To poll a long job yourself, start it with async: true. Globals the script assigns go to the realm's _G (they outlive the job and the next job sees them) unless fresh_env: true. async: true starts the job and returns {job_id, state, realm, generation} at once: poll it with lua_job_status (wait_s to wait), stop it with lua_job_cancel; two jobs can then run side by side, e.g. one per realm. A job started while another runs in the same realm is reported in concurrent_jobs: their timings and state mix. Returned values come back whole (no cut unless depth/limit/max_string; then the result says truncated). include() only resolves paths under lua/: when it loads nothing because the file is not there, the result has include_failed and a warning; lua_exec_file with an absolute path loads a file from anywhere. The LuaJIT compiler stays on (timings are real), except with resume_limit_s, whose count hook makes LuaJIT interpret. A resume that never yields freezes the game: polling it then fails with main_thread_timeout (about 10 s) and status shows main_thread_stalled. resume_limit_s (optional, best effort) aborts a resume that runs that long without yielding, for loops written in the script itself. Cancelling the request (or the task) stops the coroutine at the next frame. The job dies with its realm (map change). Example: local hits = 0 for i = 1, 5000 do local tr = util.TraceLine({ start = Vector(0, 0, 64), endpos = VectorRand() * 4096 }) if tr.Hit then hits = hits + 1 end if i % 250 == 0 then job:progress(i, 5000, hits .. " hits") end job:step() end return { hits = hits } called as {"realm": "server", "code": "", "timeout_s": 120}.

Inputs: args, code, path, async, +12 more. Returns: n, next, note, realm, +24 more

lua_job_cancelCancel a Lua jobA
Destructive

lua_job_cancel(id). Asks a running job (started by lua_job, e.g. with async: true) to stop: it ends at its next frame, before resuming. Result: {job_id, cancelled (false if the id is unknown), note}. Its final state (cancelled) stays readable once with lua_job_status. Example: {"id": "server-g3-1"}.

Inputs: id (required), instance. Returns: next, note, job_id, warning, +6 more

lua_job_statusState of a Lua jobA

lua_job_status(fields?, id?, wait_s?). With id: the state of a job started by lua_job (frames, elapsed_s, cpu_ms, last progress, reports_count); once it has finished, its full result exactly like lua_job's, and the job is then forgotten. wait_s waits up to that long for the end (the game's main thread is not held: the wait is a poll). With wait_s of 15 or more the call runs as a background task (when the client supports tasks), like lua_job: the result then arrives as the task notification. A wait that stops with the job still running says why: state running with stopped "wait_elapsed" (waited_s, wait_s; elapsed_s is the job's own age, not the time waited), or the error cancelled when the request itself was cancelled (the job keeps running: call again with the same id). A result is delivered once: after that, the id answers not_found with details.delivered_at / delivered_by (the task notification of lua_job, or an earlier lua_job_status) while the Lua state lives; the plain "realm reloaded or result already collected" wording means no memory of it (reload, or more than 1 h ago), and dropped_at says a result nobody collected in time. A job id belongs to one Lua state: after a map change (new realm) an id of the old state answers realm_reset. Without id: every job of every realm, running or finished but not collected yet.

Inputs: id, fields, wait_s, instance. Returns: n, jobs, next, note, +26 more

lua_mountLoad Lua from another folder firstA
Idempotent

lua_mount(path?, allow_shadow?, empty_cache?). Mounted Lua folder: plugs a folder (e.g. the git worktree of an addon: the folder that contains lua/) into THIS game process only. Every Lua lookup of this game then looks there first: autorun, include(), AddCSLuaFile (the client gets the folder's copy), lua_openscript, file.Read/Find with "LUA", and gmod-mcp's own lua_exec_file / lua_job {path} / lua_check / lua_reload / lua_function_source. A file in the folder hides the installed addon's file of the same Lua path; files only in the game are still loaded. Other games are not affected. Example: path "D:/dev/my-addon-wt" (a worktree of the addon installed as addons/my_addon): D:/dev/my-addon-wt/lua/autorun/my_addon.lua runs as autorun/my_addon.lua; D:/dev/my-addon-wt/lua/my_addon/core.lua is what include("my_addon/core.lua") loads, instead of addons/my_addon/lua/my_addon/core.lua; D:/dev/my-addon-wt/gamemodes//... are gamemode files; materials/, sound/, models/ and everything outside lua/ and gamemodes/ are not mounted: file.Read("tests/x.lua", "LUA") cannot reach a fixture of the worktree; load a data file from anywhere with lua_exec_file {path: absolute, assign_to: "NAME"} (the file returns its table, NAME keeps it). IT TAKES EFFECT AT THE NEXT MAP LOAD: call map_load right after (code already running stays until loaded again). No autorefresh: status.lua_mount.stale_files lists the folder's files that changed since each realm loaded them; lua_reload {mounted_changed: true} runs them again (or lua_reload {path}, or map_load); lua_function_source / lua_inspect of a function say which copy it came from (from_mount, disk). The engine names the folder's files from the folder's root (debug.getinfo source "@lua/my_addon/x.lua", not "@addons/my_addon/lua/my_addon/x.lua"). Only Lua (not materials, sounds, data/). path: the addon's root or its lua/ folder, absolute; null removes it (from the next map load); omitted: the current folder and the engine's Lua search paths (lsv = server, lcl = client). If the result says base_lua_mounted: false, remove the folder at once. engine_serves_folder (with a map loaded) is what the game's own file system says: false means it lists the folder but finds none of its files (a path it cannot read), so the game runs the installed code whatever else says mounted: a warning names the way out. A test client can start with one: instances_launch {lua_mount}. empty_cache (default true) empties the engine's Lua file cache. Windows game clients only (unsupported_platform on Linux; client only, unsupported on srcds). Full guide: resource mcpagent://guide, section "Mounted Lua folder".

Inputs: path, instance, empty_cache, allow_shadow. Returns: next, note, removed, warning, +17 more

lua_reloadReload a Lua file from diskA
Destructive

lua_reload(path?, timeout_s?, budget?, chunkname?, depth?, fields?, limit?, max_string?, ...). Reads an addon or gamemode file from the disk again and runs it in its realms, to test an edit without reloading the map, in every realm it belongs to in one call. On the machine that hosts the game (singleplayer or listen server) include() from lua_exec also reads the edited file, in the server and the client realm (checked live); a client connected to a separate server (e.g. a local srcds) only has the copies that server sent, so there lua_reload is the way to run an edit on the client. Looks under the mounted Lua folder if any (lua_mount), then lua/, gamemodes/, addons//lua|gamemodes/: the engine's order, so the copy the game would load. Which file ran: file (the real path), from_mount (true: the lua_mount folder's copy) and, when several files match, other_matches (they did NOT run) with a warning: the first match wins, and the mounted folder is searched before the installed addons. Errors name the real file. Running a file again redefines its functions and hooks; what it built at load time (entities, timers, net strings) is not reset. Pitfalls: a file that does MyAddon.Config = {...} resets that state to the file's values on every reload; a file that builds a local Class = {} with methods makes a new table, so objects created before the reload keep the old table and its old methods (rebuild them, or map_load: the result's note says so when it sees one); clients receive new or changed files only at the next map load or reconnect, even if the file calls AddCSLuaFile (the note says so too; lua_reload runs the file in the client realm itself, but code on the client that include()s a file it never received fails until then). A NEW shared file must be reloaded with realms set, server first then client (a client that never got the file does not receive it otherwise, and a server half that registers something the client half reads, a replicated convar for instance, must run first): {"path": "my_addon/sh_core.lua", "realms": ["server", "client"]}; when a file that looks shared (sh_.lua, shared.lua, or one that calls AddCSLuaFile) ran in one realm only, the note says so. Dependent files are reloaded in dependency order by hand. The hooks the file adds are registered exactly as the game would, with the file's own functions: the hook guard never wraps a reload (hook.GetTable() holds your functions, so a test may compare them), and hook_list {added_by: "mcp"} names them added_by "lua_reload". In each realm's result, compile_ms is the time to compile the file and duration_ms the time to run its top level (a file that only defines functions runs in microseconds: that is not an empty reload). Several agents on one game: mounted_changed also reloads files another agent is editing; to reload only your own files, call this tool once per file with path (there is no list mode). Returns {ok, file, from_mount, chunkname, realms: {: lua_exec result or {error}}, other_matches?, note?, warning?}. Example: {"path": "my_addon/sh_core.lua"} (shared file: runs in server then client). With a mounted folder (lua_mount) there is no autorefresh: mounted_changed: true (instead of path) runs again every file of that folder whose time differs from what each realm loaded (modified, added; the list is status.lua_mount.stale_files), in alphabetical order and in the realms each file belongs to, and returns {ok, mode, path, reloaded: [{file, chunkname, reason, realms: {: lua_exec result or {error}}}], skipped: [{file, why}] (deleted files, entity/weapon/effect files: map_load or lua_reload {path}), realms_without_mount, note?, warning?}; error no_mount if no folder is mounted, error reload_failed (isError, the whole result in details) if a file fails in a realm. Limits: a reload re-runs the file, it does not undo what the old copy did (hooks and timers it added under another name, net strings, entities), and it does not reload a realm that loaded before the folder was mounted (map_load).

Inputs: path, depth, limit, budget, +7 more. Returns: ok, file, mode, next, +15 more

map_listList mapsA
Read-only

map_list(filter?, limit?). Installed maps: every maps/*.bsp on the game's GAME path (garrysmod, addons, workshop, mounted games such as HL2), names without .bsp, sorted, filtered by a case-insensitive substring. Same answer on every instance of this game folder (callable without instance). Result: {maps: [names], count (all matches), truncated, filter}. Example: {"filter": "gm_"}.

Inputs: limit, filter, instance. Returns: maps, next, note, count, +8 more

map_loadLoad a mapA
Destructive

map_load(map, timeout_s?, gamemode?, maxplayers?). Loads a map and WAITS until it is playable: client mode = the console map command (singleplayer when maxplayers is 1, listen server otherwise), then it waits until NEW server and client realms are up and ready (gamemode loaded, local player valid) and the loading screen is gone; srcds = changelevel, server realm only. Every Lua state of the previous map is destroyed: its globals, hooks, timers, jobs and debug drawings are gone, and the addons' files are loaded again from disk. InitPostEntity and Initialize have ALREADY run when it returns: a hook added afterwards with lua_exec never fires, and one added before is destroyed with the old state. To test code that reacts to them, put it in a file loaded at map load (an addon autorun, or a lua_mount folder) and map_load, or call your init function by hand (guide: "Map load and InitPostEntity"). Changing maxplayers on a running game disconnects first (client mode only). Result: {map, gamemode, maxplayers, requested_map, duration_s, server_generation, client_generation, warning?, lua_mount?, lua_cache_emptied?}. With a mounted Lua folder (lua_mount) it empties the engine's Lua file cache before loading (lua_cache_emptied), and when the load ends it checks the folder: if its files changed since the realms loaded them (edited during the load) or a realm did not get the folder, warning says so and lua_mount is the status.lua_mount object. Errors: not_found (no maps/.bsp), busy (another map_load/disconnect runs), timeout (with which realms are up), cancelled. If the game crashes during the load, the call through the coordinator answers client_crashed (dump name in details; relaunch with instances_launch). IMPORTANT: when your client runs it as a background MCP task, wait for its result before calling a realm tool: a call made before it ends reaches the OLD map's state. Every lua_exec/lua_job result carries the realm's generation: equal to server_generation/client_generation = the new map's state. Starting a game makes every other running Garry's Mod release its GPU resources for 2-10 s, and a map load ending in that window crashes that game (engine bug, Facepunch garrysmod-issues #7137). So a map_load that goes through the bridge (any session, any target instance) first waits while a game is being started (instances_launch) and for 15 s after the last start. A call that waited carries waited_s and waited_reason (and progress; as a task, in statusMessage). If the wait would exceed timeout_s it fails with error launch_in_progress and sends nothing to the game: retry later, or with a larger timeout_s. When another game was loading a map at that moment (started by anything: console, Lua, a script, another session), the result lists it as other_games_loading; it does not delay the load. A launch, however, waits for loads like that. Not held back by the bridge: a game started by hand, and a map change triggered from Lua or the console while a game is being started (changelevel, map through console_exec): do not do those. Right after a game starts, the other games can be unreachable for 15-18 s (instance_unreachable, timeouts): expected, wait and retry. Example: {"map": "gm_construct"}.

Inputs: map (required), gamemode, instance, timeout_s, +1 more. Returns: map, next, note, warning, +13 more

perf_hook_costCost of a hook's functionsA
Read-only

perf_hook_cost(event, realm?, duration_s?). Measures over duration_s the time spent in each function of a hook event: every hook.Add function registered when it starts, and GAMEMODE:. Each one is wrapped with a timer for the measurement and put back afterwards (restored = how many hooks were put back; a hook replaced meanwhile is left alone). Waits the whole duration. Result: {event, duration_s, functions: [{id, calls, total_ms, avg_ms, max_ms, src {source, line}}] sorted by total_ms, most expensive first, restored}. The game runs at its real frame rate: on a light test client (20 fps) the number of calls is lower than in a normal game. Example: {"realm": "client", "event": "Think", "duration_s": 10} (event is required; the length is duration_s, not seconds).

Inputs: event (required), realm, instance, duration_s. Returns: next, note, event, warning, +8 more

perf_snapshotPerformance snapshotA
Read-only

perf_snapshot(). Quick performance numbers of this game process. Result: {frame: {fps, frametime_avg_ms, frametime_max_ms, samples} over the last 256 frames of the main thread, last_tick_age_s (seconds since the last frame: large = frozen), realms: {menu|client|server: {lua_memory_kb, entity_count, frametime, tick_interval, real_frametime (client)}}} for the realms that exist. Note the frame cap (status fps_max: 20 on a light test client). For per-hook costs use perf_hook_cost.

Inputs: instance. Returns: next, note, frame, realms, +7 more

player_setMove/configure a playerA
Idempotent

player_set(ang?, god?, id?, noclip?, pos?). Changes a player in the server realm: pos teleports it (velocity reset to zero), ang sets its eye angles, noclip switches MOVETYPE_NOCLIP/WALK, god toggles god mode. Only the given fields change. Default player: the first one (the local player in singleplayer). Result: {id, class, model, nick, pos, ang, eye_ang, noclip, god} read right after. The client sees it on a later frame: check with lua_exec {realm: "client", code: "return LocalPlayer():GetPos()"}. Example: {"pos": [0, 0, 64], "ang": [0, 90, 0], "noclip": true}. Needs a loaded map (map_load): the server and client realms do not exist at the main menu.

Inputs: id, ang, god, pos, +2 more. Returns: id, ang, bot, god, +19 more

players_listList playersA
Read-only

players_list(realm?). Every player (bots included). Result: {players: [{id (entity index, for player_set), class, model, nick, pos, ang, userid, steamid, bot, alive, health, eye_pos, eye_ang, noclip, god (server realm only)}], count, maxplayers}. Needs a loaded map (map_load): the server and client realms do not exist at the main menu.

Inputs: realm, instance. Returns: next, note, count, players, +7 more

reports_channelsList report channelsB
Read-only

reports_channels(). Report channels of this instance: {channels: [{channel, buffered (values kept), total (ever published), next_cursor}]}.

Inputs: instance. Returns: next, note, warning, channels, +5 more

reports_clearClear report channelsA
DestructiveIdempotent

reports_clear(channel?). Deletes a report channel and its values (all channels if channel is absent). Result: {cleared}.

Inputs: channel, instance. Returns: next, note, cleared, warning, +5 more

reports_readRead a report channelA
Read-only

reports_read(channel, cursor?, limit?, wait_s?). Reads the values that game code published with mcpagent.report(channel, value) (a Lua function gmod-mcp adds in every realm; job:report(value) of a lua_job publishes on "job:"). Values come back whole, as JSON. Read incrementally: cursor 0 = the oldest kept value, then pass next_cursor. wait_s > 0 waits until a new value arrives (or wait_s passes). Each channel keeps its last 10000 values (lost > 0 = dropped before you read them); channels survive map changes and live until reports_clear or the game exits. Result: {channel, items: [{seq, time, realm, value}], next_cursor, lost, timed_out}. Example: in the game mcpagent.report("scan", {map = game.GetMap(), hits = n}), then {"channel": "scan", "cursor": 0, "wait_s": 30}.

Inputs: channel (required), limit, cursor, wait_s, +1 more. Returns: lost, next, note, items, +9 more

screenshotTake a screenshotA
Read-only

screenshot(crop?, format?, h?, quality?, scale?, scale_filter?, source?, w?). Client only (unsupported on srcds). Captures what the game shows and returns it as an MCP image (plus {source, format, w, h, screen_w, screen_h, method, bytes}). Size: an image over 8 MB once encoded is never sent (a client drops the whole connection above 16 MB). A png without w/h can be that big (a full window): it is retaken as a JPEG at lower quality and the result says size_capped: true (requested_format, quality); if nothing fits the call fails with result_too_large and no image. Ask for jpeg, a smaller w/h or a crop to avoid it. crop {x, y, w, h} captures only that rectangle (result crop); scale 1-16 enlarges the picture as a PNG (scale_filter nearest or smooth; result scale, scaled_from): to read a small HUD element, crop it and scale 8 (not w/h: that renders the view again without the HUD). Two sources, chosen by source (auto by default). render: what the local player sees, drawn by the engine; needs a loaded map (client realm); without w/h it is the game window as it is, HUD included (method backbuffer), with w/h the player's view rendered again at that size, without HUD or view model (method render_target); debug_draw primitives are visible; a minimized or frozen game gives timeout after 10 s. engine_jpeg: the engine's own jpeg console command, the only way to see the main menu, a VGUI2 dialog ("Disconnected by the server") or a loading screen, when there is no client realm. It is the engine's own capture, so it works while other windows cover the game, takes no focus and does not touch the window. The engine writes the picture to garrysmod/screenshots/.jpg and prints the name in its console; the module reads exactly that file and deletes it (and nothing else; result file, file_deleted, and a warning with the path if the file could not be deleted). The image is the game's screen size (the space ui_click coordinates are read on) as a JPEG at the engine's own quality (convar jpeg_quality, not changed): format, w, h and quality are not applied (nor crop, scale and scale_filter) and, when given, are listed in ignored. A picture the user takes with their own jpeg command in the same instant can be mistaken for it. One capture at a time. Errors: realm_unavailable (source render without a map), unsupported (srcds), client_locked, capture_timeout (no Wrote line from the engine within 4 s: game minimized or frozen, or the console capture is off), capture_failed (the file named by the engine could not be taken; it is left in place and named). Example: {"w": 1280, "h": 720, "format": "png"} with a map, or {"source": "engine_jpeg"} at the main menu.

Inputs: h, w, crop, scale, +5 more. Returns: h, w, crop, file, +25 more

screenshot_fromScreenshot from a viewpointA
Read-only

screenshot_from(pos, ang, format?, fov?, h?, quality?, w?). Captures the scene from an arbitrary camera (pos, ang, fov) and returns it as an MCP image; the player does not move. Client only (unsupported on srcds), with a loaded map. Without w/h: a temporary CalcView hook moves the view for 3 frames, the window is captured, then the hook is removed (result method calcview, camera_restored: true when the player's view is back). With w/h: rendered into an off-screen target of that size (method render_target), the view is not touched. The local player's body is drawn (it is not the camera). debug_draw primitives are visible. Example: {"pos": [0, -300, 200], "ang": [30, 90, 0], "w": 800, "h": 600}.

Inputs: ang (required), pos (required), h, w, +4 more. Returns: h, w, crop, file, +25 more

sound_emitEmit a soundA

sound_emit(name, realm?, dsp?, ent?, level?, pitch?, pos?, volume?). Plays a sound once, from a position (global EmitSound) or from an entity (Entity:EmitSound, it follows the entity), on CHAN_AUTO. Pass pos or ent. name is a soundscript name or a path under sound/ (e.g. "ambient/alarms/klaxon1.wav"); error not_found if neither exists. Server realm by default (networked to the client); realm client plays it only locally. Returns at once: {emitted, pos or ent, level, pitch, volume, dsp}. To see what the engine and the hooks received, run sound_trace meanwhile. Example: {"name": "ambient/alarms/klaxon1.wav", "pos": [0, 0, 64], "level": 90}. Needs a loaded map (map_load): the server and client realms do not exist at the main menu.

Inputs: name (required), dsp, ent, pos, +5 more. Returns: dsp, ent, pos, next, +11 more

sound_traceTrace emitted soundsA
Read-only

sound_trace(realm?, duration_s?, max_calls?). Records the sounds the game emits through the EntityEmitSound hook during duration_s (or until max_calls), then removes its recorder: game behaviour is unchanged. Waits the whole duration (progress reported; can run as an MCP task). Result: {event, calls: [{t (s since start), sound: {name, original_name, level, pitch, volume, dsp, channel, flags, sound_time, pos, entity}}], recorded, total_calls, capped, duration_s, tracer_removed}. Checked live: realm server sees Entity:EmitSound and sound.Play run on the server; realm client sees the client's Entity:EmitSound and the server's sound.Play; surface.PlaySound (UI sounds) is seen by neither. Also not seen: sounds that a hook running before the recorder suppressed (returned a value). Example: {"duration_s": 3, "realm": "server"}. Needs a loaded map (map_load): the server and client realms do not exist at the main menu.

Inputs: realm, instance, max_calls, duration_s. Returns: next, note, calls, event, +11 more

statusInstance statusA
Read-only

status(timeout_s?, fields?). GMod version, branch, platform, map, gamemode, maxplayers, available realms (and injection generation), client lock, fps/frametime (perf), fps_max (the frame cap: 20 on a light test client) and host_timescale, loading (a map load in progress: the same flag as instances_list; menu.loading is the loading screen alone), uptime, age of the main thread's last tick (main_thread_stalled if > 5 s), Lua temporary directory (tmp_dir, absolute path), and with a mounted Lua folder (lua_mount) lua_mount: {path, loaded_with_mount, realms_without_mount, stale_files: [{file, disk, reason, realms}], warning?} (the folder's files that changed since each realm loaded them), and on a client started with instances_launch {early_lua} early_lua: {mounted, error?} (false = the early Lua did not run). Call this first. Works even if the game is frozen. Result: summary fields at the top (instance, mode, map, gamemode, maxplayers, fps_max, loading, main_thread_stalled...) and one object per realm (menu, server, client) with its own details; fields keeps only some top-level keys. Example: {"fields": ["map", "realms", "perf"]}.

Inputs: fields, instance, timeout_s. Returns: map, pid, menu, mode, +37 more

tests_runRun Lua testsA
Destructive

tests_run(path, realm?, timeout_s?, budget?, case?, fields?, frames_between_files?, only_failures?, output?). Runs test files in GLuaTest format in one realm and returns structured results. A file returns {groupName, beforeAll, beforeEach, afterEach, afterAll, cases = {{name, func, skip?, when?, timeout?, timing?}}}; inside, expect(x).to.equal(y) / .notTo / .beTrue / .beNil / .exist / .beA(type) / .beValid / .beGreaterThan / .beLessThan / .beBetween / .aboutEqual(x, tol) / .haveLength / .contain / .err / .errWith(msg) / .succeed. A failed expect() raises a string "file:line: expected ..." (so assert(ok, err) keeps it). Skip a case with skip = "reason", when = false, or expect.skip(reason) inside it (status skip, with the reason). state (first argument of every step) is ONE table per file, shared by beforeAll, beforeEach, the cases, afterEach and afterAll, and NOT reset between cases: reset what you need in beforeEach. path: a file or a pattern in the file name (*.lua, or **/.lua for subfolders); absolute, or relative to lua/mcpagent_tmp/, then the mounted folder (lua_mount) and the game folder (so addons/<addon>/tests/x.lua works). There is no filter argument: which files = path, which cases = case. Result: {files: [{file, group, cases: [{name, status: pass|fail|error|skip, message?, line? (of the failing assertion), traceback?, output?, duration_ms}], totals {pass, fail, error, skip}, error?, setup_error?, filtered?, realm? (with realm both)}], totals, ok, realms? (with realm both: what each realm did, or why it could not run)}. Big runs: only_failures lists only the fail/error cases (each file keeps its totals); fields: ["totals", "ok"] returns just the verdict. A result too big for your client may be saved to a file: read the path it gives. case runs only the cases whose name contains it. What a failing case prints (print, MsgN) comes back as output (cut at 4 KB; output: all or none). The run is one call on the main thread (the game is frozen meanwhile; for multi-frame tests use lua_job), so every file runs in the same frame: Entity:Remove() only takes effect next frame, a removed entity is still valid for the next file. frames_between_files (default 0) waits that many frames between files. Calls sent together are queued and run one after the other; Lua globals, entities and convars persist between calls. realm: "both" runs the files in the server, then the client (each file says its realm; for sh_ files). The budget (default 10 s per step) installs a count hook, which makes LuaJIT interpret: code under it, and helpers it calls, run several times slower (up to 40x measured) and are not compiled. Never time anything under a budget: give that case timing = true (or timeout = 0), or pass budget 0 for the whole run (no time limit then: a loop freezes the game until timeout_s). Full format: resource mcpagent://tests-format. Examples: {"realm": "server", "path": "tests/.lua", "only_failures": true}; one case of one file: {"path": "addons/myaddon/tests/sh_x.lua", "realm": "both", "case": "saves the value"}.

Inputs: path (required), case, realm, budget, +6 more. Returns: ok, next, note, files, +9 more

traceTrace a lineA
Read-only

trace(start, end, realm?, filter?, mask?). One util.TraceLine from start to end. Result: hit, hit_world, hit_sky, hit_nodraw, pos (hit position, or end if nothing was hit), normal, fraction (0..1 along the segment), distance (to the hit, or the whole length), mat_type + mat_name (MAT_* constant), surfaceprop (name) + surfaceprop_id, texture, entity (summary, {id: 0, class: worldspawn} for the world, or null), start_solid, all_solid, fraction_left_solid, hitgroup, physics_bone. Example: {"start": [0, 0, 64], "end": [0, 0, -1000]}. For everything a segment crosses (walls, doors, thickness), use trace_through. Needs a loaded map (map_load): the server and client realms do not exist at the main menu.

Inputs: end (required), start (required), mask, realm, +2 more. Returns: hit, pos, next, note, +23 more

trace_throughSurfaces crossed by a segmentA
Read-only

trace_through(start, end, realm?, filter?, mask?, max_surfaces?). Lists every solid the segment start->end goes through, in order, by repeated traces (FractionLeftSolid gives where each solid is left). Result: {surfaces: [{entry, entry_normal, entry_surface (same surface fields as trace: mat_name, surfaceprop, texture, entity), distance_from_start, exit, exit_normal, exit_surface, thickness (units), reaches_end_inside?}], count, total_thickness, distance (segment length), truncated}. A start point inside a solid gives a first entry with entry_surface null. Made for sound propagation through walls and doors. Example: {"start": [0, 0, 64], "end": [800, 0, 64]}. Needs a loaded map (map_load): the server and client realms do not exist at the main menu.

Inputs: end (required), start (required), mask, realm, +3 more. Returns: next, note, count, warning, +9 more

ui_clickClick in the game UIA
Destructive

ui_click(x, y, allow_user_game?, button?, coords?, double?, screenshot_after?, screenshot_size?, wait_frames?, wheel?). Clicks (or scrolls the wheel) at a point of the game window: use it for what has no console command, the buttons of VGUI2 dialogs ("Disconnected by the server" > Close), Derma panels and the menu's HTML. Take the coordinates from a screenshot (coords "screenshot", the default: pixels of that image, origin top-left; if the image you read has another size than the game window's, e.g. a screenshot with w/h, pass screenshot_size [w, h] and the point is scaled) or give coords "window" (pixels of the window's client area, title bar excluded). DPI scaling is handled: the result says the window size, DPI and the scale applied. Posts WM_MOUSEMOVE, then the button down and up (double: down, up, double-click, up) one frame apart, or WM_MOUSEMOVE and one WM_MOUSEWHEEL (wheel: notches, positive = up). Result: {sent: [messages], at: {x, y} (client pixels), coords, button | wheel, scale?, frames_waited, window: {client_w, client_h, dpi, dpi_awareness, class}, screen: {w, h}, cursor_via (game_ui | vgui), screenshot?, screenshot_error?} plus the image with screenshot_after (the engine's jpeg capture when there is no client realm). The cursor is visible when the game menu (main menu, ESC menu, a dialog on it) is up, gui.IsGameUIVisible(), or a Derma popup, the context or spawn menu has it, vgui.CursorVisible() in the client realm. Windows game client only (unsupported on srcds). Refusals, each its own error code: unsupported; not_a_test_client (the game was not started by instances_launch: pass allow_user_game: true to post into the user's own game); client_locked (connected to a server that is not on this machine); loading (a map is loading: events_wait map_loaded); window_unavailable (window minimized or not found); cursor_hidden (the mouse is captured by the game view: no menu, dialog or popup is open; open one first, e.g. console_exec gameui_activate); out_of_bounds (ui_click only: the point is outside the image or window). The input is posted to the game's own window (PostMessage): the user's real cursor does not move and no window takes the focus. Example: {"x": 640, "y": 400, "screenshot_after": true}.

Inputs: x (required), y (required), wheel, button, +7 more. Returns: at, next, note, sent, +17 more

ui_keyPress a key or type text in the game UIA
Destructive

ui_key(allow_lossy?, allow_user_game?, key?, screenshot_after?, text?, wait_frames?). Presses a key and/or types text into the focused part of the game UI (a text entry of a dialog, a Derma TextEntry, an HTML input): key is a named key (enter, escape, tab, backspace, space, up, down, left, right, home, end, pageup, pagedown, insert, delete, f1..f12, a letter, a digit or space: those type the character, as WM_CHAR like text, they are not pressed as keys), text is typed character by character as WM_CHAR (up to 256 characters; no control characters: use key). The engine narrows every typed character through the machine's ANSI code page with best-fit (live, CP1252: accents of western Europe arrive, l-stroke becomes l, Greek a, Cyrillic and CJK ?): a text with such a character is refused with text_not_representable (before anything is typed; details: code_page, characters) unless allow_lossy: true. For those, set the text from Lua with lua_exec in the realm that owns the panel (menu for the main menu's dialogs, client for Derma in game): entry:SetText("...") on a DTextEntry (DTextEntry:SetValue does nothing while the entry has the keyboard focus, which a ui_click gives it; entry:OnValueChange(text) afterwards if the page listens to it). With both, the text is typed first, then the key is pressed (text "hello" + key enter). Click the field first with ui_click. Result: {sent: [messages], key?, text_units?, lossy_characters? and ansi_code_page? (allow_lossy), frames_waited, window, screen, cursor_via, screenshot?}. Windows game client only (unsupported on srcds). Refusals, each its own error code: unsupported; not_a_test_client (the game was not started by instances_launch: pass allow_user_game: true to post into the user's own game); client_locked (connected to a server that is not on this machine); loading (a map is loading: events_wait map_loaded); window_unavailable (window minimized or not found); cursor_hidden (the mouse is captured by the game view: no menu, dialog or popup is open; open one first, e.g. console_exec gameui_activate); out_of_bounds (ui_click only: the point is outside the image or window). The input is posted to the game's own window (PostMessage): the user's real cursor does not move and no window takes the focus. Example: {"text": "my name", "key": "enter"}.

Inputs: key, text, instance, allow_lossy, +3 more. Returns: key, next, note, sent, +16 more

wait_forWait for a Lua conditionA
Destructive

wait_for(condition, realm?, timeout_s?, interval_s?). Waits until a Lua condition is true. condition is an expression ("IsValid(Entity(57))") or a block with return ("local d = Entity(57) return IsValid(d) and d:GetInternalVariable('m_eDoorState') == 2"), compiled once and evaluated in realm every frame (or every interval_s); true = anything but nil/false. Each evaluation may run 1 s at most. Result: {satisfied: true, elapsed_s, polls, value (the last value)}. Errors: timeout (details: polls, last_value), realm_lost (the realm was destroyed or recreated, e.g. a map change, during the wait), realm_unavailable, lua_syntax_error, lua_error. Reports progress; can run as an MCP task.

Inputs: condition (required), realm, instance, timeout_s, +1 more. Returns: next, note, polls, value, +8 more

wait_framesWait N framesA
Read-only

wait_frames(n, timeout_s?). Waits until the game's main loop has run n more frames (counted by gmod-mcp every frame, map or not), e.g. to let a console command, a spawn or a SetPos take effect. Result: {frames, elapsed_s}. Error timeout if the game renders fewer frames in timeout_s (frozen, minimized with a low fps_max_nofocus). A light test client runs at 20 fps: 20 frames = 1 s.

Inputs: n (required), instance, timeout_s. Returns: next, note, frames, warning, +6 more

wiki_pageRead a GMod wiki pageA
Read-only

wiki_page(name, format?, refresh?). Reads one wiki page by its exact name (as wiki_search returns it): format text = the page's raw wiki markup (realm, arguments, returns, notes), format json = the wiki's JSON form. Cached 7 days (stale cache used offline; refresh: true re-downloads). Result: {name, format, url, cache, content (text) or page (json)}. A name that is not a page is looked up: CurTime reads Global.CurTime (resolved_from says so) when only one page can mean it, otherwise not_found lists the close pages in details.candidates. Error not_found for an unknown name (use wiki_search). Example: {"name": "Entity:EmitSound"}.

Inputs: name (required), format, refresh, instance. Returns: url, name, next, note, +11 more

Tool Schema Changelog

Recent tool additions, removals, and schema changes observed during successful MCP inspections.

Loading tool schema changelog…

    TDQS

    A3.8/5.0

    Scored across 65 tools

    Disambiguation3/5

    Most tools have recognizable, separate roles, but several clusters overlap in practice: lua_exec/lua_exec_file/lua_job/lua_reload/tests_run all execute Lua, and wait_for/wait_frames/console_wait/events_wait all provide different waiting semantics. status, perf_snapshot, and instances_list also share health/performance information. The very detailed descriptions help avoid misselection, but an agent still needs careful reading to choose correctly.

    Naming Consistency4/5

    Names are overwhelmingly snake_case and follow a predictable domain-prefix + action pattern (lua_*, ent_*, console_*, instance*, hook_*). There are minor inconsistencies such as singular versus plural prefixes (ent_info vs ents_find, player_set vs players_list) and a few bare names like status, disconnect, trace, and screenshot. Overall the convention is readable and stable, not chaotic.

    Tool Count2/5

    Sixty-five tools is far beyond the comfortable 3-15 range and imposes a large selection and context burden on the agent. The domain is genuinely broad, and many tools are purposeful, but several could be consolidated or grouped behind fewer high-level entry points. This is a heavy tool surface even for a professional game-testing harness.

    Completeness5/5

    The surface covers an unusually complete lifecycle: Lua execution, file management, map loading, console access, convars, entities, players/bots, traces, screenshots, debug drawing, sound, UI input, hooks, tests, jobs, reports, events, wiki/API lookup, and instance management. Missing direct conveniences such as entity property setters can be handled through lua_exec, so there are no obvious dead ends for the stated testing domain.

    Maintenance

    ActivityMaintained
    ResponsivenessLimited data

    Related MCP Connectors

    Related MCP Servers

    • F
      license
      Not graded
      quality
      F
      maintenance
      MCP server suite for the s&box game engine, enabling AI assistants to manipulate scenes, create objects, compile code, manage assets, and more via editor, API, and docs servers.
      3
      -
    • A
      license
      Not graded
      quality
      B
      maintenance
      Open-source, engine-agnostic MCP server shared by Unity-MCP, Godot-MCP, and Unreal-MCP. Additionally you can use AI Game Dev app (https://ai-game.dev) to generate images, video, audio, 3D, rig, animation and much more.
      22
      Apache 2.0