Skip to main content

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 connection
  • tools/list - List available tools
  • tools/call - Execute a tool
  • resources/list - List resources
  • prompts/list - List prompts

Server Lifecycle

  1. Start: Spawn subprocess with command + args
  2. Initialize: Send initialize request
  3. Query: Send tools/list or other queries
  4. Execute: Call tools as needed
  5. 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.