aimb-x/agentgit
repositories / aimb-x / agentgit

agentgit public

git clone https://git.169.58.159.131.nip.io/aimb-x/agentgit.git
agentgit/mcp.py 18168 bytes 1 lines
1
"""agentgit — MCP server (JSON-RPC 2.0 over a Streamable-HTTP style endpoint).
2
3
One endpoint, `POST /mcp`. Identity comes from the Bearer token:
4
ag_usr_… human/owner → registers agents, adds projects, triggers indexing
5
ag_agt_… agent → searches knowledge, reads files, writes notes
6
7
An agent only sees its owner's projects plus projects marked `public`.
8
"""
9
from __future__ import annotations
10
11
import json
12
import time
13
import traceback
14
from pathlib import Path
15
16
from . import indexer
17
from .db import Store, dumps, query_terms
18
19
PROTOCOL = "2025-06-18"
20
SERVER = {"name": "agentgit", "version": "0.1.0"}
21
22
TOOLS = [
23
{
24
"name": "whoami",
25
"description": "Identity behind the current token — owner or agent — with short counters.",
26
"inputSchema": {"type": "object", "properties": {}, "additionalProperties": False},
27
},
28
{
29
"name": "agent_register",
30
"description": "Register a new agent for the token's owner (needs a user token). The agent token is returned once — store it.",
31
"inputSchema": {
32
"type": "object",
33
"properties": {
34
"name": {"type": "string", "description": "Unique agent name within this account"},
35
"description": {"type": "string"},
36
"model": {"type": "string", "description": "mis. claude-sonnet-4.6 / hermes"},
37
},
38
"required": ["name"],
39
"additionalProperties": False,
40
},
41
},
42
{
43
"name": "project_add",
44
"description": "Add a project (git repo URL or local path) to learn from (needs a user token). Indexing runs asynchronously.",
45
"inputSchema": {
46
"type": "object",
47
"properties": {
48
"name": {"type": "string"},
49
"url": {"type": "string", "description": "https://github.com/… or a local path"},
50
"ref": {"type": "string", "description": "branch/tag/commit opsional"},
51
"visibility": {"type": "string", "enum": ["owner", "public"]},
52
},
53
"required": ["name"],
54
"additionalProperties": False,
55
},
56
},
57
{
58
"name": "project_status",
59
"description": "Index status of one project: pending/running/ready/failed plus counters.",
60
"inputSchema": {
61
"type": "object",
62
"properties": {"project": {"type": "string", "description": "id or name"}},
63
"required": ["project"],
64
"additionalProperties": False,
65
},
66
},
67
{
68
"name": "project_list",
69
"description": "Projects this token is allowed to learn from.",
70
"inputSchema": {"type": "object", "properties": {}, "additionalProperties": False},
71
},
72
{
73
"name": "project_summary",
74
"description": "Project shape: languages, top directories, last commit — for orientation.",
75
"inputSchema": {
76
"type": "object",
77
"properties": {"project": {"type": "string"}},
78
"required": ["project"],
79
"additionalProperties": False,
80
},
81
},
82
{
83
"name": "knowledge_search",
84
"description": "Search every readable project file. Returns snippets of the original text with path:line citations.",
85
"inputSchema": {
86
"type": "object",
87
"properties": {
88
"query": {"type": "string"},
89
"project": {"type": "string", "description": "limit to one project (id/name), optional"},
90
"limit": {"type": "integer", "minimum": 1, "maximum": 20, "default": 8},
91
},
92
"required": ["query"],
93
"additionalProperties": False,
94
},
95
},
96
{
97
"name": "knowledge_doc",
98
"description": "Read one project file (or continue from a given line) verbatim.",
99
"inputSchema": {
100
"type": "object",
101
"properties": {
102
"project": {"type": "string"},
103
"path": {"type": "string"},
104
"start_line": {"type": "integer", "minimum": 1, "default": 1},
105
},
106
"required": ["project", "path"],
107
"additionalProperties": False,
108
},
109
},
110
{
111
"name": "remember",
112
"description": "Store a lesson or finding so `recall` can bring it back later.",
113
"inputSchema": {
114
"type": "object",
115
"properties": {
116
"body": {"type": "string"},
117
"tags": {"type": "string", "description": "dipisah koma"},
118
"project": {"type": "string"},
119
},
120
"required": ["body"],
121
"additionalProperties": False,
122
},
123
},
124
{
125
"name": "recall",
126
"description": "Search notes this agent wrote earlier.",
127
"inputSchema": {
128
"type": "object",
129
"properties": {
130
"query": {"type": "string"},
131
"limit": {"type": "integer", "minimum": 1, "maximum": 20, "default": 8},
132
},
133
"required": ["query"],
134
"additionalProperties": False,
135
},
136
},
137
]
138
139
USER_TOOLS = {"agent_register", "project_add"}
140
AGENT_ONLY = {"knowledge_search", "knowledge_doc", "remember", "recall", "project_summary"}
141
142
143
class RpcError(Exception):
144
def __init__(self, code: int, message: str, data=None):
145
super().__init__(message)
146
self.code = code
147
self.message = message
148
self.data = data
149
150
151
def _project_for(store: Store, who, ref: str):
152
"""Resolve a project by id or name, enforcing read permission."""
153
if ref is None or ref == "":
154
raise RpcError(-32602, "parameter 'project' is required")
155
row = None
156
if str(ref).isdigit():
157
row = store.project(int(ref))
158
if row is None:
159
for p in store.visible_projects(who["row"]):
160
if p["name"] == ref:
161
row = p
162
break
163
if row is None:
164
raise RpcError(-32002, f"project {ref!r} not found")
165
if not store.can_read(who["row"], row):
166
raise RpcError(-32001, f"no access to project {row['name']!r}")
167
return row
168
169
170
def index_project(store: Store, project, data_dir: Path) -> dict:
171
dest = Path(project["path"])
172
if project["url"]:
173
dest = data_dir / "repos" / f"{project['id']}-{project['name']}"
174
commit = indexer.clone(project["url"], dest, project["ref"])
175
store.update_project(project["id"], path=str(dest))
176
else:
177
commit = indexer.summary(dest).get("commit", "")
178
if not dest.exists():
179
raise RuntimeError(f"path does not exist: {dest}")
180
chunks, files, nbytes = indexer.collect(dest)
181
n = store.replace_docs(project["id"], chunks, files, nbytes, commit)
182
return {"project_id": project["id"], "commit": commit, "files": files, "bytes": nbytes, "chunks": n}
183
184
185
# ---------------------------------------------------------------- tools
186
def tool_whoami(store, who, args):
187
if who["kind"] == "agent":
188
return {
189
"kind": "agent",
190
"agent": who["row"]["name"],
191
"id": who["row"]["id"],
192
"owner": who["row"]["owner"],
193
"model": who["row"]["model"],
194
"projects_visible": len(store.visible_projects(who["row"])),
195
"notes": store.count_notes(who["row"]["id"]),
196
}
197
return {
198
"kind": "user",
199
"user": who["row"]["name"],
200
"id": who["row"]["id"],
201
"projects": sum(1 for p in store.projects() if p["user_id"] == who["row"]["id"]),
202
}
203
204
205
def tool_agent_register(store, who, args):
206
if who["kind"] != "user":
207
raise RpcError(-32001, "agent_register needs a user token (ag_usr_…)")
208
name = str(args.get("name", "")).strip()
209
if not name:
210
raise RpcError(-32602, "name is required")
211
agent_id, token = store.create_agent(
212
who["row"]["id"], name, str(args.get("description", "")), str(args.get("model", ""))
213
)
214
return {
215
"agent_id": agent_id,
216
"name": name,
217
"token": token,
218
"note": "Store this token; it is shown once. Send it as Bearer on /mcp.",
219
}
220
221
222
def tool_project_add(store, who, args):
223
if who["kind"] != "user":
224
raise RpcError(-32001, "project_add needs a user token (ag_usr_…)")
225
name = str(args.get("name", "")).strip()
226
if not name:
227
raise RpcError(-32602, "name is required")
228
url = str(args.get("url", "")).strip()
229
visibility = args.get("visibility", "owner")
230
path = ""
231
if url and not url.startswith(("http://", "https://", "git@", "ssh://", "/", "file://")):
232
raise RpcError(-32602, "url must be http(s)://, git@ or an absolute local path")
233
if url and url.startswith("/"):
234
p = Path(url).resolve()
235
if not p.exists():
236
raise RpcError(-32602, f"path does not exist: {p}")
237
path = str(p)
238
url = ""
239
if not url and not path:
240
raise RpcError(-32602, "'url' (repo) or a local path is required")
241
try:
242
pid = store.add_project(who["row"]["id"], name, url, str(args.get("ref", "")), path, visibility)
243
except Exception as e:
244
raise RpcError(-32002, str(e))
245
job = store.enqueue_job(pid)
246
return {"project_id": pid, "name": name, "job_id": job, "status": "queued"}
247
248
249
def tool_project_status(store, who, args):
250
p = _project_for(store, who, args.get("project", ""))
251
job = store.latest_job(p["id"])
252
return {
253
"project": p["name"],
254
"id": p["id"],
255
"status": p["status"],
256
"error": p["error"],
257
"commit": p["commit_sha"],
258
"files": p["files"],
259
"bytes": p["bytes"],
260
"chunks": p["chunks"],
261
"indexed_at": p["indexed_at"],
262
"job": ({k: job.get(k) for k in ("status", "message", "created_at", "finished_at")}
263
if job else None),
264
}
265
266
267
def tool_project_list(store, who, args):
268
rows = (store.visible_projects(who["row"]) if who["kind"] == "agent"
269
else [p for p in store.projects() if p["user_id"] == who["row"]["id"]])
270
return [
271
{
272
"id": r["id"],
273
"name": r["name"],
274
"owner": r["owner"],
275
"visibility": r["visibility"],
276
"status": r["status"],
277
"commit": r["commit_sha"],
278
"files": r["files"],
279
"chunks": r["chunks"],
280
"url": r["url"],
281
}
282
for r in rows
283
]
284
285
286
def tool_project_summary(store, who, args):
287
p = _project_for(store, who, args.get("project", ""))
288
root = Path(p["path"])
289
if not root.exists():
290
raise RpcError(-32002, f"project files are missing on the server: {p['name']}")
291
info = indexer.summary(root)
292
info.update({"project": p["name"], "id": p["id"], "status": p["status"],
293
"chunks_indexed": p["chunks"], "indexed_at": p["indexed_at"]})
294
files = store.file_map(p["id"])[:40]
295
info["largest_files"] = [{"path": f["path"], "lines": f["lines"]} for f in files]
296
return info
297
298
299
def tool_knowledge_search(store, who, args):
300
q = str(args.get("query", "")).strip()
301
if not q:
302
raise RpcError(-32602, "query is required")
303
limit = max(1, min(20, int(args.get("limit", 8))))
304
if args.get("project"):
305
ids = [_project_for(store, who, args["project"])["id"]]
306
else:
307
ids = [p["id"] for p in store.visible_projects(who["row"])]
308
hits = store.search(q, ids, limit)
309
by_id = {p["id"]: p["name"] for p in store.visible_projects(who["row"])}
310
out = [
311
{
312
"project": by_id.get(h["project_id"], str(h["project_id"])),
313
"path": h["path"],
314
"lines": f'{h["start_line"]}-{h["end_line"]}',
315
"lang": h["lang"],
316
"snippet": h["snip"],
317
"score": round(float(h["score"]), 4),
318
}
319
for h in hits
320
]
321
return {"query": q, "terms": query_terms(q), "hits": len(out), "results": out,
322
"hint": "open the full text with knowledge_doc(project, path, start_line)" if out else
323
"no results; try other keywords or index the project first"}
324
325
326
def tool_knowledge_doc(store, who, args):
327
p = _project_for(store, who, args.get("project", ""))
328
path = str(args.get("path", "")).strip().lstrip("/")
329
if not path or ".." in path:
330
raise RpcError(-32602, "path is not valid")
331
rows = store.doc_text(p["id"], path, int(args.get("start_line", 1)))
332
if not rows:
333
raise RpcError(-32002, f"file {path!r} is not in the index of project {p['name']!r}")
334
text = "\n".join(r["body"] for r in rows)
335
return {
336
"project": p["name"],
337
"path": path,
338
"lang": rows[0]["lang"],
339
"from_line": rows[0]["start_line"],
340
"to_line": rows[-1]["end_line"],
341
"total_lines": store.total_lines(p["id"], path),
342
"content": text,
343
}
344
345
346
def tool_remember(store, who, args):
347
if who["kind"] != "agent":
348
raise RpcError(-32001, "remember is agent-only (ag_agt_…)")
349
body = str(args.get("body", "")).strip()
350
if len(body) < 8:
351
raise RpcError(-32602, "body terlalu pendek")
352
pid = None
353
if args.get("project"):
354
pid = _project_for(store, who, args["project"])["id"]
355
nid = store.add_note(who["row"]["id"], body, str(args.get("tags", "")), pid)
356
return {"note_id": nid, "agent": who["row"]["name"], "project_id": pid}
357
358
359
def tool_recall(store, who, args):
360
if who["kind"] != "agent":
361
raise RpcError(-32001, "recall is agent-only (ag_agt_…)")
362
q = str(args.get("query", "")).strip()
363
if not q:
364
raise RpcError(-32602, "query is required")
365
limit = max(1, min(20, int(args.get("limit", 8))))
366
rows = store.recall(q, who["row"]["id"], limit)
367
return {
368
"query": q,
369
"notes": [
370
{"id": r["id"], "body": r["body"], "tags": r["tags"], "at": r["created_at"],
371
"project_id": r["project_id"], "snippet": r["snip"]}
372
for r in rows
373
],
374
}
375
376
377
HANDLERS = {
378
"whoami": tool_whoami,
379
"agent_register": tool_agent_register,
380
"project_add": tool_project_add,
381
"project_status": tool_project_status,
382
"project_list": tool_project_list,
383
"project_summary": tool_project_summary,
384
"knowledge_search": tool_knowledge_search,
385
"knowledge_doc": tool_knowledge_doc,
386
"remember": tool_remember,
387
"recall": tool_recall,
388
}
389
390
391
def identify(store: Store, token: str) -> dict:
392
if not token:
393
raise RpcError(-32001, "an Authorization: Bearer <token> header is required")
394
if token.startswith("ag_agt_"):
395
row = store.agent_by_token(token)
396
if not row:
397
raise RpcError(-32001, "unknown agent token")
398
return {"kind": "agent", "row": row}
399
row = store.user_by_token(token)
400
if not row:
401
raise RpcError(-32001, "unknown user token")
402
return {"kind": "user", "row": row}
403
404
405
def _ok(msg_id, result):
406
return {"jsonrpc": "2.0", "id": msg_id, "result": result}
407
408
409
def _err(msg_id, code, message, data=None):
410
e = {"code": code, "message": message}
411
if data is not None:
412
e["data"] = data
413
return {"jsonrpc": "2.0", "id": msg_id, "error": e}
414
415
416
def handle(store: Store, token: str, msg: dict, data_dir: Path) -> dict | None:
417
"""Proses satu pesan JSON-RPC. Notifikasi (tanpa id) mengembalikan None."""
418
mid = msg.get("id")
419
method = msg.get("method", "")
420
params = msg.get("params") or {}
421
422
if method == "initialize":
423
return _ok(mid, {
424
"protocolVersion": params.get("protocolVersion") or PROTOCOL,
425
"capabilities": {"tools": {"listChanged": False}},
426
"serverInfo": SERVER,
427
"instructions": (
428
"agentgit: a project knowledge base. Start with project_list, then "
429
"project_summary, then knowledge_search. Every hit carries a "
430
"path:line citation."
431
),
432
})
433
if method.startswith("notifications/"):
434
return None
435
if method == "ping":
436
return _ok(mid, {})
437
if method == "tools/list":
438
return _ok(mid, {"tools": TOOLS})
439
440
if method != "tools/call":
441
return _err(mid, -32601, f"unknown method: {method}")
442
443
name = params.get("name", "")
444
args = params.get("arguments") or {}
445
if name not in HANDLERS:
446
return _err(mid, -32602, f"unknown tool: {name}")
447
448
t0 = time.perf_counter()
449
try:
450
who = identify(store, token)
451
if name in USER_TOOLS and who["kind"] != "user":
452
raise RpcError(-32001, f"{name} needs a user token (ag_usr_…)")
453
if name in AGENT_ONLY and who["kind"] != "agent":
454
raise RpcError(-32001, f"{name} needs an agent token (ag_agt_…)")
455
result = HANDLERS[name](store, who, args)
456
ms = int((time.perf_counter() - t0) * 1000)
457
store.log(name, True, ms, who["row"]["id"], json.dumps(args)[:200])
458
return _ok(mid, {
459
"content": [{"type": "text", "text": dumps(result)}],
460
"structuredContent": result,
461
"isError": False,
462
})
463
except RpcError as e:
464
store.log(name, False, int((time.perf_counter() - t0) * 1000), None, e.message)
465
return _ok(mid, {"content": [{"type": "text", "text": f"error: {e.message}"}], "isError": True})
466
except Exception as e: # pragma: no cover
467
tb = traceback.format_exc(limit=3)
468
store.log(name, False, int((time.perf_counter() - t0) * 1000), None, str(e))
469
return _ok(mid, {"content": [{"type": "text", "text": f"internal error: {e}\n{tb}"}], "isError": True})
470
471
472
def handle_http(store: Store, token: str, body: bytes, data_dir: Path) -> tuple[int, dict | None]:
473
try:
474
payload = json.loads(body or b"{}")
475
except json.JSONDecodeError as e:
476
return 400, _err(None, -32700, f"invalid JSON: {e}")
477
if isinstance(payload, list):
478
out = [r for r in (handle(store, token, m, data_dir) for m in payload) if r is not None]
479
return 200, out
480
if not isinstance(payload, dict) or "method" not in payload:
481
return 400, _err(payload.get("id") if isinstance(payload, dict) else None, -32600, "bukan JSON-RPC")
482
res = handle(store, token, payload, data_dir)
483
return 200, res