Skip to content

mcp: a malformed JSON frame terminates the stdio session #1209

Open

Description

@blackwell-systems

Describe the bug

The stdio transport ends the entire session on a single syntactically malformed JSON-RPC frame, instead of replying with a JSON-RPC parse error (-32700) and continuing. Any client that sends one malformed frame terminates the session.

Root cause: newIOConn reads from a single streaming json.Decoder over stdin. A malformed frame makes Decode return a *json.SyntaxError; the read goroutine returns on that error, ending the connection. A streaming decoder also cannot resynchronize after a syntax error, since its buffered stream state is poisoned.

This is the transport-level cousin of #976 (empty-method requests), fixed in #1000. mark3labs/mcp-go handles the same input correctly: it reads newline-delimited frames, unmarshals each independently, and on a bad frame replies -32700 and keeps serving.

To Reproduce

  1. Start any stdio server (e.g. conformance/everything-server).
  2. Complete the initialize handshake.
  3. Send a syntactically invalid frame, e.g. {bad json followed by a newline.
  4. The session ends: no -32700 is returned, and later valid requests get no response.

Minimal transport-level repro:

tr := newIOConn(rwc{rc: io.NopCloser(strings.NewReader(
    "{bad\n" + `{"jsonrpc":"2.0","id":1,"method":"ping"}` + "\n"))})
_, err := tr.Read(context.Background())
// returns the decode error; the following valid "ping" is never read.

Expected behavior

Per JSON-RPC 2.0, a malformed frame should be answered with a -32700 parse error (id: null) and the session should continue: the read loop resynchronizes to the next frame and delivers the following valid request. This matches mark3labs/mcp-go and the recoverable-decode direction of #1000.

Additional context

Tested v1.4.1 through v1.7.0 (latest); behavior is unchanged. Surfaced by an MCP conformance study run against a downstream server (blackwell-systems/agent-lsp#14); because the behavior lives in the shared stdio transport, every server built on the SDK's stdio transport exhibits it.

I have a fix ready (reply -32700, resync to the next newline-delimited frame, terminate only on a genuine EOF/I/O error, with tests) and will open a PR referencing this issue.

Activity

  1. serverplumber commented on Sep 27, 2026

    @serverplumber

    Confirming this is still present in v1.8.0-pre.2. Two findings below go beyond the issue: answers to requests the server has already received are lost too, and #1210 as it stands (3906b01) leaves part of this open.

    Still present after v1.7.0

    conformance/everything-server built from v1.8.0-pre.2 exits on the first malformed line:

    go build -o everything-server github.com/modelcontextprotocol/go-sdk/conformance/everything-server
    
    INIT='{"jsonrpc":"2.0","id":1,"method":"initialize","params":{"protocolVersion":"2025-11-25","capabilities":{},"clientInfo":{"name":"repro","version":"0"}}}'
    NOTE='{"jsonrpc":"2.0","method":"notifications/initialized"}'
    P2='{"jsonrpc":"2.0","id":2,"method":"ping"}'
    P3='{"jsonrpc":"2.0","id":3,"method":"ping"}'
    
    # one line every 0.5s
    { for l in "$INIT" "$NOTE" "$P2" '{bad json' "$P3"; do echo "$l"; sleep 0.5; done; sleep 1; } | ./everything-server

    initialize and ping 2 are answered, then Server failed: invalid character 'b' looking for beginning of object key string and exit 1. Ping 3 is never answered and no -32700 is sent, as the issue describes.

    Answers already owed are lost too

    Sending the same lines all at once:

    { printf '%s\n' "$INIT" "$NOTE" "$P2" '{bad json' "$P3"; sleep 1; } | ./everything-server

    Across three runs the server wrote 0, 0 and 1 of the two answers it owed (initialize and ping 2), both for requests that arrived before the malformed line. The read error closes the session while those handlers are still running, and their replies are never written. Which ones survive depends on timing. So a client can't rely on "earlier requests are answered" either. From outside I can't tell whether the connection closing or the process exiting is what drops them.

    What #1210 fixes, and what it leaves open

    I built everything-server from the PR head (3906b01) and ran a set of single bad frames between ping 2 and ping 3, both paced and all at once (three runs each). The script is below.

    Bad frame v1.8.0-pre.2 #1210
    JSON syntax error: {bad json, an unbalanced object, a NUL byte, nesting 11000 deep session ends; earlier answers lost when frames arrive together session survives, all three pings answered, but -32700 is sent twice for each malformed frame, in every run
    valid JSON that is not a JSON-RPC message: 42, {}, [] session ends, no reply; earlier answers lost unchanged: session ends, no reply, earlier answers lost
    an object with an id and no method survives, no reply survives, no reply
    • The duplicate -32700. One malformed frame should get one error. My guess, from reading the diff rather than tracing it: the resync reads from dec.Buffered(), and when that starts at the newline ending the previous frame, ReadBytes('\n') consumes only that newline. The malformed frame is then decoded, and answered, a second time.
    • Valid JSON that isn't JSON-RPC. These decode without a syntax error and fail later, in readBatch. Read still returns that error, and the session ends exactly as before. JSON-RPC 2.0's own examples answer 1 and [] with -32600 Invalid Request and "id": null, and the server should keep serving after that just as after a parse error.
    • An id with no method is at least not fatal, before or after the PR. It goes unanswered where -32600 would be expected. That's closer to Stdio server leaves some malformed JSON-RPC requests unanswered while the session remains alive #976 than to this issue.

    A test that would cover all of it: for each bad frame above, the all-at-once input yields the initialize result, pong 2, exactly one error (-32700 for a syntax error, -32600 for the rest), and pong 3, on every run.

    Reproduction script (pass the server binary as the argument)
    import subprocess, sys, time, json
    INIT='{"jsonrpc":"2.0","id":1,"method":"initialize","params":{"protocolVersion":"2025-11-25","capabilities":{},"clientInfo":{"name":"repro","version":"0"}}}'
    NOTE='{"jsonrpc":"2.0","method":"notifications/initialized"}'
    P2='{"jsonrpc":"2.0","id":2,"method":"ping"}'
    P3='{"jsonrpc":"2.0","id":3,"method":"ping"}'
    BAD = {
      "syntax {bad json":   b'{bad json',
      "unbalanced": b'{"jsonrpc":"2.0","id":9,"method":"ping"',
      "number 42":          b'42',
      "empty object {}":    b'{}',
      "empty batch []":     b'[]',
      "id, no method":      b'{"jsonrpc":"2.0","id":9}',
      "NUL byte":           b'{"jsonrpc":"2.0",\x00"id":9,"method":"ping"}',
      "nesting 11000":      b'[' * 11000,
    }
    def run(binary, bad, paced):
        p = subprocess.Popen([binary], stdin=subprocess.PIPE, stdout=subprocess.PIPE, stderr=subprocess.PIPE)
        lines = [INIT.encode(), NOTE.encode(), P2.encode(), bad, P3.encode()]
        try:
            if paced:
                for l in lines:
                    p.stdin.write(l + b'\n'); p.stdin.flush(); time.sleep(0.3)
            else:
                p.stdin.write(b'\n'.join(lines) + b'\n'); p.stdin.flush()
            time.sleep(1.0)
        except BrokenPipeError:
            pass
        try: p.stdin.close()
        except Exception: pass
        try: out, err = p.communicate(timeout=5)
        except subprocess.TimeoutExpired:
            p.kill(); out, err = p.communicate()
        ids, perr = [], 0
        for line in out.splitlines():
            try: m = json.loads(line)
            except Exception: continue
            if m.get("error", {}).get("code") == -32700: perr += 1
            elif "id" in m: ids.append(m["id"])
        return ids, perr, p.returncode
    binary = sys.argv[1]
    if True:
        for label, bad in BAD.items():
            paced = run(binary, bad, True)
            burst = [run(binary, bad, False) for _ in range(3)]
            fmt = lambda r: f"ids={r[0]} -32700x{r[1]} exit={r[2]}"
            print(f"{label:22} paced: {fmt(paced)}")
            print(f"{'':22} burst: " + " | ".join(f"{r[0]} x{r[1]} e{r[2]}" for r in burst))

    A downstream server shows the same behaviour

    github/github-mcp-server v1.12.2, built on go-sdk v1.7.0, exits the same way on a malformed stdio frame (error running server: invalid character '{' after object key:value pair).

    Streamable HTTP is unaffected

    The same binary run with --http answers the same malformed body with 400 (malformed payload: unmarshaling jsonrpc message: …), answers the next ping with 200, and keeps serving. So the fault is specific to the stdio transport's read path.

    #1210 is the right direction and would be good to get reviewed. It has been waiting about a month and now conflicts with main. The duplicate reply and the non-JSON-RPC frames seem worth covering before it lands.

  2. serverplumber commented on Nov 3, 2026

    @serverplumber

    Thanks @jmrplens and @Ahmad-Faraj for your input on #1210

    @blackwell-systems all this could go into #1210

    I wrote regression tests for this. They cover the cases from my earlier comments and the bad-frame cases @jmrplens provided. His -32601 and -32602 cases are left out and {"hello":"world"} isn't included.

    The tests drive a real Server over stdio pipes and check 4 things:

    • that each bad frame gets exactly one error;
    • initialize, ping 2 and ping 3 are all answered
    • a reply already in flight survives the bad frame (middleware holds ping 2 until ping 3 arrives, so this doesn't depend on timing)
    • a blank line gets no reply.

    Two tests check that ioConn resynchronises after a bad frame and reaches EOF cleanly.
    A third tests oversized frames TestIOConnOversizedFrame.
    The session tests fail for every bad frame on main (3a46369).

    Before moving forward I'd need the maintainers to decide on the following behaviours:

    1. The error id. The tests expect error replies to omit id, since MCP's JSONRPCErrorResponse allows a string or a number but not null, unlike JSON-RPC 2.0. This includes {"jsonrpc":"2.0","id":9} whose id names one of the server's own requests. Is that correct?
    2. Replies owed at EOF. Should replies be written when stdin closes with handlers still running?

    Oversized frames. I believe a frame over MaxLineLength should be discarded without buffering, answered with an error and we keep reading. TestIOConnFrameCap still holds, since Read still reports errFrameTooLarge. However "cap does not reset per new line" case would need changing. It assumes values can span lines but the spec says "MUST NOT contain embedded newlines".

    I can write a test for 2 once I get a reply and I'll update 1 if need be.

    Links to the specs:

    1. The error id
    1. Replies owed at EOF

    Oversized frames

    AI disclosure: Claude wrote most of the test code and drafted this comment. I directed it, reviewed the results, and decided the expected behaviour.

  3. aibeshkov commented on Nov 16, 2026

    @aibeshkov

    Same root cause, with one more consequence on the input side: the read side is a streaming json.Decoder, so a frame is not delimited by its newline at all. A line that is incomplete JSON (for example a truncated frame) is not rejected at the newline; the decoder keeps reading and absorbs the following line(s) into the same value. The next, valid request is then never answered, and any resulting decode error ends the session as described here.

    Observed on v1.8.0 with an mcp.IOTransport over io.Pipe (initialize handshake, then a truncated line followed by a valid ping): the ping gets no response.

    Reading newline-delimited frames and decoding each line independently would fix both this and the original report: a bad frame gets -32700 and the next line is read normally. The behaviour is trusted-client only (the client has to send the truncated line), so this is robustness and spec conformance rather than a security issue.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Type

    No type

    Projects

    No projects

      Milestone

      No milestone

      Relationships

      None yet

      Development

      No branches or pull requests

      Issue actions