fix: improve error handling and add guard check to deserializeMessage #1225
+143 −15
Add this suggestion to a batch that can be applied as a single commit. This suggestion is invalid because no changes were made to the code. Suggestions cannot be applied while the pull request is closed. Suggestions cannot be applied while viewing a subset of changes. Only one suggestion per line can be applied in a batch. Add this suggestion to a batch that can be applied as a single commit. Applying suggestions on deleted lines is not supported. You must change the existing code in this line in order to create a valid suggestion. Outdated suggestions cannot be applied. This suggestion has been applied or marked resolved. Suggestions cannot be applied from pending reviews. Suggestions cannot be applied on multi-line comments. Suggestions cannot be applied while the pull request is queued to merge. Suggestion cannot be applied right now. Please check back later.
This PR adds a guard check to the MCP TypeScript SDK’s stdio message deserialization logic to prevent JSON parsing errors when non-JSON RPC lines are received on the stdio stream.
Motivation and Context
The MCP SDK currently assumes that every line received over stdio is a valid JSON-RPC message.
However, there are scenarios where non-JSON or otherwise invalid JSON RPC data may be written to stdout
whether from the runtime environment, external tooling, or other processes that share the same output stream.
When these invalid messages reach the SDK, the deserializer attempts to parse them and throws a SyntaxError, which impacts overall stability.
This update adds a safeguard that gracefully skips any line that is not valid JSON, making the stdio transport more robust and tolerant of incidental or malformed output on the stream.
How Has This Been Tested?
I added a unit test covering this scenario to ensure that non-JSON RPC valid input is gracefully ignored by the stdio transport.
I'm going to build the MCP Inspector against the RC version of this fix and verify that the issue is no longer reproducible and that invalid JSON-RPC messages are handled safely without causing errors.
Breaking Changes
None.
This change is fully backward compatible
Types of changes
Checklist
Additional context
reference to the issue #700