kimetsu 0.1.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.
- kimetsu/__init__.py +26 -0
- kimetsu/_transport.py +126 -0
- kimetsu/async_client.py +132 -0
- kimetsu/client.py +141 -0
- kimetsu/errors.py +31 -0
- kimetsu/models.py +22 -0
- kimetsu/py.typed +0 -0
- kimetsu-0.1.0.dist-info/METADATA +124 -0
- kimetsu-0.1.0.dist-info/RECORD +11 -0
- kimetsu-0.1.0.dist-info/WHEEL +4 -0
- kimetsu-0.1.0.dist-info/licenses/LICENSE +150 -0
kimetsu/__init__.py
ADDED
|
@@ -0,0 +1,26 @@
|
|
|
1
|
+
from .async_client import AsyncKimetsuClient
|
|
2
|
+
from .client import KimetsuClient
|
|
3
|
+
from .errors import (
|
|
4
|
+
KimetsuError,
|
|
5
|
+
KimetsuAuthError,
|
|
6
|
+
KimetsuRateLimitError,
|
|
7
|
+
KimetsuToolError,
|
|
8
|
+
KimetsuProtocolError,
|
|
9
|
+
)
|
|
10
|
+
from .models import Context, Memory, Status
|
|
11
|
+
|
|
12
|
+
__version__ = "0.1.0"
|
|
13
|
+
|
|
14
|
+
__all__ = [
|
|
15
|
+
"AsyncKimetsuClient",
|
|
16
|
+
"KimetsuClient",
|
|
17
|
+
"__version__",
|
|
18
|
+
"Context",
|
|
19
|
+
"Memory",
|
|
20
|
+
"Status",
|
|
21
|
+
"KimetsuError",
|
|
22
|
+
"KimetsuAuthError",
|
|
23
|
+
"KimetsuRateLimitError",
|
|
24
|
+
"KimetsuToolError",
|
|
25
|
+
"KimetsuProtocolError",
|
|
26
|
+
]
|
kimetsu/_transport.py
ADDED
|
@@ -0,0 +1,126 @@
|
|
|
1
|
+
from __future__ import annotations
|
|
2
|
+
|
|
3
|
+
import asyncio
|
|
4
|
+
import itertools
|
|
5
|
+
from typing import Any
|
|
6
|
+
from typing import Dict
|
|
7
|
+
from typing import Optional
|
|
8
|
+
|
|
9
|
+
import httpx
|
|
10
|
+
|
|
11
|
+
from .errors import KimetsuAuthError
|
|
12
|
+
from .errors import KimetsuProtocolError
|
|
13
|
+
from .errors import KimetsuRateLimitError
|
|
14
|
+
from .errors import KimetsuToolError
|
|
15
|
+
|
|
16
|
+
PROTOCOL_VERSION = "2024-11-05"
|
|
17
|
+
|
|
18
|
+
|
|
19
|
+
def build_call(name: str, arguments: Dict[str, Any], *, request_id: int) -> Dict[str, Any]:
|
|
20
|
+
return {"jsonrpc": "2.0", "id": request_id, "method": "tools/call",
|
|
21
|
+
"params": {"name": name, "arguments": arguments}}
|
|
22
|
+
|
|
23
|
+
|
|
24
|
+
def _build_initialize(request_id: int, protocol_version: str) -> Dict[str, Any]:
|
|
25
|
+
return {"jsonrpc": "2.0", "id": request_id, "method": "initialize",
|
|
26
|
+
"params": {"protocolVersion": protocol_version, "capabilities": {},
|
|
27
|
+
"clientInfo": {"name": "kimetsu-py", "version": "0.1.0"}}}
|
|
28
|
+
|
|
29
|
+
|
|
30
|
+
def parse_envelope(status_code: int, body: Dict[str, Any], headers: Dict[str, str]) -> Dict[str, Any]:
|
|
31
|
+
if status_code in (401, 403):
|
|
32
|
+
raise KimetsuAuthError(f"authentication failed (HTTP {status_code})")
|
|
33
|
+
if status_code == 429:
|
|
34
|
+
ra = headers.get("retry-after")
|
|
35
|
+
retry_after: Optional[float] = None
|
|
36
|
+
if ra:
|
|
37
|
+
try:
|
|
38
|
+
retry_after = float(ra)
|
|
39
|
+
except ValueError:
|
|
40
|
+
retry_after = None
|
|
41
|
+
raise KimetsuRateLimitError("rate limited (HTTP 429)", retry_after=retry_after)
|
|
42
|
+
if status_code >= 400:
|
|
43
|
+
raise KimetsuProtocolError(f"unexpected HTTP {status_code}")
|
|
44
|
+
if "error" in body:
|
|
45
|
+
err = body["error"]
|
|
46
|
+
raise KimetsuToolError(err.get("message", "tool error"), code=err.get("code"))
|
|
47
|
+
if "result" not in body:
|
|
48
|
+
raise KimetsuProtocolError("missing result in JSON-RPC envelope")
|
|
49
|
+
result: Dict[str, Any] = body["result"]
|
|
50
|
+
return result
|
|
51
|
+
|
|
52
|
+
|
|
53
|
+
class SyncTransport:
|
|
54
|
+
def __init__(self, base_url: str, token: str, repo: str, *,
|
|
55
|
+
timeout: float = 30.0, protocol_version: str = PROTOCOL_VERSION,
|
|
56
|
+
client: Optional[httpx.Client] = None) -> None:
|
|
57
|
+
self._url = f"{base_url.rstrip('/')}/mcp/{repo}"
|
|
58
|
+
self._headers = {"authorization": f"Bearer {token}", "content-type": "application/json"}
|
|
59
|
+
self._protocol_version = protocol_version
|
|
60
|
+
self._ids = itertools.count(1)
|
|
61
|
+
self._client = client or httpx.Client(timeout=timeout)
|
|
62
|
+
self._initialized = False
|
|
63
|
+
|
|
64
|
+
def _post(self, payload: Dict[str, Any]) -> Dict[str, Any]:
|
|
65
|
+
resp = self._client.post(self._url, headers=self._headers, json=payload)
|
|
66
|
+
try:
|
|
67
|
+
body = resp.json() if resp.content else {}
|
|
68
|
+
except ValueError:
|
|
69
|
+
body = {}
|
|
70
|
+
return parse_envelope(resp.status_code, body, dict(resp.headers))
|
|
71
|
+
|
|
72
|
+
def _ensure_init(self) -> None:
|
|
73
|
+
if self._initialized:
|
|
74
|
+
return
|
|
75
|
+
result = self._post(_build_initialize(next(self._ids), self._protocol_version))
|
|
76
|
+
got = result.get("protocolVersion")
|
|
77
|
+
if got and got != self._protocol_version:
|
|
78
|
+
raise KimetsuProtocolError(f"server protocol {got} != {self._protocol_version}")
|
|
79
|
+
self._initialized = True
|
|
80
|
+
|
|
81
|
+
def call(self, name: str, arguments: Dict[str, Any]) -> Dict[str, Any]:
|
|
82
|
+
self._ensure_init()
|
|
83
|
+
return self._post(build_call(name, arguments, request_id=next(self._ids)))
|
|
84
|
+
|
|
85
|
+
def close(self) -> None:
|
|
86
|
+
self._client.close()
|
|
87
|
+
|
|
88
|
+
|
|
89
|
+
class AsyncTransport:
|
|
90
|
+
def __init__(self, base_url: str, token: str, repo: str, *,
|
|
91
|
+
timeout: float = 30.0, protocol_version: str = PROTOCOL_VERSION,
|
|
92
|
+
client: Optional[httpx.AsyncClient] = None) -> None:
|
|
93
|
+
self._url = f"{base_url.rstrip('/')}/mcp/{repo}"
|
|
94
|
+
self._headers = {"authorization": f"Bearer {token}", "content-type": "application/json"}
|
|
95
|
+
self._protocol_version = protocol_version
|
|
96
|
+
self._ids = itertools.count(1)
|
|
97
|
+
self._client = client or httpx.AsyncClient(timeout=timeout)
|
|
98
|
+
self._initialized = False
|
|
99
|
+
self._init_lock = asyncio.Lock()
|
|
100
|
+
|
|
101
|
+
async def _post(self, payload: Dict[str, Any]) -> Dict[str, Any]:
|
|
102
|
+
resp = await self._client.post(self._url, headers=self._headers, json=payload)
|
|
103
|
+
try:
|
|
104
|
+
body = resp.json() if resp.content else {}
|
|
105
|
+
except ValueError:
|
|
106
|
+
body = {}
|
|
107
|
+
return parse_envelope(resp.status_code, body, dict(resp.headers))
|
|
108
|
+
|
|
109
|
+
async def _ensure_init(self) -> None:
|
|
110
|
+
if self._initialized:
|
|
111
|
+
return
|
|
112
|
+
async with self._init_lock:
|
|
113
|
+
if self._initialized:
|
|
114
|
+
return
|
|
115
|
+
result = await self._post(_build_initialize(next(self._ids), self._protocol_version))
|
|
116
|
+
got = result.get("protocolVersion")
|
|
117
|
+
if got and got != self._protocol_version:
|
|
118
|
+
raise KimetsuProtocolError(f"server protocol {got} != {self._protocol_version}")
|
|
119
|
+
self._initialized = True
|
|
120
|
+
|
|
121
|
+
async def call(self, name: str, arguments: Dict[str, Any]) -> Dict[str, Any]:
|
|
122
|
+
await self._ensure_init()
|
|
123
|
+
return await self._post(build_call(name, arguments, request_id=next(self._ids)))
|
|
124
|
+
|
|
125
|
+
async def aclose(self) -> None:
|
|
126
|
+
await self._client.aclose()
|
kimetsu/async_client.py
ADDED
|
@@ -0,0 +1,132 @@
|
|
|
1
|
+
from __future__ import annotations
|
|
2
|
+
from typing import Any, Dict, List, Optional
|
|
3
|
+
import os
|
|
4
|
+
from ._transport import AsyncTransport
|
|
5
|
+
from .client import _clean
|
|
6
|
+
from .models import Context, Memory, Status
|
|
7
|
+
|
|
8
|
+
|
|
9
|
+
class _AsyncMemory:
|
|
10
|
+
def __init__(self, t: Any) -> None:
|
|
11
|
+
self._t = t
|
|
12
|
+
|
|
13
|
+
async def search(self, query: str, **kw: Any) -> Dict[str, Any]:
|
|
14
|
+
res: Dict[str, Any] = await self._t.call("kimetsu_brain_memory_search", _clean({"query": query, **kw}))
|
|
15
|
+
return res
|
|
16
|
+
|
|
17
|
+
async def add(self, text: str, *, scope: str, kind: Optional[str] = None, **kw: Any) -> Memory:
|
|
18
|
+
return Memory.model_validate(await self._t.call("kimetsu_brain_memory_add", _clean({"text": text, "scope": scope, "kind": kind, **kw})))
|
|
19
|
+
|
|
20
|
+
async def list(self, **kw: Any) -> Dict[str, Any]:
|
|
21
|
+
res: Dict[str, Any] = await self._t.call("kimetsu_brain_memory_list", _clean(kw))
|
|
22
|
+
return res
|
|
23
|
+
|
|
24
|
+
async def top(self, **kw: Any) -> Dict[str, Any]:
|
|
25
|
+
res: Dict[str, Any] = await self._t.call("kimetsu_brain_memory_top", _clean(kw))
|
|
26
|
+
return res
|
|
27
|
+
|
|
28
|
+
async def accept(self, proposal_id: str, **kw: Any) -> Dict[str, Any]:
|
|
29
|
+
res: Dict[str, Any] = await self._t.call("kimetsu_brain_memory_accept", _clean({"proposal_id": proposal_id, **kw}))
|
|
30
|
+
return res
|
|
31
|
+
|
|
32
|
+
async def reject(self, proposal_id: str, **kw: Any) -> Dict[str, Any]:
|
|
33
|
+
res: Dict[str, Any] = await self._t.call("kimetsu_brain_memory_reject", _clean({"proposal_id": proposal_id, **kw}))
|
|
34
|
+
return res
|
|
35
|
+
|
|
36
|
+
async def invalidate(self, memory_id: str, **kw: Any) -> Dict[str, Any]:
|
|
37
|
+
res: Dict[str, Any] = await self._t.call("kimetsu_brain_memory_invalidate", _clean({"memory_id": memory_id, **kw}))
|
|
38
|
+
return res
|
|
39
|
+
|
|
40
|
+
async def blame(self, run_id: str, **kw: Any) -> Dict[str, Any]:
|
|
41
|
+
"""Per-run citation attribution: which memories a run cited. Pass a run_id (ULID)."""
|
|
42
|
+
res: Dict[str, Any] = await self._t.call("kimetsu_brain_memory_blame", _clean({"run_id": run_id, **kw}))
|
|
43
|
+
return res
|
|
44
|
+
|
|
45
|
+
async def proposals(self, **kw: Any) -> Dict[str, Any]:
|
|
46
|
+
res: Dict[str, Any] = await self._t.call("kimetsu_brain_memory_proposals", _clean(kw))
|
|
47
|
+
return res
|
|
48
|
+
|
|
49
|
+
async def conflicts(self, **kw: Any) -> Dict[str, Any]:
|
|
50
|
+
res: Dict[str, Any] = await self._t.call("kimetsu_brain_memory_conflicts", _clean(kw))
|
|
51
|
+
return res
|
|
52
|
+
|
|
53
|
+
async def conflict_resolve(self, **kw: Any) -> Dict[str, Any]:
|
|
54
|
+
res: Dict[str, Any] = await self._t.call("kimetsu_brain_conflict_resolve", _clean(kw))
|
|
55
|
+
return res
|
|
56
|
+
|
|
57
|
+
async def prune(self, **kw: Any) -> Dict[str, Any]:
|
|
58
|
+
res: Dict[str, Any] = await self._t.call("kimetsu_brain_prune", _clean(kw))
|
|
59
|
+
return res
|
|
60
|
+
|
|
61
|
+
|
|
62
|
+
class _AsyncConfig:
|
|
63
|
+
def __init__(self, t: Any) -> None:
|
|
64
|
+
self._t = t
|
|
65
|
+
|
|
66
|
+
async def show(self, **kw: Any) -> Dict[str, Any]:
|
|
67
|
+
res: Dict[str, Any] = await self._t.call("kimetsu_brain_config_show", _clean(kw))
|
|
68
|
+
return res
|
|
69
|
+
|
|
70
|
+
|
|
71
|
+
class _AsyncModels:
|
|
72
|
+
def __init__(self, t: Any) -> None:
|
|
73
|
+
self._t = t
|
|
74
|
+
|
|
75
|
+
async def list(self, **kw: Any) -> Dict[str, Any]:
|
|
76
|
+
res: Dict[str, Any] = await self._t.call("kimetsu_brain_model_list", _clean(kw))
|
|
77
|
+
return res
|
|
78
|
+
|
|
79
|
+
|
|
80
|
+
class _AsyncBenchmark:
|
|
81
|
+
def __init__(self, t: Any) -> None:
|
|
82
|
+
self._t = t
|
|
83
|
+
|
|
84
|
+
async def context(self, query: str, **kw: Any) -> Dict[str, Any]:
|
|
85
|
+
res: Dict[str, Any] = await self._t.call("kimetsu_benchmark_context", _clean({"query": query, **kw}))
|
|
86
|
+
return res
|
|
87
|
+
|
|
88
|
+
async def record_outcome(self, task: str, **kw: Any) -> Dict[str, Any]:
|
|
89
|
+
res: Dict[str, Any] = await self._t.call("kimetsu_benchmark_record_outcome", _clean({"task": task, **kw}))
|
|
90
|
+
return res
|
|
91
|
+
|
|
92
|
+
|
|
93
|
+
class AsyncKimetsuClient:
|
|
94
|
+
def __init__(self, base_url: Optional[str] = None, token: Optional[str] = None,
|
|
95
|
+
repo: Optional[str] = None, *, timeout: float = 30.0,
|
|
96
|
+
transport: Optional[Any] = None) -> None:
|
|
97
|
+
if transport is not None:
|
|
98
|
+
self._t = transport
|
|
99
|
+
else:
|
|
100
|
+
base_url = base_url or os.environ["KIMETSU_REMOTE_URL"]
|
|
101
|
+
token = token or os.environ["KIMETSU_REMOTE_TOKEN"]
|
|
102
|
+
repo = repo or os.environ["KIMETSU_REMOTE_REPO"]
|
|
103
|
+
self._t = AsyncTransport(base_url, token, repo, timeout=timeout)
|
|
104
|
+
self.memory = _AsyncMemory(self._t)
|
|
105
|
+
self.config = _AsyncConfig(self._t)
|
|
106
|
+
self.models = _AsyncModels(self._t)
|
|
107
|
+
self.benchmark = _AsyncBenchmark(self._t)
|
|
108
|
+
|
|
109
|
+
async def context(self, query: str, *, tags: Optional[List[str]] = None, **kw: Any) -> Context:
|
|
110
|
+
return Context.model_validate(await self._t.call("kimetsu_brain_context", _clean({"query": query, "tags": tags, **kw})))
|
|
111
|
+
|
|
112
|
+
async def record(self, lesson: str, *, tags: List[str],
|
|
113
|
+
kind: Optional[str] = None, **kw: Any) -> Dict[str, Any]:
|
|
114
|
+
res: Dict[str, Any] = await self._t.call("kimetsu_brain_record", _clean({"lesson": lesson, "tags": tags, "kind": kind, **kw}))
|
|
115
|
+
return res
|
|
116
|
+
|
|
117
|
+
async def status(self) -> Status:
|
|
118
|
+
return Status.model_validate(await self._t.call("kimetsu_brain_status", {}))
|
|
119
|
+
|
|
120
|
+
async def insights(self) -> Dict[str, Any]:
|
|
121
|
+
res: Dict[str, Any] = await self._t.call("kimetsu_brain_insights", {})
|
|
122
|
+
return res
|
|
123
|
+
|
|
124
|
+
async def aclose(self) -> None:
|
|
125
|
+
if hasattr(self._t, "aclose"):
|
|
126
|
+
await self._t.aclose()
|
|
127
|
+
|
|
128
|
+
async def __aenter__(self) -> "AsyncKimetsuClient":
|
|
129
|
+
return self
|
|
130
|
+
|
|
131
|
+
async def __aexit__(self, *exc: Any) -> None:
|
|
132
|
+
await self.aclose()
|
kimetsu/client.py
ADDED
|
@@ -0,0 +1,141 @@
|
|
|
1
|
+
from __future__ import annotations
|
|
2
|
+
from typing import Any, Dict, List, Optional
|
|
3
|
+
import os
|
|
4
|
+
from ._transport import SyncTransport
|
|
5
|
+
from .models import Context, Memory, Status
|
|
6
|
+
|
|
7
|
+
|
|
8
|
+
def _clean(d: Dict[str, Any]) -> Dict[str, Any]:
|
|
9
|
+
return {k: v for k, v in d.items() if v is not None}
|
|
10
|
+
|
|
11
|
+
|
|
12
|
+
class _Memory:
|
|
13
|
+
def __init__(self, t: Any) -> None:
|
|
14
|
+
self._t = t
|
|
15
|
+
|
|
16
|
+
def search(self, query: str, **kw: Any) -> Dict[str, Any]:
|
|
17
|
+
res: Dict[str, Any] = self._t.call("kimetsu_brain_memory_search", _clean({"query": query, **kw}))
|
|
18
|
+
return res
|
|
19
|
+
|
|
20
|
+
def add(self, text: str, *, scope: str, kind: Optional[str] = None, **kw: Any) -> Memory:
|
|
21
|
+
return Memory.model_validate(
|
|
22
|
+
self._t.call("kimetsu_brain_memory_add", _clean({"text": text, "scope": scope, "kind": kind, **kw}))
|
|
23
|
+
)
|
|
24
|
+
|
|
25
|
+
def list(self, **kw: Any) -> Dict[str, Any]:
|
|
26
|
+
res: Dict[str, Any] = self._t.call("kimetsu_brain_memory_list", _clean(kw))
|
|
27
|
+
return res
|
|
28
|
+
|
|
29
|
+
def top(self, **kw: Any) -> Dict[str, Any]:
|
|
30
|
+
res: Dict[str, Any] = self._t.call("kimetsu_brain_memory_top", _clean(kw))
|
|
31
|
+
return res
|
|
32
|
+
|
|
33
|
+
def accept(self, proposal_id: str, **kw: Any) -> Dict[str, Any]:
|
|
34
|
+
res: Dict[str, Any] = self._t.call("kimetsu_brain_memory_accept", _clean({"proposal_id": proposal_id, **kw}))
|
|
35
|
+
return res
|
|
36
|
+
|
|
37
|
+
def reject(self, proposal_id: str, **kw: Any) -> Dict[str, Any]:
|
|
38
|
+
res: Dict[str, Any] = self._t.call("kimetsu_brain_memory_reject", _clean({"proposal_id": proposal_id, **kw}))
|
|
39
|
+
return res
|
|
40
|
+
|
|
41
|
+
def invalidate(self, memory_id: str, **kw: Any) -> Dict[str, Any]:
|
|
42
|
+
res: Dict[str, Any] = self._t.call("kimetsu_brain_memory_invalidate", _clean({"memory_id": memory_id, **kw}))
|
|
43
|
+
return res
|
|
44
|
+
|
|
45
|
+
def blame(self, run_id: str, **kw: Any) -> Dict[str, Any]:
|
|
46
|
+
"""Per-run citation attribution: which memories a run cited. Pass a run_id (ULID)."""
|
|
47
|
+
res: Dict[str, Any] = self._t.call("kimetsu_brain_memory_blame", _clean({"run_id": run_id, **kw}))
|
|
48
|
+
return res
|
|
49
|
+
|
|
50
|
+
def proposals(self, **kw: Any) -> Dict[str, Any]:
|
|
51
|
+
res: Dict[str, Any] = self._t.call("kimetsu_brain_memory_proposals", _clean(kw))
|
|
52
|
+
return res
|
|
53
|
+
|
|
54
|
+
def conflicts(self, **kw: Any) -> Dict[str, Any]:
|
|
55
|
+
res: Dict[str, Any] = self._t.call("kimetsu_brain_memory_conflicts", _clean(kw))
|
|
56
|
+
return res
|
|
57
|
+
|
|
58
|
+
def conflict_resolve(self, **kw: Any) -> Dict[str, Any]:
|
|
59
|
+
res: Dict[str, Any] = self._t.call("kimetsu_brain_conflict_resolve", _clean(kw))
|
|
60
|
+
return res
|
|
61
|
+
|
|
62
|
+
def prune(self, **kw: Any) -> Dict[str, Any]:
|
|
63
|
+
res: Dict[str, Any] = self._t.call("kimetsu_brain_prune", _clean(kw))
|
|
64
|
+
return res
|
|
65
|
+
|
|
66
|
+
|
|
67
|
+
class _Config:
|
|
68
|
+
def __init__(self, t: Any) -> None:
|
|
69
|
+
self._t = t
|
|
70
|
+
|
|
71
|
+
def show(self, **kw: Any) -> Dict[str, Any]:
|
|
72
|
+
res: Dict[str, Any] = self._t.call("kimetsu_brain_config_show", _clean(kw))
|
|
73
|
+
return res
|
|
74
|
+
|
|
75
|
+
|
|
76
|
+
class _Models:
|
|
77
|
+
def __init__(self, t: Any) -> None:
|
|
78
|
+
self._t = t
|
|
79
|
+
|
|
80
|
+
def list(self, **kw: Any) -> Dict[str, Any]:
|
|
81
|
+
res: Dict[str, Any] = self._t.call("kimetsu_brain_model_list", _clean(kw))
|
|
82
|
+
return res
|
|
83
|
+
|
|
84
|
+
|
|
85
|
+
class _Benchmark:
|
|
86
|
+
def __init__(self, t: Any) -> None:
|
|
87
|
+
self._t = t
|
|
88
|
+
|
|
89
|
+
def context(self, query: str, **kw: Any) -> Dict[str, Any]:
|
|
90
|
+
res: Dict[str, Any] = self._t.call("kimetsu_benchmark_context", _clean({"query": query, **kw}))
|
|
91
|
+
return res
|
|
92
|
+
|
|
93
|
+
def record_outcome(self, task: str, **kw: Any) -> Dict[str, Any]:
|
|
94
|
+
res: Dict[str, Any] = self._t.call("kimetsu_benchmark_record_outcome", _clean({"task": task, **kw}))
|
|
95
|
+
return res
|
|
96
|
+
|
|
97
|
+
|
|
98
|
+
class KimetsuClient:
|
|
99
|
+
def __init__(self, base_url: Optional[str] = None, token: Optional[str] = None,
|
|
100
|
+
repo: Optional[str] = None, *, timeout: float = 30.0,
|
|
101
|
+
transport: Optional[Any] = None) -> None:
|
|
102
|
+
if transport is not None:
|
|
103
|
+
self._t = transport
|
|
104
|
+
else:
|
|
105
|
+
base_url = base_url or os.environ["KIMETSU_REMOTE_URL"]
|
|
106
|
+
token = token or os.environ["KIMETSU_REMOTE_TOKEN"]
|
|
107
|
+
repo = repo or os.environ["KIMETSU_REMOTE_REPO"]
|
|
108
|
+
self._t = SyncTransport(base_url, token, repo, timeout=timeout)
|
|
109
|
+
self.memory = _Memory(self._t)
|
|
110
|
+
self.config = _Config(self._t)
|
|
111
|
+
self.models = _Models(self._t)
|
|
112
|
+
self.benchmark = _Benchmark(self._t)
|
|
113
|
+
|
|
114
|
+
def context(self, query: str, *, tags: Optional[List[str]] = None, **kw: Any) -> Context:
|
|
115
|
+
return Context.model_validate(
|
|
116
|
+
self._t.call("kimetsu_brain_context", _clean({"query": query, "tags": tags, **kw}))
|
|
117
|
+
)
|
|
118
|
+
|
|
119
|
+
def record(self, lesson: str, *, tags: List[str],
|
|
120
|
+
kind: Optional[str] = None, **kw: Any) -> Dict[str, Any]:
|
|
121
|
+
res: Dict[str, Any] = self._t.call(
|
|
122
|
+
"kimetsu_brain_record", _clean({"lesson": lesson, "tags": tags, "kind": kind, **kw})
|
|
123
|
+
)
|
|
124
|
+
return res
|
|
125
|
+
|
|
126
|
+
def status(self) -> Status:
|
|
127
|
+
return Status.model_validate(self._t.call("kimetsu_brain_status", {}))
|
|
128
|
+
|
|
129
|
+
def insights(self) -> Dict[str, Any]:
|
|
130
|
+
res: Dict[str, Any] = self._t.call("kimetsu_brain_insights", {})
|
|
131
|
+
return res
|
|
132
|
+
|
|
133
|
+
def close(self) -> None:
|
|
134
|
+
if hasattr(self._t, "close"):
|
|
135
|
+
self._t.close()
|
|
136
|
+
|
|
137
|
+
def __enter__(self) -> "KimetsuClient":
|
|
138
|
+
return self
|
|
139
|
+
|
|
140
|
+
def __exit__(self, *exc: Any) -> None:
|
|
141
|
+
self.close()
|
kimetsu/errors.py
ADDED
|
@@ -0,0 +1,31 @@
|
|
|
1
|
+
from __future__ import annotations
|
|
2
|
+
from typing import Optional
|
|
3
|
+
|
|
4
|
+
|
|
5
|
+
class KimetsuError(Exception):
|
|
6
|
+
"""Base class for all Kimetsu SDK errors."""
|
|
7
|
+
|
|
8
|
+
|
|
9
|
+
class KimetsuAuthError(KimetsuError):
|
|
10
|
+
"""HTTP 401 (missing/invalid token) or 403 (wrong repo / scope)."""
|
|
11
|
+
|
|
12
|
+
|
|
13
|
+
class KimetsuRateLimitError(KimetsuError):
|
|
14
|
+
"""HTTP 429."""
|
|
15
|
+
|
|
16
|
+
def __init__(self, message: str, *, retry_after: Optional[float] = None) -> None:
|
|
17
|
+
super().__init__(message)
|
|
18
|
+
self.retry_after = retry_after
|
|
19
|
+
|
|
20
|
+
|
|
21
|
+
class KimetsuToolError(KimetsuError):
|
|
22
|
+
"""A JSON-RPC `error` object returned in the MCP envelope."""
|
|
23
|
+
|
|
24
|
+
def __init__(self, message: str, *, code: Optional[int] = None) -> None:
|
|
25
|
+
super().__init__(message)
|
|
26
|
+
self.code = code
|
|
27
|
+
self.message = message
|
|
28
|
+
|
|
29
|
+
|
|
30
|
+
class KimetsuProtocolError(KimetsuError):
|
|
31
|
+
"""Handshake failure or malformed JSON-RPC envelope."""
|
kimetsu/models.py
ADDED
|
@@ -0,0 +1,22 @@
|
|
|
1
|
+
from __future__ import annotations
|
|
2
|
+
from typing import Any, Dict, List, Optional
|
|
3
|
+
from pydantic import BaseModel, ConfigDict
|
|
4
|
+
|
|
5
|
+
|
|
6
|
+
class _Base(BaseModel):
|
|
7
|
+
model_config = ConfigDict(extra="allow")
|
|
8
|
+
|
|
9
|
+
|
|
10
|
+
class Memory(_Base):
|
|
11
|
+
id: Optional[str] = None
|
|
12
|
+
text: Optional[str] = None
|
|
13
|
+
tags: Optional[List[str]] = None
|
|
14
|
+
|
|
15
|
+
|
|
16
|
+
class Context(_Base):
|
|
17
|
+
capsules: List[Dict[str, Any]] = []
|
|
18
|
+
|
|
19
|
+
|
|
20
|
+
class Status(_Base):
|
|
21
|
+
initialized: Optional[bool] = None
|
|
22
|
+
accepted: Optional[int] = None
|
kimetsu/py.typed
ADDED
|
File without changes
|
|
@@ -0,0 +1,124 @@
|
|
|
1
|
+
Metadata-Version: 2.4
|
|
2
|
+
Name: kimetsu
|
|
3
|
+
Version: 0.1.0
|
|
4
|
+
Summary: Typed Python client for the Kimetsu remote brain
|
|
5
|
+
Project-URL: Homepage, https://github.com/RodCor/kimetsu-py
|
|
6
|
+
Project-URL: Repository, https://github.com/RodCor/kimetsu-py
|
|
7
|
+
Project-URL: Main project, https://github.com/RodCor/kimetsu
|
|
8
|
+
Author: Rodrigo Cordoba
|
|
9
|
+
License-Expression: MIT OR Apache-2.0
|
|
10
|
+
License-File: LICENSE
|
|
11
|
+
Keywords: agent,kimetsu,llm,mcp,memory,sdk
|
|
12
|
+
Classifier: License :: OSI Approved :: Apache Software License
|
|
13
|
+
Classifier: License :: OSI Approved :: MIT License
|
|
14
|
+
Classifier: Programming Language :: Python :: 3
|
|
15
|
+
Classifier: Typing :: Typed
|
|
16
|
+
Requires-Python: >=3.9
|
|
17
|
+
Requires-Dist: httpx>=0.27
|
|
18
|
+
Requires-Dist: pydantic>=2
|
|
19
|
+
Provides-Extra: dev
|
|
20
|
+
Requires-Dist: mypy; extra == 'dev'
|
|
21
|
+
Requires-Dist: pytest-asyncio>=0.23; extra == 'dev'
|
|
22
|
+
Requires-Dist: pytest>=8; extra == 'dev'
|
|
23
|
+
Requires-Dist: respx>=0.21; extra == 'dev'
|
|
24
|
+
Requires-Dist: ruff; extra == 'dev'
|
|
25
|
+
Description-Content-Type: text/markdown
|
|
26
|
+
|
|
27
|
+
# kimetsu
|
|
28
|
+
|
|
29
|
+
Typed Python client for the Kimetsu remote brain.
|
|
30
|
+
|
|
31
|
+
## What it is
|
|
32
|
+
|
|
33
|
+
A sync + async client over the Kimetsu remote brain's MCP JSON-RPC endpoint.
|
|
34
|
+
Requires a running `kimetsu-remote` server; you supply its base URL, a bearer
|
|
35
|
+
token, and the repo name.
|
|
36
|
+
|
|
37
|
+
## Install
|
|
38
|
+
|
|
39
|
+
```
|
|
40
|
+
pip install kimetsu
|
|
41
|
+
```
|
|
42
|
+
|
|
43
|
+
## Quickstart (sync)
|
|
44
|
+
|
|
45
|
+
```python
|
|
46
|
+
from kimetsu import KimetsuClient
|
|
47
|
+
|
|
48
|
+
client = KimetsuClient(base_url="https://brain.example.com", token="tok_...", repo="web")
|
|
49
|
+
client.record("Use `just migrate`, never raw sqlx", tags=["db", "workflow"])
|
|
50
|
+
ctx = client.context("how do we run migrations?", tags=["db"])
|
|
51
|
+
print(ctx.capsules)
|
|
52
|
+
```
|
|
53
|
+
|
|
54
|
+
## Quickstart (async)
|
|
55
|
+
|
|
56
|
+
```python
|
|
57
|
+
import asyncio
|
|
58
|
+
from kimetsu import AsyncKimetsuClient
|
|
59
|
+
|
|
60
|
+
async def main():
|
|
61
|
+
async with AsyncKimetsuClient(base_url="https://brain.example.com", token="tok_...", repo="web") as client:
|
|
62
|
+
ctx = await client.context("how do we run migrations?", tags=["db"])
|
|
63
|
+
print(ctx.capsules)
|
|
64
|
+
|
|
65
|
+
asyncio.run(main())
|
|
66
|
+
```
|
|
67
|
+
|
|
68
|
+
## Configuration / env vars
|
|
69
|
+
|
|
70
|
+
`KIMETSU_REMOTE_URL`, `KIMETSU_REMOTE_TOKEN`, `KIMETSU_REMOTE_REPO` (used when
|
|
71
|
+
the matching constructor arg is omitted). Optional `timeout` (default 30s).
|
|
72
|
+
|
|
73
|
+
## API surface — method → remote tool
|
|
74
|
+
|
|
75
|
+
| SDK call | Remote tool |
|
|
76
|
+
| --- | --- |
|
|
77
|
+
| `context` | `kimetsu_brain_context` |
|
|
78
|
+
| `record` | `kimetsu_brain_record` |
|
|
79
|
+
| `status` | `kimetsu_brain_status` |
|
|
80
|
+
| `insights` | `kimetsu_brain_insights` |
|
|
81
|
+
| `memory.search` | `kimetsu_brain_memory_search` |
|
|
82
|
+
| `memory.add` | `kimetsu_brain_memory_add` |
|
|
83
|
+
| `memory.list` | `kimetsu_brain_memory_list` |
|
|
84
|
+
| `memory.top` | `kimetsu_brain_memory_top` |
|
|
85
|
+
| `memory.accept` | `kimetsu_brain_memory_accept` |
|
|
86
|
+
| `memory.reject` | `kimetsu_brain_memory_reject` |
|
|
87
|
+
| `memory.invalidate` | `kimetsu_brain_memory_invalidate` |
|
|
88
|
+
| `memory.blame` | `kimetsu_brain_memory_blame` (per-run citation attribution — pass a `run_id`, returns which memories that run cited) |
|
|
89
|
+
| `memory.proposals` | `kimetsu_brain_memory_proposals` |
|
|
90
|
+
| `memory.conflicts` | `kimetsu_brain_memory_conflicts` |
|
|
91
|
+
| `memory.conflict_resolve` | `kimetsu_brain_conflict_resolve` |
|
|
92
|
+
| `memory.prune` | `kimetsu_brain_prune` |
|
|
93
|
+
| `config.show` | `kimetsu_brain_config_show` |
|
|
94
|
+
| `models.list` | `kimetsu_brain_model_list` |
|
|
95
|
+
| `benchmark.context` | `kimetsu_benchmark_context` |
|
|
96
|
+
| `benchmark.record_outcome` | `kimetsu_benchmark_record_outcome` |
|
|
97
|
+
|
|
98
|
+
(`AsyncKimetsuClient` mirrors every method with `await`.)
|
|
99
|
+
|
|
100
|
+
Required arguments: `record` requires `tags`, `memory.add` requires `scope`,
|
|
101
|
+
and `benchmark.record_outcome` requires `task` — all three raise `TypeError`
|
|
102
|
+
if omitted, e.g. `client.benchmark.record_outcome(task="my-task", passed=True)`.
|
|
103
|
+
|
|
104
|
+
## Errors
|
|
105
|
+
|
|
106
|
+
All error types are exported from the top level: `from kimetsu import KimetsuAuthError`.
|
|
107
|
+
|
|
108
|
+
`KimetsuError` (base), `KimetsuAuthError` (401/403), `KimetsuRateLimitError`
|
|
109
|
+
(429, `.retry_after`), `KimetsuToolError` (JSON-RPC tool error, `.code`),
|
|
110
|
+
`KimetsuProtocolError` (handshake/malformed envelope).
|
|
111
|
+
|
|
112
|
+
## Typed returns
|
|
113
|
+
|
|
114
|
+
`context`→`Context` (`.capsules`), `status`→`Status` (`.initialized`,
|
|
115
|
+
`.accepted`), `memory.add`→`Memory` (`.id`, `.text`, `.tags`). Other methods
|
|
116
|
+
return `dict`.
|
|
117
|
+
|
|
118
|
+
## License
|
|
119
|
+
|
|
120
|
+
MIT OR Apache-2.0.
|
|
121
|
+
|
|
122
|
+
## Links
|
|
123
|
+
|
|
124
|
+
Main project: https://github.com/RodCor/kimetsu
|
|
@@ -0,0 +1,11 @@
|
|
|
1
|
+
kimetsu/__init__.py,sha256=ClUo2u5NrEYBJHYn9VPEwZq56dHb235dp-zGs9GF1a4,534
|
|
2
|
+
kimetsu/_transport.py,sha256=AJ7nJurvlhkd4Qi5W7ONB-qy8UUhi3elzMubtzaXrIA,5172
|
|
3
|
+
kimetsu/async_client.py,sha256=xrFmyHDJv9ESsNGR4-wJiqnHRVEG641jDIMj6KvQ-Ho,5529
|
|
4
|
+
kimetsu/client.py,sha256=Ypk6ZKCEhlxigau5ISE_WPX7-zuvf8EyBTS5dKjDP5E,5342
|
|
5
|
+
kimetsu/errors.py,sha256=9ZJkrAIfJsTadOQbb867JbLjTC6TwewyLn2RJQGAIZc,860
|
|
6
|
+
kimetsu/models.py,sha256=cYCfFEuYUuqPQnlIzp8tPwiUeZ3DEUTNWwcm5I0-0q0,475
|
|
7
|
+
kimetsu/py.typed,sha256=47DEQpj8HBSa-_TImW-5JCeuQeRkm5NMpJWZG3hSuFU,0
|
|
8
|
+
kimetsu-0.1.0.dist-info/METADATA,sha256=YjLWuHzHSzipVb5Xk44qgftrbT9qfsNhdPB0gQnueuU,4173
|
|
9
|
+
kimetsu-0.1.0.dist-info/WHEEL,sha256=lCkmxWfQsSc9CfIClYeavTdQeEX2toPqufh9gI35EQA,87
|
|
10
|
+
kimetsu-0.1.0.dist-info/licenses/LICENSE,sha256=FhlD8Gb80t26OwsXm9p-SxRhNoNn4lznMl7LFMilrmc,7135
|
|
11
|
+
kimetsu-0.1.0.dist-info/RECORD,,
|
|
@@ -0,0 +1,150 @@
|
|
|
1
|
+
Licensed under either of MIT or Apache-2.0 at your option.
|
|
2
|
+
|
|
3
|
+
================================================================================
|
|
4
|
+
MIT License
|
|
5
|
+
================================================================================
|
|
6
|
+
|
|
7
|
+
Copyright (c) 2026 RodCor
|
|
8
|
+
|
|
9
|
+
Permission is hereby granted, free of charge, to any person obtaining a copy
|
|
10
|
+
of this software and associated documentation files (the "Software"), to deal
|
|
11
|
+
in the Software without restriction, including without limitation the rights
|
|
12
|
+
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
|
|
13
|
+
copies of the Software, and to permit persons to whom the Software is
|
|
14
|
+
furnished to do so, subject to the following conditions:
|
|
15
|
+
|
|
16
|
+
The above copyright notice and this permission notice shall be included in all
|
|
17
|
+
copies or substantial portions of the Software.
|
|
18
|
+
|
|
19
|
+
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
|
|
20
|
+
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
|
|
21
|
+
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
|
|
22
|
+
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
|
|
23
|
+
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
|
|
24
|
+
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
|
|
25
|
+
SOFTWARE.
|
|
26
|
+
|
|
27
|
+
================================================================================
|
|
28
|
+
Apache License
|
|
29
|
+
Version 2.0, January 2004
|
|
30
|
+
http://www.apache.org/licenses/
|
|
31
|
+
================================================================================
|
|
32
|
+
|
|
33
|
+
Copyright 2026 RodCor
|
|
34
|
+
|
|
35
|
+
Licensed under the Apache License, Version 2.0 (the "License");
|
|
36
|
+
you may not use this file except in compliance with the License.
|
|
37
|
+
You may obtain a copy of the License at
|
|
38
|
+
|
|
39
|
+
http://www.apache.org/licenses/LICENSE-2.0
|
|
40
|
+
|
|
41
|
+
Unless required by applicable law or agreed to in writing, software
|
|
42
|
+
distributed under the License is distributed on an "AS IS" BASIS,
|
|
43
|
+
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
|
44
|
+
See the License for the specific language governing permissions and
|
|
45
|
+
limitations under the License.
|
|
46
|
+
|
|
47
|
+
TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
|
|
48
|
+
|
|
49
|
+
1. Definitions.
|
|
50
|
+
|
|
51
|
+
"License" shall mean the terms and conditions for use, reproduction, and
|
|
52
|
+
distribution as defined by Sections 1 through 9 of this document.
|
|
53
|
+
|
|
54
|
+
"Licensor" shall mean the copyright owner or entity authorized by the
|
|
55
|
+
copyright owner that is granting the License.
|
|
56
|
+
|
|
57
|
+
"Legal Entity" shall mean the union of the acting entity and all other
|
|
58
|
+
entities that control, are controlled by, or are under common control with
|
|
59
|
+
that entity. For the purposes of this definition, "control" means (i) the
|
|
60
|
+
power, direct or indirect, to cause the direction or management of such
|
|
61
|
+
entity, whether by contract or otherwise, or (ii) ownership of fifty percent
|
|
62
|
+
(50%) or more of the outstanding shares, or (iii) beneficial ownership of such
|
|
63
|
+
entity.
|
|
64
|
+
|
|
65
|
+
"You" (or "Your") shall mean an individual or Legal Entity exercising
|
|
66
|
+
permissions granted by this License.
|
|
67
|
+
|
|
68
|
+
"Source" form shall mean the preferred form for making modifications,
|
|
69
|
+
including but not limited to software source code, documentation source, and
|
|
70
|
+
configuration files.
|
|
71
|
+
|
|
72
|
+
"Object" form shall mean any form resulting from mechanical transformation or
|
|
73
|
+
translation of a Source form, including but not limited to compiled object
|
|
74
|
+
code, generated documentation, and conversions to other media types.
|
|
75
|
+
|
|
76
|
+
"Work" shall mean the work of authorship, whether in Source or Object form,
|
|
77
|
+
made available under the License, as indicated by a copyright notice that is
|
|
78
|
+
included in or attached to the work (an example is provided in the Appendix
|
|
79
|
+
below).
|
|
80
|
+
|
|
81
|
+
"Derivative Works" shall mean any work, whether in Source or Object form,
|
|
82
|
+
that is based on (or derived from) the Work and for which the editorial
|
|
83
|
+
revisions, annotations, elaborations, or other modifications represent, as a
|
|
84
|
+
whole, an original work of authorship.
|
|
85
|
+
|
|
86
|
+
"Contribution" shall mean any work of authorship, including the original
|
|
87
|
+
version of the Work and any modifications or additions to that Work or
|
|
88
|
+
Derivative Works thereof, that is intentionally submitted to Licensor for
|
|
89
|
+
inclusion in the Work by the copyright owner or by an individual or Legal
|
|
90
|
+
Entity authorized to submit on behalf of the copyright owner.
|
|
91
|
+
|
|
92
|
+
"Contributor" shall mean Licensor and any individual or Legal Entity on
|
|
93
|
+
behalf of whom a Contribution has been received by Licensor and subsequently
|
|
94
|
+
incorporated within the Work.
|
|
95
|
+
|
|
96
|
+
2. Grant of Copyright License. Subject to the terms and conditions of this
|
|
97
|
+
License, each Contributor hereby grants to You a perpetual, worldwide,
|
|
98
|
+
non-exclusive, no-charge, royalty-free, irrevocable copyright license to
|
|
99
|
+
reproduce, prepare Derivative Works of, publicly display, publicly perform,
|
|
100
|
+
sublicense, and distribute the Work and such Derivative Works in Source or
|
|
101
|
+
Object form.
|
|
102
|
+
|
|
103
|
+
3. Grant of Patent License. Subject to the terms and conditions of this
|
|
104
|
+
License, each Contributor hereby grants to You a perpetual, worldwide,
|
|
105
|
+
non-exclusive, no-charge, royalty-free, irrevocable (except as stated in this
|
|
106
|
+
section) patent license to make, have made, use, offer to sell, sell, import,
|
|
107
|
+
and otherwise transfer the Work.
|
|
108
|
+
|
|
109
|
+
4. Redistribution. You may reproduce and distribute copies of the Work or
|
|
110
|
+
Derivative Works thereof in any medium, with or without modifications, and in
|
|
111
|
+
Source or Object form, provided that You meet the following conditions:
|
|
112
|
+
|
|
113
|
+
(a) You must give any other recipients of the Work or Derivative Works a
|
|
114
|
+
copy of this License; and
|
|
115
|
+
|
|
116
|
+
(b) You must cause any modified files to carry prominent notices stating
|
|
117
|
+
that You changed the files; and
|
|
118
|
+
|
|
119
|
+
(c) You must retain, in the Source form of any Derivative Works that You
|
|
120
|
+
distribute, all copyright, patent, trademark, and attribution notices
|
|
121
|
+
from the Source form of the Work; and
|
|
122
|
+
|
|
123
|
+
(d) If the Work includes a "NOTICE" text file as part of its
|
|
124
|
+
distribution, then any Derivative Works that You distribute must
|
|
125
|
+
include a readable copy of the attribution notices contained within
|
|
126
|
+
such NOTICE file.
|
|
127
|
+
|
|
128
|
+
5. Submission of Contributions. Unless You explicitly state otherwise, any
|
|
129
|
+
Contribution intentionally submitted for inclusion in the Work by You to the
|
|
130
|
+
Licensor shall be under the terms and conditions of this License, without any
|
|
131
|
+
additional terms or conditions.
|
|
132
|
+
|
|
133
|
+
6. Trademarks. This License does not grant permission to use the trade
|
|
134
|
+
names, trademarks, service marks, or product names of the Licensor.
|
|
135
|
+
|
|
136
|
+
7. Disclaimer of Warranty. Unless required by applicable law or agreed to in
|
|
137
|
+
writing, Licensor provides the Work on an "AS IS" BASIS, WITHOUT WARRANTIES
|
|
138
|
+
OR CONDITIONS OF ANY KIND, either express or implied.
|
|
139
|
+
|
|
140
|
+
8. Limitation of Liability. In no event and under no legal theory shall any
|
|
141
|
+
Contributor be liable to You for damages, including any direct, indirect,
|
|
142
|
+
special, incidental, or consequential damages arising as a result of this
|
|
143
|
+
License.
|
|
144
|
+
|
|
145
|
+
9. Accepting Warranty or Additional Liability. While redistributing the Work
|
|
146
|
+
or Derivative Works thereof, You may choose to offer, and charge a fee for,
|
|
147
|
+
acceptance of support, warranty, indemnity, or other liability obligations
|
|
148
|
+
consistent with this License.
|
|
149
|
+
|
|
150
|
+
END OF TERMS AND CONDITIONS
|