unstring 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.
- unstring/__init__.py +6 -0
- unstring/__main__.py +5 -0
- unstring/_relay.py +151 -0
- unstring/cli.py +113 -0
- unstring/core.py +373 -0
- unstring/proxy.py +143 -0
- unstring-0.1.0.dist-info/METADATA +166 -0
- unstring-0.1.0.dist-info/RECORD +11 -0
- unstring-0.1.0.dist-info/WHEEL +4 -0
- unstring-0.1.0.dist-info/entry_points.txt +2 -0
- unstring-0.1.0.dist-info/licenses/LICENSE +21 -0
unstring/__init__.py
ADDED
unstring/__main__.py
ADDED
unstring/_relay.py
ADDED
|
@@ -0,0 +1,151 @@
|
|
|
1
|
+
"""A stdio relay between an MCP client and an MCP server, with hooks to rewrite messages.
|
|
2
|
+
|
|
3
|
+
MCP over stdio is one JSON-RPC message (or batch) per line. The relay starts the server,
|
|
4
|
+
copies lines both ways, and gives each parsed message to a hook that may change it, drop it,
|
|
5
|
+
or answer it directly. Lines that are not changed are passed on byte for byte.
|
|
6
|
+
"""
|
|
7
|
+
|
|
8
|
+
from __future__ import annotations
|
|
9
|
+
|
|
10
|
+
import json
|
|
11
|
+
import os
|
|
12
|
+
import shutil
|
|
13
|
+
import signal
|
|
14
|
+
import subprocess
|
|
15
|
+
import sys
|
|
16
|
+
import threading
|
|
17
|
+
from typing import Any, BinaryIO, Callable, Iterator, List, Optional, Tuple
|
|
18
|
+
|
|
19
|
+
# A hook gets one message and returns (message to pass on or None, replies to send back).
|
|
20
|
+
Hook = Callable[[dict], Tuple[Optional[dict], List[dict]]]
|
|
21
|
+
|
|
22
|
+
|
|
23
|
+
def _dump(msg: Any) -> bytes:
|
|
24
|
+
return json.dumps(msg, ensure_ascii=False, separators=(",", ":")).encode("utf-8") + b"\n"
|
|
25
|
+
|
|
26
|
+
|
|
27
|
+
def _lines(stream: BinaryIO) -> Iterator[bytes]:
|
|
28
|
+
"""Lines from ``stream``, read from its file descriptor when it has one.
|
|
29
|
+
|
|
30
|
+
A thread blocked inside a buffered reader holds the reader's lock, and Python aborts at
|
|
31
|
+
exit if a daemon thread still holds it; ``os.read`` takes no lock.
|
|
32
|
+
"""
|
|
33
|
+
try:
|
|
34
|
+
fd = stream.fileno()
|
|
35
|
+
read: Callable[[int], bytes] = lambda n: os.read(fd, n) # noqa: E731
|
|
36
|
+
except (AttributeError, OSError, ValueError):
|
|
37
|
+
read = getattr(stream, "read1", stream.read)
|
|
38
|
+
buf = b""
|
|
39
|
+
while True:
|
|
40
|
+
try:
|
|
41
|
+
chunk = read(65536)
|
|
42
|
+
except (OSError, ValueError):
|
|
43
|
+
break
|
|
44
|
+
if not chunk:
|
|
45
|
+
break
|
|
46
|
+
buf += chunk
|
|
47
|
+
while b"\n" in buf:
|
|
48
|
+
line, buf = buf.split(b"\n", 1)
|
|
49
|
+
yield line + b"\n"
|
|
50
|
+
if buf:
|
|
51
|
+
yield buf
|
|
52
|
+
|
|
53
|
+
|
|
54
|
+
class Relay:
|
|
55
|
+
def __init__(self, command: List[str], *, to_server: Hook, to_client: Hook,
|
|
56
|
+
stdin: Optional[BinaryIO] = None, stdout: Optional[BinaryIO] = None,
|
|
57
|
+
name: str = "proxy") -> None:
|
|
58
|
+
if not command:
|
|
59
|
+
raise ValueError("no server command given")
|
|
60
|
+
exe = shutil.which(command[0]) # finds npx.cmd and friends on Windows
|
|
61
|
+
self.command = [exe or command[0]] + list(command[1:])
|
|
62
|
+
self.name = name
|
|
63
|
+
self.to_server = to_server
|
|
64
|
+
self.to_client = to_client
|
|
65
|
+
self.stdin = stdin or sys.stdin.buffer
|
|
66
|
+
self.stdout = stdout or sys.stdout.buffer
|
|
67
|
+
self._lock = threading.Lock()
|
|
68
|
+
self.proc: Optional[subprocess.Popen] = None
|
|
69
|
+
|
|
70
|
+
def _write(self, stream: BinaryIO, data: bytes) -> None:
|
|
71
|
+
with self._lock:
|
|
72
|
+
try:
|
|
73
|
+
stream.write(data)
|
|
74
|
+
stream.flush()
|
|
75
|
+
except (BrokenPipeError, OSError, ValueError):
|
|
76
|
+
pass
|
|
77
|
+
|
|
78
|
+
def _handle(self, line: bytes, hook: Hook, forward: BinaryIO, back: BinaryIO) -> None:
|
|
79
|
+
line = line if line.endswith(b"\n") else line + b"\n"
|
|
80
|
+
try:
|
|
81
|
+
msg = json.loads(line)
|
|
82
|
+
except ValueError:
|
|
83
|
+
self._write(forward, line)
|
|
84
|
+
return
|
|
85
|
+
batch = isinstance(msg, list)
|
|
86
|
+
out: List[Any] = []
|
|
87
|
+
replies: List[dict] = []
|
|
88
|
+
changed = False
|
|
89
|
+
for item in (msg if batch else [msg]):
|
|
90
|
+
if not isinstance(item, dict):
|
|
91
|
+
out.append(item)
|
|
92
|
+
continue
|
|
93
|
+
try:
|
|
94
|
+
new, extra = hook(item)
|
|
95
|
+
except Exception as exc: # never break the connection over a rewrite
|
|
96
|
+
print(f"{self.name}: {type(exc).__name__}: {exc}", file=sys.stderr)
|
|
97
|
+
new, extra = item, []
|
|
98
|
+
if new is not item:
|
|
99
|
+
changed = True
|
|
100
|
+
if new is not None:
|
|
101
|
+
out.append(new)
|
|
102
|
+
replies += extra
|
|
103
|
+
if out:
|
|
104
|
+
self._write(forward, _dump(out if batch else out[0]) if changed else line)
|
|
105
|
+
for reply in replies:
|
|
106
|
+
self._write(back, _dump(reply))
|
|
107
|
+
|
|
108
|
+
def _pump_server(self) -> None:
|
|
109
|
+
assert self.proc and self.proc.stdout and self.proc.stdin
|
|
110
|
+
for line in _lines(self.proc.stdout):
|
|
111
|
+
if line.strip():
|
|
112
|
+
self._handle(line, self.to_client, self.stdout, self.proc.stdin)
|
|
113
|
+
|
|
114
|
+
def _pump_client(self) -> None:
|
|
115
|
+
assert self.proc and self.proc.stdin
|
|
116
|
+
for line in _lines(self.stdin):
|
|
117
|
+
if line.strip():
|
|
118
|
+
self._handle(line, self.to_server, self.proc.stdin, self.stdout)
|
|
119
|
+
try:
|
|
120
|
+
self.proc.stdin.close()
|
|
121
|
+
except OSError:
|
|
122
|
+
pass
|
|
123
|
+
|
|
124
|
+
def run(self) -> int:
|
|
125
|
+
try:
|
|
126
|
+
self.proc = subprocess.Popen(self.command, stdin=subprocess.PIPE,
|
|
127
|
+
stdout=subprocess.PIPE, bufsize=0)
|
|
128
|
+
except OSError as exc:
|
|
129
|
+
print(f"{self.name}: can't start {self.command[0]}: {exc}", file=sys.stderr)
|
|
130
|
+
return 127
|
|
131
|
+
pump = threading.Thread(target=self._pump_server, daemon=True)
|
|
132
|
+
pump.start()
|
|
133
|
+
threading.Thread(target=self._pump_client, daemon=True).start()
|
|
134
|
+
|
|
135
|
+
previous = None
|
|
136
|
+
if hasattr(signal, "SIGTERM") and threading.current_thread() is threading.main_thread():
|
|
137
|
+
def forward(signum, frame): # pass a shutdown request on to the server
|
|
138
|
+
if self.proc and self.proc.poll() is None:
|
|
139
|
+
self.proc.terminate()
|
|
140
|
+
previous = signal.signal(signal.SIGTERM, forward)
|
|
141
|
+
try:
|
|
142
|
+
try:
|
|
143
|
+
code = self.proc.wait()
|
|
144
|
+
except KeyboardInterrupt:
|
|
145
|
+
self.proc.terminate()
|
|
146
|
+
code = self.proc.wait()
|
|
147
|
+
pump.join(timeout=5)
|
|
148
|
+
finally:
|
|
149
|
+
if previous is not None:
|
|
150
|
+
signal.signal(signal.SIGTERM, previous)
|
|
151
|
+
return 128 - code if code < 0 else code
|
unstring/cli.py
ADDED
|
@@ -0,0 +1,113 @@
|
|
|
1
|
+
"""unstring: repair MCP tool-call arguments that clients send as JSON strings."""
|
|
2
|
+
|
|
3
|
+
from __future__ import annotations
|
|
4
|
+
|
|
5
|
+
import argparse
|
|
6
|
+
import json
|
|
7
|
+
import os
|
|
8
|
+
import sys
|
|
9
|
+
from typing import Any, List, Optional
|
|
10
|
+
|
|
11
|
+
from . import __version__
|
|
12
|
+
from .core import repair
|
|
13
|
+
|
|
14
|
+
|
|
15
|
+
def main(argv: Optional[List[str]] = None) -> int:
|
|
16
|
+
argv = list(sys.argv[1:] if argv is None else argv)
|
|
17
|
+
command: List[str] = []
|
|
18
|
+
if "--" in argv:
|
|
19
|
+
at = argv.index("--")
|
|
20
|
+
argv, command = argv[:at], argv[at + 1:]
|
|
21
|
+
parser = argparse.ArgumentParser(
|
|
22
|
+
prog="unstring",
|
|
23
|
+
description="Repair MCP tool-call arguments that arrive as JSON strings "
|
|
24
|
+
"(\"expected array, received string\") before the server validates them.")
|
|
25
|
+
parser.add_argument("--version", action="version", version=f"unstring {__version__}")
|
|
26
|
+
sub = parser.add_subparsers(dest="command", required=True)
|
|
27
|
+
|
|
28
|
+
p = sub.add_parser(
|
|
29
|
+
"proxy", help="run a stdio MCP server and repair the arguments of every tool call",
|
|
30
|
+
description="Start the MCP server given after -- and sit between it and the client. "
|
|
31
|
+
"Tool-call arguments that are JSON strings where the tool's schema wants "
|
|
32
|
+
"an array, object, number or boolean are decoded before the server sees "
|
|
33
|
+
"them. Example: unstring proxy -- npx -y @acme/server")
|
|
34
|
+
p.add_argument("--wrap", action="store_true",
|
|
35
|
+
help="also wrap a single value in a list where the schema wants an array")
|
|
36
|
+
p.add_argument("--quiet", action="store_true", help="don't report repairs on stderr")
|
|
37
|
+
p.add_argument("--log", metavar="FILE", help="append repair reports to FILE, not stderr")
|
|
38
|
+
|
|
39
|
+
f = sub.add_parser(
|
|
40
|
+
"fix", help="repair one set of arguments against a schema and print the result",
|
|
41
|
+
description="Read tool arguments (JSON) from ARGS or stdin, repair them against the "
|
|
42
|
+
"schema, print the result. Each repair is listed on stderr. Exit code 0 "
|
|
43
|
+
"when nothing needed repair, 2 when something was repaired.")
|
|
44
|
+
f.add_argument("--schema", required=True, metavar="FILE|JSON",
|
|
45
|
+
help="the tool's inputSchema, or a tool object or tools/list result "
|
|
46
|
+
"(then also give --tool)")
|
|
47
|
+
f.add_argument("--tool", metavar="NAME", help="pick this tool from a tool list")
|
|
48
|
+
f.add_argument("--wrap", action="store_true",
|
|
49
|
+
help="also wrap a single value in a list where the schema wants an array")
|
|
50
|
+
f.add_argument("args", nargs="?", metavar="ARGS", help="the arguments as JSON (default: stdin)")
|
|
51
|
+
args = parser.parse_args(argv)
|
|
52
|
+
|
|
53
|
+
if args.command == "fix":
|
|
54
|
+
return _fix(args, parser)
|
|
55
|
+
if not command:
|
|
56
|
+
parser.error("proxy needs the server command after --, e.g. "
|
|
57
|
+
"unstring proxy -- npx -y @acme/server")
|
|
58
|
+
from .proxy import run
|
|
59
|
+
|
|
60
|
+
log = None
|
|
61
|
+
if args.log:
|
|
62
|
+
try:
|
|
63
|
+
log = open(os.path.expanduser(args.log), "a", encoding="utf-8", buffering=1)
|
|
64
|
+
except OSError as exc:
|
|
65
|
+
parser.error(f"can't open {args.log}: {exc.strerror}")
|
|
66
|
+
try:
|
|
67
|
+
return run(command, wrap=args.wrap, quiet=args.quiet, log=log)
|
|
68
|
+
finally:
|
|
69
|
+
if log is not None:
|
|
70
|
+
log.close()
|
|
71
|
+
|
|
72
|
+
|
|
73
|
+
def _load(text: str, what: str, parser: argparse.ArgumentParser) -> Any:
|
|
74
|
+
try:
|
|
75
|
+
return json.loads(text)
|
|
76
|
+
except ValueError as exc:
|
|
77
|
+
parser.error(f"{what} is not JSON: {exc}")
|
|
78
|
+
|
|
79
|
+
|
|
80
|
+
def _fix(args: argparse.Namespace, parser: argparse.ArgumentParser) -> int:
|
|
81
|
+
raw = args.schema
|
|
82
|
+
if not raw.lstrip().startswith(("{", "[")):
|
|
83
|
+
try:
|
|
84
|
+
with open(os.path.expanduser(raw), encoding="utf-8") as fh:
|
|
85
|
+
raw = fh.read()
|
|
86
|
+
except OSError as exc:
|
|
87
|
+
parser.error(f"can't read {args.schema}: {exc.strerror}")
|
|
88
|
+
schema = _pick(_load(raw, "--schema", parser), args.tool, parser)
|
|
89
|
+
text = args.args if args.args is not None else sys.stdin.read()
|
|
90
|
+
arguments = _load(text, "ARGS", parser)
|
|
91
|
+
result = repair(arguments, schema, wrap=args.wrap)
|
|
92
|
+
for fix in result.fixes:
|
|
93
|
+
print(f"repaired {fix}", file=sys.stderr)
|
|
94
|
+
print(json.dumps(result.value, ensure_ascii=False, indent=2))
|
|
95
|
+
return 2 if result.changed else 0
|
|
96
|
+
|
|
97
|
+
|
|
98
|
+
def _pick(doc: Any, tool: Optional[str], parser: argparse.ArgumentParser) -> Any:
|
|
99
|
+
"""Accept an inputSchema, a tool, a list of tools or a tools/list result (or response)."""
|
|
100
|
+
if isinstance(doc, dict) and isinstance(doc.get("result"), dict):
|
|
101
|
+
doc = doc["result"]
|
|
102
|
+
if isinstance(doc, dict) and isinstance(doc.get("tools"), list):
|
|
103
|
+
doc = doc["tools"]
|
|
104
|
+
if isinstance(doc, list):
|
|
105
|
+
names = [t.get("name") for t in doc if isinstance(t, dict)]
|
|
106
|
+
match = [t for t in doc if isinstance(t, dict) and t.get("name") == tool]
|
|
107
|
+
if not match:
|
|
108
|
+
parser.error(f"--tool must name one of: {', '.join(map(str, names))}" if tool is None
|
|
109
|
+
else f"no tool {tool!r} in the list (have: {', '.join(map(str, names))})")
|
|
110
|
+
doc = match[0]
|
|
111
|
+
if isinstance(doc, dict) and "inputSchema" in doc:
|
|
112
|
+
doc = doc["inputSchema"]
|
|
113
|
+
return doc
|
unstring/core.py
ADDED
|
@@ -0,0 +1,373 @@
|
|
|
1
|
+
"""Repair tool-call arguments that arrive as JSON strings, guided by the tool's JSON Schema.
|
|
2
|
+
|
|
3
|
+
Some MCP clients and models send ``"pages": "[{\\"title\\": \\"A\\"}]"`` where the schema says
|
|
4
|
+
``array``, ``"limit": "5"`` where it says ``integer``, or the whole ``arguments`` object as one
|
|
5
|
+
string. The server then rejects the call (``expected array, received string``).
|
|
6
|
+
|
|
7
|
+
:func:`repair` walks the arguments next to the schema and decodes a string only when:
|
|
8
|
+
|
|
9
|
+
* the schema at that spot does not allow a string (so a real string is never touched), and
|
|
10
|
+
* the decoded value has a type the schema does allow.
|
|
11
|
+
|
|
12
|
+
Everything else is returned as it was. The input is never modified; changed parts are copied.
|
|
13
|
+
"""
|
|
14
|
+
|
|
15
|
+
from __future__ import annotations
|
|
16
|
+
|
|
17
|
+
import ast
|
|
18
|
+
import json
|
|
19
|
+
import math
|
|
20
|
+
import re
|
|
21
|
+
from dataclasses import dataclass
|
|
22
|
+
from typing import Any, Dict, List, Optional, Set, Tuple
|
|
23
|
+
|
|
24
|
+
TYPES = ("null", "boolean", "integer", "number", "string", "array", "object")
|
|
25
|
+
MAX_DEPTH = 64
|
|
26
|
+
|
|
27
|
+
|
|
28
|
+
@dataclass(frozen=True)
|
|
29
|
+
class Fix:
|
|
30
|
+
"""One repaired value: where it was, and what type it had before and after."""
|
|
31
|
+
|
|
32
|
+
path: str
|
|
33
|
+
was: str
|
|
34
|
+
now: str
|
|
35
|
+
# "json", "python" (a Python repr such as ['a', 'b']), "index" ({"0": x} -> [x]) or "wrap"
|
|
36
|
+
how: str = "json"
|
|
37
|
+
|
|
38
|
+
def __str__(self) -> str:
|
|
39
|
+
where = self.path or "arguments"
|
|
40
|
+
extra = {"python": " (Python literal)", "wrap": " (wrapped in a list)",
|
|
41
|
+
"index": " (index-keyed object)"}.get(self.how, "")
|
|
42
|
+
return f"{where}: {self.was} -> {self.now}{extra}"
|
|
43
|
+
|
|
44
|
+
|
|
45
|
+
@dataclass
|
|
46
|
+
class Result:
|
|
47
|
+
"""What :func:`repair` returns: the arguments to use, and the fixes it made."""
|
|
48
|
+
|
|
49
|
+
value: Any
|
|
50
|
+
fixes: List[Fix]
|
|
51
|
+
|
|
52
|
+
@property
|
|
53
|
+
def changed(self) -> bool:
|
|
54
|
+
return bool(self.fixes)
|
|
55
|
+
|
|
56
|
+
|
|
57
|
+
def type_of(value: Any) -> str:
|
|
58
|
+
"""The JSON Schema type name of a decoded JSON value."""
|
|
59
|
+
if value is None:
|
|
60
|
+
return "null"
|
|
61
|
+
if isinstance(value, bool):
|
|
62
|
+
return "boolean"
|
|
63
|
+
if isinstance(value, int):
|
|
64
|
+
return "integer"
|
|
65
|
+
if isinstance(value, float):
|
|
66
|
+
return "integer" if value.is_integer() else "number"
|
|
67
|
+
if isinstance(value, str):
|
|
68
|
+
return "string"
|
|
69
|
+
if isinstance(value, (list, tuple)):
|
|
70
|
+
return "array"
|
|
71
|
+
if isinstance(value, dict):
|
|
72
|
+
return "object"
|
|
73
|
+
return type(value).__name__
|
|
74
|
+
|
|
75
|
+
|
|
76
|
+
def _fits(value: Any, allowed: Set[str]) -> bool:
|
|
77
|
+
t = type_of(value)
|
|
78
|
+
return t in allowed or (t == "integer" and "number" in allowed)
|
|
79
|
+
|
|
80
|
+
|
|
81
|
+
class _Walker:
|
|
82
|
+
def __init__(self, root: Any, wrap: bool) -> None:
|
|
83
|
+
self.root = root
|
|
84
|
+
self.wrap = wrap
|
|
85
|
+
self.fixes: List[Fix] = []
|
|
86
|
+
|
|
87
|
+
# -- schema helpers ---------------------------------------------------------------
|
|
88
|
+
|
|
89
|
+
def resolve(self, schema: Any, seen: Tuple[str, ...] = ()) -> Any:
|
|
90
|
+
"""Follow a local ``$ref`` (``#/$defs/X``, ``#/definitions/X``, ``#``)."""
|
|
91
|
+
while isinstance(schema, dict) and isinstance(schema.get("$ref"), str):
|
|
92
|
+
ref = schema["$ref"]
|
|
93
|
+
if not ref.startswith("#") or ref in seen or len(seen) > 32:
|
|
94
|
+
return {}
|
|
95
|
+
seen = seen + (ref,)
|
|
96
|
+
target: Any = self.root
|
|
97
|
+
for part in ref[1:].lstrip("/").split("/") if ref != "#" else []:
|
|
98
|
+
part = part.replace("~1", "/").replace("~0", "~")
|
|
99
|
+
if isinstance(target, dict) and part in target:
|
|
100
|
+
target = target[part]
|
|
101
|
+
elif isinstance(target, list) and part.isdigit() and int(part) < len(target):
|
|
102
|
+
target = target[int(part)]
|
|
103
|
+
else:
|
|
104
|
+
return {}
|
|
105
|
+
# Sibling keywords next to $ref (allowed since 2019-09) still apply.
|
|
106
|
+
rest = {k: v for k, v in schema.items() if k != "$ref"}
|
|
107
|
+
schema = dict(target, **rest) if rest and isinstance(target, dict) else target
|
|
108
|
+
return schema
|
|
109
|
+
|
|
110
|
+
def allowed(self, schema: Any, depth: int = 0) -> Optional[Set[str]]:
|
|
111
|
+
"""Types this schema accepts, or None if it doesn't say (then nothing is decoded)."""
|
|
112
|
+
schema = self.resolve(schema)
|
|
113
|
+
if not isinstance(schema, dict) or not schema or depth > MAX_DEPTH:
|
|
114
|
+
return None
|
|
115
|
+
found: Optional[Set[str]] = None
|
|
116
|
+
|
|
117
|
+
def narrow(types: Optional[Set[str]]) -> None:
|
|
118
|
+
nonlocal found
|
|
119
|
+
if types is None:
|
|
120
|
+
return
|
|
121
|
+
found = set(types) if found is None else _meet(found, types)
|
|
122
|
+
|
|
123
|
+
t = schema.get("type")
|
|
124
|
+
if isinstance(t, str):
|
|
125
|
+
narrow({t})
|
|
126
|
+
elif isinstance(t, list) and all(isinstance(x, str) for x in t):
|
|
127
|
+
narrow(set(t))
|
|
128
|
+
if schema.get("nullable") is True and found is not None: # OpenAPI 3.0 style
|
|
129
|
+
found.add("null")
|
|
130
|
+
if "const" in schema:
|
|
131
|
+
narrow({type_of(schema["const"])})
|
|
132
|
+
if isinstance(schema.get("enum"), list) and schema["enum"]:
|
|
133
|
+
narrow({type_of(v) for v in schema["enum"]})
|
|
134
|
+
for key in ("anyOf", "oneOf"):
|
|
135
|
+
branches = schema.get(key)
|
|
136
|
+
if isinstance(branches, list) and branches:
|
|
137
|
+
union: Set[str] = set()
|
|
138
|
+
for b in branches:
|
|
139
|
+
bt = self.allowed(b, depth + 1)
|
|
140
|
+
if bt is None: # one open branch makes the whole union open
|
|
141
|
+
union = set()
|
|
142
|
+
break
|
|
143
|
+
union |= bt
|
|
144
|
+
if union:
|
|
145
|
+
narrow(union)
|
|
146
|
+
for b in schema.get("allOf") or []:
|
|
147
|
+
narrow(self.allowed(b, depth + 1))
|
|
148
|
+
if found is None:
|
|
149
|
+
if any(k in schema for k in ("properties", "patternProperties", "required",
|
|
150
|
+
"additionalProperties")):
|
|
151
|
+
found = {"object"}
|
|
152
|
+
elif any(k in schema for k in ("items", "prefixItems")):
|
|
153
|
+
found = {"array"}
|
|
154
|
+
return found
|
|
155
|
+
|
|
156
|
+
# -- decoding -------------------------------------------------------------------
|
|
157
|
+
|
|
158
|
+
def decode(self, text: str, allowed: Set[str]) -> Optional[Tuple[Any, str]]:
|
|
159
|
+
"""The value ``text`` stands for, if it has an allowed type."""
|
|
160
|
+
s = text.strip()
|
|
161
|
+
if not s:
|
|
162
|
+
return None
|
|
163
|
+
value: Any = _NOTHING
|
|
164
|
+
how = "json"
|
|
165
|
+
try:
|
|
166
|
+
value = json.loads(s)
|
|
167
|
+
if isinstance(value, str) and value.strip()[:1] in ("[", "{"):
|
|
168
|
+
value = json.loads(value) # double-encoded: "\"[1, 2]\""
|
|
169
|
+
except ValueError:
|
|
170
|
+
value = _NOTHING
|
|
171
|
+
if value is _NOTHING and s[:1] in ("[", "{", "(") and allowed & {"array", "object"} \
|
|
172
|
+
and len(s) <= 1_000_000:
|
|
173
|
+
try: # some bridges send Python reprs: ['a', 'b'] or {'k': True}
|
|
174
|
+
value = ast.literal_eval(s)
|
|
175
|
+
how = "python"
|
|
176
|
+
if isinstance(value, tuple):
|
|
177
|
+
value = list(value)
|
|
178
|
+
if not _json_safe(value):
|
|
179
|
+
value = _NOTHING
|
|
180
|
+
except (ValueError, SyntaxError, MemoryError, RecursionError, TypeError):
|
|
181
|
+
value = _NOTHING
|
|
182
|
+
if value is _NOTHING and "boolean" in allowed and s.lower() in ("true", "false"):
|
|
183
|
+
value, how = s.lower() == "true", "json"
|
|
184
|
+
if value is _NOTHING or isinstance(value, str):
|
|
185
|
+
return None
|
|
186
|
+
if isinstance(value, float) and not math.isfinite(value):
|
|
187
|
+
return None
|
|
188
|
+
if isinstance(value, float) and value.is_integer() and "integer" in allowed \
|
|
189
|
+
and "number" not in allowed:
|
|
190
|
+
value = int(value)
|
|
191
|
+
if not _fits(value, allowed):
|
|
192
|
+
return None
|
|
193
|
+
return value, how
|
|
194
|
+
|
|
195
|
+
# -- walking --------------------------------------------------------------------
|
|
196
|
+
|
|
197
|
+
def walk(self, value: Any, schema: Any, path: str, depth: int = 0) -> Any:
|
|
198
|
+
if depth > MAX_DEPTH:
|
|
199
|
+
return value
|
|
200
|
+
schema = self.resolve(schema)
|
|
201
|
+
if not isinstance(schema, dict):
|
|
202
|
+
return value
|
|
203
|
+
allowed = self.allowed(schema)
|
|
204
|
+
|
|
205
|
+
if isinstance(value, str) and allowed is not None and "string" not in allowed:
|
|
206
|
+
decoded = self.decode(value, allowed)
|
|
207
|
+
if decoded is not None:
|
|
208
|
+
new, how = decoded
|
|
209
|
+
self.fixes.append(Fix(path, "string", type_of(new), how))
|
|
210
|
+
value = new
|
|
211
|
+
elif self.wrap and "array" in allowed:
|
|
212
|
+
return self._wrap(value, schema, path, depth)
|
|
213
|
+
elif isinstance(value, dict) and allowed is not None and "array" in allowed \
|
|
214
|
+
and "object" not in allowed and _index_keys(value):
|
|
215
|
+
# Some bridges turn [x, y] into {"0": x, "1": y}.
|
|
216
|
+
value = [value[str(i)] for i in range(len(value))]
|
|
217
|
+
self.fixes.append(Fix(path, "object", "array", "index"))
|
|
218
|
+
elif self.wrap and allowed is not None and "array" in allowed \
|
|
219
|
+
and not isinstance(value, list) and not _fits(value, allowed):
|
|
220
|
+
return self._wrap(value, schema, path, depth)
|
|
221
|
+
|
|
222
|
+
# Pick the branch(es) of a union that the value now fits, and walk into them too.
|
|
223
|
+
for key in ("anyOf", "oneOf"):
|
|
224
|
+
branches = schema.get(key)
|
|
225
|
+
if isinstance(branches, list):
|
|
226
|
+
value = self.walk_union(value, branches, path, depth)
|
|
227
|
+
for sub in schema.get("allOf") or []:
|
|
228
|
+
value = self.walk(value, sub, path, depth + 1)
|
|
229
|
+
|
|
230
|
+
if isinstance(value, dict):
|
|
231
|
+
value = self.walk_object(value, schema, path, depth)
|
|
232
|
+
elif isinstance(value, list):
|
|
233
|
+
value = self.walk_array(value, schema, path, depth)
|
|
234
|
+
return value
|
|
235
|
+
|
|
236
|
+
def walk_union(self, value: Any, branches: List[Any], path: str, depth: int) -> Any:
|
|
237
|
+
# A branch the value already matches by type wins; otherwise the first branch that
|
|
238
|
+
# can decode it. Branches are tried on a scratch walker so a failed try leaves no fixes.
|
|
239
|
+
fitting = []
|
|
240
|
+
for branch in branches:
|
|
241
|
+
bt = self.allowed(branch)
|
|
242
|
+
if bt is not None and _fits(value, bt):
|
|
243
|
+
fitting.append(branch)
|
|
244
|
+
if isinstance(value, dict) and len(fitting) > 1: # prefer a branch whose keys it has
|
|
245
|
+
have = [b for b in fitting if set(_required(self.resolve(b))) <= set(value)]
|
|
246
|
+
fitting = have or fitting
|
|
247
|
+
for want_fit in (True, False):
|
|
248
|
+
for branch in (fitting if want_fit else branches):
|
|
249
|
+
trial = _Walker(self.root, self.wrap)
|
|
250
|
+
new = trial.walk(value, branch, path, depth + 1)
|
|
251
|
+
nt = self.allowed(branch)
|
|
252
|
+
if nt is None or _fits(new, nt):
|
|
253
|
+
if trial.fixes or want_fit:
|
|
254
|
+
self.fixes += trial.fixes
|
|
255
|
+
return new
|
|
256
|
+
return value
|
|
257
|
+
|
|
258
|
+
def walk_object(self, value: Dict[str, Any], schema: Dict[str, Any], path: str,
|
|
259
|
+
depth: int) -> Dict[str, Any]:
|
|
260
|
+
props = schema.get("properties") if isinstance(schema.get("properties"), dict) else {}
|
|
261
|
+
patterns = schema.get("patternProperties")
|
|
262
|
+
extra = schema.get("additionalProperties")
|
|
263
|
+
out: Optional[Dict[str, Any]] = None
|
|
264
|
+
for key, item in value.items():
|
|
265
|
+
subs: List[Any] = []
|
|
266
|
+
if key in props:
|
|
267
|
+
subs.append(props[key])
|
|
268
|
+
if isinstance(patterns, dict):
|
|
269
|
+
for pattern, sub in patterns.items():
|
|
270
|
+
try:
|
|
271
|
+
if re.search(pattern, key):
|
|
272
|
+
subs.append(sub)
|
|
273
|
+
except re.error:
|
|
274
|
+
pass
|
|
275
|
+
if not subs and isinstance(extra, dict):
|
|
276
|
+
subs.append(extra)
|
|
277
|
+
new = item
|
|
278
|
+
for sub in subs:
|
|
279
|
+
new = self.walk(new, sub, _join(path, key), depth + 1)
|
|
280
|
+
if new is not item:
|
|
281
|
+
if out is None:
|
|
282
|
+
out = dict(value)
|
|
283
|
+
out[key] = new
|
|
284
|
+
return value if out is None else out
|
|
285
|
+
|
|
286
|
+
def walk_array(self, value: List[Any], schema: Dict[str, Any], path: str,
|
|
287
|
+
depth: int) -> List[Any]:
|
|
288
|
+
prefix = schema.get("prefixItems")
|
|
289
|
+
items = schema.get("items")
|
|
290
|
+
if isinstance(items, list): # draft 4-7 tuple form
|
|
291
|
+
prefix, items = items, schema.get("additionalItems")
|
|
292
|
+
out: Optional[List[Any]] = None
|
|
293
|
+
for i, item in enumerate(value):
|
|
294
|
+
if isinstance(prefix, list) and i < len(prefix):
|
|
295
|
+
sub = prefix[i]
|
|
296
|
+
elif isinstance(items, dict):
|
|
297
|
+
sub = items
|
|
298
|
+
else:
|
|
299
|
+
continue
|
|
300
|
+
new = self.walk(item, sub, f"{path}[{i}]", depth + 1)
|
|
301
|
+
if new is not item:
|
|
302
|
+
if out is None:
|
|
303
|
+
out = list(value)
|
|
304
|
+
out[i] = new
|
|
305
|
+
return value if out is None else out
|
|
306
|
+
|
|
307
|
+
def _wrap(self, value: Any, schema: Dict[str, Any], path: str, depth: int) -> Any:
|
|
308
|
+
self.fixes.append(Fix(path, type_of(value), "array", "wrap"))
|
|
309
|
+
return self.walk_array([value], schema, path, depth)
|
|
310
|
+
|
|
311
|
+
|
|
312
|
+
_NOTHING = object()
|
|
313
|
+
|
|
314
|
+
|
|
315
|
+
def _meet(a: Set[str], b: Set[str]) -> Set[str]:
|
|
316
|
+
"""Types allowed by both (an integer is also a number)."""
|
|
317
|
+
out = a & b
|
|
318
|
+
if "number" in a and "integer" in b or "number" in b and "integer" in a:
|
|
319
|
+
out.add("integer")
|
|
320
|
+
return out
|
|
321
|
+
|
|
322
|
+
|
|
323
|
+
def _index_keys(value: Dict[str, Any]) -> bool:
|
|
324
|
+
"""True for {"0": .., "1": .., ...}: every key a decimal index, 0 to n-1, in any order."""
|
|
325
|
+
return bool(value) and set(value) == {str(i) for i in range(len(value))}
|
|
326
|
+
|
|
327
|
+
|
|
328
|
+
def _required(schema: Any) -> List[str]:
|
|
329
|
+
req = schema.get("required") if isinstance(schema, dict) else None
|
|
330
|
+
return [r for r in req if isinstance(r, str)] if isinstance(req, list) else []
|
|
331
|
+
|
|
332
|
+
|
|
333
|
+
def _json_safe(value: Any) -> bool:
|
|
334
|
+
if value is None or isinstance(value, (bool, int, str)):
|
|
335
|
+
return True
|
|
336
|
+
if isinstance(value, float):
|
|
337
|
+
return math.isfinite(value)
|
|
338
|
+
if isinstance(value, (list, tuple)):
|
|
339
|
+
return all(_json_safe(v) for v in value)
|
|
340
|
+
if isinstance(value, dict):
|
|
341
|
+
return all(isinstance(k, str) and _json_safe(v) for k, v in value.items())
|
|
342
|
+
return False
|
|
343
|
+
|
|
344
|
+
|
|
345
|
+
def _join(path: str, key: str) -> str:
|
|
346
|
+
if re.fullmatch(r"[A-Za-z_][A-Za-z0-9_-]*", key):
|
|
347
|
+
return f"{path}.{key}" if path else key
|
|
348
|
+
return f"{path}[{json.dumps(key)}]"
|
|
349
|
+
|
|
350
|
+
|
|
351
|
+
def repair(arguments: Any, schema: Any, *, wrap: bool = False) -> Result:
|
|
352
|
+
"""Repair ``arguments`` for a tool whose ``inputSchema`` is ``schema``.
|
|
353
|
+
|
|
354
|
+
``arguments`` may itself be a JSON string (some clients send the whole object that way).
|
|
355
|
+
With ``wrap=True`` a single value where the schema wants an array becomes a one-item list.
|
|
356
|
+
"""
|
|
357
|
+
walker = _Walker(schema, wrap)
|
|
358
|
+
value = arguments
|
|
359
|
+
if isinstance(value, str):
|
|
360
|
+
try:
|
|
361
|
+
parsed = json.loads(value) if value.strip() else {}
|
|
362
|
+
except ValueError:
|
|
363
|
+
parsed = None
|
|
364
|
+
if isinstance(parsed, dict):
|
|
365
|
+
walker.fixes.append(Fix("", "string", "object"))
|
|
366
|
+
value = parsed
|
|
367
|
+
value = walker.walk(value, schema if isinstance(schema, (dict, bool)) else {}, "")
|
|
368
|
+
return Result(value, walker.fixes)
|
|
369
|
+
|
|
370
|
+
|
|
371
|
+
def repair_arguments(arguments: Any, schema: Any, *, wrap: bool = False) -> Any:
|
|
372
|
+
"""Like :func:`repair`, returning only the repaired arguments."""
|
|
373
|
+
return repair(arguments, schema, wrap=wrap).value
|
unstring/proxy.py
ADDED
|
@@ -0,0 +1,143 @@
|
|
|
1
|
+
"""``unstring proxy``: repair tool-call arguments between any MCP client and any stdio server.
|
|
2
|
+
|
|
3
|
+
The proxy starts the server and passes every message through unchanged, except
|
|
4
|
+
``tools/call``: there it repairs ``params.arguments`` against the tool's ``inputSchema``
|
|
5
|
+
(learned from ``tools/list`` results) before the server sees them.
|
|
6
|
+
|
|
7
|
+
If a call names a tool whose schema the proxy has not seen yet (the client cached the tool
|
|
8
|
+
list, or never asked for it), the proxy asks the server for its tool list itself, holds the
|
|
9
|
+
call until the answer is in, then sends it on, repaired. The client never sees that request.
|
|
10
|
+
"""
|
|
11
|
+
|
|
12
|
+
from __future__ import annotations
|
|
13
|
+
|
|
14
|
+
import json
|
|
15
|
+
import sys
|
|
16
|
+
import threading
|
|
17
|
+
from typing import Any, BinaryIO, Dict, List, Optional, TextIO, Tuple
|
|
18
|
+
|
|
19
|
+
from ._relay import Relay
|
|
20
|
+
from .core import repair
|
|
21
|
+
|
|
22
|
+
LIST_ID_PREFIX = "unstring-tools-"
|
|
23
|
+
|
|
24
|
+
|
|
25
|
+
class ArgProxy:
|
|
26
|
+
"""The message hooks, kept apart from the process handling so they are easy to test."""
|
|
27
|
+
|
|
28
|
+
def __init__(self, *, wrap: bool = False, quiet: bool = False,
|
|
29
|
+
log: Optional[TextIO] = None) -> None:
|
|
30
|
+
self.wrap = wrap
|
|
31
|
+
self.quiet = quiet
|
|
32
|
+
self.log = log or sys.stderr
|
|
33
|
+
self.schemas: Dict[str, Any] = {}
|
|
34
|
+
self.complete = False # a full tool list (every page) has been seen
|
|
35
|
+
self.fetching = False # the proxy's own tools/list is in flight
|
|
36
|
+
self.held: List[dict] = [] # tools/call requests waiting for that list
|
|
37
|
+
self.fixed_calls = 0
|
|
38
|
+
self._client_lists: set = set()
|
|
39
|
+
self._next = 0
|
|
40
|
+
self._lock = threading.Lock()
|
|
41
|
+
|
|
42
|
+
# -- client -> server -------------------------------------------------------------
|
|
43
|
+
|
|
44
|
+
def to_server(self, msg: dict) -> Tuple[Optional[dict], List[dict]]:
|
|
45
|
+
method = msg.get("method")
|
|
46
|
+
if method == "tools/list" and "id" in msg:
|
|
47
|
+
with self._lock:
|
|
48
|
+
self._client_lists.add(_key(msg["id"]))
|
|
49
|
+
return msg, []
|
|
50
|
+
if method != "tools/call" or not isinstance(msg.get("params"), dict):
|
|
51
|
+
return msg, []
|
|
52
|
+
name = msg["params"].get("name")
|
|
53
|
+
with self._lock:
|
|
54
|
+
if name in self.schemas or self.complete:
|
|
55
|
+
return self._fix(msg), []
|
|
56
|
+
self.held.append(msg)
|
|
57
|
+
if self.fetching:
|
|
58
|
+
return None, []
|
|
59
|
+
self.fetching = True
|
|
60
|
+
return self._list_request(None), []
|
|
61
|
+
|
|
62
|
+
# -- server -> client -------------------------------------------------------------
|
|
63
|
+
|
|
64
|
+
def to_client(self, msg: dict) -> Tuple[Optional[dict], List[dict]]:
|
|
65
|
+
"""Returns (message for the client, messages for the server)."""
|
|
66
|
+
if msg.get("method") == "notifications/tools/list_changed":
|
|
67
|
+
with self._lock:
|
|
68
|
+
self.complete = False
|
|
69
|
+
return msg, []
|
|
70
|
+
if "method" in msg or "id" not in msg:
|
|
71
|
+
return msg, []
|
|
72
|
+
key = _key(msg["id"])
|
|
73
|
+
if isinstance(msg["id"], str) and msg["id"].startswith(LIST_ID_PREFIX):
|
|
74
|
+
return None, self._own_list_result(msg)
|
|
75
|
+
with self._lock:
|
|
76
|
+
if key not in self._client_lists:
|
|
77
|
+
return msg, []
|
|
78
|
+
self._client_lists.discard(key)
|
|
79
|
+
self._learn(msg.get("result"))
|
|
80
|
+
return msg, []
|
|
81
|
+
|
|
82
|
+
def _own_list_result(self, msg: dict) -> List[dict]:
|
|
83
|
+
with self._lock:
|
|
84
|
+
result = msg.get("result")
|
|
85
|
+
if isinstance(result, dict) and isinstance(result.get("tools"), list):
|
|
86
|
+
self._learn(result)
|
|
87
|
+
cursor = result.get("nextCursor")
|
|
88
|
+
if isinstance(cursor, str) and cursor:
|
|
89
|
+
return [self._list_request(cursor)]
|
|
90
|
+
elif not self.quiet:
|
|
91
|
+
print(f"unstring: the server did not list its tools "
|
|
92
|
+
f"({json.dumps(msg.get('error'))[:200]}); passing calls on as they are",
|
|
93
|
+
file=self.log)
|
|
94
|
+
self.complete = True # also on error: don't ask again for every call
|
|
95
|
+
self.fetching = False
|
|
96
|
+
held, self.held = self.held, []
|
|
97
|
+
return [self._fix(m) for m in held]
|
|
98
|
+
|
|
99
|
+
# -- helpers ----------------------------------------------------------------------
|
|
100
|
+
|
|
101
|
+
def _list_request(self, cursor: Optional[str]) -> dict:
|
|
102
|
+
self._next += 1
|
|
103
|
+
params = {"cursor": cursor} if cursor else {}
|
|
104
|
+
return {"jsonrpc": "2.0", "id": f"{LIST_ID_PREFIX}{self._next}", "method": "tools/list",
|
|
105
|
+
"params": params}
|
|
106
|
+
|
|
107
|
+
def _learn(self, result: Any) -> None:
|
|
108
|
+
if not isinstance(result, dict) or not isinstance(result.get("tools"), list):
|
|
109
|
+
return
|
|
110
|
+
for tool in result["tools"]:
|
|
111
|
+
if isinstance(tool, dict) and isinstance(tool.get("name"), str):
|
|
112
|
+
self.schemas[tool["name"]] = tool.get("inputSchema")
|
|
113
|
+
if not result.get("nextCursor"):
|
|
114
|
+
self.complete = True
|
|
115
|
+
|
|
116
|
+
def _fix(self, msg: dict) -> dict:
|
|
117
|
+
params = msg["params"]
|
|
118
|
+
if "arguments" not in params:
|
|
119
|
+
return msg
|
|
120
|
+
name = params.get("name")
|
|
121
|
+
schema = self.schemas.get(name)
|
|
122
|
+
result = repair(params["arguments"], schema if schema is not None else {},
|
|
123
|
+
wrap=self.wrap)
|
|
124
|
+
if not result.changed:
|
|
125
|
+
return msg
|
|
126
|
+
self.fixed_calls += 1
|
|
127
|
+
if not self.quiet:
|
|
128
|
+
fixes = "; ".join(str(f) for f in result.fixes)
|
|
129
|
+
print(f"unstring: {name}: {fixes}", file=self.log)
|
|
130
|
+
return dict(msg, params=dict(params, arguments=result.value))
|
|
131
|
+
|
|
132
|
+
|
|
133
|
+
def _key(value: Any) -> str:
|
|
134
|
+
return repr(value) # ids may be numbers or strings; 1 and "1" are different requests
|
|
135
|
+
|
|
136
|
+
|
|
137
|
+
def run(command: List[str], *, wrap: bool = False, quiet: bool = False,
|
|
138
|
+
log: Optional[TextIO] = None, stdin: Optional[BinaryIO] = None,
|
|
139
|
+
stdout: Optional[BinaryIO] = None) -> int:
|
|
140
|
+
proxy = ArgProxy(wrap=wrap, quiet=quiet, log=log)
|
|
141
|
+
relay = Relay(command, to_server=proxy.to_server, to_client=proxy.to_client,
|
|
142
|
+
stdin=stdin, stdout=stdout, name="unstring proxy")
|
|
143
|
+
return relay.run()
|
|
@@ -0,0 +1,166 @@
|
|
|
1
|
+
Metadata-Version: 2.5
|
|
2
|
+
Name: unstring
|
|
3
|
+
Version: 0.1.0
|
|
4
|
+
Summary: Fix MCP tool calls that fail with "expected array, received string": repairs tool-call arguments that clients and models send as JSON strings (arrays, objects, numbers, booleans), guided by the tool's inputSchema, as a stdio proxy for any MCP server or one function
|
|
5
|
+
Project-URL: Homepage, https://github.com/srikrishnaL/kitforge/tree/main/packages/unstring
|
|
6
|
+
Project-URL: Source, https://github.com/srikrishnaL/kitforge
|
|
7
|
+
Project-URL: Issues, https://github.com/srikrishnaL/kitforge/issues
|
|
8
|
+
Project-URL: Changelog, https://github.com/srikrishnaL/kitforge/blob/main/packages/unstring/CHANGELOG.md
|
|
9
|
+
Author: Sri Krishna Lingamaneni
|
|
10
|
+
License-Expression: MIT
|
|
11
|
+
License-File: LICENSE
|
|
12
|
+
Keywords: agents,claude code,claude desktop,coerce,expected array,function calling,invalid arguments,json schema,json string,llm,mcp,mcp proxy,mcp server,model context protocol,n8n,opencode,pydantic,received string,stringified,tool arguments,tool calling,zod
|
|
13
|
+
Classifier: Development Status :: 4 - Beta
|
|
14
|
+
Classifier: Intended Audience :: Developers
|
|
15
|
+
Classifier: Operating System :: OS Independent
|
|
16
|
+
Classifier: Programming Language :: Python :: 3
|
|
17
|
+
Classifier: Programming Language :: Python :: 3 :: Only
|
|
18
|
+
Classifier: Topic :: Scientific/Engineering :: Artificial Intelligence
|
|
19
|
+
Classifier: Topic :: Software Development :: Libraries
|
|
20
|
+
Requires-Python: >=3.9
|
|
21
|
+
Provides-Extra: test
|
|
22
|
+
Requires-Dist: pytest>=7; extra == 'test'
|
|
23
|
+
Description-Content-Type: text/markdown
|
|
24
|
+
|
|
25
|
+
# unstring
|
|
26
|
+
|
|
27
|
+
Some MCP clients and models send tool arguments as JSON strings: `"pages": "[{\"title\": \"A\"}]"`
|
|
28
|
+
where the tool's schema says array, `"limit": "5"` where it says integer. The server rejects
|
|
29
|
+
the call with `expected array, received string` (or `Input should be a valid list`), and the
|
|
30
|
+
agent retries, gives up, or writes nothing.
|
|
31
|
+
|
|
32
|
+
unstring repairs those arguments before the server sees them, guided by the tool's own
|
|
33
|
+
`inputSchema`. A value is decoded only where the schema does not allow a string, and only when
|
|
34
|
+
the decoded value has a type the schema does allow, so real strings are never touched. Use it
|
|
35
|
+
as a stdio proxy around any MCP server (no code changes, any language) or as one function.
|
|
36
|
+
|
|
37
|
+
```bash
|
|
38
|
+
pip install unstring
|
|
39
|
+
```
|
|
40
|
+
|
|
41
|
+
## Quick start: any stdio server
|
|
42
|
+
|
|
43
|
+
Put `unstring proxy --` in front of the server command in your client's config:
|
|
44
|
+
|
|
45
|
+
```json
|
|
46
|
+
{
|
|
47
|
+
"mcpServers": {
|
|
48
|
+
"notion": {
|
|
49
|
+
"command": "unstring",
|
|
50
|
+
"args": ["proxy", "--", "npx", "-y", "@notionhq/notion-mcp-server"]
|
|
51
|
+
}
|
|
52
|
+
}
|
|
53
|
+
}
|
|
54
|
+
```
|
|
55
|
+
|
|
56
|
+
Or with `uvx`, nothing to install first: `"command": "uvx", "args": ["unstring", "proxy", "--", ...]`.
|
|
57
|
+
|
|
58
|
+
Each repair is reported on stderr (most clients show it in their MCP log):
|
|
59
|
+
|
|
60
|
+
```text
|
|
61
|
+
unstring: create_pages: pages: string -> array; pages[0].position: string -> integer
|
|
62
|
+
```
|
|
63
|
+
|
|
64
|
+
### Proxy options
|
|
65
|
+
|
|
66
|
+
| Option | What it does |
|
|
67
|
+
|---|---|
|
|
68
|
+
| `--wrap` | Also turn a single value into a one-item list where the schema wants an array (`"ids": 4` becomes `[4]`). Off by default. |
|
|
69
|
+
| `--quiet` | Don't report repairs. |
|
|
70
|
+
| `--log FILE` | Append repair reports to a file instead of stderr. |
|
|
71
|
+
|
|
72
|
+
The proxy learns each tool's schema from the `tools/list` results the client asks for. If a
|
|
73
|
+
call names a tool it has not seen (the client cached the list), it asks the server for the
|
|
74
|
+
tool list itself, holds the call until the answer is in, and then sends it on, repaired. All
|
|
75
|
+
other messages pass through byte for byte.
|
|
76
|
+
|
|
77
|
+
## In your own server or client: one function
|
|
78
|
+
|
|
79
|
+
```python
|
|
80
|
+
from unstring import repair
|
|
81
|
+
|
|
82
|
+
schema = {
|
|
83
|
+
"type": "object",
|
|
84
|
+
"properties": {
|
|
85
|
+
"pages": {"type": "array", "items": {"type": "object", "properties": {
|
|
86
|
+
"title": {"type": "string"}, "position": {"type": "integer"}}}},
|
|
87
|
+
"query": {"type": "string"},
|
|
88
|
+
"limit": {"anyOf": [{"type": "integer"}, {"type": "null"}]},
|
|
89
|
+
},
|
|
90
|
+
}
|
|
91
|
+
result = repair({"pages": '[{"title": "A", "position": "2"}]', "query": "[1, 2]",
|
|
92
|
+
"limit": "10"}, schema)
|
|
93
|
+
|
|
94
|
+
print(result.value)
|
|
95
|
+
# {'pages': [{'title': 'A', 'position': 2}], 'query': '[1, 2]', 'limit': 10}
|
|
96
|
+
print([str(f) for f in result.fixes])
|
|
97
|
+
# ['pages: string -> array', 'pages[0].position: string -> integer', 'limit: string -> integer']
|
|
98
|
+
```
|
|
99
|
+
|
|
100
|
+
`query` stays a string: the schema says it is one. `repair_arguments(args, schema)` returns
|
|
101
|
+
only the value. Check one call from the command line:
|
|
102
|
+
|
|
103
|
+
```console
|
|
104
|
+
$ unstring fix --schema tools.json --tool create_pages '{"pages": "[{\"title\": \"A\"}]"}'
|
|
105
|
+
repaired pages: string -> array
|
|
106
|
+
{
|
|
107
|
+
"pages": [
|
|
108
|
+
{
|
|
109
|
+
"title": "A"
|
|
110
|
+
}
|
|
111
|
+
]
|
|
112
|
+
}
|
|
113
|
+
```
|
|
114
|
+
|
|
115
|
+
`--schema` takes an `inputSchema`, a tool, or a saved `tools/list` result. The exit code is 2
|
|
116
|
+
when something was repaired, 0 when nothing needed it.
|
|
117
|
+
|
|
118
|
+
## What gets repaired
|
|
119
|
+
|
|
120
|
+
- JSON text for arrays, objects, integers, numbers, booleans and `null` where the schema wants
|
|
121
|
+
those types, at any depth: inside arrays, nested objects, `$ref`/`$defs`, `anyOf`/`oneOf`/
|
|
122
|
+
`allOf`, `additionalProperties`, `patternProperties`, `prefixItems`.
|
|
123
|
+
- Double-encoded JSON (`"\"[1, 2]\""`).
|
|
124
|
+
- Python literals some bridges send (`"['a', 'b']"`, `"{'k': True}"`), parsed safely with
|
|
125
|
+
`ast.literal_eval`, never `eval`.
|
|
126
|
+
- Arrays that arrived as index-keyed objects (`{"0": x, "1": y}` where the schema wants an
|
|
127
|
+
array), as some HTTP bridges send them.
|
|
128
|
+
- `"True"`/`"FALSE"` for booleans, `"5.0"` for an integer field.
|
|
129
|
+
- The whole `arguments` object sent as one JSON string.
|
|
130
|
+
|
|
131
|
+
## Limits
|
|
132
|
+
|
|
133
|
+
- Where the schema allows a string (`"type": ["string", "array"]`, an untyped field, `{}`),
|
|
134
|
+
the string is left alone, because there is no safe way to tell. Give the field a type if
|
|
135
|
+
you want it repaired.
|
|
136
|
+
- `unstring proxy` works with stdio servers. For a remote (Streamable HTTP) server, call
|
|
137
|
+
`repair` in the server where the arguments arrive.
|
|
138
|
+
- It fixes types, not values: a wrong enum, a missing required field or a bad date still
|
|
139
|
+
reaches the server and fails there, as it should.
|
|
140
|
+
- Strings like `"007"` or `"1,2"` are not valid JSON and are not guessed at.
|
|
141
|
+
|
|
142
|
+
## Why this exists
|
|
143
|
+
|
|
144
|
+
Clients keep sending stringified arguments, intermittently, and every server works around it
|
|
145
|
+
on its own (`tryParseJson` helpers, `z.preprocess`, accept-a-string-too unions):
|
|
146
|
+
|
|
147
|
+
- [anthropics/claude-code#26094](https://github.com/anthropics/claude-code/issues/26094): Claude
|
|
148
|
+
Desktop serializes MCP object parameters as strings, breaking Notion MCP writes (21 upvotes).
|
|
149
|
+
- [makenotion/notion-mcp-server#215](https://github.com/makenotion/notion-mcp-server/issues/215):
|
|
150
|
+
`pages` array parameter received as a string.
|
|
151
|
+
- [anthropics/claude-code#86459](https://github.com/anthropics/claude-code/issues/86459): array
|
|
152
|
+
parameters silently stringified mid-call, breaking any tool expecting `List[str]`.
|
|
153
|
+
- [n8n-io/n8n#33864](https://github.com/n8n-io/n8n/issues/33864): typed tool parameters arrive as
|
|
154
|
+
strings, `expected array, received string`.
|
|
155
|
+
- [czlonkowski/n8n-mcp#814](https://github.com/czlonkowski/n8n-mcp/issues/814): nested arrays and
|
|
156
|
+
objects mis-serialized by HTTP MCP clients (strings, and arrays turned into `{"0": ..}`
|
|
157
|
+
objects); the server's `tryParseJson` misses cases.
|
|
158
|
+
- [continuedev/continue#13350](https://github.com/continuedev/continue/issues/13350) and
|
|
159
|
+
[exa-labs/exa-mcp-server#477](https://github.com/exa-labs/exa-mcp-server/issues/477): the same
|
|
160
|
+
error from Continue and Exa.
|
|
161
|
+
- [anomalyco/opencode#57023](https://github.com/anomalyco/opencode/issues/57023): the whole
|
|
162
|
+
`arguments` object passed as a string.
|
|
163
|
+
|
|
164
|
+
## License
|
|
165
|
+
|
|
166
|
+
MIT
|
|
@@ -0,0 +1,11 @@
|
|
|
1
|
+
unstring/__init__.py,sha256=peTNHTMsnXANnVHwDaZLARvbVldlifcjRqG2dJ6G-60,225
|
|
2
|
+
unstring/__main__.py,sha256=E6Gls0DNz8GQK2K-kOUIx8cYhgANW_CH54VKrfCfs14,52
|
|
3
|
+
unstring/_relay.py,sha256=f05_dPv4tS4FvJbZrTLJiIN5OFC4DZIQu3Fv7hWWLOw,5648
|
|
4
|
+
unstring/cli.py,sha256=KmbQniWBlGo0f-E5p3igVGwt7Y0DiT0RNnrVsvscOA8,5153
|
|
5
|
+
unstring/core.py,sha256=vRSsL-UjOWetiJddahg3XgirErVWO375_57cTzDJ2cY,15254
|
|
6
|
+
unstring/proxy.py,sha256=c44U0biz5r87K3D1qGnL86qNnbCwyorDVSh7LtKpBGM,6021
|
|
7
|
+
unstring-0.1.0.dist-info/METADATA,sha256=lNgW00JOI0qTiiBe3l8Iq1bzISA1AdkXZt7G_lImUFU,7411
|
|
8
|
+
unstring-0.1.0.dist-info/WHEEL,sha256=2iZrJkDIkeDh0k9SikKMqFuRP-ua6mb4Ir1AsER4BEw,87
|
|
9
|
+
unstring-0.1.0.dist-info/entry_points.txt,sha256=7p7gAWQDK61wlftC_BCeH4gWO9GbHhgYaD1gHFMgyu4,47
|
|
10
|
+
unstring-0.1.0.dist-info/licenses/LICENSE,sha256=fl9U1idgeyJw-8GWneEYxVzZM_C29cBR63IAlNv7KjE,1080
|
|
11
|
+
unstring-0.1.0.dist-info/RECORD,,
|
|
@@ -0,0 +1,21 @@
|
|
|
1
|
+
MIT License
|
|
2
|
+
|
|
3
|
+
Copyright (c) 2026 Sri Krishna Lingamaneni
|
|
4
|
+
|
|
5
|
+
Permission is hereby granted, free of charge, to any person obtaining a copy
|
|
6
|
+
of this software and associated documentation files (the "Software"), to deal
|
|
7
|
+
in the Software without restriction, including without limitation the rights
|
|
8
|
+
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
|
|
9
|
+
copies of the Software, and to permit persons to whom the Software is
|
|
10
|
+
furnished to do so, subject to the following conditions:
|
|
11
|
+
|
|
12
|
+
The above copyright notice and this permission notice shall be included in all
|
|
13
|
+
copies or substantial portions of the Software.
|
|
14
|
+
|
|
15
|
+
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
|
|
16
|
+
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
|
|
17
|
+
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
|
|
18
|
+
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
|
|
19
|
+
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
|
|
20
|
+
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
|
|
21
|
+
SOFTWARE.
|