-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathfirst_mcp.py
More file actions
51 lines (48 loc) · 1.77 KB
/
first_mcp.py
File metadata and controls
51 lines (48 loc) · 1.77 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
from mcp.server.fastmcp import FastMCP
from first_con import main as init_server
import logging,threading,socket,time
mcp = FastMCP("hola_mundo")
_server_thread: threading.Thread | None = None
def _wait_until_ready(host="127.0.0.1",port = 5678,timeout = 3.0) -> str | None:
t0 = time.time()
while time.time() - t0 < timeout:
try:
with socket.create_connection((host,port),timeout=0.5) as s:
s.settimeout(0.5)
s.sendall(b"PING\n")
resp = s.recv(128).decode("utf-8","ignore").strip()
return resp or "OK"
except Exception:
time.sleep(.2)
@mcp.tool()
def encender_canal() -> dict:
global _server_thread
try:
ok = _wait_until_ready()
if ok is not None:
return {"ok" : True,"status":"arduino escuchando","resp":"ok"}
except Exception:
pass
logging.info("Arduino escuchando en paralelo")
_server_thread = threading.Thread(target=init_server,daemon = True)
_server_thread.start()
ok = _wait_until_ready()
if ok is None:
return {"ok": False, "error": "server_not_ready"}
return {"ok": True, "status": "started", "resp": ok}
@mcp.tool()
def arduino_cmd(cmd: str) -> dict:
"""
Cliente rápido: conecta -> manda -> lee una línea -> cierra.
No bloquea a Claude; usa timeouts cortos.
"""
try:
with socket.create_connection(("127.0.0.1", 5678), timeout=1.5) as s:
s.settimeout(1.5)
s.sendall((cmd.strip() + "\n").encode("utf-8"))
resp = s.recv(1024).decode("utf-8", "ignore").strip()
return {"ok": True, "cmd": cmd, "resp": resp or "OK"}
except Exception as e:
return {"ok": False, "error": str(e)}
if __name__ == "__main__":
mcp.run()