MCP Client
The MCP Client handles JSON-RPC communication with STDIO-based MCP servers.
Overview
MCP (Model Context Protocol) uses JSON-RPC 2.0 for communication between clients and servers via STDIO.
Implementation
File: apps/backend/app/services/mcp_client.py
Key Features:
- Async subprocess management
- JSON-RPC 2.0 protocol
- STDIN/STDOUT communication
- Tool discovery and listing
- Error handling and retries
Communication Flow
MCP Client
↓ (spawn subprocess)
MCP Server Process
↓ (STDIN: JSON-RPC request)
MCP Server
↓ (STDOUT: JSON-RPC response)
MCP Client
↓ (parse and return)
API Response
JSON-RPC Protocol
Request Format
{
"jsonrpc": "2.0",
"id": 1,
"method": "tools/list",
"params": {}
}
Response Format
{
"jsonrpc": "2.0",
"id": 1,
"result": {
"tools": [
{
"name": "read_file",
"description": "Read contents of a file"
}
]
}
}
Supported Methods
initialize- Initialize connectiontools/list- List available toolstools/call- Execute a toolresources/list- List resourcesprompts/list- List prompts
Server Lifecycle
- Start: Spawn subprocess with command + args
- Initialize: Send initialize request
- Query: Send tools/list or other queries
- Execute: Call tools as needed
- Shutdown: Terminate subprocess
Error Handling
- Subprocess failures captured
- JSON parse errors handled
- Timeout management
- Process cleanup on errors
For HTTP-based servers, see HTTP Servers.