tokensafe 4.12.2 → 4.12.3
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.
- package/.codex-plugin/plugin.json +1 -1
- package/kimi.plugin.json +1 -1
- package/package.json +1 -1
- package/plugin.json +1 -1
- package/server.json +3 -3
- package/src/mcp_config_manager.py +64 -18
- package/src/mcp_server.py +1 -1
- package/src/telemetry_sync.py +1 -1
- package/src/toml_mcp_config.py +347 -0
- package/src/version_checker.py +1 -1
package/kimi.plugin.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "tokensafe",
|
|
3
|
-
"version": "4.12.
|
|
3
|
+
"version": "4.12.3",
|
|
4
4
|
"description": "Your AI agent is smart enough to code all day. Now it actually can. Local runtime firewall & zero-loss context optimizer for AI coding agents.",
|
|
5
5
|
"homepage": "https://tokensafe.dev",
|
|
6
6
|
"license": "Apache-2.0",
|
package/package.json
CHANGED
|
@@ -1,7 +1,7 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "tokensafe",
|
|
3
3
|
"mcpName": "dev.tokensafe/tokensafe",
|
|
4
|
-
"version": "4.12.
|
|
4
|
+
"version": "4.12.3",
|
|
5
5
|
"description": "Your AI agent is smart enough to code all day. Now it actually can. Local runtime firewall & zero-loss context optimizer for AI coding agents.",
|
|
6
6
|
"main": "bin/tokensafe.js",
|
|
7
7
|
"bin": {
|
package/plugin.json
CHANGED
|
@@ -1,7 +1,7 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "tokensafe",
|
|
3
3
|
"displayName": "TokenSafe",
|
|
4
|
-
"version": "4.12.
|
|
4
|
+
"version": "4.12.3",
|
|
5
5
|
"license": "Apache-2.0",
|
|
6
6
|
"description": "Your AI agent is smart enough to code all day. Now it actually can. Local runtime firewall & zero-loss context optimizer for AI coding agents.",
|
|
7
7
|
"logo": "assets/logo.png",
|
package/server.json
CHANGED
|
@@ -3,7 +3,7 @@
|
|
|
3
3
|
"name": "dev.tokensafe/tokensafe",
|
|
4
4
|
"title": "TokenSafe",
|
|
5
5
|
"description": "Your AI agent is smart enough to code all day. Local firewall & zero-loss runtime.",
|
|
6
|
-
"version": "4.12.
|
|
6
|
+
"version": "4.12.3",
|
|
7
7
|
"websiteUrl": "https://tokensafe.dev",
|
|
8
8
|
"repository": {
|
|
9
9
|
"url": "https://github.com/tokensafe-dev/tokensafe",
|
|
@@ -23,7 +23,7 @@
|
|
|
23
23
|
"registryType": "npm",
|
|
24
24
|
"registryBaseUrl": "https://registry.npmjs.org",
|
|
25
25
|
"identifier": "tokensafe",
|
|
26
|
-
"version": "4.12.
|
|
26
|
+
"version": "4.12.3",
|
|
27
27
|
"runtimeHint": "npx",
|
|
28
28
|
"transport": {
|
|
29
29
|
"type": "stdio"
|
|
@@ -39,7 +39,7 @@
|
|
|
39
39
|
"registryType": "pypi",
|
|
40
40
|
"registryBaseUrl": "https://pypi.org",
|
|
41
41
|
"identifier": "tokensafe",
|
|
42
|
-
"version": "4.12.
|
|
42
|
+
"version": "4.12.3",
|
|
43
43
|
"runtimeHint": "uvx",
|
|
44
44
|
"transport": {
|
|
45
45
|
"type": "stdio"
|
|
@@ -2,21 +2,23 @@
|
|
|
2
2
|
TokenSafe MCP Config Manager (v3.3.0).
|
|
3
3
|
|
|
4
4
|
Inspects, wraps, and unwraps third-party MCP servers across AI coding agent configs
|
|
5
|
-
(Claude Code/Desktop, Cursor,
|
|
5
|
+
(Claude Code/Desktop, Cursor, Windsurf, Codex, Antigravity, ZCode, Copilot, Kimi,
|
|
6
6
|
Cline/Roo) to route them through `tokensafe mcp-proxy`. Preserves original command
|
|
7
7
|
& arguments under `_tokensafe_orig` for 100% reversible unwrapping.
|
|
8
8
|
|
|
9
|
-
Codex CLI
|
|
10
|
-
|
|
11
|
-
|
|
12
|
-
|
|
9
|
+
Codex CLI stores its servers in `~/.codex/config.toml`, so it goes through
|
|
10
|
+
`src/toml_mcp_config.py`: a splice editor that touches only the two keys it must
|
|
11
|
+
and keeps the original definition in a `# tokensafe:orig {json}` comment inside
|
|
12
|
+
the table. Hand-written comments, ordering and other tables stay byte-identical.
|
|
13
13
|
"""
|
|
14
14
|
|
|
15
15
|
import os
|
|
16
16
|
import sys
|
|
17
17
|
import json
|
|
18
18
|
import shutil
|
|
19
|
-
from typing import Dict, Any, List, Optional, Tuple
|
|
19
|
+
from typing import Dict, Any, List, Optional, Sequence, Tuple
|
|
20
|
+
|
|
21
|
+
from src import toml_mcp_config as toml_mcp
|
|
20
22
|
|
|
21
23
|
HOME = os.path.expanduser("~")
|
|
22
24
|
|
|
@@ -36,6 +38,7 @@ CONFIG_CANDIDATES = [
|
|
|
36
38
|
("Claude Settings", os.path.join(HOME, ".claude", "settings.json")),
|
|
37
39
|
("Cursor Global", os.path.join(HOME, ".cursor", "mcp.json")),
|
|
38
40
|
("Codex Global", os.path.join(HOME, ".codex", "config.json")),
|
|
41
|
+
("Codex CLI (TOML)", os.path.join(HOME, ".codex", "config.toml")),
|
|
39
42
|
("Windsurf Global", os.path.join(HOME, ".codeium", "windsurf", "mcp_config.json")),
|
|
40
43
|
("Antigravity", os.path.join(HOME, ".gemini", "config", "mcp_config.json")),
|
|
41
44
|
("ZCode", os.path.join(HOME, ".zcode", "cli", "config.json")),
|
|
@@ -92,6 +95,17 @@ class MCPConfigManager:
|
|
|
92
95
|
"""Lists all registered MCP servers and their wrapping status."""
|
|
93
96
|
results = []
|
|
94
97
|
for agent_name, path in cls.get_existing_configs():
|
|
98
|
+
if toml_mcp.is_toml_path(path):
|
|
99
|
+
try:
|
|
100
|
+
for entry in toml_mcp.list_servers(toml_mcp.read_text(path)):
|
|
101
|
+
if entry["server_name"] in ("tokensafe", "tokensafe-mcp", "tokensafe-cloud"):
|
|
102
|
+
continue
|
|
103
|
+
entry["config_path"] = path
|
|
104
|
+
results.append(entry)
|
|
105
|
+
except Exception:
|
|
106
|
+
continue
|
|
107
|
+
continue
|
|
108
|
+
|
|
95
109
|
data = cls._read_config(path)
|
|
96
110
|
if not data:
|
|
97
111
|
continue
|
|
@@ -126,9 +140,49 @@ class MCPConfigManager:
|
|
|
126
140
|
})
|
|
127
141
|
return results
|
|
128
142
|
|
|
143
|
+
@classmethod
|
|
144
|
+
def _proxy_command(cls, orig_cmd: str, orig_args: Sequence[str]) -> Tuple[str, List[str]]:
|
|
145
|
+
"""The `tokensafe mcp-proxy -- <cmd>` invocation for this machine."""
|
|
146
|
+
tokensafe_bin = shutil.which("tokensafe")
|
|
147
|
+
if tokensafe_bin:
|
|
148
|
+
return tokensafe_bin, ["mcp-proxy", "--", orig_cmd] + list(orig_args)
|
|
149
|
+
script_dir = os.path.dirname(os.path.realpath(__file__))
|
|
150
|
+
cli_path = os.path.join(script_dir, "cli.py")
|
|
151
|
+
return sys.executable, [cli_path, "mcp-proxy", "--", orig_cmd] + list(orig_args)
|
|
152
|
+
|
|
153
|
+
@classmethod
|
|
154
|
+
def _wrap_toml_server(cls, config_path: str, server_name: str) -> bool:
|
|
155
|
+
try:
|
|
156
|
+
text = toml_mcp.read_text(config_path)
|
|
157
|
+
entry = next(
|
|
158
|
+
(s for s in toml_mcp.list_servers(text) if s["server_name"] == server_name),
|
|
159
|
+
None,
|
|
160
|
+
)
|
|
161
|
+
if not entry or not entry["command"]:
|
|
162
|
+
return False
|
|
163
|
+
proxy_cmd, proxy_args = cls._proxy_command(entry["command"], entry["args"])
|
|
164
|
+
new_text = toml_mcp.wrap_server_text(text, server_name, proxy_cmd, proxy_args)
|
|
165
|
+
toml_mcp.write_text(config_path, new_text)
|
|
166
|
+
return True
|
|
167
|
+
except Exception:
|
|
168
|
+
return False
|
|
169
|
+
|
|
170
|
+
@classmethod
|
|
171
|
+
def _unwrap_toml_server(cls, config_path: str, server_name: str) -> bool:
|
|
172
|
+
try:
|
|
173
|
+
text = toml_mcp.read_text(config_path)
|
|
174
|
+
new_text = toml_mcp.unwrap_server_text(text, server_name)
|
|
175
|
+
toml_mcp.write_text(config_path, new_text)
|
|
176
|
+
return True
|
|
177
|
+
except Exception:
|
|
178
|
+
return False
|
|
179
|
+
|
|
129
180
|
@classmethod
|
|
130
181
|
def wrap_server(cls, config_path: str, server_name: str) -> bool:
|
|
131
182
|
"""Wraps a specific server in config_path to route through tokensafe mcp-proxy."""
|
|
183
|
+
if toml_mcp.is_toml_path(config_path):
|
|
184
|
+
return cls._wrap_toml_server(config_path, server_name)
|
|
185
|
+
|
|
132
186
|
data = cls._read_config(config_path)
|
|
133
187
|
if not data:
|
|
134
188
|
return False
|
|
@@ -156,18 +210,7 @@ class MCPConfigManager:
|
|
|
156
210
|
"args": list(orig_args)
|
|
157
211
|
}
|
|
158
212
|
|
|
159
|
-
|
|
160
|
-
tokensafe_bin = shutil.which("tokensafe")
|
|
161
|
-
if tokensafe_bin:
|
|
162
|
-
proxy_cmd = tokensafe_bin
|
|
163
|
-
proxy_args = ["mcp-proxy", "--", orig_cmd] + list(orig_args)
|
|
164
|
-
else:
|
|
165
|
-
proxy_cmd = sys.executable
|
|
166
|
-
# Find cli.py path
|
|
167
|
-
script_dir = os.path.dirname(os.path.realpath(__file__))
|
|
168
|
-
cli_path = os.path.join(script_dir, "cli.py")
|
|
169
|
-
proxy_args = [cli_path, "mcp-proxy", "--", orig_cmd] + list(orig_args)
|
|
170
|
-
|
|
213
|
+
proxy_cmd, proxy_args = cls._proxy_command(orig_cmd, list(orig_args))
|
|
171
214
|
s_def["command"] = proxy_cmd
|
|
172
215
|
s_def["args"] = proxy_args
|
|
173
216
|
|
|
@@ -176,6 +219,9 @@ class MCPConfigManager:
|
|
|
176
219
|
@classmethod
|
|
177
220
|
def unwrap_server(cls, config_path: str, server_name: str) -> bool:
|
|
178
221
|
"""Restores original command and args for a wrapped server."""
|
|
222
|
+
if toml_mcp.is_toml_path(config_path):
|
|
223
|
+
return cls._unwrap_toml_server(config_path, server_name)
|
|
224
|
+
|
|
179
225
|
data = cls._read_config(config_path)
|
|
180
226
|
if not data:
|
|
181
227
|
return False
|
package/src/mcp_server.py
CHANGED
package/src/telemetry_sync.py
CHANGED
|
@@ -311,7 +311,7 @@ class TelemetrySync:
|
|
|
311
311
|
current_last_id = last_id
|
|
312
312
|
headers = {
|
|
313
313
|
"Content-Type": "application/json",
|
|
314
|
-
"User-Agent": "TokenSafe-Sync/4.12.
|
|
314
|
+
"User-Agent": "TokenSafe-Sync/4.12.3"
|
|
315
315
|
}
|
|
316
316
|
if active_key:
|
|
317
317
|
headers["Authorization"] = f"Bearer {active_key}"
|
|
@@ -0,0 +1,347 @@
|
|
|
1
|
+
"""
|
|
2
|
+
Codex CLI MCP config editor (TOML).
|
|
3
|
+
|
|
4
|
+
Codex keeps its MCP servers in `~/.codex/config.toml`, so the JSON manager
|
|
5
|
+
cannot wrap them. A general TOML serializer is the wrong tool here: it would
|
|
6
|
+
reformat a hand-edited file (comments, ordering, inline tables) and turn a
|
|
7
|
+
one-line change into an unreviewable diff.
|
|
8
|
+
|
|
9
|
+
This module edits by splice instead. It locates `[mcp_servers.<name>]`, parses
|
|
10
|
+
just the `command`/`args` values it needs, and rewrites those lines only. The
|
|
11
|
+
original definition is preserved in a `# tokensafe:orig {json}` comment inside
|
|
12
|
+
the table, so `unwrap` restores byte-identical content while remaining readable
|
|
13
|
+
to a human (and ignored by Codex's parser).
|
|
14
|
+
|
|
15
|
+
One documented limit: an `args` array spread over several lines is collapsed to
|
|
16
|
+
one line when wrapped, and unwrap restores the same values in that single-line
|
|
17
|
+
form — semantically identical, not byte-identical. The usual single-line form,
|
|
18
|
+
which is what Codex's own docs show, round-trips exactly.
|
|
19
|
+
|
|
20
|
+
Python's stdlib has `tomllib` for reading only, and only from 3.11; the project
|
|
21
|
+
supports 3.10, so the small subset parser below is the primary path. Tests
|
|
22
|
+
cross-check it against `tomllib` whenever the interpreter has one.
|
|
23
|
+
"""
|
|
24
|
+
|
|
25
|
+
from __future__ import annotations
|
|
26
|
+
|
|
27
|
+
import json
|
|
28
|
+
import os
|
|
29
|
+
import re
|
|
30
|
+
from dataclasses import dataclass
|
|
31
|
+
from typing import Any, Dict, List, Optional, Sequence, Tuple
|
|
32
|
+
|
|
33
|
+
MARKER_PREFIX = "# tokensafe:orig "
|
|
34
|
+
_TABLE_RE = re.compile(r"^\s*\[(?!\[)(?P<path>.+?)\]\s*(?:#.*)?$")
|
|
35
|
+
_KEY_RE = re.compile(r"^\s*(?P<key>[A-Za-z_][\w-]*)\s*=\s*(?P<value>.*)$")
|
|
36
|
+
_STRING_TOKEN_RE = re.compile(r'"(?:[^"\\]|\\.)*"|\'[^\']*\'')
|
|
37
|
+
|
|
38
|
+
|
|
39
|
+
@dataclass
|
|
40
|
+
class TomlSection:
|
|
41
|
+
path: Tuple[str, ...]
|
|
42
|
+
header_index: int # line index of the `[table]` header
|
|
43
|
+
body_start: int # first line after the header
|
|
44
|
+
body_end: int # exclusive
|
|
45
|
+
|
|
46
|
+
|
|
47
|
+
class TomlServerError(ValueError):
|
|
48
|
+
"""Raised when the file cannot be edited safely."""
|
|
49
|
+
|
|
50
|
+
|
|
51
|
+
# ---------------------------------------------------------------------------
|
|
52
|
+
# Subset parsing
|
|
53
|
+
# ---------------------------------------------------------------------------
|
|
54
|
+
|
|
55
|
+
def _unquote(token: str) -> str:
|
|
56
|
+
token = token.strip()
|
|
57
|
+
if len(token) >= 2 and token[0] == token[-1] and token[0] in ("'", '"'):
|
|
58
|
+
inner = token[1:-1]
|
|
59
|
+
if token[0] == "'":
|
|
60
|
+
return inner
|
|
61
|
+
try:
|
|
62
|
+
return json.loads(f'"{inner}"')
|
|
63
|
+
except Exception:
|
|
64
|
+
return inner
|
|
65
|
+
return token
|
|
66
|
+
|
|
67
|
+
|
|
68
|
+
def _split_table_path(raw: str) -> Tuple[str, ...]:
|
|
69
|
+
"""`mcp_servers."my server"` -> ("mcp_servers", "my server")."""
|
|
70
|
+
parts: List[str] = []
|
|
71
|
+
current: List[str] = []
|
|
72
|
+
quote: Optional[str] = None
|
|
73
|
+
for ch in raw:
|
|
74
|
+
if quote:
|
|
75
|
+
current.append(ch)
|
|
76
|
+
if ch == quote:
|
|
77
|
+
quote = None
|
|
78
|
+
elif ch in ('"', "'"):
|
|
79
|
+
quote = ch
|
|
80
|
+
current.append(ch)
|
|
81
|
+
elif ch == ".":
|
|
82
|
+
parts.append(_unquote("".join(current)))
|
|
83
|
+
current = []
|
|
84
|
+
else:
|
|
85
|
+
current.append(ch)
|
|
86
|
+
tail = _unquote("".join(current))
|
|
87
|
+
if tail:
|
|
88
|
+
parts.append(tail)
|
|
89
|
+
return tuple(parts)
|
|
90
|
+
|
|
91
|
+
|
|
92
|
+
def iter_sections(text: str) -> List[TomlSection]:
|
|
93
|
+
lines = text.splitlines()
|
|
94
|
+
headers: List[Tuple[int, Tuple[str, ...]]] = []
|
|
95
|
+
for idx, line in enumerate(lines):
|
|
96
|
+
match = _TABLE_RE.match(line)
|
|
97
|
+
if match:
|
|
98
|
+
headers.append((idx, _split_table_path(match.group("path"))))
|
|
99
|
+
sections: List[TomlSection] = []
|
|
100
|
+
for pos, (idx, path) in enumerate(headers):
|
|
101
|
+
end = headers[pos + 1][0] if pos + 1 < len(headers) else len(lines)
|
|
102
|
+
sections.append(TomlSection(path=path, header_index=idx, body_start=idx + 1, body_end=end))
|
|
103
|
+
return sections
|
|
104
|
+
|
|
105
|
+
|
|
106
|
+
def find_section(text: str, server_name: str) -> Optional[TomlSection]:
|
|
107
|
+
for section in iter_sections(text):
|
|
108
|
+
if len(section.path) == 2 and section.path[0] == "mcp_servers" and section.path[1] == server_name:
|
|
109
|
+
return section
|
|
110
|
+
return None
|
|
111
|
+
|
|
112
|
+
|
|
113
|
+
def _scan_value(lines: Sequence[str], start: int, end: int) -> Optional[Tuple[str, int]]:
|
|
114
|
+
"""Returns (raw literal text, last line index) for a possibly multi-line value."""
|
|
115
|
+
if start >= end:
|
|
116
|
+
return None
|
|
117
|
+
match = _KEY_RE.match(lines[start])
|
|
118
|
+
if not match:
|
|
119
|
+
return None
|
|
120
|
+
first = match.group("value")
|
|
121
|
+
stripped = first.strip()
|
|
122
|
+
if not stripped:
|
|
123
|
+
return None
|
|
124
|
+
if not stripped.startswith("["):
|
|
125
|
+
return stripped, start
|
|
126
|
+
# Array: accumulate until brackets balance outside strings.
|
|
127
|
+
depth = 0
|
|
128
|
+
quote: Optional[str] = None
|
|
129
|
+
for idx in range(start, end):
|
|
130
|
+
chunk = lines[idx] if idx > start else first
|
|
131
|
+
for ch in chunk:
|
|
132
|
+
if quote:
|
|
133
|
+
if ch == quote:
|
|
134
|
+
quote = None
|
|
135
|
+
elif ch in ('"', "'"):
|
|
136
|
+
quote = ch
|
|
137
|
+
elif ch == "[":
|
|
138
|
+
depth += 1
|
|
139
|
+
elif ch == "]":
|
|
140
|
+
depth -= 1
|
|
141
|
+
if depth <= 0:
|
|
142
|
+
return " ".join(l.strip() for l in lines[start:idx + 1]).split("=", 1)[1].strip(), idx
|
|
143
|
+
return None
|
|
144
|
+
|
|
145
|
+
|
|
146
|
+
def _parse_string_array(raw: str) -> List[str]:
|
|
147
|
+
tokens = _STRING_TOKEN_RE.findall(raw)
|
|
148
|
+
remainder = _STRING_TOKEN_RE.sub("", raw).replace("[", "").replace("]", "").replace(",", "")
|
|
149
|
+
if remainder.strip():
|
|
150
|
+
raise TomlServerError(
|
|
151
|
+
f"args holds non-string elements ({remainder.strip()!r}); wrap this server by hand"
|
|
152
|
+
)
|
|
153
|
+
return [_unquote(token) for token in tokens]
|
|
154
|
+
|
|
155
|
+
|
|
156
|
+
def _parse_string(raw: str) -> str:
|
|
157
|
+
raw = raw.strip()
|
|
158
|
+
if raw[:1] not in ('"', "'"):
|
|
159
|
+
raise TomlServerError(f"expected a quoted string, got {raw[:40]!r}")
|
|
160
|
+
return _unquote(raw)
|
|
161
|
+
|
|
162
|
+
|
|
163
|
+
def _find_key(lines: Sequence[str], section: TomlSection, key: str) -> Optional[Tuple[int, int, str]]:
|
|
164
|
+
"""Returns (first_line, last_line, raw_value) for `key = value` in the section."""
|
|
165
|
+
for idx in range(section.body_start, section.body_end):
|
|
166
|
+
if lines[idx].lstrip().startswith(MARKER_PREFIX):
|
|
167
|
+
continue
|
|
168
|
+
match = _KEY_RE.match(lines[idx])
|
|
169
|
+
if not match or match.group("key") != key:
|
|
170
|
+
continue
|
|
171
|
+
scanned = _scan_value(lines, idx, section.body_end)
|
|
172
|
+
if scanned is None:
|
|
173
|
+
return None
|
|
174
|
+
raw, last = scanned
|
|
175
|
+
return idx, last, raw
|
|
176
|
+
return None
|
|
177
|
+
|
|
178
|
+
|
|
179
|
+
def list_servers(text: str) -> List[Dict[str, Any]]:
|
|
180
|
+
"""Server entries of `[mcp_servers.*]` tables with their wrap state."""
|
|
181
|
+
lines = text.splitlines()
|
|
182
|
+
found: List[Dict[str, Any]] = []
|
|
183
|
+
for section in iter_sections(text):
|
|
184
|
+
if len(section.path) != 2 or section.path[0] != "mcp_servers":
|
|
185
|
+
continue
|
|
186
|
+
name = section.path[1]
|
|
187
|
+
orig: Optional[Dict[str, Any]] = None
|
|
188
|
+
for idx in range(section.body_start, section.body_end):
|
|
189
|
+
line = lines[idx]
|
|
190
|
+
if line.lstrip().startswith(MARKER_PREFIX):
|
|
191
|
+
try:
|
|
192
|
+
orig = json.loads(line.lstrip()[len(MARKER_PREFIX):])
|
|
193
|
+
except Exception:
|
|
194
|
+
orig = None
|
|
195
|
+
break
|
|
196
|
+
command_loc = _find_key(lines, section, "command")
|
|
197
|
+
args_loc = _find_key(lines, section, "args")
|
|
198
|
+
try:
|
|
199
|
+
command = _parse_string(command_loc[2]) if command_loc else ""
|
|
200
|
+
args = _parse_string_array(args_loc[2]) if args_loc else []
|
|
201
|
+
except TomlServerError:
|
|
202
|
+
command, args = "", []
|
|
203
|
+
found.append({
|
|
204
|
+
"agent": "Codex CLI",
|
|
205
|
+
"server_name": name,
|
|
206
|
+
"command": command,
|
|
207
|
+
"args": args,
|
|
208
|
+
"is_wrapped": orig is not None,
|
|
209
|
+
"orig_def": orig,
|
|
210
|
+
})
|
|
211
|
+
return found
|
|
212
|
+
|
|
213
|
+
|
|
214
|
+
# ---------------------------------------------------------------------------
|
|
215
|
+
# Editing
|
|
216
|
+
# ---------------------------------------------------------------------------
|
|
217
|
+
|
|
218
|
+
def _toml_string(value: str) -> str:
|
|
219
|
+
"""A TOML basic string. json.dumps produces an accepted subset."""
|
|
220
|
+
return json.dumps(str(value), ensure_ascii=False)
|
|
221
|
+
|
|
222
|
+
|
|
223
|
+
def _toml_string_array(values: Sequence[str]) -> str:
|
|
224
|
+
return "[" + ", ".join(_toml_string(v) for v in values) + "]"
|
|
225
|
+
|
|
226
|
+
|
|
227
|
+
def _replace_lines(lines: List[str], replacements: List[Tuple[int, int, str]]) -> List[str]:
|
|
228
|
+
"""Applies (first, last_inclusive, new_text) from the bottom up."""
|
|
229
|
+
out = list(lines)
|
|
230
|
+
for first, last, new_text in sorted(replacements, key=lambda r: r[0], reverse=True):
|
|
231
|
+
out[first:last + 1] = new_text.splitlines()
|
|
232
|
+
return out
|
|
233
|
+
|
|
234
|
+
|
|
235
|
+
def wrap_server_text(
|
|
236
|
+
text: str,
|
|
237
|
+
server_name: str,
|
|
238
|
+
proxy_cmd: str,
|
|
239
|
+
proxy_args: Sequence[str],
|
|
240
|
+
) -> str:
|
|
241
|
+
"""Rewrites one server to route through `tokensafe mcp-proxy`."""
|
|
242
|
+
section = find_section(text, server_name)
|
|
243
|
+
if section is None:
|
|
244
|
+
raise TomlServerError(f"no [mcp_servers.{server_name}] table in this file")
|
|
245
|
+
lines = text.splitlines()
|
|
246
|
+
if any(lines[idx].lstrip().startswith(MARKER_PREFIX)
|
|
247
|
+
for idx in range(section.body_start, section.body_end)):
|
|
248
|
+
raise TomlServerError(f"server {server_name!r} is already wrapped")
|
|
249
|
+
|
|
250
|
+
command_loc = _find_key(lines, section, "command")
|
|
251
|
+
if command_loc is None:
|
|
252
|
+
raise TomlServerError(f"server {server_name!r} has no command key")
|
|
253
|
+
args_loc = _find_key(lines, section, "args")
|
|
254
|
+
|
|
255
|
+
original = {
|
|
256
|
+
"command": _parse_string(command_loc[2]),
|
|
257
|
+
"args": _parse_string_array(args_loc[2]) if args_loc else [],
|
|
258
|
+
# Remembered so unwrap restores a server that never had `args`
|
|
259
|
+
# instead of leaving a synthetic `args = []` behind.
|
|
260
|
+
"args_present": args_loc is not None,
|
|
261
|
+
}
|
|
262
|
+
marker = MARKER_PREFIX + json.dumps(original, ensure_ascii=False)
|
|
263
|
+
|
|
264
|
+
new_command = f"command = {_toml_string(proxy_cmd)}"
|
|
265
|
+
new_args = f"args = {_toml_string_array(proxy_args)}"
|
|
266
|
+
if args_loc:
|
|
267
|
+
replacements: List[Tuple[int, int, str]] = [
|
|
268
|
+
(command_loc[0], command_loc[1], new_command),
|
|
269
|
+
(args_loc[0], args_loc[1], new_args),
|
|
270
|
+
]
|
|
271
|
+
else:
|
|
272
|
+
# No args key yet: emit both lines in one replacement so the two edits
|
|
273
|
+
# cannot overwrite each other.
|
|
274
|
+
replacements = [(command_loc[0], command_loc[1], new_command + "\n" + new_args)]
|
|
275
|
+
lines = _replace_lines(lines, replacements)
|
|
276
|
+
lines.insert(section.header_index + 1, marker)
|
|
277
|
+
return "\n".join(lines) + ("\n" if text.endswith("\n") else "")
|
|
278
|
+
|
|
279
|
+
|
|
280
|
+
def unwrap_server_text(text: str, server_name: str) -> str:
|
|
281
|
+
"""Restores `command`/`args` from the marker and drops it."""
|
|
282
|
+
section = find_section(text, server_name)
|
|
283
|
+
if section is None:
|
|
284
|
+
raise TomlServerError(f"no [mcp_servers.{server_name}] table in this file")
|
|
285
|
+
lines = text.splitlines()
|
|
286
|
+
marker_index: Optional[int] = None
|
|
287
|
+
original: Optional[Dict[str, Any]] = None
|
|
288
|
+
for idx in range(section.body_start, section.body_end):
|
|
289
|
+
stripped = lines[idx].lstrip()
|
|
290
|
+
if stripped.startswith(MARKER_PREFIX):
|
|
291
|
+
marker_index = idx
|
|
292
|
+
try:
|
|
293
|
+
original = json.loads(stripped[len(MARKER_PREFIX):])
|
|
294
|
+
except Exception as exc:
|
|
295
|
+
raise TomlServerError(f"unreadable TokenSafe marker on line {idx + 1}: {exc}")
|
|
296
|
+
break
|
|
297
|
+
if marker_index is None or not isinstance(original, dict) or "command" not in original:
|
|
298
|
+
raise TomlServerError(f"server {server_name!r} is not wrapped by TokenSafe")
|
|
299
|
+
|
|
300
|
+
command_loc = _find_key(lines, section, "command")
|
|
301
|
+
args_loc = _find_key(lines, section, "args")
|
|
302
|
+
if command_loc is None:
|
|
303
|
+
raise TomlServerError(f"server {server_name!r} lost its command key while wrapped")
|
|
304
|
+
|
|
305
|
+
new_command = f"command = {_toml_string(original['command'])}"
|
|
306
|
+
new_args = f"args = {_toml_string_array(original.get('args') or [])}"
|
|
307
|
+
if args_loc and not original.get("args_present", True):
|
|
308
|
+
# The server had no args key before wrapping: drop the synthetic line.
|
|
309
|
+
replacements: List[Tuple[int, int, str]] = [
|
|
310
|
+
(command_loc[0], command_loc[1], new_command),
|
|
311
|
+
(args_loc[0], args_loc[1], ""),
|
|
312
|
+
]
|
|
313
|
+
elif args_loc:
|
|
314
|
+
replacements = [
|
|
315
|
+
(command_loc[0], command_loc[1], new_command),
|
|
316
|
+
(args_loc[0], args_loc[1], new_args),
|
|
317
|
+
]
|
|
318
|
+
else:
|
|
319
|
+
replacements = [(command_loc[0], command_loc[1], new_command + "\n" + new_args)]
|
|
320
|
+
lines = _replace_lines(lines, replacements)
|
|
321
|
+
# The marker moved if it sat above the replaced lines.
|
|
322
|
+
for idx in range(len(lines)):
|
|
323
|
+
if lines[idx].lstrip().startswith(MARKER_PREFIX):
|
|
324
|
+
del lines[idx]
|
|
325
|
+
break
|
|
326
|
+
return "\n".join(lines) + ("\n" if text.endswith("\n") else "")
|
|
327
|
+
|
|
328
|
+
|
|
329
|
+
def read_text(path: str) -> str:
|
|
330
|
+
with open(path, "r", encoding="utf-8") as handle:
|
|
331
|
+
return handle.read()
|
|
332
|
+
|
|
333
|
+
|
|
334
|
+
def write_text(path: str, text: str) -> None:
|
|
335
|
+
"""Atomic write with a one-time `.bak.tokensafe` backup."""
|
|
336
|
+
backup = f"{path}.bak.tokensafe"
|
|
337
|
+
if not os.path.exists(backup):
|
|
338
|
+
with open(backup, "w", encoding="utf-8") as handle:
|
|
339
|
+
handle.write(read_text(path))
|
|
340
|
+
tmp = f"{path}.tmp.{os.getpid()}"
|
|
341
|
+
with open(tmp, "w", encoding="utf-8") as handle:
|
|
342
|
+
handle.write(text)
|
|
343
|
+
os.replace(tmp, path)
|
|
344
|
+
|
|
345
|
+
|
|
346
|
+
def is_toml_path(path: str) -> bool:
|
|
347
|
+
return str(path).lower().endswith(".toml")
|
package/src/version_checker.py
CHANGED
|
@@ -17,7 +17,7 @@ import urllib.request
|
|
|
17
17
|
import urllib.error
|
|
18
18
|
from typing import Dict, Any, Optional, Tuple
|
|
19
19
|
|
|
20
|
-
CURRENT_VERSION = "4.12.
|
|
20
|
+
CURRENT_VERSION = "4.12.3"
|
|
21
21
|
CACHE_TTL = 86400 # 24 hours
|
|
22
22
|
# When the cloud is unreachable we must NOT cache the synthesized "up to date"
|
|
23
23
|
# answer for a full day — otherwise an update released right after an outage
|