Resolved

FastMCP sampling validation errors and JSON-RPC protocol corruption

FastMCP
JSON-RPC
Pydantic
Middleware
Debugging

The system encountered validation errors when constructing sampling messages with raw strings and JSON-RPC protocol corruption due to mixed stdout output, preventing effective communication between client and server.

A FastMCP-based system relied on multi-turn conversations and JSON-RPC protocol for communication. However, it encountered two critical failures: validation errors in sampling messages and protocol corruption due to stdout interference.

Issue

The system exhibited two main issues:

  1. Validation Errors: Pydantic validation errors occurred when constructing SamplingMessage objects with raw strings instead of structured content types, resulting in errors like "Input should be a valid dictionary or instance of TextContent."
  2. JSON-RPC Protocol Corruption: Debug output from middleware print() statements mixed emoji and text with JSON-RPC protocol messages, causing the client to fail parsing valid JSON-RPC messages.

Culprit

The root causes included:

  • Improper Message Construction: Manual construction of SamplingMessage objects with raw strings violated Pydantic’s validation requirements.
  • Middleware stdout Interference: Direct print() statements to stdout corrupted the JSON-RPC protocol, as MCP uses stdio transport for communication.

Solution

FastMCP Automatic Message Handling

Leveraged FastMCP’s built-in message handling to ensure proper validation and structure. Plain strings were passed to ctx.sample(), allowing FastMCP to automatically wrap them in valid SamplingMessage objects and manage content type conversion.

MCP-Compliant Logging

Replaced all direct stdout/stderr print() statements with context-based logging methods, ensuring the JSON-RPC protocol remained intact. Debug messages were logged using ctx.debug() and similar methods, preventing protocol corruption.

Result: The system now correctly handles multi-turn conversations with structured messages and maintains protocol integrity, eliminating validation errors and JSON parsing failures.