-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathmcp_server.py
More file actions
1145 lines (971 loc) · 37.6 KB
/
mcp_server.py
File metadata and controls
1145 lines (971 loc) · 37.6 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
"""SchemaWiki MCP Server - Record AI agent activities with rich context."""
import asyncio
import json
import os
from datetime import datetime
from pathlib import Path
from typing import Any, Optional
import uvicorn
from fastapi import FastAPI, HTTPException
# MCP imports
from mcp.server import NotificationOptions, Server
from mcp.server.stdio import stdio_server
from mcp.types import TextContent, Tool
from pydantic import BaseModel
app = FastAPI(title="SchemaWiki MCP Server")
# Store for in-memory feature data
FEATURES: dict[str, dict] = {}
# Wiki data path - where wikis are saved
WIKI_DATA_PATH = os.environ.get("WIKI_DATA_PATH", "/data/wikis")
Path(WIKI_DATA_PATH).mkdir(parents=True, exist_ok=True)
# Project configuration
PROJECT_NAME = os.environ.get("PROJECT_NAME", "SchemaWiki")
PROJECT_URL = os.environ.get("PROJECT_URL", "")
PROJECT_GITHUB_URL = os.environ.get("PROJECT_GITHUB_URL", "")
# GitHub repository for wiki uploads (optional)
GITHUB_REPO = os.environ.get("GITHUB_REPO", "") # e.g., "owner/repo"
GITHUB_TOKEN = os.environ.get("GITHUB_TOKEN", "") # GitHub token for pushing
WIKI_BRANCH = os.environ.get("WIKI_BRANCH", "main")
class FeatureRecord(BaseModel):
name: str
description: Optional[str] = None
version: str = "0.1.0"
tags: list[str] = []
plan_content: Optional[str] = None
user_id: Optional[str] = None # Session/user identifier to group features
class StepRecord(BaseModel):
feature_name: str
step: str
why: Optional[str] = None # Why this step was taken
trigger: Optional[str] = (
None # What triggered this (e.g., "user_request", "error", "test_failure")
)
command: Optional[str] = None
files_modified: list[str] = []
output: Optional[str] = None
status: str = "in_progress"
context: Optional[str] = None # Additional context
class EventRecord(BaseModel):
feature_name: str
event_type: str # feature_coded, service_restarted, change_pushed, missing_code, lint_error, test_passed, test_failed, bug_fix, code_review, refactor
why: str # Why this happened
details: Optional[str] = None
files: list[str] = []
# MCP Server Setup
server = Server("schemawiki")
@server.list_tools()
async def list_tools() -> list[Tool]:
"""List available MCP tools."""
return [
Tool(
name="create_feature",
description="Create a new feature record in SchemaWiki",
inputSchema={
"type": "object",
"properties": {
"name": {"type": "string", "description": "Feature name"},
"description": {"type": "string", "description": "Feature description"},
"version": {"type": "string", "description": "Semantic version"},
"tags": {
"type": "array",
"items": {"type": "string"},
"description": "Feature tags",
},
"plan": {"type": "string", "description": "Initial plan content"},
"why": {"type": "string", "description": "Why this feature is being built"},
"user_id": {
"type": "string",
"description": "User/session identifier to group features (e.g., 'session-1', 'claude-code', 'user@email.com')",
},
"session_id": {"type": "string", "description": "Alias for user_id"},
},
"required": ["name"],
},
),
Tool(
name="record_step",
description="Record an implementation step with reasoning",
inputSchema={
"type": "object",
"properties": {
"feature_name": {"type": "string", "description": "Feature name"},
"step": {"type": "string", "description": "Description of the step"},
"why": {"type": "string", "description": "Why this step was taken"},
"trigger": {
"type": "string",
"description": "What triggered this (user_request, error, test_failure, lint_error, missing_code, bug_fix)",
},
"command": {"type": "string", "description": "Command executed"},
"files_modified": {
"type": "array",
"items": {"type": "string"},
"description": "Files modified",
},
"output": {"type": "string", "description": "Command output"},
"status": {
"type": "string",
"enum": ["in_progress", "completed", "failed"],
"description": "Step status",
},
"context": {"type": "string", "description": "Additional context"},
},
"required": ["feature_name", "step", "why"],
},
),
Tool(
name="record_event",
description="Record a development event (restart, push, test, etc.) with reasoning",
inputSchema={
"type": "object",
"properties": {
"feature_name": {"type": "string", "description": "Feature name"},
"event_type": {
"type": "string",
"enum": [
"feature_coded",
"service_restarted",
"change_pushed",
"missing_code",
"lint_error",
"test_passed",
"test_failed",
"bug_fix",
"code_review",
"refactor",
"dependency_added",
"config_changed",
"api_contract_change",
"db_migration",
],
"description": "Type of event",
},
"why": {"type": "string", "description": "Why this happened"},
"details": {"type": "string", "description": "Event details"},
"files": {
"type": "array",
"items": {"type": "string"},
"description": "Related files",
},
"auto_wiki": {
"type": "boolean",
"description": "Auto-generate and push wiki after this event (if GITHUB_REPO set)",
},
},
"required": ["feature_name", "event_type", "why"],
},
),
Tool(
name="update_implementation",
description="Update the implementation documentation",
inputSchema={
"type": "object",
"properties": {
"feature_name": {"type": "string", "description": "Feature name"},
"content": {"type": "string", "description": "Implementation content"},
"why": {"type": "string", "description": "Why this was added"},
},
"required": ["feature_name", "content"],
},
),
Tool(
name="add_debug_log",
description="Add a debug log with error analysis",
inputSchema={
"type": "object",
"properties": {
"feature_name": {"type": "string", "description": "Feature name"},
"attempt": {"type": "integer", "description": "Attempt number"},
"error": {"type": "string", "description": "Error message"},
"why_failed": {
"type": "string",
"description": "Why it failed (root cause analysis)",
},
"fix_applied": {"type": "string", "description": "Fix that was applied"},
"log": {"type": "string", "description": "Debug log content"},
},
"required": ["feature_name", "attempt", "error"],
},
),
Tool(
name="get_feature",
description="Get full feature details",
inputSchema={
"type": "object",
"properties": {
"name": {"type": "string", "description": "Feature name"},
},
"required": ["name"],
},
),
Tool(
name="generate_wiki",
description="Generate a wiki page for a feature",
inputSchema={
"type": "object",
"properties": {
"feature_name": {"type": "string", "description": "Feature name"},
"format": {
"type": "string",
"enum": ["markdown", "html"],
"description": "Output format",
},
"push_to_github": {
"type": "boolean",
"description": "Push wiki to GitHub repo (requires GITHUB_REPO and GITHUB_TOKEN env vars)",
},
},
"required": ["feature_name"],
},
),
Tool(
name="list_features",
description="List all recorded features",
inputSchema={"type": "object", "properties": {}},
),
Tool(
name="search_features",
description="Search features by query",
inputSchema={
"type": "object",
"properties": {
"query": {"type": "string", "description": "Search query"},
},
"required": ["query"],
},
),
]
@server.call_tool()
async def call_tool(name: str, arguments: Any) -> list[TextContent]:
"""Handle tool calls."""
if name == "create_feature":
return await create_feature(arguments)
elif name == "record_step":
return await record_step(arguments)
elif name == "record_event":
return await record_event(arguments)
elif name == "update_implementation":
return await update_implementation(arguments)
elif name == "add_debug_log":
return await add_debug_log(arguments)
elif name == "get_feature":
return await get_feature(arguments)
elif name == "generate_wiki":
return await generate_wiki(arguments)
elif name == "list_features":
return await list_features()
elif name == "search_features":
return await search_features(arguments)
else:
raise ValueError(f"Unknown tool: {name}")
def get_user_id_from_env() -> str:
"""Auto-detect user_id/session_id from environment variables."""
# Priority order for session identification
env_vars = [
"CLAUDE_SESSION_ID", # Claude Code session
"SESSION_ID", # Generic session
"XDG_SESSION_ID", # XDG display session
"SSH_CONNECTION", # SSH session info (contains IP)
"SSH_CLIENT", # SSH client info
"TERM_SESSION", # Terminal session
"USER", # System user
"USERNAME", # System username
]
for var in env_vars:
value = os.environ.get(var)
if value:
# For SSH vars, extract useful part
if var in ("SSH_CONNECTION", "SSH_CLIENT"):
parts = value.split()
if parts:
return parts[0] # Return IP address
return value
return "default"
async def create_feature(args: dict) -> list[TextContent]:
"""Create a new feature."""
name = args.get("name")
if not name:
raise ValueError("Feature name is required")
# Auto-detect user_id from environment if not provided
user_id = args.get("user_id") or args.get("session_id") or get_user_id_from_env()
feature = {
"name": name,
"description": args.get("description", ""),
"version": args.get("version", "0.1.0"),
"tags": args.get("tags", []),
"status": "planning",
"why": args.get("why", ""), # Why this feature exists
"plan": args.get("plan", ""),
"user_id": user_id, # Track which user/session created this
"implementation": "",
"steps": [],
"events": [],
"debug_logs": [],
"created_at": datetime.utcnow().isoformat(),
}
FEATURES[name] = feature
return [
TextContent(
type="text",
text=json.dumps({"status": "created", "feature": name, "user_id": user_id}, indent=2),
)
]
async def record_step(args: dict) -> list[TextContent]:
"""Record an implementation step with reasoning."""
feature_name = args.get("feature_name")
if not feature_name or feature_name not in FEATURES:
raise ValueError(f"Feature '{feature_name}' not found")
step = {
"step": args.get("step", ""),
"why": args.get("why", ""), # Why this step was taken
"trigger": args.get("trigger", ""), # What triggered this
"command": args.get("command", ""),
"files_modified": args.get("files_modified", []),
"output": args.get("output", ""),
"status": args.get("status", "in_progress"),
"context": args.get("context", ""),
"timestamp": datetime.utcnow().isoformat(),
}
FEATURES[feature_name]["steps"].append(step)
# Update status
if args.get("status") == "completed":
FEATURES[feature_name]["status"] = "in_progress"
elif args.get("status") == "failed":
FEATURES[feature_name]["status"] = "failed"
return [
TextContent(
type="text",
text=json.dumps(
{"status": "recorded", "step": len(FEATURES[feature_name]["steps"])}, indent=2
),
)
]
async def record_event(args: dict) -> list[TextContent]:
"""Record a development event."""
feature_name = args.get("feature_name")
if not feature_name or feature_name not in FEATURES:
raise ValueError(f"Feature '{feature_name}' not found")
event = {
"event_type": args.get("event_type", ""),
"why": args.get("why", ""), # Why this happened
"details": args.get("details", ""),
"files": args.get("files", []),
"timestamp": datetime.utcnow().isoformat(),
}
FEATURES[feature_name]["events"].append(event)
# Auto-generate wiki on these events
auto_wiki_events = ["feature_coded", "change_pushed", "service_restarted"]
auto_push = args.get("auto_wiki", False) or GITHUB_REPO
if args.get("event_type") in auto_wiki_events and auto_push:
try:
wiki = generate_markdown_wiki(FEATURES[feature_name])
filename = f"{feature_name}.md"
wiki_path = Path(WIKI_DATA_PATH) / filename
wiki_path.write_text(wiki)
FEATURES[feature_name]["wiki_path"] = str(wiki_path)
# Push to GitHub if configured
if GITHUB_REPO and GITHUB_TOKEN:
github_url = await push_wiki_to_github(feature_name, wiki, "markdown")
FEATURES[feature_name]["github_wiki_url"] = github_url
except Exception as e:
pass # Don't fail the event recording
return [
TextContent(
type="text",
text=json.dumps({"status": "recorded", "event": args.get("event_type")}, indent=2),
)
]
async def update_implementation(args: dict) -> list[TextContent]:
"""Update implementation documentation."""
feature_name = args.get("feature_name")
if not feature_name or feature_name not in FEATURES:
raise ValueError(f"Feature '{feature_name}' not found")
content = args.get("content", "")
why = args.get("why", "")
entry = f"\n\n## {datetime.utcnow().strftime('%Y-%m-%d %H:%M')}"
if why:
entry += f"\n**Why:** {why}"
entry += f"\n\n{content}"
FEATURES[feature_name]["implementation"] += entry
return [
TextContent(
type="text", text=json.dumps({"status": "updated", "feature": feature_name}, indent=2)
)
]
async def add_debug_log(args: dict) -> list[TextContent]:
"""Add a debug log with root cause analysis."""
feature_name = args.get("feature_name")
if not feature_name or feature_name not in FEATURES:
raise ValueError(f"Feature '{feature_name}' not found")
log_entry = {
"attempt": args.get("attempt", 1),
"error": args.get("error", ""),
"why_failed": args.get("why_failed", ""), # Root cause
"fix_applied": args.get("fix_applied", ""), # What was done to fix
"log": args.get("log", ""),
"timestamp": datetime.utcnow().isoformat(),
}
FEATURES[feature_name]["debug_logs"].append(log_entry)
return [
TextContent(
type="text",
text=json.dumps({"status": "logged", "attempt": log_entry["attempt"]}, indent=2),
)
]
async def get_feature(args: dict) -> list[TextContent]:
"""Get feature details."""
name = args.get("name")
if not name or name not in FEATURES:
raise ValueError(f"Feature '{name}' not found")
return [TextContent(type="text", text=json.dumps(FEATURES[name], indent=2))]
async def generate_wiki(args: dict) -> list[TextContent]:
"""Generate wiki page for a feature."""
feature_name = args.get("feature_name")
if not feature_name or feature_name not in FEATURES:
raise ValueError(f"Feature '{feature_name}' not found")
feature = FEATURES[feature_name]
fmt = args.get("format", "markdown")
push_to_github = args.get("push_to_github", False)
if fmt == "html":
wiki = generate_html_wiki(feature)
filename = f"{feature_name}.html"
else:
wiki = generate_markdown_wiki(feature)
filename = f"{feature_name}.md"
# Save wiki to disk
wiki_path = Path(WIKI_DATA_PATH) / filename
wiki_path.write_text(wiki)
# Also save to feature for reference
feature["wiki_path"] = str(wiki_path)
feature["wiki_format"] = fmt
# Optionally push to GitHub
if push_to_github or GITHUB_REPO:
github_path = await push_wiki_to_github(feature_name, wiki, fmt)
feature["github_wiki_url"] = github_path
return [TextContent(type="text", text=wiki)]
async def push_wiki_to_github(feature_name: str, content: str, fmt: str) -> str:
"""Push wiki file to GitHub repository."""
if not GITHUB_REPO or not GITHUB_TOKEN:
raise ValueError("GITHUB_REPO and GITHUB_TOKEN must be set to push to GitHub")
import httpx
branch = WIKI_BRANCH
filename = f"SchemaWiki/{feature_name}.{'md' if fmt == 'markdown' else 'html'}"
# Get the current file SHA if it exists (for updates)
sha = None
async with httpx.AsyncClient() as client:
# Try to get existing file
get_url = f"https://api.github.com/repos/{GITHUB_REPO}/contents/{filename}"
headers = {
"Authorization": f"token {GITHUB_TOKEN}",
"Accept": "application/vnd.github.v3+json",
}
resp = await client.get(get_url, headers=headers)
if resp.status_code == 200:
sha = resp.json().get("sha")
# Create or update file
data = {
"message": f"Update wiki: {feature_name}",
"content": content.encode("utf-8").decode("latin-1"),
"branch": branch,
}
if sha:
data["sha"] = sha
put_url = f"https://api.github.com/repos/{GITHUB_REPO}/contents/{filename}"
resp = await client.put(put_url, json=data, headers=headers)
if resp.status_code not in (200, 201):
raise ValueError(f"GitHub push failed: {resp.text}")
return resp.json().get("content", {}).get("html_url", "")
def generate_markdown_wiki(feature: dict) -> str:
"""Generate Markdown wiki page with rich context."""
lines = [
f"**[{PROJECT_NAME}](/)** ",
"",
f"# {feature['name']}",
"",
f"**Version:** {feature['version']} ",
f"**Status:** {feature['status']} ",
f"**Created:** {feature.get('created_at', 'N/A')}",
"",
]
# WHY this feature exists
if feature.get("why"):
lines.extend(
[
"## Why This Feature Exists",
"",
feature["why"],
"",
]
)
if feature.get("description"):
lines.extend(
[
"## Description",
"",
feature.get("description", "No description provided."),
"",
]
)
if feature.get("tags"):
lines.extend(
[
"## Tags",
"",
", ".join(f"`{tag}`" for tag in feature["tags"]),
"",
]
)
if feature.get("plan"):
lines.extend(
[
"## Plan",
"",
feature["plan"],
"",
]
)
if feature.get("implementation"):
lines.extend(
[
"## Implementation",
"",
feature["implementation"],
"",
]
)
# EVENTS - Major things that happened
if feature.get("events"):
lines.append("## Development Events")
lines.append("")
for event in feature["events"]:
event_emoji = {
"service_restarted": "🔄",
"change_pushed": "📤",
"test_passed": "✅",
"test_failed": "❌",
"lint_error": "⚠️",
"bug_fix": "🐛",
"code_review": "👀",
"refactor": "♻️",
"dependency_added": "📦",
"config_changed": "⚙️",
"api_contract_change": "🔗",
"db_migration": "🗄️",
"feature_coded": "💻",
}.get(event["event_type"], "📝")
lines.append(f"### {event_emoji} {event['event_type'].replace('_', ' ').title()}")
lines.append("")
lines.append(f"**Why:** {event.get('why', 'N/A')}")
if event.get("details"):
lines.append("")
lines.append(f"**Details:** {event['details']}")
if event.get("files"):
lines.append("")
lines.append("**Files:**")
for f in event["files"]:
lines.append(f"- `{f}`")
lines.append("")
# IMPLEMENTATION STEPS with WHY
if feature.get("steps"):
lines.append("## Implementation Steps")
lines.append("")
for i, step in enumerate(feature["steps"], 1):
lines.append(f"### Step {i}: {step['step']}")
lines.append("")
# WHY this step was taken
if step.get("why"):
lines.append(f"> **Why:** {step['why']}")
# Trigger
if step.get("trigger"):
lines.append(f"> **Trigger:** {step['trigger']}")
# Command
if step.get("command"):
lines.append("")
lines.append("```bash")
lines.append(step["command"])
lines.append("```")
# Files modified
if step.get("files_modified"):
lines.append("")
lines.append("**Files modified:**")
for f in step["files_modified"]:
lines.append(f"- `{f}`")
# Context
if step.get("context"):
lines.append("")
lines.append(f"**Context:** {step['context']}")
# Output (truncated)
if step.get("output"):
lines.append("")
lines.append("**Output:**")
lines.append("```")
lines.append(step["output"][:500])
lines.append("```")
lines.append("")
lines.append(f"**Status:** {step.get('status', 'unknown')}")
lines.append("")
# DEBUG LOGS with root cause analysis
if feature.get("debug_logs"):
lines.extend(
[
"## Debug Logs & Root Cause Analysis",
"",
]
)
for log in feature["debug_logs"]:
lines.append(f"### Attempt {log['attempt']}")
lines.append("")
lines.append(f"**Error:** `{log.get('error', 'N/A')}`")
# WHY it failed
if log.get("why_failed"):
lines.append("")
lines.append(f"**Why it failed:** {log['why_failed']}")
# What was done to fix
if log.get("fix_applied"):
lines.append("")
lines.append(f"**Fix applied:** {log['fix_applied']}")
# Full log
if log.get("log"):
lines.append("")
lines.append("**Debug log:**")
lines.append("```")
lines.append(log["log"])
lines.append("```")
lines.append("")
return "\n".join(lines)
def generate_html_wiki(feature: dict) -> str:
"""Generate HTML wiki page."""
md = generate_markdown_wiki(feature)
# Simple conversion
html = md.replace("# ", "<h1>").replace("\n## ", "</h1>\n<h2>").replace("\n### ", "</h2>\n<h3>")
html = html.replace("**", "<strong>").replace("`", "<code>").replace(">", "<blockquote>")
html = html.replace("\n\n", "</p>\n<p>")
return f"""<!DOCTYPE html>
<html>
<head>
<title>{feature['name']} - SchemaWiki</title>
<style>
body {{ font-family: -apple-system, BlinkMacSystemFont, 'Segoe UI', Roboto, sans-serif; max-width: 900px; margin: 0 auto; padding: 20px; line-height: 1.6; }}
h1, h2, h3 {{ color: #1a1a1a; margin-top: 30px; }}
code {{ background: #f4f4f4; padding: 2px 6px; border-radius: 3px; }}
pre {{ background: #f4f4f4; padding: 15px; border-radius: 5px; overflow-x: auto; }}
blockquote {{ border-left: 4px solid #0066cc; margin: 10px 0; padding-left: 15px; color: #555; }}
</style>
</head>
<body>
{html}
</body>
</html>"""
async def list_features() -> list[TextContent]:
"""List all features."""
return [TextContent(type="text", text=json.dumps(list(FEATURES.keys()), indent=2))]
async def search_features(args: dict) -> list[TextContent]:
"""Search features."""
query = args.get("query", "").lower()
results = []
for name, feature in FEATURES.items():
if query in name.lower() or query in feature.get("description", "").lower():
results.append(feature)
return [TextContent(type="text", text=json.dumps(results, indent=2))]
# REST API endpoints
from fastapi import Request
@app.post("/features")
async def create_feature_api(feature: FeatureRecord, request: Request):
"""REST API: Create feature."""
args = feature.model_dump()
# Auto-detect user_id from headers if not provided
if not args.get("user_id") and not args.get("session_id"):
# Try headers first
user_id = request.headers.get("X-User-ID") or request.headers.get("X-Session-ID")
if not user_id:
user_id = get_user_id_from_env()
args["user_id"] = user_id
result = await create_feature(args)
return json.loads(result[0].text)
@app.get("/features")
async def list_features_api():
"""REST API: List all features."""
features = []
for name, data in FEATURES.items():
features.append({"name": name, **data})
return features
@app.post("/steps")
async def record_step_api(step: StepRecord):
"""REST API: Record step."""
args = step.model_dump()
result = await record_step(args)
return json.loads(result[0].text)
@app.post("/events")
async def record_event_api(event: EventRecord):
"""REST API: Record event."""
args = event.model_dump()
result = await record_event(args)
return json.loads(result[0].text)
@app.get("/features/{name}")
async def get_feature_api(name: str):
"""REST API: Get feature."""
result = await get_feature({"name": name})
return json.loads(result[0].text)
@app.get("/wiki/{name}")
async def generate_wiki_api(name: str, format: str = "markdown"):
"""REST API: Generate wiki."""
result = await generate_wiki({"feature_name": name, "format": format})
return result[0].text
@app.get("/wiki/{name}/view")
async def view_wiki_html(name: str):
"""View wiki as rendered HTML page."""
from fastapi.responses import HTMLResponse
# Get markdown wiki
result = await generate_wiki({"feature_name": name, "format": "markdown"})
md_content = result[0].text
# Simple markdown to HTML conversion
html_content = md_to_html(md_content)
# Wrap in HTML page
html_page = f"""<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<title>{name} - SchemaWiki</title>
<style>
body {{
font-family: -apple-system, BlinkMacSystemFont, 'Segoe UI', Roboto, sans-serif;
max-width: 900px;
margin: 0 auto;
padding: 20px;
line-height: 1.6;
color: #333;
}}
h1 {{ color: #1a1a1a; border-bottom: 2px solid #0066cc; padding-bottom: 10px; }}
h2 {{ color: #2a2a2a; margin-top: 30px; }}
h3 {{ color: #3a3a3a; }}
code {{
background: #f4f4f4;
padding: 2px 6px;
border-radius: 3px;
font-family: 'Monaco', 'Menlo', monospace;
}}
pre {{
background: #f4f4f4;
padding: 15px;
border-radius: 5px;
overflow-x: auto;
}}
blockquote {{
border-left: 4px solid #0066cc;
margin: 10px 0;
padding-left: 15px;
color: #555;
background: #f9f9f9;
}}
ul, ol {{ padding-left: 25px; }}
li {{ margin: 5px 0; }}
strong {{ color: #0066cc; }}
hr {{ border: none; border-top: 1px solid #ddd; margin: 30px 0; }}
.meta {{ color: #666; font-size: 0.9em; }}
</style>
</head>
<body>
{html_content}
</body>
</html>"""
return HTMLResponse(html_page)
def md_to_html(md: str) -> str:
"""Simple markdown to HTML conversion."""
import re
html = md
# Headers
html = re.sub(r"^### (.+)$", r"<h3>\1</h3>", html, flags=re.MULTILINE)
html = re.sub(r"^## (.+)$", r"<h2>\1</h2>", html, flags=re.MULTILINE)
html = re.sub(r"^# (.+)$", r"<h1>\1</h1>", html, flags=re.MULTILINE)
# Bold
html = re.sub(r"\*\*(.+?)\*\*", r"<strong>\1</strong>", html)
# Code blocks
html = re.sub(r"```(\w*)\n(.*?)```", r"<pre><code>\2</code></pre>", html, flags=re.DOTALL)
# Inline code
html = re.sub(r"`([^`]+)`", r"<code>\1</code>", html)
# Lists
html = re.sub(r"^- (.+)$", r"<li>\1</li>", html, flags=re.MULTILINE)
html = re.sub(r"^(\d+)\. (.+)$", r"<li>\2</li>", html, flags=re.MULTILINE)
# Wrap consecutive li in ul
html = re.sub(r"(<li>.*?</li>\n?)+", r"<ul>\g<0></ul>", html)
# Blockquotes
html = re.sub(r"^> (.+)$", r"<blockquote>\1</blockquote>", html, flags=re.MULTILINE)
# Paragraphs
html = re.sub(r"\n\n+", "\n", html)
lines = html.split("\n")
result = []
in_pre = False
in_ul = False
in_blockquote = False
for line in lines:
line = line.strip()
if not line:
if in_pre or in_ul or in_blockquote:
if in_pre:
result.append("</code></pre>")
in_pre = False
if in_ul:
result.append("</ul>")
in_ul = False
if in_blockquote:
result.append("</blockquote>")
in_blockquote = False
continue
if line.startswith("<pre>") or line.startswith("<ul>") or line.startswith("<blockquote>"):
result.append(line)
continue
if "</pre>" in line or "</ul>" in line or "</blockquote>" in line:
result.append(line)
continue
if not line.startswith("<") and not line.startswith("#"):
line = f"<p>{line}</p>"
result.append(line)
return "\n".join(result)
@app.get("/wikis")
async def list_wikis():
"""List all saved wiki pages."""
wikis = []
for f in Path(WIKI_DATA_PATH).iterdir():
if f.is_file():
wikis.append(
{
"name": f.stem,
"format": f.suffix[1],
"path": str(f),
"size": f.stat().st_size,
"modified": datetime.fromtimestamp(f.stat().st_mtime).isoformat(),
}
)
return {"wikis": wikis}
@app.get("/wikis/{name}")
async def get_wiki(name: str):
"""Get a saved wiki page."""
# Try markdown first, then html
md_path = Path(WIKI_DATA_PATH) / f"{name}.md"
html_path = Path(WIKI_DATA_PATH) / f"{name}.html"
if md_path.exists():
return {"name": name, "format": "markdown", "content": md_path.read_text()}
elif html_path.exists():
return {"name": name, "format": "html", "content": html_path.read_text()}
else:
raise HTTPException(status_code=404, detail="Wiki not found")