1
"""agentgit tests: MCP JSON-RPC, auth, local indexing, project scoping, notes, web."""
2
from __future__ import annotations
12
from pathlib import Path
14
ROOT = Path(__file__).resolve().parent.parent
15
sys.path.insert(0, str(ROOT))
17
from agentgit import mcp # noqa: E402
18
from agentgit.db import Store # noqa: E402
20
PROJ = Path("/root/sinema") # small repo that exists on this machine
23
def call(store, token, name, args=None, rid=1):
24
msg = {"jsonrpc": "2.0", "id": rid, "method": "tools/call",
25
"params": {"name": name, "arguments": args or {}}}
26
res = mcp.handle(store, token, msg, PROJ)
31
"""Return structuredContent, or {"error": text} when the tool reported failure."""
33
return r["structuredContent"] if not r.get("isError") else {"error": r["content"][0]["text"]}
36
class Base(unittest.TestCase):
38
self.tmp = Path(tempfile.mkdtemp(prefix="agentgit-test-"))
39
self.store = Store(self.tmp / "t.sqlite3")
40
self.uid, self.utok = self.store.create_user("bagas", "bagas@aimb-x.xyz")
41
self.aid, self.atok = self.store.create_agent(self.uid, "nara", "riset", "hermes")
42
self.uid2, self.utok2 = self.store.create_user("sena", "sena@aimb-x.xyz")
43
self.aid2, self.atok2 = self.store.create_agent(self.uid2, "adit", "qa", "hermes")
47
shutil.rmtree(self.tmp, ignore_errors=True)
49
def add_project(self, user_id=1, name="sinema", visibility="owner", path=str(PROJ)):
50
pid = self.store.add_project(user_id, name, "", "", path, visibility)
51
proj = self.store.project(pid)
52
mcp.index_project(self.store, proj, self.tmp)
56
class ProtocolTests(Base):
57
def test_initialize_and_tools_list(self):
58
res = mcp.handle(self.store, self.utok,
59
{"jsonrpc": "2.0", "id": 1, "method": "initialize",
60
"params": {"protocolVersion": "2025-06-18"}}, self.tmp)
61
self.assertEqual(res["result"]["serverInfo"]["name"], "agentgit")
62
self.assertIn("tools", res["result"]["capabilities"])
63
tl = mcp.handle(self.store, self.utok, {"jsonrpc": "2.0", "id": 2, "method": "tools/list"}, self.tmp)
64
names = {t["name"] for t in tl["result"]["tools"]}
65
self.assertEqual(len(names), 10)
66
self.assertTrue({"agent_register", "knowledge_search", "remember"} <= names)
68
def test_notification_without_id(self):
69
self.assertIsNone(mcp.handle(self.store, self.utok,
70
{"jsonrpc": "2.0", "method": "notifications/initialized"}, self.tmp))
72
def test_unknown_method(self):
73
res = mcp.handle(self.store, self.utok, {"jsonrpc": "2.0", "id": 9, "method": "sapu"}, self.tmp)
74
self.assertEqual(res["error"]["code"], -32601)
76
def test_token_required(self):
77
res = mcp.handle(self.store, "", {"jsonrpc": "2.0", "id": 1, "method": "tools/call",
78
"params": {"name": "whoami", "arguments": {}}}, self.tmp)
79
self.assertTrue(res["result"]["isError"])
80
self.assertIn("Bearer", payload(res)["error"])
83
class RegistrationTests(Base):
84
def test_agent_registers_over_mcp(self):
85
res = call(self.store, self.utok, "agent_register",
86
{"name": "mira", "description": "data", "model": "hermes"})
88
self.assertFalse(res["result"].get("isError"))
89
self.assertTrue(body["token"].startswith("ag_agt_"))
90
self.assertEqual(body["name"], "mira")
91
# token hasil registrasi benar-benar bisa dipakai
92
who = payload(call(self.store, body["token"], "whoami"))
93
self.assertEqual(who["agent"], "mira")
94
self.assertEqual(who["owner"], "bagas")
96
def test_agent_token_cannot_register_agents(self):
97
res = call(self.store, self.atok, "agent_register", {"name": "penyusup"})
98
self.assertTrue(res["result"]["isError"])
99
self.assertIn("user token", payload(res)["error"])
101
def test_user_token_cannot_search_knowledge(self):
103
res = call(self.store, self.utok, "knowledge_search", {"query": "chrome cdp"})
104
self.assertTrue(res["result"]["isError"])
105
self.assertIn("agent token", payload(res)["error"])
108
class IndexTests(Base):
109
def test_local_index_and_search_with_citations(self):
110
pid = self.add_project()
111
proj = self.store.project(pid)
112
self.assertEqual(proj["status"], "ready")
113
self.assertGreater(proj["chunks"], 20)
114
body = payload(call(self.store, self.atok, "knowledge_search", {"query": "chrome cdp frame", "limit": 3}))
115
self.assertGreaterEqual(body["hits"], 1)
116
hit = body["results"][0]
117
self.assertIn("path", hit)
118
self.assertRegex(hit["lines"], r"^\d+-\d+$")
119
self.assertTrue(hit["snippet"])
121
def test_read_full_file(self):
123
body = payload(call(self.store, self.atok, "knowledge_doc",
124
{"project": "sinema", "path": "README.md"}))
125
self.assertEqual(body["path"], "README.md")
126
self.assertIn("sinema", body["content"])
127
self.assertGreaterEqual(body["total_lines"], 100)
129
def test_rejects_path_traversal(self):
131
res = call(self.store, self.atok, "knowledge_doc", {"project": "sinema", "path": "../../etc/passwd"})
132
self.assertTrue(res["result"]["isError"])
134
def test_project_summary(self):
136
body = payload(call(self.store, self.atok, "project_summary", {"project": "sinema"}))
137
self.assertEqual(body["files"] > 5, True)
138
self.assertIn("python", body["languages"])
139
self.assertTrue(body["largest_files"])
141
def test_odd_queries_do_not_break_search(self):
143
for q in ['"', "AND OR", "a" * 300, "path:etc", "*", "((", "chrome AND"]:
144
res = call(self.store, self.atok, "knowledge_search", {"query": q})
145
self.assertFalse(res["result"]["isError"], q)
148
class ScopeTests(Base):
149
def test_owner_project_hidden_from_other_agents(self):
150
pid = self.add_project(user_id=self.uid, name="rahasia", visibility="owner")
151
res = call(self.store, self.atok2, "knowledge_search", {"query": "chrome", "project": "rahasia"})
152
self.assertTrue(res["result"]["isError"])
153
self.assertIn("not found", payload(res)["error"])
154
# dan tidak muncul di daftar proyek agent lain
155
lst = payload(call(self.store, self.atok2, "project_list"))
156
self.assertEqual([p for p in lst if p["name"] == "rahasia"], [])
158
def test_public_project_visible_to_all_agents(self):
159
self.add_project(user_id=self.uid, name="terbuka", visibility="public")
160
lst = payload(call(self.store, self.atok2, "project_list"))
161
self.assertIn("terbuka", [p["name"] for p in lst])
162
body = payload(call(self.store, self.atok2, "knowledge_search", {"query": "chrome"}))
163
self.assertGreaterEqual(body["hits"], 1)
164
self.assertTrue(all(r["project"] == "terbuka" for r in body["results"]))
167
class MemoryTests(Base):
168
def test_remember_then_recall(self):
169
pid = self.add_project()
170
r = payload(call(self.store, self.atok, "remember",
171
{"body": "Render 180 frame perlu ~32 detik di 4 vCPU", "tags": "sinema,render",
172
"project": "sinema"}))
173
self.assertGreater(r["note_id"], 0)
174
rec = payload(call(self.store, self.atok, "recall", {"query": "render detik"}))
175
self.assertEqual(len(rec["notes"]), 1)
176
self.assertIn("32 detik", rec["notes"][0]["body"])
178
def test_notes_do_not_leak_between_agents(self):
179
call(self.store, self.atok, "remember", {"body": "temuan milik nara soal chrome"})
180
rec = payload(call(self.store, self.atok2, "recall", {"query": "chrome"}))
181
self.assertEqual(rec["notes"], [])
184
class HttpTests(Base):
185
"""HTTP layer: /mcp and /healthz as an MCP client sees them."""
189
cls.tmp = Path(tempfile.mkdtemp(prefix="agentgit-http-"))
190
os.environ["AGENTGIT_DATA"] = str(cls.tmp)
191
os.environ["AGENTGIT_DB"] = str(cls.tmp / "h.sqlite3")
192
os.environ["AGENTGIT_ADMIN_TOKEN"] = "uji-admin"
193
from agentgit import httpd
195
httpd._store = Store(cls.tmp / "h.sqlite3")
196
from http.server import ThreadingHTTPServer
198
cls.srv = ThreadingHTTPServer(("127.0.0.1", 0), httpd.Handler)
199
cls.port = cls.srv.server_address[1]
200
threading.Thread(target=cls.srv.serve_forever, daemon=True).start()
201
cls.store = httpd._store
202
cls.uid, cls.utok = cls.store.create_user("uji", "")
203
cls.aid, cls.atok = cls.store.create_agent(cls.uid, "ujiagent", "", "")
206
def tearDownClass(cls):
208
shutil.rmtree(cls.tmp, ignore_errors=True)
210
def setUp(self): # reuse the class database instead of a fresh one
216
def post(self, obj, token=None):
217
c = http.client.HTTPConnection("127.0.0.1", self.port, timeout=10)
218
body = json.dumps(obj).encode()
219
h = {"Content-Type": "application/json", "Content-Length": str(len(body))}
221
h["Authorization"] = f"Bearer {token}"
222
c.request("POST", "/mcp", body=body, headers=h)
226
return r.status, (json.loads(data) if data else None)
228
def test_initialize_via_http(self):
229
code, res = self.post({"jsonrpc": "2.0", "id": 1, "method": "initialize", "params": {}}, self.atok)
230
self.assertEqual(code, 200)
231
self.assertEqual(res["result"]["serverInfo"]["name"], "agentgit")
233
def test_healthz(self):
234
c = http.client.HTTPConnection("127.0.0.1", self.port, timeout=10)
235
c.request("GET", "/healthz")
237
body = json.loads(r.read())
239
self.assertEqual(r.status, 200)
240
self.assertTrue(body["ok"])
241
self.assertIn("agents", body)
243
def test_without_token_rejected_but_json_valid(self):
244
code, res = self.post({"jsonrpc": "2.0", "id": 2, "method": "tools/call",
245
"params": {"name": "whoami", "arguments": {}}})
246
self.assertEqual(code, 200)
247
self.assertTrue(res["result"]["isError"])
249
def test_broken_json_400(self):
250
c = http.client.HTTPConnection("127.0.0.1", self.port, timeout=10)
251
c.request("POST", "/mcp", body=b"{bukan json", headers={"Content-Length": "11"})
253
self.assertEqual(r.status, 400)
257
def test_admin_dashboard_requires_token(self):
258
for path, want in [("/admin", 404), ("/admin?token=uji-admin", 302), ("/", 200)]:
259
c = http.client.HTTPConnection("127.0.0.1", self.port, timeout=10)
260
c.request("GET", path)
262
self.assertEqual(r.status, want, path)
267
class WebTests(HttpTests):
268
"""Halaman web: beranda, repo, pencarian, agent, activity, CSS."""
273
# dua proyek: satu publik (sinema), satu owner (rahasia)
274
for name, vis in (("sinema-uji", "public"), ("rahasia-uji", "owner")):
275
pid = cls.store.add_project(cls.uid, name, "", "", "/root/sinema", vis)
276
mcp.index_project(cls.store, cls.store.project(pid), cls.tmp)
279
c = http.client.HTTPConnection("127.0.0.1", self.port, timeout=10)
280
c.request("GET", path)
282
body = r.read().decode("utf-8", "replace")
284
return r.status, body
286
def test_public_home_lists_public_only(self):
287
code, html = self.get("/")
288
self.assertEqual(code, 200)
289
self.assertIn("sinema-uji", html)
290
self.assertNotIn("rahasia-uji", html)
291
self.assertIn("/static/app.css", html)
293
def test_admin_sees_everything(self):
294
code, html = self.get("/?token=uji-admin")
295
self.assertEqual(code, 200)
296
self.assertIn("rahasia-uji", html)
297
self.assertIn("admin", html)
299
def test_repo_page_and_file_tree(self):
300
code, html = self.get("/r/sinema-uji")
301
self.assertEqual(code, 200)
302
self.assertIn("sinema-uji", html)
303
self.assertIn("README.md", html)
305
def test_file_view_with_line_numbers(self):
306
code, html = self.get("/r/sinema-uji?path=README.md")
307
self.assertEqual(code, 200)
308
self.assertIn('class="ln"', html)
309
self.assertIn("sinema", html)
310
self.assertIn('class="n"', html)
312
def test_owner_repo_not_public(self):
313
code, _ = self.get("/r/rahasia-uji")
314
self.assertEqual(code, 404)
315
code, _ = self.get("/r/rahasia-uji?token=uji-admin")
316
self.assertEqual(code, 200)
318
def test_unknown_routes_404(self):
319
self.assertEqual(self.get("/r/zzz-tidak-ada")[0], 404)
320
self.assertEqual(self.get("/halaman-asing")[0], 404)
322
def test_public_search(self):
323
code, html = self.get("/search?q=chrome+cdp")
324
self.assertEqual(code, 200)
325
self.assertIn("sinema-uji", html)
326
self.assertIn("<mark>", html)
327
self.assertIn("</mark>", html)
329
def test_search_does_not_leak_owner_projects(self):
330
code, html = self.get("/search?q=rahasia")
331
self.assertEqual(code, 200)
332
self.assertNotIn("rahasia-uji", html)
334
def test_agents_dan_activity(self):
335
code, html = self.get("/agents")
336
self.assertEqual(code, 200)
337
self.assertIn("ujiagent", html)
338
self.assertNotIn("ag_agt_", html)
339
code, html = self.get("/activity")
340
self.assertEqual(code, 200)
341
self.assertIn("tool", html)
343
def test_css_is_served(self):
344
c = http.client.HTTPConnection("127.0.0.1", self.port, timeout=10)
345
c.request("GET", "/static/app.css")
347
body = r.read().decode()
349
self.assertEqual(r.status, 200)
350
self.assertIn("--accent:#ffb020", body)
351
self.assertEqual(r.getheader("Content-Type"), "text/css; charset=utf-8")
353
def test_html_is_escaped(self):
354
pid = self.store.add_project(self.uid, "<script>alert(1)</script>", "", "",
355
"/root/sinema", "public")
356
mcp.index_project(self.store, self.store.project(pid), self.tmp)
357
code, html = self.get("/")
358
self.assertEqual(code, 200)
359
self.assertIn("<script>", html)
360
self.assertNotIn("<script>alert(1)</script>", html)
363
if __name__ == "__main__":
364
unittest.main(verbosity=2)