MCPcopy Create free account
hub / github.com/Serial-Studio/Serial-Studio / MCPClient

Class MCPClient

examples/MCP Client/client.py:31–186  ·  view source on GitHub ↗

Simple MCP client for Serial Studio

Source from the content-addressed store, hash-verified

29
30
31class MCPClient:
32 """Simple MCP client for Serial Studio"""
33
34 def __init__(self, host="localhost", port=7777):
35 self.host = host
36 self.port = port
37 self.sock = None
38 self.request_id = 0
39 self._buffer = b""
40
41 def connect(self):
42 """Connect to Serial Studio API server"""
43 try:
44 self.sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
45 self.sock.connect((self.host, self.port))
46 print(f"✓ Connected to Serial Studio at {self.host}:{self.port}")
47 except ConnectionRefusedError:
48 print(f"\n✗ Connection refused to {self.host}:{self.port}")
49 print("\nMake sure:")
50 print(" 1. Serial Studio is running")
51 print(" 2. API Server is enabled in Settings (⚙️)")
52 print(' Enable "Enable API Server (Port 7777)" switch')
53 print(" 3. No firewall is blocking port 7777\n")
54 raise
55
56 def send_request(self, method, params=None):
57 """Send MCP JSON-RPC 2.0 request"""
58 self.request_id += 1
59 request = {
60 "jsonrpc": "2.0",
61 "id": self.request_id,
62 "method": method,
63 "params": params or {},
64 }
65
66 message = json.dumps(request) + "\n"
67 self.sock.sendall(message.encode("utf-8"))
68
69 response = self._read_response(self.request_id)
70 return response
71
72 def _read_line(self):
73 """Read one newline-delimited JSON line, preserving leftover data"""
74 while b"\n" not in self._buffer:
75 chunk = self.sock.recv(4096)
76 if not chunk:
77 raise ConnectionError("Connection closed by server")
78 self._buffer += chunk
79
80 line, self._buffer = self._buffer.split(b"\n", 1)
81 return json.loads(line.decode("utf-8"))
82
83 def _read_response(self, request_id):
84 """Read lines until we get the JSON-RPC response matching request_id.
85
86 The server may send raw data events ({"data": "..."}) interleaved
87 with JSON-RPC responses. These are silently skipped.
88 """

Callers 1

mainFunction · 0.70

Calls

no outgoing calls

Tested by

no test coverage detected