From 1a58ee947ff21f68b15d1f111b58f00f26366fc5 Mon Sep 17 00:00:00 2001 From: Nova Date: Thu, 3 Dec 2026 22:46:13 +0700 Subject: [PATCH 1/3] feat: Emit Unicode CLI JSON on UTF streams MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Use the declared stdout codec to preserve literal Unicode on UTF streams. Keep ASCII escapes when stdout uses a legacy encoding or does not declare one. Exercise the café example through real text streams, including a Windows UTF-8 alias and a legacy code page. Refs #334 --- src/semble/cli.py | 6 +++++- tests/test_cli.py | 32 +++++++++++++++++++++++++++++++- 2 files changed, 36 insertions(+), 2 deletions(-) diff --git a/src/semble/cli.py b/src/semble/cli.py index b625a043a..13dc6c5af 100644 --- a/src/semble/cli.py +++ b/src/semble/cli.py @@ -1,5 +1,6 @@ import argparse import asyncio +import codecs import io import json import logging @@ -172,7 +173,10 @@ def _load_index(paths: list[str], content: list[ContentType]) -> tuple[SembleInd def _print_results(out: dict, output_format: str) -> None: """Print a format_results() payload as JSON or as human-readable text.""" if output_format == "json": - print(json.dumps(out)) + # Legacy encodings may reject or alter non-ASCII characters, so keep their JSON ASCII-only. + encoding = getattr(sys.stdout, "encoding", "") or "" + ensure_ascii = not encoding or not codecs.lookup(encoding).name.startswith("utf") + print(json.dumps(out, ensure_ascii=ensure_ascii)) elif "error" in out: print(out["error"]) else: diff --git a/tests/test_cli.py b/tests/test_cli.py index 716610139..42909d6cd 100644 --- a/tests/test_cli.py +++ b/tests/test_cli.py @@ -1,5 +1,6 @@ import asyncio import hashlib +import io import json import signal import sys @@ -10,8 +11,9 @@ import pytest -from semble.cli import _cli_main, _maybe_save_index, _run_clear, main +from semble.cli import _cli_main, _maybe_save_index, _print_results, _run_clear, main from semble.types import ContentType, SearchResult +from semble.utils import format_results from semble.version import __version__ from tests.conftest import make_chunk @@ -156,6 +158,34 @@ def test_main_dispatches_to_cli( assert "query text" in capsys.readouterr().out +@pytest.mark.parametrize( + ("encoding", "expected"), + [ + ("utf-8", "café 咖啡"), + ("utf-16", "café 咖啡"), + ("cp65001", "café 咖啡"), + ("cp1251", r"caf\u00e9 \u5496\u5561"), + (None, r"caf\u00e9 \u5496\u5561"), + ], +) +def test_print_results_json_respects_stdout_encoding( + encoding: str | None, expected: str, monkeypatch: pytest.MonkeyPatch +) -> None: + """CLI JSON uses literal Unicode for UTF streams and ASCII escapes otherwise.""" + chunk = make_chunk('def cafe():\n return "café 咖啡"', "example.py") + payload = format_results("cafe", [SearchResult(chunk=chunk, score=0.9)]) + buffer = io.BytesIO() + stdout = io.StringIO() if encoding is None else io.TextIOWrapper(buffer, encoding=encoding) + with buffer, stdout, monkeypatch.context() as streams: + streams.setattr(sys, "stdout", stdout) + _print_results(payload, "json") + stdout.flush() + text = stdout.getvalue() if isinstance(stdout, io.StringIO) else buffer.getvalue().decode(stdout.encoding) + + assert expected in text + assert json.loads(text) == payload + + @pytest.mark.parametrize( ("argv", "expected_stdout", "expect_system_exit"), [ From 0fc5b46f77dd6785d8d277938f850a25fa2848a0 Mon Sep 17 00:00:00 2001 From: Nova Date: Thu, 3 Dec 2026 22:47:27 +0700 Subject: [PATCH 2/3] feat: Emit literal Unicode in MCP JSON results MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Use ensure_ascii=False for search and find_related JSON responses. MCP transports encode tool responses as UTF-8, so the terminal encoding does not constrain their text. Use the cafe example to verify both tools expose literal café in the raw response. Checking decoded JSON alone would also pass with escaped output. Refs #334 --- src/semble/mcp.py | 9 +++++---- tests/test_mcp.py | 14 +++++++------- 2 files changed, 12 insertions(+), 11 deletions(-) diff --git a/src/semble/mcp.py b/src/semble/mcp.py index 63af97aff..88c70501d 100644 --- a/src/semble/mcp.py +++ b/src/semble/mcp.py @@ -119,9 +119,10 @@ async def search( except ValueError as exc: return str(exc) results = index.search(query, top_k=top_k, max_snippet_lines=max_snippet_lines) + # MCP transports encode tool responses as UTF-8 regardless of the terminal encoding. if not results: - return json.dumps({"error": "No results found."}) - return json.dumps(format_results(query, results, max_snippet_lines, index.sources)) + return json.dumps({"error": "No results found."}, ensure_ascii=False) + return json.dumps(format_results(query, results, max_snippet_lines, index.sources), ensure_ascii=False) @server.tool() async def find_related( @@ -166,9 +167,9 @@ async def find_related( ) results = index.find_related(chunk, top_k=top_k, max_snippet_lines=max_snippet_lines) if not results: - return json.dumps({"error": f"No related chunks found for {file_path}:{line}."}) + return json.dumps({"error": f"No related chunks found for {file_path}:{line}."}, ensure_ascii=False) label = f"Chunks related to {file_path}:{line}" - return json.dumps(format_results(label, results, max_snippet_lines, index.sources)) + return json.dumps(format_results(label, results, max_snippet_lines, index.sources), ensure_ascii=False) return server diff --git a/tests/test_mcp.py b/tests/test_mcp.py index 52cbc7b6b..459967165 100644 --- a/tests/test_mcp.py +++ b/tests/test_mcp.py @@ -297,11 +297,11 @@ async def test_tool_index_failure(cache: _IndexCache, tool: str, args: dict[str, [ pytest.param( "search", - {"query": "bar", "repo": "/some/path"}, + {"query": "cafe", "repo": "/some/path"}, "search", - [SearchResult(chunk=make_chunk("def bar(): pass", "src/bar.py"), score=0.9)], + [SearchResult(chunk=make_chunk('def cafe():\n return "café 咖啡"', "example.py"), score=0.9)], None, - ["bar", "0.9"], + ["example.py", "0.9", "café 咖啡"], id="search_with_results", ), pytest.param( @@ -315,11 +315,11 @@ async def test_tool_index_failure(cache: _IndexCache, tool: str, args: dict[str, ), pytest.param( "find_related", - {"file_path": "src/foo.py", "line": 1, "repo": "/some/path"}, + {"file_path": "src/seed.py", "line": 1, "repo": "/some/path"}, "find_related", - [SearchResult(chunk=make_chunk("class Foo: pass", "src/foo.py"), score=0.8)], - [make_chunk("class Foo: pass", "src/foo.py")], - ["src/foo.py:1", "0.8"], + [SearchResult(chunk=make_chunk('def cafe():\n return "café 咖啡"', "example.py"), score=0.8)], + [make_chunk("def seed(): pass", "src/seed.py")], + ["example.py", "src/seed.py:1", "0.8", "café 咖啡"], id="find_related_with_results", ), pytest.param( From 5aed5ce8445bc5dbe1e05c2e10791aefd97c7f1d Mon Sep 17 00:00:00 2001 From: Pringled Date: Fri, 4 Dec 2026 07:06:40 +0100 Subject: [PATCH 3/3] chore: simplify encoding check and tests --- src/semble/cli.py | 3 +-- src/semble/mcp.py | 1 - tests/test_cli.py | 20 +++++++------------- tests/test_mcp.py | 6 +++--- 4 files changed, 11 insertions(+), 19 deletions(-) diff --git a/src/semble/cli.py b/src/semble/cli.py index 13dc6c5af..061208cd3 100644 --- a/src/semble/cli.py +++ b/src/semble/cli.py @@ -174,8 +174,7 @@ def _print_results(out: dict, output_format: str) -> None: """Print a format_results() payload as JSON or as human-readable text.""" if output_format == "json": # Legacy encodings may reject or alter non-ASCII characters, so keep their JSON ASCII-only. - encoding = getattr(sys.stdout, "encoding", "") or "" - ensure_ascii = not encoding or not codecs.lookup(encoding).name.startswith("utf") + ensure_ascii = not codecs.lookup(sys.stdout.encoding or "ascii").name.startswith("utf") print(json.dumps(out, ensure_ascii=ensure_ascii)) elif "error" in out: print(out["error"]) diff --git a/src/semble/mcp.py b/src/semble/mcp.py index 88c70501d..fb3b7ba4b 100644 --- a/src/semble/mcp.py +++ b/src/semble/mcp.py @@ -119,7 +119,6 @@ async def search( except ValueError as exc: return str(exc) results = index.search(query, top_k=top_k, max_snippet_lines=max_snippet_lines) - # MCP transports encode tool responses as UTF-8 regardless of the terminal encoding. if not results: return json.dumps({"error": "No results found."}, ensure_ascii=False) return json.dumps(format_results(query, results, max_snippet_lines, index.sources), ensure_ascii=False) diff --git a/tests/test_cli.py b/tests/test_cli.py index 42909d6cd..1e923a86f 100644 --- a/tests/test_cli.py +++ b/tests/test_cli.py @@ -162,26 +162,20 @@ def test_main_dispatches_to_cli( ("encoding", "expected"), [ ("utf-8", "café 咖啡"), - ("utf-16", "café 咖啡"), ("cp65001", "café 咖啡"), ("cp1251", r"caf\u00e9 \u5496\u5561"), - (None, r"caf\u00e9 \u5496\u5561"), ], ) def test_print_results_json_respects_stdout_encoding( - encoding: str | None, expected: str, monkeypatch: pytest.MonkeyPatch + encoding: str, expected: str, monkeypatch: pytest.MonkeyPatch ) -> None: """CLI JSON uses literal Unicode for UTF streams and ASCII escapes otherwise.""" - chunk = make_chunk('def cafe():\n return "café 咖啡"', "example.py") - payload = format_results("cafe", [SearchResult(chunk=chunk, score=0.9)]) - buffer = io.BytesIO() - stdout = io.StringIO() if encoding is None else io.TextIOWrapper(buffer, encoding=encoding) - with buffer, stdout, monkeypatch.context() as streams: - streams.setattr(sys, "stdout", stdout) - _print_results(payload, "json") - stdout.flush() - text = stdout.getvalue() if isinstance(stdout, io.StringIO) else buffer.getvalue().decode(stdout.encoding) - + payload = format_results("cafe", [SearchResult(chunk=make_chunk('return "café 咖啡"', "example.py"), score=0.9)]) + stdout = io.TextIOWrapper(io.BytesIO(), encoding=encoding) + monkeypatch.setattr(sys, "stdout", stdout) + _print_results(payload, "json") + stdout.flush() + text = stdout.buffer.getvalue().decode(encoding) assert expected in text assert json.loads(text) == payload diff --git a/tests/test_mcp.py b/tests/test_mcp.py index 459967165..584a89c35 100644 --- a/tests/test_mcp.py +++ b/tests/test_mcp.py @@ -315,11 +315,11 @@ async def test_tool_index_failure(cache: _IndexCache, tool: str, args: dict[str, ), pytest.param( "find_related", - {"file_path": "src/seed.py", "line": 1, "repo": "/some/path"}, + {"file_path": "src/foo.py", "line": 1, "repo": "/some/path"}, "find_related", [SearchResult(chunk=make_chunk('def cafe():\n return "café 咖啡"', "example.py"), score=0.8)], - [make_chunk("def seed(): pass", "src/seed.py")], - ["example.py", "src/seed.py:1", "0.8", "café 咖啡"], + [make_chunk("class Foo: pass", "src/foo.py")], + ["example.py", "src/foo.py:1", "0.8", "café 咖啡"], id="find_related_with_results", ), pytest.param(