tracebase-cli 0.3.0__py3-none-any.whl
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- tracebase_cli/__init__.py +1 -0
- tracebase_cli/client.py +192 -0
- tracebase_cli/connect.py +135 -0
- tracebase_cli/main.py +708 -0
- tracebase_cli/mcp_server.py +286 -0
- tracebase_cli/merge.py +312 -0
- tracebase_cli/plans.py +130 -0
- tracebase_cli/project.py +134 -0
- tracebase_cli/reuse.py +261 -0
- tracebase_cli/ui.py +113 -0
- tracebase_cli-0.3.0.dist-info/METADATA +95 -0
- tracebase_cli-0.3.0.dist-info/RECORD +15 -0
- tracebase_cli-0.3.0.dist-info/WHEEL +4 -0
- tracebase_cli-0.3.0.dist-info/entry_points.txt +2 -0
- tracebase_cli-0.3.0.dist-info/licenses/LICENSE.md +105 -0
|
@@ -0,0 +1 @@
|
|
|
1
|
+
__version__ = "0.3.0"
|
tracebase_cli/client.py
ADDED
|
@@ -0,0 +1,192 @@
|
|
|
1
|
+
"""HTTP client for the Tracebase server (the box that indexed your repos and runs Ollama)."""
|
|
2
|
+
from __future__ import annotations
|
|
3
|
+
|
|
4
|
+
import json
|
|
5
|
+
import os
|
|
6
|
+
from pathlib import Path
|
|
7
|
+
|
|
8
|
+
import httpx
|
|
9
|
+
|
|
10
|
+
DEFAULT_URL = "http://localhost:8080"
|
|
11
|
+
CONFIG = Path(os.environ.get("XDG_CONFIG_HOME") or Path.home() / ".config") / "tracebase" / "config.json"
|
|
12
|
+
|
|
13
|
+
|
|
14
|
+
def load_config() -> dict:
|
|
15
|
+
try:
|
|
16
|
+
return json.loads(CONFIG.read_text())
|
|
17
|
+
except (OSError, ValueError):
|
|
18
|
+
return {}
|
|
19
|
+
|
|
20
|
+
|
|
21
|
+
def save_config(data: dict) -> None:
|
|
22
|
+
"""URL + token from `tracebase login`, readable only by this user (agents read it, so no token in their config)."""
|
|
23
|
+
CONFIG.parent.mkdir(parents=True, exist_ok=True)
|
|
24
|
+
tmp = CONFIG.with_suffix(".tmp")
|
|
25
|
+
tmp.write_text(json.dumps(data, indent=2))
|
|
26
|
+
tmp.chmod(0o600)
|
|
27
|
+
tmp.replace(CONFIG)
|
|
28
|
+
|
|
29
|
+
|
|
30
|
+
class TracebaseError(RuntimeError):
|
|
31
|
+
pass
|
|
32
|
+
|
|
33
|
+
|
|
34
|
+
class Client:
|
|
35
|
+
def __init__(self, url: str | None = None, timeout: float = 900, token: str | None = None) -> None:
|
|
36
|
+
cfg = load_config()
|
|
37
|
+
self.url = (url or os.environ.get("TRACEBASE_URL") or cfg.get("url") or DEFAULT_URL).rstrip("/")
|
|
38
|
+
self.token = token or os.environ.get("TRACEBASE_TOKEN") or (cfg.get("token") if cfg.get("url", self.url).rstrip("/") == self.url else None)
|
|
39
|
+
headers = {"Authorization": f"Bearer {self.token}"} if self.token else {}
|
|
40
|
+
self.http = httpx.Client(base_url=self.url, timeout=httpx.Timeout(timeout, connect=5), headers=headers)
|
|
41
|
+
|
|
42
|
+
def _req(self, method: str, path: str, **kw) -> dict | list:
|
|
43
|
+
try:
|
|
44
|
+
r = self.http.request(method, path, **kw)
|
|
45
|
+
except httpx.ConnectError as e:
|
|
46
|
+
raise TracebaseError(f"Cannot reach Tracebase at {self.url}. Is it running? "
|
|
47
|
+
f"(set TRACEBASE_URL if it runs elsewhere)") from e
|
|
48
|
+
except httpx.TimeoutException as e:
|
|
49
|
+
raise TracebaseError("Tracebase took too long to answer (the local LLM may be overloaded).") from e
|
|
50
|
+
if r.status_code == 401:
|
|
51
|
+
raise TracebaseError(f"{self.url} is a team server and needs your token: run `tracebase login <token>`"
|
|
52
|
+
+ (" (the saved token was rejected)" if self.token else ""))
|
|
53
|
+
if r.status_code >= 400:
|
|
54
|
+
try:
|
|
55
|
+
detail = r.json().get("detail")
|
|
56
|
+
except ValueError:
|
|
57
|
+
detail = r.text[:300]
|
|
58
|
+
raise TracebaseError(f"{r.status_code}: {detail}")
|
|
59
|
+
return r.json()
|
|
60
|
+
|
|
61
|
+
def health(self) -> dict:
|
|
62
|
+
return self._req("GET", "/api/health")
|
|
63
|
+
|
|
64
|
+
def repos(self) -> list[dict]:
|
|
65
|
+
return self._req("GET", "/api/code/repos")
|
|
66
|
+
|
|
67
|
+
def search(self, q: str, repo: str | None = None, language: str | None = None, limit: int = 8) -> dict:
|
|
68
|
+
params = {k: v for k, v in {"q": q, "repo": repo, "language": language, "limit": limit}.items() if v}
|
|
69
|
+
return self._req("GET", "/api/code/search", params=params)
|
|
70
|
+
|
|
71
|
+
def read(self, repo: str, path: str, start: int | None = None, end: int | None = None) -> dict:
|
|
72
|
+
params = {k: v for k, v in {"repo": repo, "path": path, "start": start, "end": end}.items() if v}
|
|
73
|
+
return self._req("GET", "/api/code/file", params=params)
|
|
74
|
+
|
|
75
|
+
def ask(self, question: str, repo: str | None = None) -> dict:
|
|
76
|
+
return self._req("POST", "/api/code/ask", json={"question": question, "repo": repo})
|
|
77
|
+
|
|
78
|
+
def examples(self, task: str, project: dict | None = None, languages: list[str] | None = None,
|
|
79
|
+
frameworks: list[str] | None = None, limit: int = 8) -> dict:
|
|
80
|
+
return self._req("POST", "/api/reuse/examples", json={
|
|
81
|
+
"task": task, "project": project, "languages": languages, "frameworks": frameworks, "limit": limit})
|
|
82
|
+
|
|
83
|
+
def bundle(self, repo: str, paths: list[str], project: dict | None = None, symbol: str | None = None,
|
|
84
|
+
renames: list[str] | None = None) -> dict:
|
|
85
|
+
return self._req("POST", "/api/reuse/bundle", json={"repo": repo, "paths": paths, "project": project,
|
|
86
|
+
"symbol": symbol, "renames": renames or []})
|
|
87
|
+
|
|
88
|
+
# ---- team mode
|
|
89
|
+
def me(self) -> dict:
|
|
90
|
+
return self._req("GET", "/api/team/me")
|
|
91
|
+
|
|
92
|
+
def members(self) -> list[dict]:
|
|
93
|
+
return self._req("GET", "/api/team/users")
|
|
94
|
+
|
|
95
|
+
def add_member(self, name: str, repos: list[str], role: str = "member") -> dict:
|
|
96
|
+
return self._req("POST", "/api/team/users", json={"name": name, "repos": repos, "role": role})
|
|
97
|
+
|
|
98
|
+
def set_member_repos(self, name: str, repos: list[str]) -> dict:
|
|
99
|
+
return self._req("PUT", f"/api/team/users/{name}/repos", json=repos)
|
|
100
|
+
|
|
101
|
+
def rotate_member(self, name: str) -> dict:
|
|
102
|
+
return self._req("POST", f"/api/team/users/{name}/rotate")
|
|
103
|
+
|
|
104
|
+
def remove_member(self, name: str) -> dict:
|
|
105
|
+
return self._req("DELETE", f"/api/team/users/{name}")
|
|
106
|
+
|
|
107
|
+
def audit(self, user: str | None = None, action: str | None = None, limit: int = 50) -> list[dict]:
|
|
108
|
+
return self._req("GET", "/api/team/audit", params={k: v for k, v in
|
|
109
|
+
{"user": user, "action": action, "limit": limit}.items() if v})
|
|
110
|
+
|
|
111
|
+
# ------------------------------------------------------------ Log Detective
|
|
112
|
+
def errors(self, service: str | None = None, since: str | None = None, status: str | None = None,
|
|
113
|
+
q: str | None = None, limit: int = 30) -> list[dict]:
|
|
114
|
+
return self._req("GET", "/api/logs/groups", params={k: v for k, v in {
|
|
115
|
+
"service": service, "since": since, "status": status, "q": q, "limit": limit}.items() if v})
|
|
116
|
+
|
|
117
|
+
def error(self, gid: str) -> dict:
|
|
118
|
+
return self._req("GET", f"/api/logs/groups/{gid}")
|
|
119
|
+
|
|
120
|
+
def explain_error(self, gid: str, refresh: bool = False) -> dict:
|
|
121
|
+
return self._req("POST", f"/api/logs/groups/{gid}/explain", params={"refresh": "true"} if refresh else None)
|
|
122
|
+
|
|
123
|
+
def set_error_status(self, gid: str, status: str) -> dict:
|
|
124
|
+
return self._req("POST", f"/api/logs/groups/{gid}/status", json={"status": status})
|
|
125
|
+
|
|
126
|
+
def ingest(self, text: str, service: str | None = None) -> dict:
|
|
127
|
+
return self._req("POST", "/api/logs/ingest", params={"service": service} if service else None,
|
|
128
|
+
content=text.encode(), headers={"content-type": "text/plain"})
|
|
129
|
+
|
|
130
|
+
def alerts(self, unread: bool = False) -> list[dict]:
|
|
131
|
+
return self._req("GET", "/api/alerts", params={"unread": "true"} if unread else None)
|
|
132
|
+
|
|
133
|
+
def read_alerts(self) -> dict:
|
|
134
|
+
return self._req("POST", "/api/alerts/read", json={})
|
|
135
|
+
|
|
136
|
+
# ------------------------------------------------------------ data & privacy (admin)
|
|
137
|
+
def data_summary(self) -> dict:
|
|
138
|
+
return self._req("GET", "/api/data/summary")
|
|
139
|
+
|
|
140
|
+
def data_prune(self) -> dict:
|
|
141
|
+
return self._req("POST", "/api/data/prune")
|
|
142
|
+
|
|
143
|
+
def forget_repo(self, name: str) -> dict:
|
|
144
|
+
return self._req("DELETE", f"/api/data/repos/{name}")
|
|
145
|
+
|
|
146
|
+
def restore_repo(self, name: str) -> dict:
|
|
147
|
+
return self._req("POST", f"/api/data/repos/{name}/restore")
|
|
148
|
+
|
|
149
|
+
def forget_service(self, name: str, exclude: bool = False) -> dict:
|
|
150
|
+
return self._req("DELETE", f"/api/data/services/{name}", params={"exclude": "true"} if exclude else None)
|
|
151
|
+
|
|
152
|
+
def restore_service(self, name: str) -> dict:
|
|
153
|
+
return self._req("POST", f"/api/data/services/{name}/restore")
|
|
154
|
+
|
|
155
|
+
def purge(self, match: str, service: str | None = None, dry_run: bool = False) -> dict:
|
|
156
|
+
return self._req("POST", "/api/data/purge", json={"match": match, "service": service, "dry_run": dry_run})
|
|
157
|
+
|
|
158
|
+
def wipe(self, keep_team: bool = True) -> dict:
|
|
159
|
+
return self._req("POST", "/api/data/wipe", json={"confirm": "delete everything", "keep_team": keep_team})
|
|
160
|
+
|
|
161
|
+
def export(self, out, service: str | None = None, match: str | None = None) -> int:
|
|
162
|
+
"""Stream the NDJSON export into the file object `out`; returns the number of records."""
|
|
163
|
+
params = {k: v for k, v in {"service": service, "match": match}.items() if v}
|
|
164
|
+
n = 0
|
|
165
|
+
try:
|
|
166
|
+
with self.http.stream("GET", "/api/data/export", params=params) as r:
|
|
167
|
+
if r.status_code >= 400:
|
|
168
|
+
r.read()
|
|
169
|
+
self._raise(r)
|
|
170
|
+
for line in r.iter_lines():
|
|
171
|
+
if line:
|
|
172
|
+
out.write(line + "\n")
|
|
173
|
+
n += 1
|
|
174
|
+
except httpx.ConnectError as e:
|
|
175
|
+
raise TracebaseError(f"Cannot reach Tracebase at {self.url}. Is it running?") from e
|
|
176
|
+
return max(n - 1, 0) # minus the header line
|
|
177
|
+
|
|
178
|
+
def _raise(self, r: httpx.Response) -> None:
|
|
179
|
+
if r.status_code == 401:
|
|
180
|
+
raise TracebaseError(f"{self.url} is a team server and needs your token: run `tracebase login <token>`")
|
|
181
|
+
try:
|
|
182
|
+
detail = r.json().get("detail")
|
|
183
|
+
except ValueError:
|
|
184
|
+
detail = r.text[:300]
|
|
185
|
+
raise TracebaseError(f"{r.status_code}: {detail}")
|
|
186
|
+
|
|
187
|
+
def event(self, action: str, repo: str | None, **detail) -> None:
|
|
188
|
+
"""Best effort: tell a team server what was written (audit log). Never fails the copy."""
|
|
189
|
+
try:
|
|
190
|
+
self._req("POST", "/api/team/events", json={"action": action, "repo": repo, "detail": detail})
|
|
191
|
+
except TracebaseError:
|
|
192
|
+
pass
|
tracebase_cli/connect.py
ADDED
|
@@ -0,0 +1,135 @@
|
|
|
1
|
+
"""`tracebase connect <agent>`: register Tracebase's MCP server with the AI agent the developer uses in their
|
|
2
|
+
terminal or editor. Config files are merged (other servers are kept) and backed up first."""
|
|
3
|
+
from __future__ import annotations
|
|
4
|
+
|
|
5
|
+
import json
|
|
6
|
+
import os
|
|
7
|
+
import re
|
|
8
|
+
import shutil
|
|
9
|
+
import subprocess
|
|
10
|
+
import sys
|
|
11
|
+
import time
|
|
12
|
+
from pathlib import Path
|
|
13
|
+
|
|
14
|
+
NAME = "tracebase"
|
|
15
|
+
|
|
16
|
+
|
|
17
|
+
def command() -> list[str]:
|
|
18
|
+
"""How the agent should start the server: the installed `tracebase` (absolute path), else this Python."""
|
|
19
|
+
exe = shutil.which("tracebase")
|
|
20
|
+
return [exe, "mcp"] if exe else [sys.executable, "-m", "tracebase_cli.main", "mcp"]
|
|
21
|
+
|
|
22
|
+
|
|
23
|
+
def _env() -> dict:
|
|
24
|
+
url = os.environ.get("TRACEBASE_URL")
|
|
25
|
+
return {"TRACEBASE_URL": url} if url else {}
|
|
26
|
+
|
|
27
|
+
|
|
28
|
+
def _backup(p: Path) -> None:
|
|
29
|
+
if p.exists():
|
|
30
|
+
shutil.copy2(p, p.with_name(p.name + f".bak-{time.strftime('%Y%m%d%H%M%S')}"))
|
|
31
|
+
|
|
32
|
+
|
|
33
|
+
def _merge_json(path: Path, key_path: list[str], entry: dict) -> None:
|
|
34
|
+
data = json.loads(path.read_text() or "{}") if path.exists() else {}
|
|
35
|
+
node = data
|
|
36
|
+
for k in key_path:
|
|
37
|
+
node = node.setdefault(k, {})
|
|
38
|
+
node[NAME] = entry
|
|
39
|
+
_backup(path)
|
|
40
|
+
path.parent.mkdir(parents=True, exist_ok=True)
|
|
41
|
+
path.write_text(json.dumps(data, indent=2) + "\n")
|
|
42
|
+
|
|
43
|
+
|
|
44
|
+
def _std_entry() -> dict:
|
|
45
|
+
cmd = command()
|
|
46
|
+
e = {"command": cmd[0], "args": cmd[1:]}
|
|
47
|
+
if _env():
|
|
48
|
+
e["env"] = _env()
|
|
49
|
+
return e
|
|
50
|
+
|
|
51
|
+
|
|
52
|
+
def _run(cmd: list[str]) -> str:
|
|
53
|
+
r = subprocess.run(cmd, capture_output=True, text=True)
|
|
54
|
+
if r.returncode != 0:
|
|
55
|
+
raise RuntimeError((r.stderr or r.stdout).strip() or f"{cmd[0]} failed")
|
|
56
|
+
return f"ran: {' '.join(cmd)}"
|
|
57
|
+
|
|
58
|
+
|
|
59
|
+
# ------------------------------------------------------------------ agents
|
|
60
|
+
def claude(home: Path) -> str:
|
|
61
|
+
"""Claude Code: `claude mcp add --scope user` (available in every project)."""
|
|
62
|
+
cmd = command()
|
|
63
|
+
if shutil.which("claude"):
|
|
64
|
+
subprocess.run(["claude", "mcp", "remove", "--scope", "user", NAME], capture_output=True)
|
|
65
|
+
env = [a for k, v in _env().items() for a in ("-e", f"{k}={v}")]
|
|
66
|
+
return _run(["claude", "mcp", "add", "--scope", "user", *env, NAME, "--", *cmd])
|
|
67
|
+
_merge_json(home / ".claude.json", ["mcpServers"], {"type": "stdio", **_std_entry()})
|
|
68
|
+
return f"wrote {home / '.claude.json'}"
|
|
69
|
+
|
|
70
|
+
|
|
71
|
+
def codex(home: Path) -> str:
|
|
72
|
+
"""OpenAI Codex CLI: [mcp_servers.tracebase] in ~/.codex/config.toml."""
|
|
73
|
+
path = home / ".codex" / "config.toml"
|
|
74
|
+
cmd = command()
|
|
75
|
+
block = f'[mcp_servers.{NAME}]\ncommand = {json.dumps(cmd[0])}\nargs = {json.dumps(cmd[1:])}\n'
|
|
76
|
+
if _env():
|
|
77
|
+
block += "env = { " + ", ".join(f'{k} = {json.dumps(v)}' for k, v in _env().items()) + " }\n"
|
|
78
|
+
text = path.read_text() if path.exists() else ""
|
|
79
|
+
# replace an existing [mcp_servers.tracebase] table (up to the next table header)
|
|
80
|
+
text = re.sub(rf"(?ms)^\[mcp_servers\.{NAME}\]\n.*?(?=^\[|\Z)", "", text).rstrip()
|
|
81
|
+
_backup(path)
|
|
82
|
+
path.parent.mkdir(parents=True, exist_ok=True)
|
|
83
|
+
path.write_text((text + "\n\n" if text else "") + block)
|
|
84
|
+
return f"wrote {path}"
|
|
85
|
+
|
|
86
|
+
|
|
87
|
+
def gemini(home: Path) -> str:
|
|
88
|
+
"""Google Gemini CLI: mcpServers in ~/.gemini/settings.json."""
|
|
89
|
+
path = home / ".gemini" / "settings.json"
|
|
90
|
+
_merge_json(path, ["mcpServers"], _std_entry())
|
|
91
|
+
return f"wrote {path}"
|
|
92
|
+
|
|
93
|
+
|
|
94
|
+
def opencode(home: Path) -> str:
|
|
95
|
+
"""opencode (works with Ollama and cloud models): mcp in ~/.config/opencode/opencode.json."""
|
|
96
|
+
path = home / ".config" / "opencode" / "opencode.json"
|
|
97
|
+
entry = {"type": "local", "command": command(), "enabled": True}
|
|
98
|
+
if _env():
|
|
99
|
+
entry["environment"] = _env()
|
|
100
|
+
_merge_json(path, ["mcp"], entry)
|
|
101
|
+
return f"wrote {path}"
|
|
102
|
+
|
|
103
|
+
|
|
104
|
+
def cursor(home: Path) -> str:
|
|
105
|
+
"""Cursor (editor + cursor-agent CLI): mcpServers in ~/.cursor/mcp.json."""
|
|
106
|
+
path = home / ".cursor" / "mcp.json"
|
|
107
|
+
_merge_json(path, ["mcpServers"], _std_entry())
|
|
108
|
+
return f"wrote {path}"
|
|
109
|
+
|
|
110
|
+
|
|
111
|
+
def ollama(home: Path) -> str:
|
|
112
|
+
"""Ollama models in the terminal through ollmcp (pip install mcp-client-for-ollama)."""
|
|
113
|
+
path = home / ".config" / "tracebase" / "mcp-servers.json"
|
|
114
|
+
_merge_json(path, ["mcpServers"], _std_entry())
|
|
115
|
+
return (f"wrote {path}\n start it in your project with: ollmcp --servers-json {path} --model qwen2.5-coder:7b\n"
|
|
116
|
+
" (any Ollama model with tool calling works: qwen2.5-coder, llama3.1, mistral-nemo…)")
|
|
117
|
+
|
|
118
|
+
|
|
119
|
+
AGENTS = {
|
|
120
|
+
"claude": (claude, "Claude Code", "claude"),
|
|
121
|
+
"codex": (codex, "OpenAI Codex CLI", "codex"),
|
|
122
|
+
"gemini": (gemini, "Gemini CLI", "gemini"),
|
|
123
|
+
"opencode": (opencode, "opencode (Ollama or cloud models)", "opencode"),
|
|
124
|
+
"cursor": (cursor, "Cursor / cursor-agent", "cursor-agent"),
|
|
125
|
+
"ollama": (ollama, "Ollama via ollmcp", "ollmcp"),
|
|
126
|
+
}
|
|
127
|
+
|
|
128
|
+
|
|
129
|
+
def detected() -> list[str]:
|
|
130
|
+
return [k for k, (_, _, exe) in AGENTS.items() if shutil.which(exe)]
|
|
131
|
+
|
|
132
|
+
|
|
133
|
+
def snippet() -> str:
|
|
134
|
+
"""Generic config for any other MCP client."""
|
|
135
|
+
return json.dumps({"mcpServers": {NAME: _std_entry()}}, indent=2)
|