dosbox-mcp 0.1.0__py3-none-any.whl
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- dosbox_mcp/__init__.py +3 -0
- dosbox_mcp/capabilities.py +26 -0
- dosbox_mcp/cli.py +177 -0
- dosbox_mcp/client.py +65 -0
- dosbox_mcp/config.py +265 -0
- dosbox_mcp/connection.py +208 -0
- dosbox_mcp/lifecycle.py +261 -0
- dosbox_mcp/protocol.py +85 -0
- dosbox_mcp/server.py +128 -0
- dosbox_mcp/tools/__init__.py +3 -0
- dosbox_mcp/tools/bridge.py +284 -0
- dosbox_mcp/tools/cpu.py +40 -0
- dosbox_mcp/tools/debug.py +53 -0
- dosbox_mcp/tools/freeze.py +93 -0
- dosbox_mcp/tools/input.py +188 -0
- dosbox_mcp/tools/io.py +81 -0
- dosbox_mcp/tools/media.py +49 -0
- dosbox_mcp/tools/memory.py +138 -0
- dosbox_mcp/tools/screen.py +56 -0
- dosbox_mcp/tools/script.py +68 -0
- dosbox_mcp/tools/session.py +85 -0
- dosbox_mcp-0.1.0.dist-info/METADATA +121 -0
- dosbox_mcp-0.1.0.dist-info/RECORD +30 -0
- dosbox_mcp-0.1.0.dist-info/WHEEL +5 -0
- dosbox_mcp-0.1.0.dist-info/entry_points.txt +2 -0
- dosbox_mcp-0.1.0.dist-info/licenses/LICENSE +13 -0
- dosbox_mcp-0.1.0.dist-info/licenses/THIRD_PARTY_LICENSES.txt +30 -0
- dosbox_mcp-0.1.0.dist-info/licenses/licenses/CC-BY-SA-4.0.txt +428 -0
- dosbox_mcp-0.1.0.dist-info/licenses/licenses/GPL-2.0-or-later.txt +339 -0
- dosbox_mcp-0.1.0.dist-info/top_level.txt +1 -0
dosbox_mcp/__init__.py
ADDED
|
@@ -0,0 +1,26 @@
|
|
|
1
|
+
# This file is part of the dosbox-mcp Project.
|
|
2
|
+
# License: GPL-2.0-or-later. Contact: dosbox-mcp@trinity2k.net
|
|
3
|
+
#
|
|
4
|
+
|
|
5
|
+
# Maps a bridge tool group to the feature flag that must be true for it
|
|
6
|
+
# to register. Groups always present (session, screen, script, media)
|
|
7
|
+
# are not gated.
|
|
8
|
+
GROUP_CAPABILITY = {
|
|
9
|
+
"memory": "memory",
|
|
10
|
+
"input": "input",
|
|
11
|
+
"freeze": "freeze",
|
|
12
|
+
"cpu_registers": "cpu_registers",
|
|
13
|
+
"cpu_control": "cpu_control",
|
|
14
|
+
"port_io": "port_io",
|
|
15
|
+
"debugger": "debugger",
|
|
16
|
+
}
|
|
17
|
+
|
|
18
|
+
ALWAYS_ON = {"session", "screen", "script", "media"}
|
|
19
|
+
|
|
20
|
+
|
|
21
|
+
def registered_groups(features: dict) -> set:
|
|
22
|
+
groups = set(ALWAYS_ON)
|
|
23
|
+
for group, flag in GROUP_CAPABILITY.items():
|
|
24
|
+
if features.get(flag) is True:
|
|
25
|
+
groups.add(group)
|
|
26
|
+
return groups
|
dosbox_mcp/cli.py
ADDED
|
@@ -0,0 +1,177 @@
|
|
|
1
|
+
# This file is part of the dosbox-mcp Project.
|
|
2
|
+
# License: GPL-2.0-or-later. Contact: dosbox-mcp@trinity2k.net
|
|
3
|
+
#
|
|
4
|
+
|
|
5
|
+
"""Command line entry point.
|
|
6
|
+
|
|
7
|
+
`dosbox-mcp` with no arguments serves MCP over stdio (what an MCP client
|
|
8
|
+
spawns). `setup` and `probe` are the human-facing configuration
|
|
9
|
+
commands; there is deliberately no interactive dialog - the commented
|
|
10
|
+
config template plays that role.
|
|
11
|
+
"""
|
|
12
|
+
|
|
13
|
+
import argparse
|
|
14
|
+
import json
|
|
15
|
+
import sys
|
|
16
|
+
|
|
17
|
+
|
|
18
|
+
from .client import DosboxClient
|
|
19
|
+
from .config import (
|
|
20
|
+
Config,
|
|
21
|
+
default_config_path,
|
|
22
|
+
update_config_file,
|
|
23
|
+
write_config_template,
|
|
24
|
+
)
|
|
25
|
+
from .connection import Connection, NotConnected
|
|
26
|
+
from .lifecycle import InstanceManager, LifecycleError
|
|
27
|
+
from .protocol import BRIDGE_PROTOCOL
|
|
28
|
+
|
|
29
|
+
|
|
30
|
+
def _serve() -> int:
|
|
31
|
+
# Local import: the MCP server pulls in asyncio machinery the other
|
|
32
|
+
# subcommands never need.
|
|
33
|
+
from .server import main as serve_main
|
|
34
|
+
serve_main()
|
|
35
|
+
return 0
|
|
36
|
+
|
|
37
|
+
|
|
38
|
+
def _connection_factory(config: Config) -> Connection:
|
|
39
|
+
return Connection(config)
|
|
40
|
+
|
|
41
|
+
|
|
42
|
+
def _cmd_setup(args) -> int:
|
|
43
|
+
path = default_config_path()
|
|
44
|
+
if args.init:
|
|
45
|
+
try:
|
|
46
|
+
write_config_template(path)
|
|
47
|
+
except FileExistsError as e:
|
|
48
|
+
print(str(e), file=sys.stderr)
|
|
49
|
+
return 2
|
|
50
|
+
print(f"wrote {path} - edit it to suit; commented lines show defaults")
|
|
51
|
+
return 0
|
|
52
|
+
|
|
53
|
+
changes = {}
|
|
54
|
+
for key in ("binary", "port", "protocol", "mode", "token_file"):
|
|
55
|
+
value = getattr(args, key)
|
|
56
|
+
if value is not None:
|
|
57
|
+
changes[key] = value
|
|
58
|
+
if args.headless is not None:
|
|
59
|
+
changes["headless"] = args.headless
|
|
60
|
+
|
|
61
|
+
if not changes:
|
|
62
|
+
config = Config.load()
|
|
63
|
+
current = {
|
|
64
|
+
"config_file": str(path),
|
|
65
|
+
"binary": str(config.binary) if config.binary else None,
|
|
66
|
+
"port": config.port,
|
|
67
|
+
"headless": config.headless,
|
|
68
|
+
"protocol": config.protocol,
|
|
69
|
+
"mode": config.mode,
|
|
70
|
+
"token_file": str(config.token_file) if config.token_file else None,
|
|
71
|
+
}
|
|
72
|
+
print(json.dumps(current, indent=2))
|
|
73
|
+
return 0
|
|
74
|
+
|
|
75
|
+
try:
|
|
76
|
+
update_config_file(path, changes)
|
|
77
|
+
except ValueError as e:
|
|
78
|
+
print(str(e), file=sys.stderr)
|
|
79
|
+
return 2
|
|
80
|
+
print(f"saved to {path}")
|
|
81
|
+
return 0
|
|
82
|
+
|
|
83
|
+
|
|
84
|
+
def _cmd_probe(args) -> int:
|
|
85
|
+
try:
|
|
86
|
+
config = Config.load()
|
|
87
|
+
except ValueError as e:
|
|
88
|
+
print(str(e), file=sys.stderr)
|
|
89
|
+
return 2
|
|
90
|
+
|
|
91
|
+
print(f"bridge protocol: {BRIDGE_PROTOCOL}")
|
|
92
|
+
print(f"config file: {default_config_path()}")
|
|
93
|
+
print(f"target: {config.base_url} (mode {config.mode})")
|
|
94
|
+
|
|
95
|
+
if config.binary is not None:
|
|
96
|
+
return _probe_binary(config)
|
|
97
|
+
print("no binary configured - trying to attach to a running instance")
|
|
98
|
+
return _probe_attach(config)
|
|
99
|
+
|
|
100
|
+
|
|
101
|
+
def _probe_binary(config: Config) -> int:
|
|
102
|
+
def attach(base_url, token):
|
|
103
|
+
client = DosboxClient(base_url, token)
|
|
104
|
+
return client.get("/api/v1/dosbox/info")
|
|
105
|
+
|
|
106
|
+
manager = InstanceManager(config, attach=attach)
|
|
107
|
+
try:
|
|
108
|
+
info = manager.start()
|
|
109
|
+
except LifecycleError as e:
|
|
110
|
+
print(str(e), file=sys.stderr)
|
|
111
|
+
return 1
|
|
112
|
+
try:
|
|
113
|
+
print(f"binary: {config.binary}")
|
|
114
|
+
print(f"engine version: {info.get('version', '?')}")
|
|
115
|
+
print(f"engine protocol: {info.get('mcp_protocol', 'implicit 1.0')}")
|
|
116
|
+
finally:
|
|
117
|
+
manager.stop()
|
|
118
|
+
return 0
|
|
119
|
+
|
|
120
|
+
|
|
121
|
+
def _probe_attach(config: Config) -> int:
|
|
122
|
+
conn = _connection_factory(config)
|
|
123
|
+
try:
|
|
124
|
+
conn.ensure_connected()
|
|
125
|
+
except NotConnected as e:
|
|
126
|
+
print(f"not connected: {e}")
|
|
127
|
+
return 1
|
|
128
|
+
status = conn.status()
|
|
129
|
+
print(f"engine version: {status['engine_version']}")
|
|
130
|
+
print(f"protocol: {status['protocol']}")
|
|
131
|
+
print(f"features: {json.dumps(status['features'])}")
|
|
132
|
+
return 0
|
|
133
|
+
|
|
134
|
+
|
|
135
|
+
def _build_parser() -> argparse.ArgumentParser:
|
|
136
|
+
parser = argparse.ArgumentParser(
|
|
137
|
+
prog="dosbox-mcp",
|
|
138
|
+
description="MCP bridge for dosbox. Without a subcommand, serves "
|
|
139
|
+
"MCP over stdio.",
|
|
140
|
+
)
|
|
141
|
+
sub = parser.add_subparsers(dest="command")
|
|
142
|
+
|
|
143
|
+
setup = sub.add_parser(
|
|
144
|
+
"setup",
|
|
145
|
+
help="write config values; --init writes a commented template; "
|
|
146
|
+
"no flags prints the current configuration",
|
|
147
|
+
)
|
|
148
|
+
setup.add_argument("--init", action="store_true",
|
|
149
|
+
help="write the commented default config")
|
|
150
|
+
setup.add_argument("--binary", help="dosbox binary that bridge_start spawns")
|
|
151
|
+
setup.add_argument("--port", type=int, help="webserver port on 127.0.0.1")
|
|
152
|
+
setup.add_argument("--headless", action=argparse.BooleanOptionalAction,
|
|
153
|
+
default=None, help="spawn without a window")
|
|
154
|
+
setup.add_argument("--protocol", help='protocol pin, "major.minor"')
|
|
155
|
+
setup.add_argument("--mode", help="capability mode: observe/interact/full")
|
|
156
|
+
setup.add_argument("--token-file", dest="token_file",
|
|
157
|
+
help="token file of an already-running instance")
|
|
158
|
+
|
|
159
|
+
sub.add_parser(
|
|
160
|
+
"probe",
|
|
161
|
+
help="validate the config and probe the binary (or a running "
|
|
162
|
+
"instance) for version and protocol",
|
|
163
|
+
)
|
|
164
|
+
return parser
|
|
165
|
+
|
|
166
|
+
|
|
167
|
+
def main(argv=None) -> int:
|
|
168
|
+
args = _build_parser().parse_args(argv)
|
|
169
|
+
if args.command == "setup":
|
|
170
|
+
return _cmd_setup(args)
|
|
171
|
+
if args.command == "probe":
|
|
172
|
+
return _cmd_probe(args)
|
|
173
|
+
return _serve()
|
|
174
|
+
|
|
175
|
+
|
|
176
|
+
if __name__ == "__main__":
|
|
177
|
+
sys.exit(main())
|
dosbox_mcp/client.py
ADDED
|
@@ -0,0 +1,65 @@
|
|
|
1
|
+
# This file is part of the dosbox-mcp Project.
|
|
2
|
+
# License: GPL-2.0-or-later. Contact: dosbox-mcp@trinity2k.net
|
|
3
|
+
#
|
|
4
|
+
|
|
5
|
+
import httpx
|
|
6
|
+
|
|
7
|
+
|
|
8
|
+
class DosboxClient:
|
|
9
|
+
"""Thin authenticated HTTP wrapper. Every request carries the bearer
|
|
10
|
+
token and the X-Client: mcp header that drives the OSD activity signal."""
|
|
11
|
+
|
|
12
|
+
def __init__(self, base_url, token, transport=None):
|
|
13
|
+
self._base = base_url.rstrip("/")
|
|
14
|
+
self._client = httpx.Client(
|
|
15
|
+
headers={
|
|
16
|
+
"Authorization": f"Bearer {token}",
|
|
17
|
+
"X-Client": "mcp",
|
|
18
|
+
},
|
|
19
|
+
transport=transport,
|
|
20
|
+
timeout=30.0,
|
|
21
|
+
)
|
|
22
|
+
|
|
23
|
+
def _handle(self, resp):
|
|
24
|
+
if resp.status_code >= 400:
|
|
25
|
+
try:
|
|
26
|
+
msg = resp.json().get("error", resp.text)
|
|
27
|
+
except Exception:
|
|
28
|
+
msg = resp.text
|
|
29
|
+
raise RuntimeError(f"{resp.status_code}: {msg}")
|
|
30
|
+
ctype = resp.headers.get("content-type", "")
|
|
31
|
+
if ctype.startswith("application/json"):
|
|
32
|
+
return resp.json()
|
|
33
|
+
return resp.content
|
|
34
|
+
|
|
35
|
+
def get(self, path, params=None, headers=None):
|
|
36
|
+
return self._handle(
|
|
37
|
+
self._client.get(self._base + path, params=params, headers=headers)
|
|
38
|
+
)
|
|
39
|
+
|
|
40
|
+
def post(self, path, json=None):
|
|
41
|
+
return self._handle(
|
|
42
|
+
self._client.post(self._base + path, json=json)
|
|
43
|
+
)
|
|
44
|
+
|
|
45
|
+
def post_text(self, path, text, content_type="text/plain", params=None):
|
|
46
|
+
# Some endpoints (script/load) take a raw body, not JSON. httpx
|
|
47
|
+
# sets Content-Type from the content= kwarg's type, so pin it.
|
|
48
|
+
return self._handle(
|
|
49
|
+
self._client.post(
|
|
50
|
+
self._base + path,
|
|
51
|
+
content=text.encode("utf-8"),
|
|
52
|
+
headers={"Content-Type": content_type},
|
|
53
|
+
params=params,
|
|
54
|
+
)
|
|
55
|
+
)
|
|
56
|
+
|
|
57
|
+
def put(self, path, json=None):
|
|
58
|
+
return self._handle(
|
|
59
|
+
self._client.put(self._base + path, json=json)
|
|
60
|
+
)
|
|
61
|
+
|
|
62
|
+
def delete(self, path, json=None):
|
|
63
|
+
return self._handle(
|
|
64
|
+
self._client.request("DELETE", self._base + path, json=json)
|
|
65
|
+
)
|
dosbox_mcp/config.py
ADDED
|
@@ -0,0 +1,265 @@
|
|
|
1
|
+
# This file is part of the dosbox-mcp Project.
|
|
2
|
+
# License: GPL-2.0-or-later. Contact: dosbox-mcp@trinity2k.net
|
|
3
|
+
#
|
|
4
|
+
|
|
5
|
+
import ipaddress
|
|
6
|
+
import os
|
|
7
|
+
import re
|
|
8
|
+
import tempfile
|
|
9
|
+
import tomllib
|
|
10
|
+
from dataclasses import dataclass
|
|
11
|
+
from pathlib import Path
|
|
12
|
+
from urllib.parse import urlparse
|
|
13
|
+
|
|
14
|
+
import tomlkit
|
|
15
|
+
from platformdirs import user_config_dir
|
|
16
|
+
|
|
17
|
+
_LOOPBACK_NAMES = {"localhost"}
|
|
18
|
+
|
|
19
|
+
MODES = ("observe", "interact", "full")
|
|
20
|
+
|
|
21
|
+
# Protocol pins are "major.minor"; the patch grade is spec-document-only
|
|
22
|
+
# and never appears on the wire (design doc, protocol levels).
|
|
23
|
+
_PROTOCOL_RE = re.compile(r"^\d+\.\d+$")
|
|
24
|
+
|
|
25
|
+
DEFAULT_PORT = 8386
|
|
26
|
+
|
|
27
|
+
|
|
28
|
+
def validate_base_url(url: str) -> str:
|
|
29
|
+
"""Accept only http(s) URLs pointing at a loopback address."""
|
|
30
|
+
parsed = urlparse(url)
|
|
31
|
+
if parsed.scheme not in ("http", "https"):
|
|
32
|
+
raise ValueError(f"scheme must be http or https, got {parsed.scheme!r}")
|
|
33
|
+
host = parsed.hostname
|
|
34
|
+
if host is None:
|
|
35
|
+
raise ValueError(f"no host in URL {url!r}")
|
|
36
|
+
if host in _LOOPBACK_NAMES:
|
|
37
|
+
return url
|
|
38
|
+
try:
|
|
39
|
+
if ipaddress.ip_address(host).is_loopback:
|
|
40
|
+
return url
|
|
41
|
+
except ValueError:
|
|
42
|
+
pass
|
|
43
|
+
raise ValueError(f"host {host!r} is not a loopback address")
|
|
44
|
+
|
|
45
|
+
|
|
46
|
+
def default_config_path() -> Path:
|
|
47
|
+
"""The bridge's own config file. DOSBOX_MCP_CONFIG overrides for
|
|
48
|
+
tests and unusual setups."""
|
|
49
|
+
env = os.environ.get("DOSBOX_MCP_CONFIG")
|
|
50
|
+
if env:
|
|
51
|
+
return Path(env)
|
|
52
|
+
return Path(user_config_dir("dosbox-mcp")) / "config.toml"
|
|
53
|
+
|
|
54
|
+
|
|
55
|
+
def default_token_path() -> Path:
|
|
56
|
+
"""Where the engine's launcher writes the API token by default."""
|
|
57
|
+
return Path.home() / ".config" / "dosbox-automation" / "webserver" / "api_token"
|
|
58
|
+
|
|
59
|
+
|
|
60
|
+
def read_token(token_file: Path | None = None) -> str | None:
|
|
61
|
+
"""Token from DOSBOX_API_TOKEN, else the given file, else the default
|
|
62
|
+
token file. Returns None if no token is available (dosbox not
|
|
63
|
+
running yet)."""
|
|
64
|
+
env = os.environ.get("DOSBOX_API_TOKEN")
|
|
65
|
+
if env:
|
|
66
|
+
return env
|
|
67
|
+
path = token_file if token_file is not None else default_token_path()
|
|
68
|
+
if path.is_file():
|
|
69
|
+
return path.read_text(encoding="utf-8").strip()
|
|
70
|
+
return None
|
|
71
|
+
|
|
72
|
+
|
|
73
|
+
def _require(condition: bool, message: str) -> None:
|
|
74
|
+
if not condition:
|
|
75
|
+
raise ValueError(message)
|
|
76
|
+
|
|
77
|
+
|
|
78
|
+
def _validate_port(value: object) -> int:
|
|
79
|
+
_require(isinstance(value, int) and not isinstance(value, bool),
|
|
80
|
+
f"port must be an integer, got {value!r}")
|
|
81
|
+
_require(1 <= value <= 65535, f"port out of range: {value}")
|
|
82
|
+
return value
|
|
83
|
+
|
|
84
|
+
|
|
85
|
+
def _validate_mode(value: object) -> str:
|
|
86
|
+
_require(isinstance(value, str) and value in MODES,
|
|
87
|
+
f"mode must be one of {MODES}, got {value!r}")
|
|
88
|
+
return value
|
|
89
|
+
|
|
90
|
+
|
|
91
|
+
def _validate_protocol(value: object) -> str:
|
|
92
|
+
_require(isinstance(value, str) and bool(_PROTOCOL_RE.match(value)),
|
|
93
|
+
f'protocol pin must be "major.minor" (e.g. "1.0"), got {value!r}')
|
|
94
|
+
return value
|
|
95
|
+
|
|
96
|
+
|
|
97
|
+
def _validate_bool(key: str):
|
|
98
|
+
def check(value: object) -> bool:
|
|
99
|
+
_require(isinstance(value, bool), f"{key} must be true or false, got {value!r}")
|
|
100
|
+
return value
|
|
101
|
+
return check
|
|
102
|
+
|
|
103
|
+
|
|
104
|
+
def _validate_path(key: str):
|
|
105
|
+
def check(value: object) -> Path:
|
|
106
|
+
_require(isinstance(value, str) and value != "",
|
|
107
|
+
f"{key} must be a non-empty string path, got {value!r}")
|
|
108
|
+
return Path(value)
|
|
109
|
+
return check
|
|
110
|
+
|
|
111
|
+
|
|
112
|
+
_TOML_KEYS = {
|
|
113
|
+
"binary": _validate_path("binary"),
|
|
114
|
+
"port": _validate_port,
|
|
115
|
+
"headless": _validate_bool("headless"),
|
|
116
|
+
"protocol": _validate_protocol,
|
|
117
|
+
"mode": _validate_mode,
|
|
118
|
+
"token_file": _validate_path("token_file"),
|
|
119
|
+
}
|
|
120
|
+
|
|
121
|
+
|
|
122
|
+
def _read_toml(path: Path) -> dict:
|
|
123
|
+
if not path.is_file():
|
|
124
|
+
return {}
|
|
125
|
+
try:
|
|
126
|
+
raw = tomllib.loads(path.read_text(encoding="utf-8"))
|
|
127
|
+
except tomllib.TOMLDecodeError as e:
|
|
128
|
+
raise ValueError(f"malformed config {path}: {e}") from e
|
|
129
|
+
unknown = sorted(set(raw) - set(_TOML_KEYS))
|
|
130
|
+
if unknown:
|
|
131
|
+
raise ValueError(
|
|
132
|
+
f"unknown key(s) in {path}: {', '.join(unknown)} "
|
|
133
|
+
f"(known: {', '.join(sorted(_TOML_KEYS))})"
|
|
134
|
+
)
|
|
135
|
+
return {key: _TOML_KEYS[key](value) for key, value in raw.items()}
|
|
136
|
+
|
|
137
|
+
|
|
138
|
+
@dataclass
|
|
139
|
+
class Config:
|
|
140
|
+
base_url: str
|
|
141
|
+
token: str | None = None
|
|
142
|
+
binary: Path | None = None
|
|
143
|
+
port: int = DEFAULT_PORT
|
|
144
|
+
headless: bool = False
|
|
145
|
+
protocol: str | None = None
|
|
146
|
+
mode: str = "full"
|
|
147
|
+
token_file: Path | None = None
|
|
148
|
+
|
|
149
|
+
@classmethod
|
|
150
|
+
def load(cls, path: Path | None = None) -> "Config":
|
|
151
|
+
"""Resolve configuration with precedence env > toml > defaults."""
|
|
152
|
+
data = _read_toml(path if path is not None else default_config_path())
|
|
153
|
+
|
|
154
|
+
port = data.get("port", DEFAULT_PORT)
|
|
155
|
+
base = os.environ.get("DOSBOX_API_URL") or f"http://127.0.0.1:{port}"
|
|
156
|
+
|
|
157
|
+
env_token_file = os.environ.get("DOSBOX_TOKEN_FILE")
|
|
158
|
+
token_file = Path(env_token_file) if env_token_file else data.get("token_file")
|
|
159
|
+
|
|
160
|
+
cfg = cls(
|
|
161
|
+
base_url=validate_base_url(base),
|
|
162
|
+
binary=data.get("binary"),
|
|
163
|
+
port=port,
|
|
164
|
+
headless=data.get("headless", False),
|
|
165
|
+
protocol=data.get("protocol"),
|
|
166
|
+
mode=data.get("mode", "full"),
|
|
167
|
+
token_file=token_file,
|
|
168
|
+
)
|
|
169
|
+
cfg.token = read_token(cfg.token_file)
|
|
170
|
+
return cfg
|
|
171
|
+
|
|
172
|
+
|
|
173
|
+
class ToolProtectedKey(ValueError):
|
|
174
|
+
"""Raised when a model-facing caller tries to write a key reserved
|
|
175
|
+
for the human-edited config."""
|
|
176
|
+
|
|
177
|
+
|
|
178
|
+
# binary: whoever sets it decides what code the bridge executes.
|
|
179
|
+
# mode: the operator's constraint on the agent - an agent that can raise
|
|
180
|
+
# it escalates its own privileges. Both are human-only (self-audit
|
|
181
|
+
# 2026-07-17).
|
|
182
|
+
_TOOL_PROTECTED_KEYS = frozenset({"binary", "mode"})
|
|
183
|
+
|
|
184
|
+
_CONFIG_TEMPLATE = """\
|
|
185
|
+
# dosbox-mcp configuration
|
|
186
|
+
# Read at bridge startup. Precedence: environment > this file > defaults.
|
|
187
|
+
# Uncomment a line to set it; commented lines show the defaults.
|
|
188
|
+
|
|
189
|
+
# Path to the dosbox binary that bridge_start spawns.
|
|
190
|
+
# Deliberately not settable through any MCP tool.
|
|
191
|
+
#binary = "/usr/local/bin/dosbox"
|
|
192
|
+
|
|
193
|
+
# Port of the instance's webserver on 127.0.0.1 (used to connect, and
|
|
194
|
+
# passed to a spawned instance).
|
|
195
|
+
#port = 8386
|
|
196
|
+
|
|
197
|
+
# Spawn without a window (SDL dummy video driver).
|
|
198
|
+
#headless = false
|
|
199
|
+
|
|
200
|
+
# Pin the bridge to a lower protocol version, "major.minor" form.
|
|
201
|
+
#protocol = "1.0"
|
|
202
|
+
|
|
203
|
+
# Capability mode: what a connected agent may do.
|
|
204
|
+
# observe - read-only tools only
|
|
205
|
+
# interact - adds input, video capture, script, instance lifecycle
|
|
206
|
+
# full - everything (memory writes, port IO, cpu control, debugger)
|
|
207
|
+
# Human-edited only: no tool can change this.
|
|
208
|
+
#mode = "full"
|
|
209
|
+
|
|
210
|
+
# Token file of an already-running instance to attach to. Leave unset
|
|
211
|
+
# to use the engine's default location.
|
|
212
|
+
#token_file = "~/.config/dosbox-automation/webserver/api_token"
|
|
213
|
+
"""
|
|
214
|
+
|
|
215
|
+
|
|
216
|
+
def _atomic_write(path: Path, text: str) -> None:
|
|
217
|
+
path.parent.mkdir(parents=True, exist_ok=True)
|
|
218
|
+
with tempfile.NamedTemporaryFile("w", encoding="utf-8", dir=path.parent,
|
|
219
|
+
delete=False) as tmp:
|
|
220
|
+
tmp.write(text)
|
|
221
|
+
tmp.flush()
|
|
222
|
+
os.fsync(tmp.fileno())
|
|
223
|
+
if path.exists():
|
|
224
|
+
os.chmod(tmp.name, path.stat().st_mode)
|
|
225
|
+
os.replace(tmp.name, path)
|
|
226
|
+
|
|
227
|
+
|
|
228
|
+
def update_config_file(path: Path, changes: dict,
|
|
229
|
+
tool_facing: bool = False) -> None:
|
|
230
|
+
"""Apply validated changes to the config file, preserving the
|
|
231
|
+
human's comments and layout (tomlkit round-trip, atomic replace).
|
|
232
|
+
|
|
233
|
+
tool_facing=True enforces the model-side boundary: protected keys
|
|
234
|
+
are rejected loudly instead of written.
|
|
235
|
+
"""
|
|
236
|
+
if not changes:
|
|
237
|
+
raise ValueError("no changes given")
|
|
238
|
+
unknown = sorted(set(changes) - set(_TOML_KEYS))
|
|
239
|
+
if unknown:
|
|
240
|
+
raise ValueError(f"unknown key(s): {', '.join(unknown)}")
|
|
241
|
+
if tool_facing:
|
|
242
|
+
protected = sorted(set(changes) & _TOOL_PROTECTED_KEYS)
|
|
243
|
+
if protected:
|
|
244
|
+
raise ToolProtectedKey(
|
|
245
|
+
f"key(s) {', '.join(protected)} are set in the human-edited "
|
|
246
|
+
"config file only - not writable through a tool"
|
|
247
|
+
)
|
|
248
|
+
for key, value in changes.items():
|
|
249
|
+
_TOML_KEYS[key](value)
|
|
250
|
+
|
|
251
|
+
if path.is_file():
|
|
252
|
+
doc = tomlkit.parse(path.read_text(encoding="utf-8"))
|
|
253
|
+
else:
|
|
254
|
+
doc = tomlkit.document()
|
|
255
|
+
for key, value in changes.items():
|
|
256
|
+
doc[key] = value
|
|
257
|
+
_atomic_write(path, tomlkit.dumps(doc))
|
|
258
|
+
|
|
259
|
+
|
|
260
|
+
def write_config_template(path: Path) -> None:
|
|
261
|
+
"""Write the commented default config (`dosbox-mcp setup --init`).
|
|
262
|
+
Refuses to clobber an existing file."""
|
|
263
|
+
if path.exists():
|
|
264
|
+
raise FileExistsError(f"{path} already exists - edit it instead")
|
|
265
|
+
_atomic_write(path, _CONFIG_TEMPLATE)
|