| 20 | |
| 21 | |
| 22 | class McpServer: |
| 23 | def __init__(self, binary, cache_dir=None, extra_env=None, cwd=None): |
| 24 | self.binary = binary |
| 25 | self._id = 0 |
| 26 | self.proc = None |
| 27 | self._stderr = [] |
| 28 | env = dict(os.environ) |
| 29 | if cache_dir: |
| 30 | env["CBM_CACHE_DIR"] = cache_dir # isolate the graph DB location |
| 31 | if extra_env: |
| 32 | env.update(extra_env) |
| 33 | self.env = env |
| 34 | self.cwd = cwd |
| 35 | |
| 36 | def __enter__(self): |
| 37 | self.start() |
| 38 | return self |
| 39 | |
| 40 | def __exit__(self, *a): |
| 41 | self.close() |
| 42 | |
| 43 | def start(self): |
| 44 | self.proc = subprocess.Popen( |
| 45 | [self.binary], |
| 46 | stdin=subprocess.PIPE, stdout=subprocess.PIPE, stderr=subprocess.PIPE, |
| 47 | env=self.env, cwd=self.cwd, bufsize=0) |
| 48 | threading.Thread(target=self._drain_stderr, daemon=True).start() |
| 49 | |
| 50 | def _drain_stderr(self): |
| 51 | try: |
| 52 | for line in self.proc.stderr: |
| 53 | self._stderr.append(line.decode("utf-8", "replace")) |
| 54 | except Exception: |
| 55 | pass |
| 56 | |
| 57 | def stderr_text(self): |
| 58 | return "".join(self._stderr) |
| 59 | |
| 60 | def _send(self, obj): |
| 61 | data = json.dumps(obj, ensure_ascii=False).encode("utf-8") |
| 62 | self.proc.stdin.write(data + b"\n") |
| 63 | self.proc.stdin.flush() |
| 64 | |
| 65 | def _read_message(self, timeout=60): |
| 66 | result = {} |
| 67 | |
| 68 | def reader(): |
| 69 | try: |
| 70 | result["line"] = self.proc.stdout.readline() |
| 71 | except Exception as ex: |
| 72 | result["exc"] = ex |
| 73 | |
| 74 | th = threading.Thread(target=reader, daemon=True) |
| 75 | th.start() |
| 76 | th.join(timeout) |
| 77 | if th.is_alive(): |
| 78 | raise McpError("timeout after %ss (hang)" % timeout) |
| 79 | if "exc" in result: |
no outgoing calls