-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathserver.py
More file actions
1532 lines (1331 loc) · 61.5 KB
/
server.py
File metadata and controls
1532 lines (1331 loc) · 61.5 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
"""
PatchworkMCP — Sidecar Service
Accepts feedback from MCP server drop-ins, stores it in SQLite, and serves
a review UI for browsing what agents report.
Run:
uv run server.py
# or: uvicorn server:app --port 8099
Configure:
FEEDBACK_DB_PATH - default: ./feedback.db
FEEDBACK_API_KEY - optional shared secret (must match drop-in)
FEEDBACK_PORT - default: 8099 (only used with `uv run server.py`)
"""
import os
import re
import uuid
import json
import base64
import sqlite3
from datetime import datetime, timezone
from contextlib import asynccontextmanager, contextmanager
from typing import Optional
import httpx
from fastapi import FastAPI, HTTPException, Header, Query
from fastapi.middleware.cors import CORSMiddleware
from fastapi.responses import HTMLResponse, StreamingResponse
from pydantic import BaseModel, Field
# ── Config ───────────────────────────────────────────────────────────────────
DB_PATH = os.environ.get("FEEDBACK_DB_PATH", "feedback.db")
API_KEY = os.environ.get("FEEDBACK_API_KEY", "")
# ── Database ─────────────────────────────────────────────────────────────────
@contextmanager
def get_db():
conn = sqlite3.connect(DB_PATH)
conn.row_factory = sqlite3.Row
conn.execute("PRAGMA journal_mode=WAL")
conn.execute("PRAGMA foreign_keys=ON")
try:
yield conn
conn.commit()
except Exception:
conn.rollback()
raise
finally:
conn.close()
def init_db():
with get_db() as conn:
conn.execute("""
CREATE TABLE IF NOT EXISTS feedback (
id TEXT PRIMARY KEY,
server_name TEXT NOT NULL,
timestamp TEXT NOT NULL,
what_i_needed TEXT NOT NULL,
what_i_tried TEXT NOT NULL,
gap_type TEXT NOT NULL,
suggestion TEXT DEFAULT '',
user_goal TEXT DEFAULT '',
resolution TEXT DEFAULT '',
agent_model TEXT DEFAULT '',
tools_available TEXT DEFAULT '[]',
session_id TEXT DEFAULT '',
reviewed INTEGER DEFAULT 0
)
""")
conn.execute("""
CREATE TABLE IF NOT EXISTS feedback_notes (
id TEXT PRIMARY KEY,
feedback_id TEXT NOT NULL REFERENCES feedback(id),
timestamp TEXT NOT NULL,
content TEXT NOT NULL
)
""")
conn.execute("""
CREATE INDEX IF NOT EXISTS idx_feedback_server
ON feedback(server_name)
""")
conn.execute("""
CREATE INDEX IF NOT EXISTS idx_feedback_timestamp
ON feedback(timestamp DESC)
""")
conn.execute("""
CREATE INDEX IF NOT EXISTS idx_feedback_gap_type
ON feedback(gap_type)
""")
conn.execute("""
CREATE INDEX IF NOT EXISTS idx_notes_feedback_id
ON feedback_notes(feedback_id)
""")
conn.execute("""
CREATE TABLE IF NOT EXISTS settings (
key TEXT PRIMARY KEY,
value TEXT NOT NULL,
updated_at TEXT NOT NULL
)
""")
def _migrate_db():
with get_db() as conn:
cols = {row[1] for row in conn.execute("PRAGMA table_info(feedback)").fetchall()}
if "pr_url" not in cols:
conn.execute("ALTER TABLE feedback ADD COLUMN pr_url TEXT DEFAULT ''")
if "client_type" not in cols:
conn.execute("ALTER TABLE feedback ADD COLUMN client_type TEXT DEFAULT ''")
# ── App ──────────────────────────────────────────────────────────────────────
@asynccontextmanager
async def lifespan(app: FastAPI):
init_db()
_migrate_db()
yield
app = FastAPI(
title="PatchworkMCP",
version="0.1.0",
lifespan=lifespan,
)
app.add_middleware(
CORSMiddleware,
allow_origins=["*"],
allow_methods=["*"],
allow_headers=["*"],
)
# ── Auth ─────────────────────────────────────────────────────────────────────
def check_auth(authorization: Optional[str] = Header(None)):
if not API_KEY:
return
if not authorization or authorization != f"Bearer {API_KEY}":
raise HTTPException(status_code=401, detail="Invalid API key")
# ── Models ───────────────────────────────────────────────────────────────────
class FeedbackIn(BaseModel):
server_name: str = "unknown"
what_i_needed: str
what_i_tried: str
gap_type: str = "other"
suggestion: str = ""
user_goal: str = ""
resolution: str = ""
agent_model: str = ""
tools_available: list[str] = Field(default_factory=list)
session_id: str = ""
client_type: str = ""
class ReviewUpdate(BaseModel):
reviewed: bool = True
class NoteIn(BaseModel):
content: str
# ── Helpers ──────────────────────────────────────────────────────────────────
def _row_to_dict(row: sqlite3.Row) -> dict:
d = dict(row)
d["reviewed"] = bool(d["reviewed"])
d.setdefault("pr_url", "")
d.setdefault("client_type", "")
if "tools_available" in d:
try:
d["tools_available"] = json.loads(d["tools_available"])
except (json.JSONDecodeError, TypeError):
d["tools_available"] = []
return d
def _attach_notes(conn, items: list[dict]) -> list[dict]:
"""Fetch notes for a batch of feedback items and attach them."""
if not items:
return items
ids = [item["id"] for item in items]
placeholders = ",".join("?" * len(ids))
note_rows = conn.execute(
f"SELECT * FROM feedback_notes WHERE feedback_id IN ({placeholders}) "
"ORDER BY timestamp ASC",
ids,
).fetchall()
notes_by_id: dict[str, list] = {}
for n in note_rows:
notes_by_id.setdefault(n["feedback_id"], []).append({
"id": n["id"],
"timestamp": n["timestamp"],
"content": n["content"],
})
for item in items:
item["notes"] = notes_by_id.get(item["id"], [])
return items
# ── Settings helpers ─────────────────────────────────────────────────────────
_DB_SETTINGS_KEYS = {"github_repo", "default_branch", "llm_provider", "llm_model"}
_ENV_KEYS = {"github_pat", "anthropic_api_key", "openai_api_key"}
_ALL_SETTINGS_KEYS = _DB_SETTINGS_KEYS | _ENV_KEYS
_PROVIDER_DEFAULTS = {
"anthropic": "claude-opus-4-6",
"openai": "GPT-5.2-Codex",
}
ENV_PATH = os.path.join(os.path.dirname(os.path.abspath(DB_PATH)), ".env")
def _mask(value: str) -> str:
if len(value) <= 4:
return "****"
return "****" + value[-4:]
def _read_env() -> dict[str, str]:
"""Read key=value pairs from .env file."""
values: dict[str, str] = {}
try:
with open(ENV_PATH) as f:
for line in f:
line = line.strip()
if not line or line.startswith("#"):
continue
if "=" not in line:
continue
key, _, val = line.partition("=")
key = key.strip()
val = val.strip().strip("\"'")
if key in _ENV_KEYS:
values[key] = val
except FileNotFoundError:
pass
return values
def _write_env(updates: dict[str, str]):
"""Merge updates into .env, preserving comments and unknown keys."""
lines: list[str] = []
seen: set[str] = set()
try:
with open(ENV_PATH) as f:
for line in f:
raw = line.rstrip("\n")
stripped = raw.strip()
if stripped and not stripped.startswith("#") and "=" in stripped:
key = stripped.partition("=")[0].strip()
if key in updates:
seen.add(key)
if updates[key]:
lines.append(f"{key}={updates[key]}")
continue
lines.append(raw)
except FileNotFoundError:
pass
for key, val in updates.items():
if key not in seen and val:
lines.append(f"{key}={val}")
with open(ENV_PATH, "w") as f:
f.write("\n".join(lines) + "\n")
def _get_settings() -> dict[str, str]:
"""Read all settings from SQLite (prefs) + .env (secrets)."""
with get_db() as conn:
rows = conn.execute("SELECT key, value FROM settings").fetchall()
result = {r["key"]: r["value"] for r in rows}
result.update(_read_env())
return result
# ── GitHub Client ────────────────────────────────────────────────────────────
_SOURCE_EXTS = {".py", ".ts", ".js", ".go", ".rs", ".tsx", ".jsx", ".rb"}
_MCP_PATTERNS = ["tool", "server", "mcp", "handler", "schema", "resource", "prompt"]
def _score_file(path: str, server_name: str) -> int:
lower = path.lower()
ext = os.path.splitext(path)[1]
if ext not in _SOURCE_EXTS:
return -1
# skip vendored / generated
for skip in ("node_modules/", "vendor/", ".git/", "__pycache__/", "dist/", "build/"):
if skip in lower:
return -1
score = 0
for pat in _MCP_PATTERNS:
if pat in lower:
score += 10
if server_name and server_name.lower().replace("-", "_") in lower.replace("-", "_"):
score += 20
if ext == ".py":
score += 2
elif ext in (".ts", ".tsx"):
score += 2
return score
class GitHubClient:
def __init__(self, token: str, repo: str):
self.repo = repo # "owner/repo"
self._client = httpx.AsyncClient(
base_url="https://api.github.com",
headers={
"Authorization": f"Bearer {token}",
"Accept": "application/vnd.github+json",
"X-GitHub-Api-Version": "2022-11-28",
},
timeout=30.0,
)
async def close(self):
await self._client.aclose()
async def _request(self, method: str, path: str, **kwargs) -> httpx.Response:
resp = await self._client.request(method, path, **kwargs)
if resp.status_code == 401:
raise HTTPException(502, "GitHub: invalid or expired PAT")
if resp.status_code == 403:
raise HTTPException(502, "GitHub: PAT lacks required permissions (need repo scope)")
if resp.status_code == 404:
raise HTTPException(502, f"GitHub: not found — check that repo '{self.repo}' exists")
if resp.status_code >= 400:
raise HTTPException(502, f"GitHub API error {resp.status_code}: {resp.text[:200]}")
return resp
async def get_tree(self, branch: str) -> list[str]:
resp = await self._request(
"GET", f"/repos/{self.repo}/git/trees/{branch}",
params={"recursive": "1"},
)
tree = resp.json().get("tree", [])
return [item["path"] for item in tree if item["type"] == "blob"]
async def read_file(self, path: str, ref: str) -> str:
resp = await self._request(
"GET", f"/repos/{self.repo}/contents/{path}",
params={"ref": ref},
)
data = resp.json()
content_b64 = data.get("content", "")
return base64.b64decode(content_b64).decode("utf-8", errors="replace")
async def get_file_sha(self, path: str, ref: str) -> Optional[str]:
"""Get the blob SHA for a file (needed for updates)."""
resp = await self._client.request(
"GET", f"/repos/{self.repo}/contents/{path}",
params={"ref": ref},
)
if resp.status_code == 404:
return None
if resp.status_code >= 400:
raise HTTPException(502, f"GitHub API error {resp.status_code}")
return resp.json().get("sha")
async def get_branch_sha(self, branch: str) -> str:
resp = await self._request("GET", f"/repos/{self.repo}/git/ref/heads/{branch}")
return resp.json()["object"]["sha"]
async def create_branch(self, name: str, from_sha: str):
await self._request(
"POST", f"/repos/{self.repo}/git/refs",
json={"ref": f"refs/heads/{name}", "sha": from_sha},
)
async def upsert_file(self, path: str, content: str, message: str, branch: str, sha: Optional[str] = None):
body: dict = {
"message": message,
"content": base64.b64encode(content.encode()).decode(),
"branch": branch,
}
if sha:
body["sha"] = sha
await self._request("PUT", f"/repos/{self.repo}/contents/{path}", json=body)
async def create_draft_pr(self, title: str, body: str, branch: str, base: str) -> str:
resp = await self._request(
"POST", f"/repos/{self.repo}/pulls",
json={"title": title, "body": body, "head": branch, "base": base, "draft": True},
)
return resp.json()["html_url"]
# ── LLM API ──────────────────────────────────────────────────────────────────
_LLM_SYSTEM_PROMPT = """You improve MCP servers based on agent feedback. You receive feedback about a gap, the repo file tree, and relevant source files.
Rules:
- For "modify" action: include the COMPLETE updated file content, not a diff
- For "create" action: provide the full new file content
- commit_message: imperative mood ("Add X" not "Added X"), under 72 chars
- pr_body: reference the original feedback
- Keep changes minimal and focused on the reported gap"""
_PR_SCHEMA = {
"type": "object",
"properties": {
"file_path": {"type": "string"},
"action": {"type": "string", "enum": ["modify", "create"]},
"content": {"type": "string"},
"commit_message": {"type": "string"},
"pr_title": {"type": "string"},
"pr_body": {"type": "string"},
},
"required": ["file_path", "action", "content", "commit_message", "pr_title", "pr_body"],
"additionalProperties": False,
}
def _build_user_message(feedback: dict, tree: list[str], file_contents: dict[str, str]) -> str:
tree_listing = "\n".join(tree[:30])
if len(tree) > 30:
tree_listing += f"\n... and {len(tree) - 30} more files"
files_section = ""
for path, content in file_contents.items():
lines = content.split("\n")[:500]
files_section += f"\n\n### {path}\n```\n" + "\n".join(lines) + "\n```"
notes_section = ""
notes = feedback.get("notes", [])
if notes:
notes_section = "\n\n## Developer notes\nThese are human-written annotations from the developer reviewing this feedback. They provide critical context — prioritize them.\n"
for n in notes:
notes_section += f"\n- [{n.get('timestamp', '')}] {n.get('content', '')}"
return f"""## Feedback about MCP server: {feedback.get('server_name', 'unknown')}
**Gap type:** {feedback.get('gap_type', 'other')}
**What the agent needed:** {feedback.get('what_i_needed', '')}
**What the agent tried:** {feedback.get('what_i_tried', '')}
**Suggestion:** {feedback.get('suggestion', '')}
**User goal:** {feedback.get('user_goal', '')}
**Resolution:** {feedback.get('resolution', '')}
**Client type:** {feedback.get('client_type', '')}
{notes_section}
## Repository file tree
{tree_listing}
## Relevant source files
{files_section}"""
def _get_llm_config(settings: dict) -> tuple[str, str, str]:
"""Return (provider, model, api_key) from settings."""
provider = settings.get("llm_provider") or "anthropic"
model = settings.get("llm_model") or _PROVIDER_DEFAULTS.get(provider, "claude-opus-4-6")
if provider == "openai":
return provider, model, settings["openai_api_key"]
return provider, model, settings["anthropic_api_key"]
async def _call_anthropic(api_key: str, model: str, user_msg: str) -> str:
"""Call Anthropic API with structured output (output_config.format)."""
async with httpx.AsyncClient(timeout=120.0) as client:
resp = await client.post(
"https://api.anthropic.com/v1/messages",
headers={
"x-api-key": api_key,
"anthropic-version": "2023-06-01",
"content-type": "application/json",
},
json={
"model": model,
"max_tokens": 16384,
"system": _LLM_SYSTEM_PROMPT,
"messages": [{"role": "user", "content": user_msg}],
"output_config": {
"format": {
"type": "json_schema",
"schema": _PR_SCHEMA,
}
},
},
)
if resp.status_code == 401:
raise ValueError("Anthropic: invalid API key")
if resp.status_code >= 400:
raise ValueError(f"Anthropic API error {resp.status_code}: {resp.text[:300]}")
data = resp.json()
if data.get("stop_reason") == "refusal":
raise ValueError("Anthropic: model refused the request")
if data.get("stop_reason") == "max_tokens":
raise ValueError("Anthropic: response truncated (file too large for max_tokens)")
text = ""
for block in data.get("content", []):
if block.get("type") == "text":
text += block["text"]
return text
async def _call_openai(api_key: str, model: str, user_msg: str) -> str:
"""Call OpenAI API with structured output (response_format json_schema)."""
async with httpx.AsyncClient(timeout=120.0) as client:
resp = await client.post(
"https://api.openai.com/v1/chat/completions",
headers={
"Authorization": f"Bearer {api_key}",
"Content-Type": "application/json",
},
json={
"model": model,
"max_tokens": 16384,
"messages": [
{"role": "system", "content": _LLM_SYSTEM_PROMPT},
{"role": "user", "content": user_msg},
],
"response_format": {
"type": "json_schema",
"json_schema": {
"name": "pr_suggestion",
"schema": _PR_SCHEMA,
"strict": True,
},
},
},
)
if resp.status_code == 401:
raise ValueError("OpenAI: invalid API key")
if resp.status_code >= 400:
raise ValueError(f"OpenAI API error {resp.status_code}: {resp.text[:300]}")
data = resp.json()
choices = data.get("choices", [])
if not choices:
raise ValueError("OpenAI returned no choices")
msg = choices[0].get("message", {})
if msg.get("refusal"):
raise ValueError(f"OpenAI: model refused — {msg['refusal']}")
return msg.get("content", "")
def _parse_llm_json(text: str) -> dict:
text = text.strip()
if not text:
raise ValueError("LLM returned an empty response")
# Try 1: direct parse (ideal case — pure JSON response)
try:
result = json.loads(text)
return _validate_llm_result(result)
except (json.JSONDecodeError, ValueError):
pass
# Try 2: strip markdown code fences
stripped = re.sub(r"^```(?:json)?\s*", "", text)
stripped = re.sub(r"\s*```$", "", stripped).strip()
try:
result = json.loads(stripped)
return _validate_llm_result(result)
except (json.JSONDecodeError, ValueError):
pass
# Try 3: extract first JSON object from mixed text (model wrote preamble)
match = re.search(r"\{", text)
if match:
depth = 0
start = match.start()
in_string = False
escape = False
for i in range(start, len(text)):
c = text[i]
if escape:
escape = False
continue
if c == "\\":
escape = True
continue
if c == '"' and not escape:
in_string = not in_string
continue
if in_string:
continue
if c == "{":
depth += 1
elif c == "}":
depth -= 1
if depth == 0:
candidate = text[start:i + 1]
try:
result = json.loads(candidate)
return _validate_llm_result(result)
except (json.JSONDecodeError, ValueError):
break
preview = text[:300] + ("..." if len(text) > 300 else "")
raise ValueError(f"Could not extract JSON from LLM response.\nResponse was: {preview}")
def _validate_llm_result(result: dict) -> dict:
for field in ("file_path", "content", "commit_message", "pr_title", "pr_body"):
if field not in result:
raise ValueError(f"LLM response missing required field: {field}")
result.setdefault("action", "modify")
return result
# ── Routes ───────────────────────────────────────────────────────────────────
@app.post("/api/feedback", status_code=201)
async def create_feedback(
feedback: FeedbackIn,
authorization: Optional[str] = Header(None),
):
check_auth(authorization)
row_id = str(uuid.uuid4())
now = datetime.now(timezone.utc).isoformat()
with get_db() as conn:
conn.execute(
"""
INSERT INTO feedback
(id, server_name, timestamp, what_i_needed, what_i_tried,
gap_type, suggestion, user_goal, resolution, agent_model,
tools_available, session_id, client_type)
VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)
""",
(
row_id,
feedback.server_name,
now,
feedback.what_i_needed,
feedback.what_i_tried,
feedback.gap_type,
feedback.suggestion,
feedback.user_goal,
feedback.resolution,
feedback.agent_model,
json.dumps(feedback.tools_available),
feedback.session_id,
feedback.client_type,
),
)
return {"id": row_id, "status": "recorded"}
@app.get("/api/feedback")
async def list_feedback(
server_name: Optional[str] = Query(None),
gap_type: Optional[str] = Query(None),
reviewed: Optional[bool] = Query(None),
resolution: Optional[str] = Query(None),
session_id: Optional[str] = Query(None),
limit: int = Query(50, le=200),
):
with get_db() as conn:
query = "SELECT * FROM feedback WHERE 1=1"
params: list = []
if server_name:
query += " AND server_name = ?"
params.append(server_name)
if gap_type:
query += " AND gap_type = ?"
params.append(gap_type)
if reviewed is not None:
query += " AND reviewed = ?"
params.append(int(reviewed))
if resolution:
query += " AND resolution = ?"
params.append(resolution)
if session_id:
query += " AND session_id = ?"
params.append(session_id)
query += " ORDER BY timestamp DESC LIMIT ?"
params.append(limit)
rows = conn.execute(query, params).fetchall()
items = [_row_to_dict(r) for r in rows]
return _attach_notes(conn, items)
@app.get("/api/feedback/{feedback_id}")
async def get_feedback(feedback_id: str):
with get_db() as conn:
row = conn.execute(
"SELECT * FROM feedback WHERE id = ?", (feedback_id,)
).fetchone()
if not row:
raise HTTPException(status_code=404, detail="Not found")
items = _attach_notes(conn, [_row_to_dict(row)])
return items[0]
@app.patch("/api/feedback/{feedback_id}")
async def update_feedback(feedback_id: str, update: ReviewUpdate):
with get_db() as conn:
result = conn.execute(
"UPDATE feedback SET reviewed = ? WHERE id = ?",
(int(update.reviewed), feedback_id),
)
if result.rowcount == 0:
raise HTTPException(status_code=404, detail="Not found")
return {"status": "updated"}
@app.post("/api/feedback/{feedback_id}/notes", status_code=201)
async def add_note(feedback_id: str, note: NoteIn):
with get_db() as conn:
exists = conn.execute(
"SELECT 1 FROM feedback WHERE id = ?", (feedback_id,)
).fetchone()
if not exists:
raise HTTPException(status_code=404, detail="Feedback item not found")
note_id = str(uuid.uuid4())
now = datetime.now(timezone.utc).isoformat()
conn.execute(
"INSERT INTO feedback_notes (id, feedback_id, timestamp, content) "
"VALUES (?, ?, ?, ?)",
(note_id, feedback_id, now, note.content),
)
return {"id": note_id, "status": "recorded"}
@app.get("/api/settings")
async def get_settings():
settings = _get_settings()
masked = {}
for key in _ALL_SETTINGS_KEYS:
val = settings.get(key, "")
if key in _ENV_KEYS and val:
masked[key] = _mask(val)
else:
masked[key] = val
provider = settings.get("llm_provider", "anthropic")
api_key_field = "anthropic_api_key" if provider == "anthropic" else "openai_api_key"
configured = bool(
settings.get("github_pat")
and settings.get("github_repo")
and settings.get(api_key_field)
)
return {**masked, "configured": configured}
class SettingsUpdate(BaseModel):
github_pat: str = ""
github_repo: str = ""
anthropic_api_key: str = ""
openai_api_key: str = ""
default_branch: str = ""
llm_provider: str = ""
llm_model: str = ""
@app.put("/api/settings")
async def update_settings(body: SettingsUpdate):
now = datetime.now(timezone.utc).isoformat()
updates = body.model_dump()
# Preferences → SQLite
with get_db() as conn:
for key, value in updates.items():
if key in _DB_SETTINGS_KEYS and value:
conn.execute(
"INSERT OR REPLACE INTO settings (key, value, updated_at) VALUES (?, ?, ?)",
(key, value, now),
)
# Secrets → .env
env_updates = {k: v for k, v in updates.items() if k in _ENV_KEYS and v}
if env_updates:
_write_env(env_updates)
return {"status": "saved"}
def _sse(event: str, data: str) -> str:
return f"event: {event}\ndata: {json.dumps(data)}\n\n"
def _sse_json(event: str, data: dict) -> str:
return f"event: {event}\ndata: {json.dumps(data)}\n\n"
@app.post("/api/feedback/{feedback_id}/draft-pr")
async def draft_pr(feedback_id: str, force: bool = Query(False)):
# Pre-validate before starting the stream
with get_db() as conn:
row = conn.execute("SELECT * FROM feedback WHERE id = ?", (feedback_id,)).fetchone()
if not row:
raise HTTPException(404, "Feedback not found")
fb = _row_to_dict(row)
if fb.get("pr_url") and not force:
raise HTTPException(409, "A draft PR already exists for this feedback")
# Attach notes so the LLM gets developer context
_attach_notes(conn, [fb])
settings = _get_settings()
provider, model, llm_api_key = _get_llm_config(settings)
if not all([settings.get("github_pat"), settings.get("github_repo"), llm_api_key]):
raise HTTPException(400, f"Settings not configured — add GitHub PAT, repo, and {provider.title()} API key")
async def generate():
repo = settings["github_repo"]
base_branch = settings.get("default_branch") or "main"
gh = GitHubClient(settings["github_pat"], repo)
try:
yield _sse("step", f"Fetching file tree from {repo}...")
tree = await gh.get_tree(base_branch)
yield _sse("step", f"Found {len(tree)} files in repo")
# Score & select relevant files
scored = [(path, _score_file(path, fb.get("server_name", ""))) for path in tree]
scored = [(p, s) for p, s in scored if s >= 0]
scored.sort(key=lambda x: x[1], reverse=True)
top_files = [p for p, _ in scored[:8]]
yield _sse("step", f"Reading {len(top_files)} relevant source files...")
file_contents = {}
for path in top_files:
try:
content = await gh.read_file(path, base_branch)
file_contents[path] = content
yield _sse("detail", f" read {path}")
except Exception:
continue
notes = fb.get("notes", [])
if notes:
yield _sse("step", f"Including {len(notes)} developer note(s) for context")
yield _sse("step", f"Calling {provider.title()} ({model}) with structured output...")
# Call LLM with schema-enforced JSON
user_msg = _build_user_message(fb, tree, file_contents)
if provider == "openai":
raw_text = await _call_openai(llm_api_key, model, user_msg)
else:
raw_text = await _call_anthropic(llm_api_key, model, user_msg)
yield _sse("step", "Validating response...")
result = _parse_llm_json(raw_text)
yield _sse("step", f"LLM suggests: {result.get('action', 'modify')} {result['file_path']}")
# Create branch (timestamp suffix ensures uniqueness on re-drafts)
branch_suffix = fb.get("gap_type", "fix").replace("_", "-")
ts = datetime.now(timezone.utc).strftime("%m%d%H%M")
branch_name = f"patchwork/feedback-{feedback_id[:8]}-{branch_suffix}-{ts}"
yield _sse("step", f"Creating branch {branch_name}...")
base_sha = await gh.get_branch_sha(base_branch)
await gh.create_branch(branch_name, base_sha)
# Commit
yield _sse("step", f"Committing: {result['commit_message']}")
file_sha = None
if result["action"] == "modify":
file_sha = await gh.get_file_sha(result["file_path"], base_branch)
await gh.upsert_file(
result["file_path"],
result["content"],
result["commit_message"],
branch_name,
sha=file_sha,
)
# Open PR
yield _sse("step", "Opening draft pull request...")
pr_url = await gh.create_draft_pr(
result["pr_title"],
result["pr_body"],
branch_name,
base_branch,
)
with get_db() as conn:
conn.execute("UPDATE feedback SET pr_url = ? WHERE id = ?", (pr_url, feedback_id))
yield _sse_json("done", {"pr_url": pr_url, "branch": branch_name})
except ValueError as e:
yield _sse("error", str(e))
except HTTPException as e:
yield _sse("error", e.detail)
except Exception as e:
yield _sse("error", f"Unexpected error: {e}")
finally:
await gh.close()
return StreamingResponse(generate(), media_type="text/event-stream")
@app.get("/api/stats")
async def stats():
with get_db() as conn:
total = conn.execute("SELECT COUNT(*) as c FROM feedback").fetchone()["c"]
unreviewed = conn.execute(
"SELECT COUNT(*) as c FROM feedback WHERE reviewed = 0"
).fetchone()["c"]
note_count = conn.execute(
"SELECT COUNT(*) as c FROM feedback_notes"
).fetchone()["c"]
by_server = conn.execute("""
SELECT server_name, COUNT(*) as count
FROM feedback GROUP BY server_name ORDER BY count DESC
""").fetchall()
by_type = conn.execute("""
SELECT gap_type, COUNT(*) as count
FROM feedback GROUP BY gap_type ORDER BY count DESC
""").fetchall()
by_resolution = conn.execute("""
SELECT resolution, COUNT(*) as count
FROM feedback WHERE resolution != '' GROUP BY resolution ORDER BY count DESC
""").fetchall()
return {
"total": total,
"unreviewed": unreviewed,
"note_count": note_count,
"by_server": [dict(r) for r in by_server],
"by_gap_type": [dict(r) for r in by_type],
"by_resolution": [dict(r) for r in by_resolution],
}
# ── Review UI ────────────────────────────────────────────────────────────────
@app.get("/", response_class=HTMLResponse)
async def review_ui():
return """<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1">
<title>PatchworkMCP</title>
<style>
/* ── Theme tokens ── */
:root {
--bg: #f5f5f5; --bg-surface: #fff; --bg-inset: #f0f0f0;
--border: #ddd; --border-strong: #ccc;
--text: #1a1a1a; --text-heading: #000; --text-muted: #666; --text-faint: #999;
--accent-blue-bg: #e8f0fe; --accent-blue: #1a6ede;
--accent-green-bg: #e6f4e6; --accent-green: #1a8a1a;
--accent-red-bg: #fde8e8; --accent-red: #c0392b;
--accent-orange-bg: #fef3e0; --accent-orange: #c57600;
--accent-yellow-bg: #fefce8; --accent-yellow: #8a7a00;
--accent-teal-bg: #e0f7f5; --accent-teal: #00796b;
--accent-purple-bg: #eee8f5; --accent-purple: #5b48a2;
--btn-bg: #fff; --btn-hover: #f0f0f0; --btn-active-bg: #e6f4e6; --btn-active-border: #4a8a4a;
--input-bg: #fff; --input-border: #ccc; --input-placeholder: #aaa;
--modal-backdrop: rgba(0,0,0,0.3); --modal-bg: #fff;
--save-bg: #e6f4e6; --save-border: #4a8a4a; --save-text: #1a8a1a;
--pr-btn-bg: #e8f0fe; --pr-btn-border: #a0c4f0; --pr-btn-text: #1a6ede;
}
[data-theme="dark"] {
--bg: #0a0a0a; --bg-surface: #161616; --bg-inset: #111;
--border: #2a2a2a; --border-strong: #333;
--text: #e0e0e0; --text-heading: #fff; --text-muted: #888; --text-faint: #666;
--accent-blue-bg: #1a2a3a; --accent-blue: #6ab0f3;
--accent-green-bg: #1a3a1a; --accent-green: #6af36a;
--accent-red-bg: #3a1a1a; --accent-red: #f36a6a;
--accent-orange-bg: #3a2a1a; --accent-orange: #f3b06a;
--accent-yellow-bg: #3a3a1a; --accent-yellow: #e8f36a;
--accent-teal-bg: #1a3a3a; --accent-teal: #6af3e8;
--accent-purple-bg: #1a1a2a; --accent-purple: #8888cc;
--btn-bg: #161616; --btn-hover: #222; --btn-active-bg: #2a4a2a; --btn-active-border: #4a8a4a;
--input-bg: #0a0a0a; --input-border: #333; --input-placeholder: #555;
--modal-backdrop: rgba(0,0,0,0.7); --modal-bg: #161616;
--save-bg: #1a3a1a; --save-border: #4a8a4a; --save-text: #6af36a;
--pr-btn-bg: #1a2a3a; --pr-btn-border: #3a6a9a; --pr-btn-text: #6ab0f3;
}
* { box-sizing: border-box; margin: 0; padding: 0; }
body { font-family: -apple-system, system-ui, sans-serif; background: var(--bg); color: var(--text); padding: 2rem; }
.top-bar { display: flex; justify-content: space-between; align-items: flex-start; margin-bottom: 1rem; }
.top-bar-left { flex: 1; }
h1 { font-size: 1.4rem; margin-bottom: 0.5rem; color: var(--text-heading); }