|
| 1 | +from typing import Any, List, Optional |
| 2 | +import logging |
| 3 | +from pydantic import BaseModel |
| 4 | + |
| 5 | +from fastapi import APIRouter, Query |
| 6 | + |
| 7 | +logger = logging.getLogger(__name__) |
| 8 | + |
| 9 | +router = APIRouter() |
| 10 | + |
| 11 | +MAX_ENTITY_LIMIT = 500 |
| 12 | + |
| 13 | + |
| 14 | +class NamespaceCreateRequest(BaseModel): |
| 15 | + namespace_id: str |
| 16 | + |
| 17 | + |
| 18 | +class EntityCreateRequest(BaseModel): |
| 19 | + type: str |
| 20 | + content: str |
| 21 | + metadata: dict = {} |
| 22 | + |
| 23 | + |
| 24 | +@router.get("/dashboard") |
| 25 | +def get_dashboard() -> dict[str, Any]: |
| 26 | + from kaizen.frontend.mcp.mcp_server import get_client |
| 27 | + |
| 28 | + client = get_client() |
| 29 | + |
| 30 | + # 1. Backend health |
| 31 | + try: |
| 32 | + health = client.ready() |
| 33 | + except Exception as e: |
| 34 | + logger.error(f"Error checking health: {e}") |
| 35 | + health = False |
| 36 | + |
| 37 | + # 2. Namespace count |
| 38 | + try: |
| 39 | + namespaces = client.all_namespaces(limit=1000) |
| 40 | + namespace_count = len(namespaces) |
| 41 | + except Exception as e: |
| 42 | + logger.error(f"Error fetching namespaces: {e}") |
| 43 | + namespaces = [] |
| 44 | + namespace_count = 0 |
| 45 | + |
| 46 | + # 3. Entity counts and recent entities across namespaces |
| 47 | + # For MVP, we will aggregate from all available namespaces up to the limit |
| 48 | + total_entities = 0 |
| 49 | + approximate_type_breakdown: dict[str, int] = {} |
| 50 | + recent_entities: list[dict[str, Any]] = [] |
| 51 | + |
| 52 | + for ns in namespaces: |
| 53 | + try: |
| 54 | + total_entities += ns.num_entities or 0 |
| 55 | + # Fetch only a small sample per namespace for the dashboard |
| 56 | + ns_entities = client.get_all_entities(ns.id, limit=10) |
| 57 | + |
| 58 | + for entity in ns_entities: |
| 59 | + etype = entity.type or "unknown" |
| 60 | + approximate_type_breakdown[etype] = approximate_type_breakdown.get(etype, 0) + 1 |
| 61 | + |
| 62 | + # Safely handle non-string content before slicing |
| 63 | + content = entity.content |
| 64 | + if isinstance(content, str): |
| 65 | + snippet = content[:100] + "..." if len(content) > 100 else content |
| 66 | + else: |
| 67 | + safe_str = str(content) |
| 68 | + snippet = safe_str[:100] + "..." if len(safe_str) > 100 else safe_str |
| 69 | + |
| 70 | + recent_entities.append( |
| 71 | + { |
| 72 | + "id": entity.id, |
| 73 | + "type": entity.type, |
| 74 | + "content": snippet, |
| 75 | + "namespace": ns.id, |
| 76 | + "created_at": entity.created_at.isoformat() if hasattr(entity, "created_at") and entity.created_at else None, |
| 77 | + } |
| 78 | + ) |
| 79 | + except Exception as e: |
| 80 | + logger.error(f"Error fetching entities for namespace {ns.id}: {e}") |
| 81 | + |
| 82 | + # sort by created_at descending (assuming we have those or just use the end of list) |
| 83 | + # the client doesn't strictly order by date right now unless we extract or sort manually |
| 84 | + recent_entities.sort(key=lambda x: x.get("created_at") or "", reverse=True) |
| 85 | + recent_entities = recent_entities[:10] # top 10 |
| 86 | + |
| 87 | + return { |
| 88 | + "health": health, |
| 89 | + "namespace_count": namespace_count, |
| 90 | + "total_entities": total_entities, |
| 91 | + "approximate_type_breakdown": [{"type": k, "count": v} for k, v in approximate_type_breakdown.items()], |
| 92 | + "type_breakdown_is_approx": True, |
| 93 | + "recent_entities": recent_entities, |
| 94 | + } |
| 95 | + |
| 96 | + |
| 97 | +@router.get("/namespaces") |
| 98 | +def list_namespaces() -> List[dict[str, Any]]: |
| 99 | + from kaizen.frontend.mcp.mcp_server import get_client |
| 100 | + |
| 101 | + client = get_client() |
| 102 | + try: |
| 103 | + namespaces = [] |
| 104 | + for ns in client.all_namespaces(limit=1000): |
| 105 | + namespaces.append({"id": ns.id, "amount_of_entities": ns.num_entities or 0}) |
| 106 | + return namespaces |
| 107 | + except Exception as e: |
| 108 | + from fastapi import HTTPException |
| 109 | + |
| 110 | + logger.error(f"Error fetching namespaces: {e}") |
| 111 | + raise HTTPException(status_code=500, detail="Internal server error while fetching namespaces") |
| 112 | + |
| 113 | + |
| 114 | +@router.post("/namespaces") |
| 115 | +def add_namespace(req: NamespaceCreateRequest) -> dict[str, Any]: |
| 116 | + from kaizen.frontend.mcp.mcp_server import get_client |
| 117 | + |
| 118 | + client = get_client() |
| 119 | + try: |
| 120 | + client.create_namespace(req.namespace_id) |
| 121 | + return {"success": True, "namespace_id": req.namespace_id} |
| 122 | + except Exception as e: |
| 123 | + from fastapi import HTTPException |
| 124 | + |
| 125 | + logger.error(f"Error creating namespace: {e}") |
| 126 | + raise HTTPException(status_code=400, detail="Internal server error while creating namespace") |
| 127 | + |
| 128 | + |
| 129 | +@router.delete("/namespaces/{namespace_id}") |
| 130 | +def delete_namespace(namespace_id: str) -> dict[str, Any]: |
| 131 | + from kaizen.frontend.mcp.mcp_server import get_client |
| 132 | + |
| 133 | + client = get_client() |
| 134 | + try: |
| 135 | + client.delete_namespace(namespace_id) |
| 136 | + return {"success": True} |
| 137 | + except Exception as e: |
| 138 | + from fastapi import HTTPException |
| 139 | + |
| 140 | + logger.error(f"Error deleting namespace: {e}") |
| 141 | + raise HTTPException(status_code=400, detail="Internal server error while deleting namespace") |
| 142 | + |
| 143 | + |
| 144 | +@router.get("/namespaces/{namespace_id}/entities") |
| 145 | +def list_namespace_entities( |
| 146 | + namespace_id: str, |
| 147 | + type: Optional[str] = Query(None, description="Filter entities by type (e.g., guideline, task)"), |
| 148 | + limit: int = Query(100, description=f"Maximum number of entities to return (max {MAX_ENTITY_LIMIT})"), |
| 149 | +) -> List[dict[str, Any]]: |
| 150 | + from kaizen.frontend.mcp.mcp_server import get_client |
| 151 | + |
| 152 | + client = get_client() |
| 153 | + try: |
| 154 | + # Sanitize limit |
| 155 | + limit = max(1, min(limit, MAX_ENTITY_LIMIT)) |
| 156 | + |
| 157 | + filters = {} |
| 158 | + if type: |
| 159 | + filters["type"] = type |
| 160 | + |
| 161 | + entities = client.get_all_entities(namespace_id, filters=filters, limit=limit) |
| 162 | + |
| 163 | + result = [] |
| 164 | + for entity in entities: |
| 165 | + result.append( |
| 166 | + { |
| 167 | + "id": entity.id, |
| 168 | + "type": entity.type, |
| 169 | + "content": entity.content, |
| 170 | + "metadata": entity.metadata or {}, |
| 171 | + "created_at": entity.created_at.isoformat() if hasattr(entity, "created_at") and entity.created_at else None, |
| 172 | + } |
| 173 | + ) |
| 174 | + |
| 175 | + # Sort by created_at descending |
| 176 | + result.sort(key=lambda x: str(x.get("created_at") or ""), reverse=True) |
| 177 | + return result |
| 178 | + except Exception as e: |
| 179 | + from fastapi import HTTPException |
| 180 | + |
| 181 | + logger.error(f"Error fetching entities for namespace {namespace_id}: {e}") |
| 182 | + raise HTTPException(status_code=500, detail="Internal server error while fetching entities") |
| 183 | + |
| 184 | + |
| 185 | +@router.delete("/namespaces/{namespace_id}/entities/{entity_id}") |
| 186 | +def delete_namespace_entity(namespace_id: str, entity_id: str) -> dict[str, Any]: |
| 187 | + from kaizen.frontend.mcp.mcp_server import get_client |
| 188 | + |
| 189 | + client = get_client() |
| 190 | + try: |
| 191 | + client.delete_entity_by_id(namespace_id, entity_id) |
| 192 | + return {"success": True} |
| 193 | + except Exception as e: |
| 194 | + from fastapi import HTTPException |
| 195 | + |
| 196 | + logger.error(f"Error deleting entity {entity_id} from namespace {namespace_id}: {e}") |
| 197 | + raise HTTPException(status_code=400, detail="Internal server error while deleting entity") |
| 198 | + |
| 199 | + |
| 200 | +@router.post("/namespaces/{namespace_id}/entities") |
| 201 | +def create_namespace_entity(namespace_id: str, req: EntityCreateRequest) -> dict[str, Any]: |
| 202 | + from kaizen.frontend.mcp.mcp_server import get_client |
| 203 | + from kaizen.schema.core import Entity |
| 204 | + from fastapi import HTTPException |
| 205 | + |
| 206 | + # 1. Normalize and validate inputs before branching |
| 207 | + entity_type = req.type.strip().lower() |
| 208 | + if not req.content or not req.content.strip(): |
| 209 | + raise HTTPException(status_code=422, detail="Entity content must be non-empty.") |
| 210 | + |
| 211 | + # 2. Enforce specific schema typing prior to insertion |
| 212 | + if entity_type == "guideline": |
| 213 | + from kaizen.schema.tips import Tip |
| 214 | + |
| 215 | + try: |
| 216 | + # Tip expects content at the root, so we map req.content and unpack the metadata |
| 217 | + tip_meta = {k: v for k, v in req.metadata.items() if k != "content"} |
| 218 | + Tip(content=req.content, **tip_meta) |
| 219 | + except Exception as e: |
| 220 | + logger.error(f"Guideline validation failed: {e}") |
| 221 | + raise HTTPException(status_code=422, detail=f"Invalid guideline metadata schema: {e}") |
| 222 | + |
| 223 | + elif entity_type == "policy": |
| 224 | + from kaizen.schema.policy import Policy, PolicyType |
| 225 | + |
| 226 | + try: |
| 227 | + # The Policy model checks the full payload |
| 228 | + policy_meta = {k: v for k, v in req.metadata.items() if k != "content"} |
| 229 | + Policy(content=req.content, type=PolicyType(req.metadata["policy_type"]), **policy_meta) |
| 230 | + except Exception as e: |
| 231 | + logger.error(f"Policy validation failed: {e}") |
| 232 | + raise HTTPException(status_code=422, detail=f"Invalid policy metadata schema: {e}") |
| 233 | + |
| 234 | + client = get_client() |
| 235 | + try: |
| 236 | + new_entity = Entity(type=entity_type, content=req.content, metadata=req.metadata) |
| 237 | + # Using enable_conflict_resolution=False for a direct insert |
| 238 | + updates = client.update_entities(namespace_id, [new_entity], enable_conflict_resolution=False) |
| 239 | + if not updates: |
| 240 | + raise Exception("Failed to insert entity. No updates returned.") |
| 241 | + return {"success": True, "id": updates[0].id} |
| 242 | + except Exception as e: |
| 243 | + logger.error(f"Error creating entity in namespace {namespace_id}: {e}") |
| 244 | + raise HTTPException(status_code=400, detail="Internal server error while creating entity") |
0 commit comments