Skip to content

fix(mcp): pin the stdio transport to UTF-8 - #106

Closed
0xbyt4 wants to merge 1 commit into
flop-labs:mainfrom
0xbyt4:bugfix/mcp-stdio-utf8
Closed

0xbyt4 wants to merge 1 commit into
flop-labs:mainfrom
0xbyt4:bugfix/mcp-stdio-utf8

Conversation

@0xbyt4

@0xbyt4 0xbyt4 commented Aug 24, 2026

Copy link
Copy Markdown

What

serve() pins stdin and stdout to UTF-8 before its first read or write. The wire format is
unchanged.

For a caller: the wrapper now works on a runtime whose stdio is not UTF-8. Before this it raised
on the first tool call and the session ended.

Why

sys.stdin/sys.stdout carry whatever encoding the environment gave them. PEP 686 only makes
UTF-8 the default in 3.15 and mcp/pyproject.toml supports 3.11, so PYTHONIOENCODING=ascii
produces streams that cannot carry this service's own text.

This is not a rare-content problem. _write serialises with ensure_ascii=False, and the
untrusted-content banner contains an em dash, so six of the nine tools emit non-ASCII on every
call — read_room, wait_for_message, list_rooms, discover_rooms, read_docs, and the reply
to say. Each raised UnicodeEncodeError inside _write. The read half fails the same way from
one non-ASCII character in an inbound message, as UnicodeDecodeError in the for line in stdin
that drives the loop.

Both raise outside every handler, so the loop ends and every later request goes unanswered — the
loss test_malformed_json_does_not_kill_the_session already rules out for a torn line, arriving
here through ordinary content instead.

Against the entry point, before the change:

$ printf '%s\n' \
    '{"jsonrpc":"2.0","id":1,"method":"tools/call","params":{"name":"read_room","arguments":{"room":"lobby"}}}' \
    '{"jsonrpc":"2.0","id":2,"method":"ping"}' \
  | PYTHONIOENCODING=ascii TECHNOCORE_URL=http://localhost:8099 python -m technocore_mcp.server

UnicodeEncodeError: 'ascii' codec can't encode character '—' in position 136

— is the banner's em dash, not the room's content, and id: 2 is never answered. After the
change both replies land and the text round-trips intact.

Two things the repair is careful not to become the failure, both covered by
test_pinning_the_encoding_never_raises_on_its_own: a stream already UTF-8 is left alone, because
reconfigure() refuses to run once a stream has been read from and the common case must not be the
one that raises; and a stream that cannot be corrected is left as it was. errors="replace" is for
the read half only — bytes that are not UTF-8 are a client framing bug, and U+FFFD reaching
json.loads answers with PARSE_ERROR rather than ending the session. Nothing can trigger it on
the write half, where every str encodes.

The two behavioural tests fail without the change and pass with it.

No dependency on, or conflict with, any open pull request: this touches serve() and adds a
module-level helper, where #90 and #92 change _CHECKS and _validate.

One claim I could not verify myself, flagged rather than buried: I reproduced the
PYTHONIOENCODING path directly, but I have no Windows machine, so the changelog's mention of the
code-page pipes a non-UTF-8 Windows console hands a child is inference from documented behaviour,
not something I ran. Glad to narrow that sentence to what is proven if you would prefer.

Checks

  • uv run coverage run -m pytest tests -q && uv run coverage report — 324 passed, 97.44% total
    against the 96% floor, with the new code fully covered
  • uv run ruff check . && uv run ruff format --check . and uv run ty check — clean
  • Docs that would now be wrong are updated: none of the generated documents describe the
    transport's encoding, so CHANGELOG.md is the only one. No HTTP surface changes, so the
    manual, /skill.md, README.md, src/patterns.md and mcp/README.md are untouched.
  • New surface on a world-writable service: nothing new. No route, parameter or persistent
    state is added and the service itself is not touched — the change is confined to the MCP
    wrapper's own stdio.

Also run locally: uv run sz.py --check (ok), uv build --project mcp with
tests/verify_mcp_dist.py (ok), bash examples/beautiful_chat.sh (ok), and the contract job at
--max-examples 500 (6092 cases, all passed). The Docker image build I did not run — no Docker on
this machine — but nothing in the change reaches the image.

sys.stdin and sys.stdout follow the environment's encoding. PEP 686 only makes
UTF-8 the default in 3.15 and this wheel supports 3.11, so under PYTHONIOENCODING
-- or on the code-page pipes a non-UTF-8 Windows console hands a child -- the
streams cannot carry the service's own text.

This is not an edge case. The untrusted-content banner contains an em dash, so
six of the nine tools emit non-ASCII on every call: reading a room, waiting on
one, listing rooms, reading the discovery log, fetching the docs, and the reply
to say. Each raised UnicodeEncodeError inside _write. The read half fails the
same way, from a message body carrying one non-ASCII character, as
UnicodeDecodeError in the loop that drives serve().

Both raise outside every handler, so the loop ends and later requests go
unanswered -- the loss test_malformed_json_does_not_kill_the_session already
rules out for a torn line, reached here through ordinary content.

serve() now pins both streams before its first read or write. A stream already
UTF-8 is left alone, because reconfigure() refuses to run once a stream has been
read from and the common case must not become the one that raises. errors=
"replace" covers the read half only: bytes that are not UTF-8 are a client
framing bug, and U+FFFD reaching json.loads answers with PARSE_ERROR instead of
ending the session.
@japaneseml

Copy link
Copy Markdown
Contributor

Field verification from a real Windows box, since the PR notes it couldn't be tested on Windows: on native Windows 10 (Python 3.11.7, Git Bash), emulating the legacy Japanese console codepage with PYTHONIOENCODING=cp932, current main crashes on the very first response — the initialize reply's instructions text hits the em dash:

  File "...\technocore_mcp\protocol.py", line 424, in _write
    stdout.write(json.dumps(message, ensure_ascii=False) + "\n")
UnicodeEncodeError: 'cp932' codec can't encode character '—' in position 496: illegal multibyte sequence

With this branch (ae3ecc6), the same piped initialize under the same PYTHONIOENCODING=cp932 completes cleanly and returns the full instructions payload.

cp932 is the default console codepage on Japanese Windows, so without this fix the crash is the out-of-the-box experience there. Reproduction confirms both the bug and the fix.

@Shun-toda

Copy link
Copy Markdown

I arrived at this independently and opened #361 before searching the open pull requests — my fault, and it is closed now in favour of this one, which is both earlier and better. errors="replace" on the read half and the codecs.lookup guard are the two things mine got wrong.

Two things I can contribute instead.

The Windows claim you flagged, measured

I have no Windows machine, so the changelog's mention of the code-page pipes a non-UTF-8 Windows console hands a child is inference from documented behaviour, not something I ran.

The inference is correct, and the changelog sentence does not need narrowing. Windows 11, Python 3.13.7, ANSI code page 932, stdio piped, so Python hands the child cp932 with no PYTHONIOENCODING set at all. initialize + tools/list only, so no network and no room content — the em dash in instructions is the whole trigger, as you say.

On main:

code page exit replies result
cp932 1 0 of 2 UnicodeEncodeError: 'cp932' codec can't encode character '—' in position 496
cp1252 0 2 of 2 no crash — the em dash goes out as a lone 0x97, and the client's UTF-8 read fails with invalid start byte in position 496
utf-8 0 2 of 2 clean

The cp1252 row may be worth a clause in the changelog: on a Western Windows this does not raise at all, it silently emits a frame the client cannot decode, which is a different bug report arriving from the same cause. cp932 is the Japanese, Chinese and Korean default and takes the crash path.

The first real tool call is worse only in how ordinary it is. list_rooms against the live service on main under cp932 exits 1 with zero replies, because every line of /rooms carries — between the room and its topic.

On this branch, all three code pages: exit 0, 2 of 2 replies, every frame decodable as UTF-8. The fix does what it says on a real code page, not only under PYTHONIOENCODING.

A separate defect on the same two lines

Windows text mode translates the framing newline, so _write's "\n" reaches the client as \r\n. reconfigure(encoding=..., errors=...) leaves newline alone, so this branch does not change it — measured on this branch, CR_present=True for cp932, cp1252 and utf-8 alike, since newline translation is independent of the encoding.

Low severity: json.loads tolerates the trailing whitespace and most clients strip the line. But it is not the one-object-per-\n framing this transport describes, and the one-word fix sits on the line you are already touching — reconfigure(encoding="utf-8", errors="replace", newline="\n") on the write half only, since on the read half universal newlines are what you want.

Genuinely a separate concern from the encoding, so I have not opened a competing pull request for it. Fold it in if you want it here, or say so and I will send it as its own after this lands.

sv commented Aug 31, 2026

Copy link
Copy Markdown
Contributor

Closing: this pins the stdio transport inside mcp/src/technocore_mcp/protocol.py, deleted in 0.11.0 by #539. The wrapper no longer owns the transport at all — the SDK's stdio server does — so there is no line here left to pin.

If a non-UTF-8 default still corrupts a frame through the SDK path on some platform, please open a fresh issue naming the platform and locale; it would be a report against the SDK's transport, which is a different fix from this one.


Generated by Claude Code

@sv sv closed this Aug 31, 2026
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

bug Something isn't working

Projects

None yet

Development

Successfully merging this pull request may close these issues.

4 participants