flatresult 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.
flatresult/__init__.py ADDED
@@ -0,0 +1,6 @@
1
+ """Make MCP tool results readable by clients that only show text and image blocks."""
2
+
3
+ from .core import Change, Flattened, flatten, links, needs_flattening
4
+
5
+ __version__ = "0.1.0"
6
+ __all__ = ["Change", "Flattened", "flatten", "links", "needs_flattening", "__version__"]
flatresult/__main__.py ADDED
@@ -0,0 +1,5 @@
1
+ import sys
2
+
3
+ from .cli import main
4
+
5
+ sys.exit(main())
flatresult/_relay.py ADDED
@@ -0,0 +1,155 @@
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 send_to_client(self, msg: Any) -> None:
79
+ """Send a message to the client from outside a hook (a timer, say)."""
80
+ self._write(self.stdout, _dump(msg))
81
+
82
+ def _handle(self, line: bytes, hook: Hook, forward: BinaryIO, back: BinaryIO) -> None:
83
+ line = line if line.endswith(b"\n") else line + b"\n"
84
+ try:
85
+ msg = json.loads(line)
86
+ except ValueError:
87
+ self._write(forward, line)
88
+ return
89
+ batch = isinstance(msg, list)
90
+ out: List[Any] = []
91
+ replies: List[dict] = []
92
+ changed = False
93
+ for item in (msg if batch else [msg]):
94
+ if not isinstance(item, dict):
95
+ out.append(item)
96
+ continue
97
+ try:
98
+ new, extra = hook(item)
99
+ except Exception as exc: # never break the connection over a rewrite
100
+ print(f"{self.name}: {type(exc).__name__}: {exc}", file=sys.stderr)
101
+ new, extra = item, []
102
+ if new is not item:
103
+ changed = True
104
+ if new is not None:
105
+ out.append(new)
106
+ replies += extra
107
+ if out:
108
+ self._write(forward, _dump(out if batch else out[0]) if changed else line)
109
+ for reply in replies:
110
+ self._write(back, _dump(reply))
111
+
112
+ def _pump_server(self) -> None:
113
+ assert self.proc and self.proc.stdout and self.proc.stdin
114
+ for line in _lines(self.proc.stdout):
115
+ if line.strip():
116
+ self._handle(line, self.to_client, self.stdout, self.proc.stdin)
117
+
118
+ def _pump_client(self) -> None:
119
+ assert self.proc and self.proc.stdin
120
+ for line in _lines(self.stdin):
121
+ if line.strip():
122
+ self._handle(line, self.to_server, self.proc.stdin, self.stdout)
123
+ try:
124
+ self.proc.stdin.close()
125
+ except OSError:
126
+ pass
127
+
128
+ def run(self) -> int:
129
+ try:
130
+ self.proc = subprocess.Popen(self.command, stdin=subprocess.PIPE,
131
+ stdout=subprocess.PIPE, bufsize=0)
132
+ except OSError as exc:
133
+ print(f"{self.name}: can't start {self.command[0]}: {exc}", file=sys.stderr)
134
+ return 127
135
+ pump = threading.Thread(target=self._pump_server, daemon=True)
136
+ pump.start()
137
+ threading.Thread(target=self._pump_client, daemon=True).start()
138
+
139
+ previous = None
140
+ if hasattr(signal, "SIGTERM") and threading.current_thread() is threading.main_thread():
141
+ def forward(signum, frame): # pass a shutdown request on to the server
142
+ if self.proc and self.proc.poll() is None:
143
+ self.proc.terminate()
144
+ previous = signal.signal(signal.SIGTERM, forward)
145
+ try:
146
+ try:
147
+ code = self.proc.wait()
148
+ except KeyboardInterrupt:
149
+ self.proc.terminate()
150
+ code = self.proc.wait()
151
+ pump.join(timeout=5)
152
+ finally:
153
+ if previous is not None:
154
+ signal.signal(signal.SIGTERM, previous)
155
+ return 128 - code if code < 0 else code
flatresult/cli.py ADDED
@@ -0,0 +1,108 @@
1
+ """flatresult: make MCP tool results readable by clients that only show text blocks."""
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 DEFAULT_MAX_TEXT, flatten
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="flatresult",
23
+ description="Rewrite MCP tool results (structuredContent without text, resource_link, "
24
+ "embedded resources, audio) into text and image blocks every client shows.")
25
+ parser.add_argument("--version", action="version", version=f"flatresult {__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 flatten the result of every tool call",
30
+ description="Start the MCP server given after -- and sit between it and the client. "
31
+ "Tool results whose data is only in structuredContent, resource_link "
32
+ "blocks, embedded resources or audio get text (or image) blocks the "
33
+ "client can show. Linked resources are read from the server and put "
34
+ "inline. Example: flatresult proxy -- npx -y mcp-remote "
35
+ "https://mcp.example.com/mcp")
36
+ _common(p)
37
+ p.add_argument("--no-inline", action="store_true",
38
+ help="don't read linked resources; turn each link into a text line")
39
+ p.add_argument("--max-links", type=int, default=5, metavar="N",
40
+ help="read at most N linked resources per result (default 5)")
41
+ p.add_argument("--timeout", type=float, default=10.0, metavar="SECONDS",
42
+ help="send the result without link contents if the server has not "
43
+ "answered resources/read by then (default 10)")
44
+ p.add_argument("--quiet", action="store_true", help="don't report rewrites on stderr")
45
+ p.add_argument("--log", metavar="FILE", help="append rewrite reports to FILE, not stderr")
46
+
47
+ c = sub.add_parser(
48
+ "check", help="flatten one tool result (JSON) and print it",
49
+ description="Read a tools/call result, or a whole JSON-RPC response, from FILE or "
50
+ "stdin, print the flattened result and list each rewrite on stderr. Exit "
51
+ "code 0 when every client can already read it, 2 when it was rewritten.")
52
+ _common(c)
53
+ c.add_argument("file", nargs="?", metavar="FILE", help="the result as JSON (default: stdin)")
54
+ args = parser.parse_args(argv)
55
+
56
+ if args.command == "check":
57
+ return _check(args, parser)
58
+ if not command:
59
+ parser.error("proxy needs the server command after --, e.g. "
60
+ "flatresult proxy -- npx -y @acme/server")
61
+ if args.max_links < 0:
62
+ parser.error("--max-links must be 0 or more")
63
+ from .proxy import run
64
+
65
+ log = None
66
+ if args.log:
67
+ try:
68
+ log = open(os.path.expanduser(args.log), "a", encoding="utf-8", buffering=1)
69
+ except OSError as exc:
70
+ parser.error(f"can't open {args.log}: {exc.strerror}")
71
+ try:
72
+ return run(command, keep=args.keep, inline=not args.no_inline,
73
+ max_links=args.max_links, max_text=args.max_text, timeout=args.timeout,
74
+ quiet=args.quiet, log=log)
75
+ finally:
76
+ if log is not None:
77
+ log.close()
78
+
79
+
80
+ def _common(p: argparse.ArgumentParser) -> None:
81
+ p.add_argument("--keep", action="store_true",
82
+ help="keep the original blocks and add the text after them (for clients "
83
+ "that skip unknown blocks instead of failing on them)")
84
+ p.add_argument("--max-text", type=int, default=DEFAULT_MAX_TEXT, metavar="CHARS",
85
+ help=f"cut resource text put inline after CHARS characters "
86
+ f"(default {DEFAULT_MAX_TEXT:,})")
87
+
88
+
89
+ def _check(args: argparse.Namespace, parser: argparse.ArgumentParser) -> int:
90
+ if args.file:
91
+ try:
92
+ with open(os.path.expanduser(args.file), encoding="utf-8") as fh:
93
+ text = fh.read()
94
+ except OSError as exc:
95
+ parser.error(f"can't read {args.file}: {exc.strerror}")
96
+ else:
97
+ text = sys.stdin.read()
98
+ try:
99
+ doc: Any = json.loads(text)
100
+ except ValueError as exc:
101
+ parser.error(f"input is not JSON: {exc}")
102
+ if isinstance(doc, dict) and isinstance(doc.get("result"), dict) and "jsonrpc" in doc:
103
+ doc = doc["result"]
104
+ flat = flatten(doc, keep=args.keep, max_text=args.max_text)
105
+ for change in flat.changes:
106
+ print(f"rewrote {change}", file=sys.stderr)
107
+ print(json.dumps(flat.result, ensure_ascii=False, indent=2))
108
+ return 2 if flat.changed else 0
flatresult/core.py ADDED
@@ -0,0 +1,229 @@
1
+ """Rewrite MCP tool results so clients that only read text blocks still see the data.
2
+
3
+ The MCP spec lets a tool return more than text: ``structuredContent``, ``resource_link``
4
+ blocks, embedded resources (``type: "resource"``, text or base64 blob) and audio. Many
5
+ clients handle only ``text`` and ``image`` blocks. They show an empty result, drop the block,
6
+ print a raw struct, or fail the whole call ("Unsupported response item type: resource_link").
7
+
8
+ :func:`flatten` turns a ``tools/call`` result into one every client can read:
9
+
10
+ * ``structuredContent`` with no text block: its JSON is added as a text block, as the spec
11
+ asks servers to do (structuredContent itself is kept);
12
+ * ``resource_link``: a text block naming the link (and, given its contents, the contents);
13
+ * embedded text resource: a text block with the resource's text;
14
+ * embedded blob resource: an ``image`` block for images, otherwise a short text note;
15
+ * ``audio``: a short text note.
16
+
17
+ ``text`` and ``image`` blocks are never changed, and a result that needs nothing is returned
18
+ as the same object.
19
+ """
20
+
21
+ from __future__ import annotations
22
+
23
+ import base64
24
+ import binascii
25
+ import json
26
+ from dataclasses import dataclass, field
27
+ from typing import Any, Callable, Dict, List, Optional
28
+
29
+ PLAIN = ("text", "image")
30
+ DEFAULT_MAX_TEXT = 100_000 # characters of resource text put inline, per block
31
+
32
+
33
+ @dataclass
34
+ class Change:
35
+ """One rewrite: ``index`` is the block's position in the original ``content`` (-1 for
36
+ the text added from ``structuredContent``)."""
37
+
38
+ index: int
39
+ kind: str
40
+ note: str
41
+
42
+ def __str__(self) -> str:
43
+ where = "structuredContent" if self.index < 0 else f"content[{self.index}]"
44
+ return f"{where}: {self.kind} -> {self.note}"
45
+
46
+
47
+ @dataclass
48
+ class Flattened:
49
+ result: Any
50
+ changes: List[Change] = field(default_factory=list)
51
+
52
+ @property
53
+ def changed(self) -> bool:
54
+ return bool(self.changes)
55
+
56
+
57
+ # A reader gets a resource_link's uri and returns that resource's ``contents`` list
58
+ # (as in a resources/read result), or None when it can't be read.
59
+ Reader = Callable[[str], Optional[List[dict]]]
60
+
61
+
62
+ def needs_flattening(result: Any, *, keep: bool = False) -> bool:
63
+ """True when :func:`flatten` would change ``result``."""
64
+ return flatten(result, keep=keep).changed
65
+
66
+
67
+ def links(result: Any) -> List[str]:
68
+ """The uris of the ``resource_link`` blocks in a tool result, in order."""
69
+ content = result.get("content") if isinstance(result, dict) else None
70
+ if not isinstance(content, list):
71
+ return []
72
+ return [b["uri"] for b in content
73
+ if isinstance(b, dict) and b.get("type") == "resource_link"
74
+ and isinstance(b.get("uri"), str)]
75
+
76
+
77
+ def flatten(result: Any, *, keep: bool = False, read: Optional[Reader] = None,
78
+ max_text: int = DEFAULT_MAX_TEXT) -> Flattened:
79
+ """Return ``result`` rewritten for text-only clients, and what was changed.
80
+
81
+ ``keep=True`` leaves the original blocks in place and adds the text after them, for
82
+ clients that only ignore unknown blocks (instead of failing on them). ``read`` is used to
83
+ put the contents of ``resource_link`` targets inline; without it a link becomes a text
84
+ line naming it. ``max_text`` caps the characters of resource text put inline per block.
85
+ """
86
+ if not isinstance(result, dict):
87
+ return Flattened(result)
88
+ content = result.get("content")
89
+ if content is None:
90
+ content = []
91
+ if not isinstance(content, list):
92
+ return Flattened(result)
93
+
94
+ changes: List[Change] = []
95
+ out: List[Any] = []
96
+ for i, block in enumerate(content):
97
+ kind = block.get("type") if isinstance(block, dict) else None
98
+ if kind in PLAIN or not isinstance(block, dict) or not isinstance(kind, str):
99
+ out.append(block)
100
+ continue
101
+ new = _convert(block, kind, read, max_text)
102
+ if new is None: # a type we don't know how to say better: leave it
103
+ out.append(block)
104
+ continue
105
+ blocks, note = new
106
+ if keep:
107
+ out.append(block)
108
+ out.extend(blocks)
109
+ changes.append(Change(i, kind, note))
110
+
111
+ structured = result.get("structuredContent")
112
+ if structured is not None and not any(
113
+ isinstance(b, dict) and b.get("type") == "text" for b in content):
114
+ text = json.dumps(structured, ensure_ascii=False)
115
+ out.append(_text(text))
116
+ changes.append(Change(-1, "structuredContent", f"text block ({len(text)} chars)"))
117
+
118
+ if not changes:
119
+ return Flattened(result)
120
+ return Flattened(dict(result, content=out), changes)
121
+
122
+
123
+ # -- block conversions -------------------------------------------------------------------
124
+
125
+ def _convert(block: dict, kind: str, read: Optional[Reader], max_text: int):
126
+ if kind == "resource_link":
127
+ return _link(block, read, max_text)
128
+ if kind == "resource":
129
+ res = block.get("resource")
130
+ if not isinstance(res, dict):
131
+ return None
132
+ blocks = _contents([res], max_text)
133
+ return blocks, _describe(blocks)
134
+ if kind == "audio":
135
+ size = _size(block.get("data"))
136
+ return [_text(f"[audio: {block.get('mimeType') or 'unknown type'}"
137
+ f"{_bytes(size)}, not shown]")], "text note"
138
+ return None
139
+
140
+
141
+ def _link(block: dict, read: Optional[Reader], max_text: int):
142
+ uri = block.get("uri")
143
+ if not isinstance(uri, str):
144
+ return None
145
+ head = _link_line(block)
146
+ contents = None
147
+ if read is not None:
148
+ try:
149
+ contents = read(uri)
150
+ except Exception: # a failed read must never lose the link itself
151
+ contents = None
152
+ if not contents:
153
+ return [_text(head)], "text line"
154
+ body = _contents(contents, max_text, default_uri=uri)
155
+ if body and body[0].get("type") == "text":
156
+ body[0] = _text(head + "\n\n" + body[0]["text"])
157
+ else:
158
+ body.insert(0, _text(head))
159
+ return body, "inline contents" + _describe(body, prefix=": ")
160
+
161
+
162
+ def _link_line(block: dict) -> str:
163
+ name = block.get("title") or block.get("name")
164
+ line = f"Resource: {name} <{block['uri']}>" if name else f"Resource: <{block['uri']}>"
165
+ extras = [str(x) for x in (block.get("mimeType"), _bytes(block.get("size")).strip(", "))
166
+ if x]
167
+ if extras:
168
+ line += f" ({', '.join(extras)})"
169
+ if isinstance(block.get("description"), str) and block["description"].strip():
170
+ line += f"\n{block['description'].strip()}"
171
+ return line
172
+
173
+
174
+ def _contents(contents: List[Any], max_text: int, default_uri: str = "") -> List[dict]:
175
+ blocks: List[dict] = []
176
+ for res in contents:
177
+ if not isinstance(res, dict):
178
+ continue
179
+ uri = res.get("uri") or default_uri
180
+ mime = res.get("mimeType")
181
+ if isinstance(res.get("text"), str):
182
+ text = res["text"]
183
+ if len(text) > max_text:
184
+ text = (text[:max_text] + f"\n[... {len(res['text']) - max_text} more "
185
+ f"characters of {uri} not shown]")
186
+ # a link's single resource is already named by the line above it
187
+ label = (f"{uri} ({mime})" if mime else uri) if uri else ""
188
+ named = label and (not default_uri or len(contents) > 1)
189
+ blocks.append(_text(f"{label}:\n{text}" if named else text))
190
+ elif isinstance(res.get("blob"), str):
191
+ if isinstance(mime, str) and mime.startswith("image/") and _valid_b64(res["blob"]):
192
+ blocks.append({"type": "image", "data": res["blob"], "mimeType": mime})
193
+ else:
194
+ blocks.append(_text(f"[binary resource {uri or '(no uri)'}: "
195
+ f"{mime or 'unknown type'}{_bytes(_size(res['blob']))}, "
196
+ "not shown]"))
197
+ return blocks
198
+
199
+
200
+ def _describe(blocks: List[dict], prefix: str = "") -> str:
201
+ if not blocks:
202
+ return prefix + "nothing"
203
+ kinds = [b.get("type", "?") for b in blocks]
204
+ return prefix + " + ".join(f"{k} block" for k in kinds)
205
+
206
+
207
+ def _text(text: str) -> Dict[str, str]:
208
+ return {"type": "text", "text": text}
209
+
210
+
211
+ def _size(data: Any) -> Optional[int]:
212
+ if not isinstance(data, str):
213
+ return None
214
+ pad = data.count("=", max(0, len(data) - 2))
215
+ return max(0, len(data) * 3 // 4 - pad)
216
+
217
+
218
+ def _bytes(size: Any) -> str:
219
+ if not isinstance(size, int) or isinstance(size, bool) or size < 0:
220
+ return ""
221
+ return f", {size:,} bytes"
222
+
223
+
224
+ def _valid_b64(data: str) -> bool:
225
+ try:
226
+ base64.b64decode(data, validate=True)
227
+ return True
228
+ except (binascii.Error, ValueError):
229
+ return False
flatresult/proxy.py ADDED
@@ -0,0 +1,192 @@
1
+ """``flatresult proxy``: make every tool result readable between any MCP client and server.
2
+
3
+ The proxy starts the server and passes every message through unchanged, except the results
4
+ of the client's ``tools/call`` requests: those are rewritten with :func:`flatresult.flatten`.
5
+
6
+ When a result carries ``resource_link`` blocks, the proxy asks the server for those
7
+ resources itself (``resources/read``), holds the result until the answers are in (or
8
+ ``timeout`` seconds pass), and puts the contents inline. The client never sees those
9
+ requests. If the server says it has no ``resources`` capability, links become text lines.
10
+ """
11
+
12
+ from __future__ import annotations
13
+
14
+ import sys
15
+ import threading
16
+ from typing import Any, BinaryIO, Callable, Dict, List, Optional, TextIO, Tuple
17
+
18
+ from ._relay import Relay
19
+ from .core import DEFAULT_MAX_TEXT, flatten, links
20
+
21
+ READ_ID_PREFIX = "flatresult-read-"
22
+ # 2026-07-28 servers want this envelope (protocol version, client capabilities...) in the
23
+ # _meta of every request; the proxy copies it from the client's own tools/call.
24
+ ENVELOPE_PREFIX = "io.modelcontextprotocol/"
25
+
26
+
27
+ class _Held:
28
+ def __init__(self, msg: dict, uris: List[str]) -> None:
29
+ self.msg = msg
30
+ self.waiting = set(uris)
31
+ self.contents: Dict[str, Optional[List[dict]]] = {}
32
+ self.timer: Optional[threading.Timer] = None
33
+ self.done = False
34
+
35
+
36
+ class ResultProxy:
37
+ """The message hooks, kept apart from the process handling so they are easy to test.
38
+
39
+ ``emit`` sends a message to the client outside a hook call; the proxy needs it only when
40
+ a held result times out.
41
+ """
42
+
43
+ def __init__(self, *, keep: bool = False, inline: bool = True, max_links: int = 5,
44
+ max_text: int = DEFAULT_MAX_TEXT, timeout: float = 10.0, quiet: bool = False,
45
+ log: Optional[TextIO] = None,
46
+ emit: Optional[Callable[[dict], None]] = None) -> None:
47
+ self.keep = keep
48
+ self.inline = inline
49
+ self.max_links = max_links
50
+ self.max_text = max_text
51
+ self.timeout = timeout
52
+ self.quiet = quiet
53
+ self.log = log or sys.stderr
54
+ self.emit = emit
55
+ self.can_read: Optional[bool] = None # unknown until the server's capabilities show
56
+ self.flattened = 0
57
+ self._calls: Dict[str, Optional[dict]] = {} # client tools/call id -> its _meta
58
+ self._handshakes: set = set() # initialize / server/discover ids
59
+ self._reads: Dict[str, Tuple[_Held, str]] = {}
60
+ self._next = 0
61
+ self._lock = threading.Lock()
62
+
63
+ # -- client -> server -------------------------------------------------------------
64
+
65
+ def to_server(self, msg: dict) -> Tuple[Optional[dict], List[dict]]:
66
+ method = msg.get("method")
67
+ if "id" not in msg or not isinstance(method, str):
68
+ return msg, []
69
+ with self._lock:
70
+ if method == "tools/call":
71
+ params = msg.get("params")
72
+ meta = params.get("_meta") if isinstance(params, dict) else None
73
+ self._calls[_key(msg["id"])] = meta if isinstance(meta, dict) else None
74
+ elif method in ("initialize", "server/discover"):
75
+ self._handshakes.add(_key(msg["id"]))
76
+ return msg, []
77
+
78
+ # -- server -> client -------------------------------------------------------------
79
+
80
+ def to_client(self, msg: dict) -> Tuple[Optional[dict], List[dict]]:
81
+ """Returns (message for the client, messages for the server)."""
82
+ if "method" in msg or "id" not in msg:
83
+ return msg, []
84
+ if isinstance(msg["id"], str) and msg["id"].startswith(READ_ID_PREFIX):
85
+ return self._read_result(msg), []
86
+ key = _key(msg["id"])
87
+ with self._lock:
88
+ if key in self._handshakes:
89
+ self._handshakes.discard(key)
90
+ self._learn_capabilities(msg.get("result"))
91
+ return msg, []
92
+ if key not in self._calls:
93
+ return msg, []
94
+ meta = self._calls.pop(key)
95
+ result = msg.get("result")
96
+ uris = _unique(links(result))[: self.max_links] if self.inline else []
97
+ if not uris or self.can_read is False:
98
+ return self._flat(msg, {}), []
99
+ held = _Held(msg, uris)
100
+ requests = [self._read_request(held, uri, meta) for uri in uris]
101
+ if self.timeout > 0 and self.emit is not None:
102
+ held.timer = threading.Timer(self.timeout, self._expire, (held,))
103
+ held.timer.daemon = True
104
+ held.timer.start()
105
+ return None, requests
106
+
107
+ # -- helpers ----------------------------------------------------------------------
108
+
109
+ def _learn_capabilities(self, result: Any) -> None:
110
+ if isinstance(result, dict) and isinstance(result.get("capabilities"), dict):
111
+ self.can_read = "resources" in result["capabilities"]
112
+
113
+ def _read_request(self, held: _Held, uri: str, meta: Optional[dict]) -> dict:
114
+ self._next += 1
115
+ rid = f"{READ_ID_PREFIX}{self._next}"
116
+ self._reads[rid] = (held, uri)
117
+ params: Dict[str, Any] = {"uri": uri}
118
+ envelope = {k: v for k, v in (meta or {}).items()
119
+ if isinstance(k, str) and k.startswith(ENVELOPE_PREFIX)}
120
+ if envelope:
121
+ params["_meta"] = envelope
122
+ return {"jsonrpc": "2.0", "id": rid, "method": "resources/read", "params": params}
123
+
124
+ def _read_result(self, msg: dict) -> Optional[dict]:
125
+ with self._lock:
126
+ entry = self._reads.pop(msg["id"], None)
127
+ if entry is None:
128
+ return None # an answer to a read that timed out; the client never asked
129
+ held, uri = entry
130
+ result = msg.get("result")
131
+ contents = result.get("contents") if isinstance(result, dict) else None
132
+ held.contents[uri] = contents if isinstance(contents, list) else None
133
+ if contents is None and not self.quiet:
134
+ print(f"flatresult: can't read {uri}: {str(msg.get('error'))[:200]}",
135
+ file=self.log)
136
+ held.waiting.discard(uri)
137
+ if held.waiting or held.done:
138
+ return None
139
+ return self._release(held)
140
+
141
+ def _expire(self, held: _Held) -> None:
142
+ with self._lock:
143
+ if held.done:
144
+ return
145
+ for rid in [r for r, (h, _) in self._reads.items() if h is held]:
146
+ del self._reads[rid]
147
+ if not self.quiet:
148
+ print(f"flatresult: no answer to resources/read within {self.timeout:g}s; "
149
+ "sending the result with links as text", file=self.log)
150
+ out = self._release(held)
151
+ if self.emit is not None:
152
+ self.emit(out)
153
+
154
+ def _release(self, held: _Held) -> dict:
155
+ held.done = True
156
+ if held.timer is not None:
157
+ held.timer.cancel()
158
+ return self._flat(held.msg, held.contents)
159
+
160
+ def _flat(self, msg: dict, contents: Dict[str, Optional[List[dict]]]) -> dict:
161
+ result = msg.get("result")
162
+ flat = flatten(result, keep=self.keep, read=contents.get if contents else None,
163
+ max_text=self.max_text)
164
+ if not flat.changed:
165
+ return msg
166
+ self.flattened += 1
167
+ if not self.quiet:
168
+ print(f"flatresult: {'; '.join(str(c) for c in flat.changes)}", file=self.log)
169
+ return dict(msg, result=flat.result)
170
+
171
+
172
+ def _key(value: Any) -> str:
173
+ return repr(value) # ids may be numbers or strings; 1 and "1" are different requests
174
+
175
+
176
+ def _unique(items: List[str]) -> List[str]:
177
+ seen: Dict[str, None] = {}
178
+ for item in items:
179
+ seen.setdefault(item, None)
180
+ return list(seen)
181
+
182
+
183
+ def run(command: List[str], *, keep: bool = False, inline: bool = True, max_links: int = 5,
184
+ max_text: int = DEFAULT_MAX_TEXT, timeout: float = 10.0, quiet: bool = False,
185
+ log: Optional[TextIO] = None, stdin: Optional[BinaryIO] = None,
186
+ stdout: Optional[BinaryIO] = None) -> int:
187
+ proxy = ResultProxy(keep=keep, inline=inline, max_links=max_links, max_text=max_text,
188
+ timeout=timeout, quiet=quiet, log=log)
189
+ relay = Relay(command, to_server=proxy.to_server, to_client=proxy.to_client,
190
+ stdin=stdin, stdout=stdout, name="flatresult proxy")
191
+ proxy.emit = relay.send_to_client
192
+ return relay.run()
@@ -0,0 +1,171 @@
1
+ Metadata-Version: 2.5
2
+ Name: flatresult
3
+ Version: 0.1.0
4
+ Summary: Fix MCP tool results that clients show as empty or reject ("Unsupported response item type: resource_link"): turns structuredContent-only results, resource_link blocks, embedded resources and audio into text and image blocks every client reads, as a stdio proxy for any MCP server or one function
5
+ Project-URL: Homepage, https://github.com/srikrishnaL/kitforge/tree/main/packages/flatresult
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/flatresult/CHANGELOG.md
9
+ Author: Sri Krishna Lingamaneni
10
+ License-Expression: MIT
11
+ License-File: LICENSE
12
+ Keywords: agents,claude,content blocks,cursor,dify,embedded resource,empty result,figma mcp,goose,kiro,librechat,llm,mcp,mcp proxy,mcp server,model context protocol,no response,resource_link,structuredContent,tool results,unsupported response item type
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: mcp>=1.10; (python_version >= '3.10') and extra == 'test'
23
+ Requires-Dist: pytest>=7; extra == 'test'
24
+ Description-Content-Type: text/markdown
25
+
26
+ # flatresult
27
+
28
+ MCP tools can return more than text: `structuredContent`, `resource_link` blocks, embedded
29
+ resources and audio. Many clients only handle text and image blocks, so the result shows up
30
+ empty, gets dropped, prints as a raw struct, or fails the whole call with
31
+ `Unsupported response item type: resource_link`.
32
+
33
+ flatresult rewrites tool results into text and image blocks every client reads. It puts the
34
+ JSON of `structuredContent` in a text block when the server sent none, reads linked resources
35
+ from the server and puts their contents inline, and turns embedded resources into text (or an
36
+ image). Use it as a stdio proxy around any MCP server (no code changes, any language) or as one
37
+ function. No dependencies.
38
+
39
+ ```bash
40
+ pip install flatresult
41
+ ```
42
+
43
+ ## Quick start: any stdio server
44
+
45
+ Put `flatresult proxy --` in front of the server command in your client's config:
46
+
47
+ ```json
48
+ {
49
+ "mcpServers": {
50
+ "my-server": {
51
+ "command": "flatresult",
52
+ "args": ["proxy", "--", "npx", "-y", "@acme/mcp-server"]
53
+ }
54
+ }
55
+ }
56
+ ```
57
+
58
+ Or with `uvx`, nothing to install first: `"command": "uvx", "args": ["flatresult", "proxy", "--", ...]`.
59
+
60
+ For a remote (HTTP) server, wrap a stdio bridge such as `mcp-remote`:
61
+
62
+ ```json
63
+ {
64
+ "mcpServers": {
65
+ "figma": {
66
+ "command": "uvx",
67
+ "args": ["flatresult", "proxy", "--", "npx", "-y", "mcp-remote", "https://mcp.figma.com/mcp"]
68
+ }
69
+ }
70
+ }
71
+ ```
72
+
73
+ Each rewrite is reported on stderr (most clients show it in their MCP log):
74
+
75
+ ```text
76
+ flatresult: content[0]: resource_link -> inline contents: text block
77
+ flatresult: structuredContent: structuredContent -> text block (412 chars)
78
+ ```
79
+
80
+ ### Proxy options
81
+
82
+ | Option | What it does |
83
+ |---|---|
84
+ | `--keep` | Keep the original blocks and add the text after them, for clients that skip unknown blocks instead of failing on them. |
85
+ | `--no-inline` | Don't read linked resources; turn each link into a text line naming it. |
86
+ | `--max-links N` | Read at most N linked resources per result (default 5). The rest become text lines. |
87
+ | `--max-text CHARS` | Cut resource text put inline after CHARS characters (default 100,000), with a note saying how much was left out. |
88
+ | `--timeout SECONDS` | If the server has not answered `resources/read` by then, send the result with the links as text (default 10). |
89
+ | `--quiet` / `--log FILE` | Don't report rewrites, or append them to a file instead of stderr. |
90
+
91
+ Only the results of the client's own `tools/call` requests are touched. Everything else passes
92
+ through byte for byte. Linked resources are read with the server's own `resources/read`, so
93
+ the proxy needs no credentials of its own; the client never sees those requests. If the server
94
+ says it has no `resources` capability, links become text lines.
95
+
96
+ ## What gets rewritten
97
+
98
+ | The server sends | The client gets |
99
+ |---|---|
100
+ | `structuredContent` with no text block | a text block with its JSON (`structuredContent` is kept), as the spec asks servers to do |
101
+ | `resource_link` | `Resource: <name> <uri> (mime type, size)` and its description, plus the resource's contents when the server can read it |
102
+ | embedded text resource (`type: "resource"`, `text`) | a text block: `<uri> (<mime type>):` and the text |
103
+ | embedded image blob | an `image` block |
104
+ | other embedded blobs, `audio` | a short note: `[binary resource file:///r.pdf: application/pdf, 52,113 bytes, not shown]` |
105
+ | `text`, `image`, unknown block types | unchanged |
106
+
107
+ ## In your own client or server: one function
108
+
109
+ ```python
110
+ from flatresult import flatten
111
+
112
+ result = {"content": [], "structuredContent": {"temp": 21.5, "unit": "C"}}
113
+ flat = flatten(result)
114
+ flat.result["content"] # [{"type": "text", "text": '{"temp": 21.5, "unit": "C"}'}]
115
+ [str(c) for c in flat.changes]
116
+ # ['structuredContent: structuredContent -> text block (27 chars)']
117
+ ```
118
+
119
+ `flatten(result, keep=False, read=None, max_text=100_000)` takes a `tools/call` result (a
120
+ dict) and returns `Flattened(result, changes)`. It never changes its input, and returns the same
121
+ object when nothing needs rewriting. Pass `read`, a function from a uri to the `contents` list
122
+ of a `resources/read` result (or `None`), to put linked resources inline. `links(result)` lists
123
+ the uris to read.
124
+
125
+ To see what a result would look like, there's a command too (exit code 2 when it rewrote
126
+ something):
127
+
128
+ ```bash
129
+ echo '{"content": [{"type": "resource_link", "uri": "file:///r.txt", "name": "report"}]}' \
130
+ | flatresult check
131
+ ```
132
+
133
+ ## Limits
134
+
135
+ - It fixes what the client is given, not how the client shows it. A client that already reads
136
+ `structuredContent` or resource links gets the same data twice with `--keep`, and as text
137
+ instead of its own UI without it. Use it for clients that show nothing.
138
+ - Links are read only from the server behind the proxy. An `https://` link the server can't
139
+ read stays a text line; the proxy never fetches URLs itself.
140
+ - Binary resources other than images are not decoded (a PDF stays a note with its size).
141
+ - The proxy speaks stdio. For a remote server, put a stdio bridge such as `mcp-remote` behind it.
142
+
143
+ ## Why this exists
144
+
145
+ The spec says a tool that returns `structuredContent` SHOULD also return the JSON as text, and
146
+ that clients should handle every content type. In practice both sides skip it, and users of
147
+ one client lose the data another client shows:
148
+
149
+ - [microsoft/work-iq#240](https://github.com/microsoft/work-iq/issues/240): the hosted Work IQ
150
+ server returns `fetch` results only in `structuredContent`; Cursor shows them blank.
151
+ - [kirodotdev/Kiro#9439](https://github.com/kirodotdev/Kiro/issues/9439): every Figma MCP tool
152
+ failed with `Unsupported response item type: resource_link` (4 upvotes).
153
+ - [langgenius/dify#43451](https://github.com/langgenius/dify/issues/43451): resource_link-only
154
+ tool results are discarded.
155
+ - [anthropics/claude-ai-mcp#1086](https://github.com/anthropics/claude-ai-mcp/issues/1086) and
156
+ [anthropics/claude-code#93946](https://github.com/anthropics/claude-code/issues/93946): blobs in
157
+ embedded-resource results are dropped or rejected.
158
+ - [charmbracelet/crush#3846](https://github.com/charmbracelet/crush/issues/3846): embedded
159
+ resources render as a raw Go struct pointer.
160
+ - [microsoft/copilot-sdk#2816](https://github.com/microsoft/copilot-sdk/issues/2816),
161
+ [agentscope-ai/agentscope#2798](https://github.com/agentscope-ai/agentscope/issues/2798),
162
+ [tobi/qmd#959](https://github.com/tobi/qmd/issues/959): more clients that drop or garble
163
+ resource blocks.
164
+
165
+ Some clients have closed their reports one by one (LibreChat#15198, goose#13182, Cherry
166
+ Studio#23290), each on its own schedule. flatresult works in front of any client today, with
167
+ servers you don't control.
168
+
169
+ ## License
170
+
171
+ MIT
@@ -0,0 +1,11 @@
1
+ flatresult/__init__.py,sha256=lzT407iVGAaHnTqdNOyn0dI0N5rw37dzdyAKZlSjhj8,269
2
+ flatresult/__main__.py,sha256=E6Gls0DNz8GQK2K-kOUIx8cYhgANW_CH54VKrfCfs14,52
3
+ flatresult/_relay.py,sha256=50octZ-qImRpqRTMPbtnGjjYKwk5gQUA7W1NZAjeK1g,5821
4
+ flatresult/cli.py,sha256=hyGoyLziSMIlDnnVXTRKkDFqht_iSSTWuHrwhgSV_1c,4997
5
+ flatresult/core.py,sha256=FwrGQI97qMim-HebleTKEo-UFlw_3iV2oo9K04e4knU,8635
6
+ flatresult/proxy.py,sha256=ahDc4dNHbWxz8niltbDkwU2iowMtGl5gvNoA1bEc0DQ,8433
7
+ flatresult-0.1.0.dist-info/METADATA,sha256=KWXGDt4wuA2VHhT-3tz_xQn6K7P-vEgXDXQ3wszcITs,8249
8
+ flatresult-0.1.0.dist-info/WHEEL,sha256=2iZrJkDIkeDh0k9SikKMqFuRP-ua6mb4Ir1AsER4BEw,87
9
+ flatresult-0.1.0.dist-info/entry_points.txt,sha256=uev12K7hMHygxgVy68fHJ0osIb3QLeHTZEvI51HVKwU,51
10
+ flatresult-0.1.0.dist-info/licenses/LICENSE,sha256=fl9U1idgeyJw-8GWneEYxVzZM_C29cBR63IAlNv7KjE,1080
11
+ flatresult-0.1.0.dist-info/RECORD,,
@@ -0,0 +1,4 @@
1
+ Wheel-Version: 1.0
2
+ Generator: hatchling 1.33.0
3
+ Root-Is-Purelib: true
4
+ Tag: py3-none-any
@@ -0,0 +1,2 @@
1
+ [console_scripts]
2
+ flatresult = flatresult.cli:main
@@ -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.