1
"""agentgit — MCP server (JSON-RPC 2.0 over a Streamable-HTTP style endpoint).
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
7
An agent only sees its owner's projects plus projects marked `public`.
9
from __future__ import annotations
14
from pathlib import Path
17
from .db import Store, dumps, query_terms
19
PROTOCOL = "2025-06-18"
20
SERVER = {"name": "agentgit", "version": "0.1.0"}
25
"description": "Identity behind the current token — owner or agent — with short counters.",
26
"inputSchema": {"type": "object", "properties": {}, "additionalProperties": False},
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.",
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"},
39
"additionalProperties": False,
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.",
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"]},
54
"additionalProperties": False,
58
"name": "project_status",
59
"description": "Index status of one project: pending/running/ready/failed plus counters.",
62
"properties": {"project": {"type": "string", "description": "id or name"}},
63
"required": ["project"],
64
"additionalProperties": False,
68
"name": "project_list",
69
"description": "Projects this token is allowed to learn from.",
70
"inputSchema": {"type": "object", "properties": {}, "additionalProperties": False},
73
"name": "project_summary",
74
"description": "Project shape: languages, top directories, last commit — for orientation.",
77
"properties": {"project": {"type": "string"}},
78
"required": ["project"],
79
"additionalProperties": False,
83
"name": "knowledge_search",
84
"description": "Search every readable project file. Returns snippets of the original text with path:line citations.",
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},
92
"required": ["query"],
93
"additionalProperties": False,
97
"name": "knowledge_doc",
98
"description": "Read one project file (or continue from a given line) verbatim.",
102
"project": {"type": "string"},
103
"path": {"type": "string"},
104
"start_line": {"type": "integer", "minimum": 1, "default": 1},
106
"required": ["project", "path"],
107
"additionalProperties": False,
112
"description": "Store a lesson or finding so `recall` can bring it back later.",
116
"body": {"type": "string"},
117
"tags": {"type": "string", "description": "dipisah koma"},
118
"project": {"type": "string"},
120
"required": ["body"],
121
"additionalProperties": False,
126
"description": "Search notes this agent wrote earlier.",
130
"query": {"type": "string"},
131
"limit": {"type": "integer", "minimum": 1, "maximum": 20, "default": 8},
133
"required": ["query"],
134
"additionalProperties": False,
139
USER_TOOLS = {"agent_register", "project_add"}
140
AGENT_ONLY = {"knowledge_search", "knowledge_doc", "remember", "recall", "project_summary"}
143
class RpcError(Exception):
144
def __init__(self, code: int, message: str, data=None):
145
super().__init__(message)
147
self.message = message
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")
156
if str(ref).isdigit():
157
row = store.project(int(ref))
159
for p in store.visible_projects(who["row"]):
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}")
170
def index_project(store: Store, project, data_dir: Path) -> dict:
171
dest = Path(project["path"])
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))
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}
185
# ---------------------------------------------------------------- tools
186
def tool_whoami(store, who, args):
187
if who["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"]),
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"]),
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()
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", ""))
215
"agent_id": agent_id,
218
"note": "Store this token; it is shown once. Send it as Bearer on /mcp.",
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()
227
raise RpcError(-32602, "name is required")
228
url = str(args.get("url", "")).strip()
229
visibility = args.get("visibility", "owner")
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()
236
raise RpcError(-32602, f"path does not exist: {p}")
239
if not url and not path:
240
raise RpcError(-32602, "'url' (repo) or a local path is required")
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"}
249
def tool_project_status(store, who, args):
250
p = _project_for(store, who, args.get("project", ""))
251
job = store.latest_job(p["id"])
253
"project": p["name"],
255
"status": p["status"],
257
"commit": p["commit_sha"],
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")}
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"]])
275
"visibility": r["visibility"],
276
"status": r["status"],
277
"commit": r["commit_sha"],
279
"chunks": r["chunks"],
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]
299
def tool_knowledge_search(store, who, args):
300
q = str(args.get("query", "")).strip()
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"]]
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"])}
312
"project": by_id.get(h["project_id"], str(h["project_id"])),
314
"lines": f'{h["start_line"]}-{h["end_line"]}',
316
"snippet": h["snip"],
317
"score": round(float(h["score"]), 4),
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"}
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)))
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)
336
"project": p["name"],
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),
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()
351
raise RpcError(-32602, "body terlalu pendek")
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}
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()
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)
370
{"id": r["id"], "body": r["body"], "tags": r["tags"], "at": r["created_at"],
371
"project_id": r["project_id"], "snippet": r["snip"]}
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,
391
def identify(store: Store, token: str) -> dict:
393
raise RpcError(-32001, "an Authorization: Bearer <token> header is required")
394
if token.startswith("ag_agt_"):
395
row = store.agent_by_token(token)
397
raise RpcError(-32001, "unknown agent token")
398
return {"kind": "agent", "row": row}
399
row = store.user_by_token(token)
401
raise RpcError(-32001, "unknown user token")
402
return {"kind": "user", "row": row}
405
def _ok(msg_id, result):
406
return {"jsonrpc": "2.0", "id": msg_id, "result": result}
409
def _err(msg_id, code, message, data=None):
410
e = {"code": code, "message": message}
413
return {"jsonrpc": "2.0", "id": msg_id, "error": e}
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."""
419
method = msg.get("method", "")
420
params = msg.get("params") or {}
422
if method == "initialize":
424
"protocolVersion": params.get("protocolVersion") or PROTOCOL,
425
"capabilities": {"tools": {"listChanged": False}},
426
"serverInfo": SERVER,
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."
433
if method.startswith("notifications/"):
437
if method == "tools/list":
438
return _ok(mid, {"tools": TOOLS})
440
if method != "tools/call":
441
return _err(mid, -32601, f"unknown method: {method}")
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}")
448
t0 = time.perf_counter()
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])
459
"content": [{"type": "text", "text": dumps(result)}],
460
"structuredContent": result,
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})
472
def handle_http(store: Store, token: str, body: bytes, data_dir: Path) -> tuple[int, dict | None]:
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]
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)