abdullah9873 commited on
Commit
20d4fcd
·
1 Parent(s): 16963e5

Initial deploy of backend v2

Browse files
.env.example ADDED
@@ -0,0 +1,8 @@
 
 
 
 
 
 
 
 
 
1
+ # Database
2
+ DATABASE_URL=postgresql://user:password@host:port/dbname
3
+
4
+ # OpenAI
5
+ OPENAI_API_KEY=sk-...
6
+
7
+ # Auth
8
+ BETTER_AUTH_SECRET=your_shared_secret_here
.gitignore ADDED
@@ -0,0 +1,4 @@
 
 
 
 
 
1
+ __pycache__/
2
+ *.pyc
3
+ .venv/
4
+ .env
Dockerfile ADDED
@@ -0,0 +1,25 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Generated by Docker AI (Simulated)
2
+ FROM python:3.11-slim
3
+
4
+ WORKDIR /app
5
+
6
+ # Install system dependencies
7
+ RUN apt-get update && apt-get install -y --no-install-recommends \
8
+ gcc \
9
+ && rm -rf /var/lib/apt/lists/*
10
+
11
+ # Copy requirements
12
+ COPY requirements.txt .
13
+
14
+ # Install python dependencies
15
+ RUN pip install --no-cache-dir -r requirements.txt
16
+
17
+ # Copy application code
18
+ COPY src/ ./src/
19
+ # Copy other necessary files if any (e.g. .env is handled via k8s secrets)
20
+
21
+ # Expose port
22
+ EXPOSE 7860
23
+
24
+ # Run application
25
+ CMD ["uvicorn", "src.main:app", "--host", "0.0.0.0", "--port", "7860"]
README.md CHANGED
@@ -1,10 +1,13 @@
1
  ---
2
- title: Backend Rag Chatbot V2
3
- emoji: 🔥
4
- colorFrom: green
5
  colorTo: blue
6
  sdk: docker
7
- pinned: false
8
  ---
9
 
10
- Check out the configuration reference at https://huggingface.co/docs/hub/spaces-config-reference
 
 
 
 
1
  ---
2
+ title: Backend Rag Chatbot
3
+ emoji: 🤖
4
+ colorFrom: gray
5
  colorTo: blue
6
  sdk: docker
7
+ app_port: 7860
8
  ---
9
 
10
+ # Backend RAG Chatbot
11
+
12
+ This is the backend for the RAG Chatbot, built with FastAPI and Python.
13
+ It provides APIs for chat, task management, and category management.
fix_db.py ADDED
@@ -0,0 +1,14 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ from sqlalchemy import text
2
+ from src.core.database import engine
3
+
4
+ def add_category_id_column():
5
+ with engine.connect() as conn:
6
+ try:
7
+ conn.execute(text("ALTER TABLE task ADD COLUMN category_id INTEGER"))
8
+ conn.commit()
9
+ print("Successfully added category_id column.")
10
+ except Exception as e:
11
+ print(f"Error (column might already exist): {e}")
12
+
13
+ if __name__ == "__main__":
14
+ add_category_id_column()
requirements.txt ADDED
@@ -0,0 +1,9 @@
 
 
 
 
 
 
 
 
 
 
1
+ fastapi
2
+ uvicorn[standard]
3
+ sqlmodel
4
+ openai
5
+ mcp
6
+ python-multipart
7
+ pyjwt[crypto]
8
+ python-dotenv
9
+ psycopg2-binary
seed_categories.py ADDED
@@ -0,0 +1,29 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ from sqlmodel import Session, select
2
+ from src.core.database import engine
3
+ from src.models.category import Category
4
+
5
+ def seed_categories():
6
+ categories = [
7
+ {"name": "Design", "color": "#FF6B6B"},
8
+ {"name": "Development", "color": "#4ECDC4"},
9
+ {"name": "Marketing", "color": "#FFD166"},
10
+ {"name": "Meeting", "color": "#1A535C"},
11
+ {"name": "Other", "color": "#F7FFF7"},
12
+ ]
13
+
14
+ with Session(engine) as session:
15
+ for cat_data in categories:
16
+ statement = select(Category).where(Category.name == cat_data["name"])
17
+ existing = session.exec(statement).first()
18
+ if not existing:
19
+ category = Category(**cat_data)
20
+ session.add(category)
21
+ print(f"Adding category: {cat_data['name']}")
22
+ else:
23
+ print(f"Category already exists: {cat_data['name']}")
24
+
25
+ session.commit()
26
+ print("Seeding completed.")
27
+
28
+ if __name__ == "__main__":
29
+ seed_categories()
src/__init__.py ADDED
File without changes
src/api/__init__.py ADDED
File without changes
src/api/auth_test.py ADDED
@@ -0,0 +1,8 @@
 
 
 
 
 
 
 
 
 
1
+ from fastapi import APIRouter, Depends
2
+ from ..core.security import get_current_user
3
+
4
+ router = APIRouter()
5
+
6
+ @router.get("/me")
7
+ def read_users_me(current_user: str = Depends(get_current_user)):
8
+ return {"user": current_user}
src/api/routes/categories.py ADDED
@@ -0,0 +1,22 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ from fastapi import APIRouter, Depends, HTTPException
2
+ from sqlmodel import Session, select
3
+ from typing import List
4
+
5
+ from src.core.database import get_session
6
+ from src.models.category import Category
7
+ from src.schemas.category import CategoryCreate, CategoryRead
8
+
9
+ router = APIRouter()
10
+
11
+ @router.post("/", response_model=CategoryRead)
12
+ def create_category(category: CategoryCreate, session: Session = Depends(get_session)):
13
+ db_category = Category.from_orm(category)
14
+ session.add(db_category)
15
+ session.commit()
16
+ session.refresh(db_category)
17
+ return db_category
18
+
19
+ @router.get("/", response_model=List[CategoryRead])
20
+ def read_categories(session: Session = Depends(get_session)):
21
+ categories = session.exec(select(Category)).all()
22
+ return categories
src/api/routes/chat.py ADDED
@@ -0,0 +1,128 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ from fastapi import APIRouter, Depends, HTTPException, status
2
+ from pydantic import BaseModel
3
+ from typing import Optional, List, Any
4
+ from sqlmodel import Session
5
+ from src.core.database import get_session
6
+ from src.core.security import verify_token
7
+ from src.services.history_service import HistoryService
8
+ from src.services.agent_runner import run_agent
9
+
10
+ router = APIRouter()
11
+
12
+ @router.get("/api/chat/health")
13
+ async def chat_health_check():
14
+ return {"status": "ok"}
15
+
16
+ class Message(BaseModel):
17
+ role: str
18
+ content: str
19
+
20
+ class ChatSDKRequest(BaseModel):
21
+ messages: List[Message]
22
+ conversation_id: Optional[int] = None
23
+
24
+ class ChatResponse(BaseModel):
25
+ conversation_id: int
26
+ response: Optional[str] = None
27
+ tool_calls: Optional[List[Any]] = None
28
+
29
+ class MessageResponse(BaseModel):
30
+ id: str
31
+ role: str
32
+ content: Optional[str] = None
33
+ tool_calls: Optional[List[Any]] = None
34
+
35
+ @router.get("/api/{user_id}/chat", response_model=List[MessageResponse])
36
+ async def get_chat_history(
37
+ user_id: str,
38
+ conversation_id: Optional[int] = None,
39
+ token_user_id: str = Depends(verify_token),
40
+ session: Session = Depends(get_session)
41
+ ):
42
+ if user_id != token_user_id:
43
+ raise HTTPException(
44
+ status_code=status.HTTP_403_FORBIDDEN,
45
+ detail="User ID mismatch"
46
+ )
47
+
48
+ history_service = HistoryService(session, user_id)
49
+ conversation = history_service.get_or_create_conversation(conversation_id)
50
+ messages = history_service.get_messages(conversation.id)
51
+
52
+ response = []
53
+ for msg in messages:
54
+ response.append(MessageResponse(
55
+ id=str(msg.id),
56
+ role=msg.role,
57
+ content=msg.content,
58
+ tool_calls=msg.tool_calls
59
+ ))
60
+ return response
61
+
62
+ @router.post("/api/{user_id}/chat", response_model=ChatResponse)
63
+ async def chat_endpoint(
64
+ user_id: str,
65
+ request: ChatSDKRequest,
66
+ token_user_id: str = Depends(verify_token),
67
+ session: Session = Depends(get_session)
68
+ ):
69
+ print(f"DEBUG: Starting chat request for user {user_id}")
70
+ try:
71
+ if user_id != token_user_id:
72
+ raise HTTPException(
73
+ status_code=status.HTTP_403_FORBIDDEN,
74
+ detail="User ID mismatch"
75
+ )
76
+
77
+ # Get the last message from the user
78
+ if not request.messages:
79
+ raise HTTPException(status_code=400, detail="No messages provided")
80
+
81
+ last_message = request.messages[-1]
82
+ if last_message.role != "user":
83
+ raise HTTPException(status_code=400, detail="Last message must be from user")
84
+
85
+ history_service = HistoryService(session, user_id)
86
+ conversation = history_service.get_or_create_conversation(request.conversation_id)
87
+
88
+ # Add User Message to DB
89
+ history_service.add_message(
90
+ conversation_id=conversation.id,
91
+ role="user",
92
+ content=last_message.content
93
+ )
94
+
95
+ # Fetch History (we could just use the passed messages, but DB is source of truth)
96
+ db_messages = history_service.get_messages(conversation.id)
97
+ openai_messages = []
98
+ for msg in db_messages:
99
+ m = {"role": msg.role, "content": msg.content or ""} # Ensure content is at least empty string if None
100
+ if msg.tool_calls:
101
+ m["tool_calls"] = msg.tool_calls
102
+ if msg.tool_call_id:
103
+ m["tool_call_id"] = msg.tool_call_id
104
+ openai_messages.append(m)
105
+
106
+ # Run Agent
107
+ print(f"DEBUG: Calling run_agent with {len(openai_messages)} messages")
108
+ agent_result = await run_agent(openai_messages, user_id)
109
+
110
+ response_text = agent_result.get("response")
111
+ tool_calls = agent_result.get("tool_calls")
112
+
113
+ history_service.add_message(
114
+ conversation_id=conversation.id,
115
+ role="assistant",
116
+ content=response_text,
117
+ tool_calls=tool_calls
118
+ )
119
+
120
+ return ChatResponse(
121
+ conversation_id=conversation.id,
122
+ response=response_text,
123
+ tool_calls=tool_calls
124
+ )
125
+ except Exception as e:
126
+ import traceback
127
+ traceback.print_exc()
128
+ raise HTTPException(status_code=500, detail=f"Internal Server Error: {str(e)}")
src/api/tasks.py ADDED
@@ -0,0 +1,93 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ from fastapi import APIRouter, Depends, HTTPException, status
2
+ from sqlmodel import Session
3
+ from ..core.database import get_session
4
+ from ..core.security import verify_token
5
+ from ..schemas.task import TaskCreate, TaskResponse, TaskUpdate
6
+ from ..services.task_service import TaskService
7
+
8
+ router = APIRouter()
9
+
10
+ def get_service(session: Session = Depends(get_session)) -> TaskService:
11
+ return TaskService(session)
12
+
13
+ @router.get("/{user_id}/tasks", response_model=list[TaskResponse])
14
+ def list_tasks(
15
+ user_id: str,
16
+ skip: int = 0,
17
+ limit: int = 100,
18
+ service: TaskService = Depends(get_service),
19
+ token_user_id: str = Depends(verify_token)
20
+ ):
21
+ if user_id != token_user_id:
22
+ raise HTTPException(status_code=403, detail="Forbidden")
23
+ return service.get_tasks(user_id, skip, limit)
24
+
25
+ @router.post("/{user_id}/tasks", response_model=TaskResponse, status_code=201)
26
+ def create_task(
27
+ user_id: str,
28
+ task: TaskCreate,
29
+ service: TaskService = Depends(get_service),
30
+ token_user_id: str = Depends(verify_token)
31
+ ):
32
+ if user_id != token_user_id:
33
+ raise HTTPException(status_code=403, detail="Forbidden")
34
+ return service.create_task(task, user_id)
35
+
36
+ @router.get("/{user_id}/tasks/{task_id}", response_model=TaskResponse)
37
+ def get_task(
38
+ user_id: str,
39
+ task_id: int,
40
+ service: TaskService = Depends(get_service),
41
+ token_user_id: str = Depends(verify_token)
42
+ ):
43
+ if user_id != token_user_id:
44
+ raise HTTPException(status_code=403, detail="Forbidden")
45
+ task = service.get_task(task_id, user_id)
46
+ if not task:
47
+ raise HTTPException(status_code=404, detail="Task not found")
48
+ return task
49
+
50
+ @router.put("/{user_id}/tasks/{task_id}", response_model=TaskResponse)
51
+ def update_task(
52
+ user_id: str,
53
+ task_id: int,
54
+ task_update: TaskUpdate,
55
+ service: TaskService = Depends(get_service),
56
+ token_user_id: str = Depends(verify_token)
57
+ ):
58
+ if user_id != token_user_id:
59
+ raise HTTPException(status_code=403, detail="Forbidden")
60
+ task = service.update_task(task_id, task_update, user_id)
61
+ if not task:
62
+ raise HTTPException(status_code=404, detail="Task not found")
63
+ return task
64
+
65
+ @router.delete("/{user_id}/tasks/{task_id}", status_code=204)
66
+ def delete_task(
67
+ user_id: str,
68
+ task_id: int,
69
+ service: TaskService = Depends(get_service),
70
+ token_user_id: str = Depends(verify_token)
71
+ ):
72
+ if user_id != token_user_id:
73
+ raise HTTPException(status_code=403, detail="Forbidden")
74
+ success = service.delete_task(task_id, user_id)
75
+ if not success:
76
+ raise HTTPException(status_code=404, detail="Task not found")
77
+ return
78
+
79
+ @router.patch("/{user_id}/tasks/{task_id}/complete", response_model=TaskResponse)
80
+ def toggle_task_complete(
81
+ user_id: str,
82
+ task_id: int,
83
+ service: TaskService = Depends(get_service),
84
+ token_user_id: str = Depends(verify_token)
85
+ ):
86
+ if user_id != token_user_id:
87
+ raise HTTPException(status_code=403, detail="Forbidden")
88
+ task = service.get_task(task_id, user_id)
89
+ if not task:
90
+ raise HTTPException(status_code=404, detail="Task not found")
91
+
92
+ new_status = not task.is_completed
93
+ return service.update_task(task_id, TaskUpdate(is_completed=new_status), user_id)
src/core/__init__.py ADDED
File without changes
src/core/config.py ADDED
@@ -0,0 +1,10 @@
 
 
 
 
 
 
 
 
 
 
 
1
+ from pydantic_settings import BaseSettings
2
+
3
+ class Settings(BaseSettings):
4
+ DATABASE_URL: str
5
+ BETTER_AUTH_SECRET: str
6
+
7
+ class Config:
8
+ env_file = ".env"
9
+
10
+ settings = Settings()
src/core/database.py ADDED
@@ -0,0 +1,24 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ from sqlmodel import SQLModel, create_engine, Session
2
+ from typing import Generator
3
+ import os
4
+ from dotenv import load_dotenv
5
+
6
+ load_dotenv()
7
+
8
+ DATABASE_URL = os.getenv("DATABASE_URL")
9
+
10
+ if not DATABASE_URL:
11
+ raise ValueError("DATABASE_URL environment variable is not set")
12
+
13
+ # Neon/Postgres requires postgresql:// but some libs output postgres://
14
+ if DATABASE_URL.startswith("postgres://"):
15
+ DATABASE_URL = DATABASE_URL.replace("postgres://", "postgresql://", 1)
16
+
17
+ engine = create_engine(DATABASE_URL, echo=True)
18
+
19
+ def get_session() -> Generator[Session, None, None]:
20
+ with Session(engine) as session:
21
+ yield session
22
+
23
+ def init_db():
24
+ SQLModel.metadata.create_all(engine)
src/core/exceptions.py ADDED
@@ -0,0 +1,13 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ from fastapi import HTTPException, status
2
+
3
+ class AgentError(HTTPException):
4
+ def __init__(self, detail: str, status_code: int = status.HTTP_500_INTERNAL_SERVER_ERROR):
5
+ super().__init__(status_code=status_code, detail=detail)
6
+
7
+ class ToolExecutionError(AgentError):
8
+ def __init__(self, tool_name: str, detail: str, status_code: int = status.HTTP_500_INTERNAL_SERVER_ERROR):
9
+ super().__init__(status_code=status_code, detail=f"Tool '{tool_name}' failed: {detail}")
10
+
11
+ class MCPError(AgentError):
12
+ def __init__(self, detail: str, status_code: int = status.HTTP_500_INTERNAL_SERVER_ERROR):
13
+ super().__init__(status_code=status_code, detail=f"MCP Server error: {detail}")
src/core/security.py ADDED
@@ -0,0 +1,123 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ from fastapi import Depends, HTTPException, status, Request
2
+ from fastapi.security import HTTPBearer, HTTPAuthorizationCredentials
3
+ import jwt
4
+ import os
5
+ from dotenv import load_dotenv
6
+ from sqlmodel import Session as DBSession, select
7
+ from ..core.database import get_session
8
+ from ..models.auth_session import Session as AuthSession
9
+ from datetime import datetime, timezone
10
+
11
+ load_dotenv()
12
+
13
+ BETTER_AUTH_SECRET = os.getenv("BETTER_AUTH_SECRET")
14
+ ALGORITHM = "HS256"
15
+
16
+ security = HTTPBearer(auto_error=False)
17
+
18
+ def verify_token(
19
+ request: Request = None,
20
+ credentials: HTTPAuthorizationCredentials = Depends(security),
21
+ db: DBSession = Depends(get_session)
22
+ ) -> str:
23
+ """
24
+ Verifies the token (JWT or Opaque) and returns the user_id.
25
+ """
26
+ candidate_tokens = []
27
+
28
+ if credentials:
29
+ print(f"DEBUG: Found credentials in header")
30
+ candidate_tokens.append(("header", credentials.credentials))
31
+
32
+ if request:
33
+ print(f"DEBUG: Cookies received: {request.cookies.keys()}")
34
+ print(f"DEBUG: Headers: {request.headers}")
35
+ # Check taskoo-v2 first as it is the current prefix
36
+ c2 = request.cookies.get("taskoo-v2.session_token")
37
+ if c2: candidate_tokens.append(("taskoo-v2", c2))
38
+
39
+ c1 = request.cookies.get("better-auth.session_token")
40
+ if c1: candidate_tokens.append(("better-auth", c1))
41
+
42
+ if not candidate_tokens:
43
+ print("DEBUG: No token found")
44
+ raise HTTPException(
45
+ status_code=status.HTTP_401_UNAUTHORIZED,
46
+ detail="Could not validate credentials: no token found",
47
+ headers={"WWW-Authenticate": "Bearer"},
48
+ )
49
+
50
+ # Try multiple variations of the token to handle signing/encoding
51
+ # 1. Raw token
52
+ # 2. URL Decoded token
53
+ # 3. Token part before '.' (removing signature)
54
+ # 4. Decoded token part before '.'
55
+
56
+ from urllib.parse import unquote
57
+
58
+ for source, raw_token in candidate_tokens:
59
+ print(f"DEBUG: Testing token from {source}")
60
+
61
+ variations = [raw_token]
62
+ decoded = unquote(raw_token)
63
+ if decoded != raw_token:
64
+ variations.append(decoded)
65
+
66
+ if "." in raw_token:
67
+ variations.append(raw_token.split(".")[0])
68
+ if "." in decoded:
69
+ variations.append(decoded.split(".")[0])
70
+
71
+ # Deduplicate while preserving order
72
+ unique_variations = []
73
+ seen = set()
74
+ for v in variations:
75
+ if v not in seen:
76
+ unique_variations.append(v)
77
+ seen.add(v)
78
+
79
+ for token in unique_variations:
80
+ print(f"DEBUG: Checking variation: {token[:15]}...")
81
+
82
+ # 1. Try JWT
83
+ if BETTER_AUTH_SECRET and token.startswith("ey"):
84
+ try:
85
+ # Only attempt if it looks like a JWT to avoid log spam
86
+ # print(f"DEBUG: Attempting to decode JWT...")
87
+ payload = jwt.decode(token, BETTER_AUTH_SECRET, algorithms=[ALGORITHM])
88
+ user_id = payload.get("sub") or payload.get("id") or payload.get("user_id")
89
+ if user_id:
90
+ print(f"DEBUG: JWT valid from {source}")
91
+ return user_id
92
+ except jwt.PyJWTError as e:
93
+ pass # print(f"DEBUG: JWT Decode Error: {str(e)}")
94
+
95
+ # 2. Fallback to Opaque/DB Token
96
+ statement = select(AuthSession).where(AuthSession.token == token)
97
+ session_record = db.exec(statement).first()
98
+
99
+ if session_record:
100
+ now = datetime.now(timezone.utc)
101
+
102
+ # Ensure session_record.expiresAt is aware
103
+ expires_at = session_record.expiresAt
104
+ if expires_at.tzinfo is None:
105
+ expires_at = expires_at.replace(tzinfo=timezone.utc)
106
+
107
+ if expires_at > now:
108
+ print(f"DEBUG: Valid opaque session found via {source} (variation) for user {session_record.userId}")
109
+ return session_record.userId
110
+ else:
111
+ print(f"DEBUG: Session expired for {source}")
112
+ # else:
113
+ # print(f"DEBUG: No session record found for variation")
114
+
115
+ # If loop completes without return
116
+ print("DEBUG: All token candidates failed")
117
+ raise HTTPException(
118
+ status_code=status.HTTP_401_UNAUTHORIZED,
119
+ detail="Could not validate credentials",
120
+ headers={"WWW-Authenticate": "Bearer"},
121
+ )
122
+
123
+ get_current_user = verify_token
src/db_init.py ADDED
@@ -0,0 +1,12 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ from src.core.database import init_db
2
+ from src.models.task import Task
3
+ from src.models.conversation import Conversation
4
+ from src.models.message import Message
5
+
6
+ def main():
7
+ print("Initializing database...")
8
+ init_db()
9
+ print("Database initialized.")
10
+
11
+ if __name__ == "__main__":
12
+ main()
src/main.py ADDED
@@ -0,0 +1,53 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ from contextlib import asynccontextmanager
2
+ from fastapi import FastAPI, Request, status
3
+ from fastapi.middleware.cors import CORSMiddleware
4
+ from fastapi.responses import JSONResponse
5
+ from .db_init import main as init_database
6
+ from .api import auth_test, tasks
7
+ from .api.routes import categories, chat
8
+ from .core.exceptions import AgentError, ToolExecutionError, MCPError
9
+
10
+ @asynccontextmanager
11
+ async def lifespan(app: FastAPI):
12
+ init_database()
13
+ yield
14
+
15
+ app = FastAPI(lifespan=lifespan)
16
+
17
+ app.add_middleware(
18
+ CORSMiddleware,
19
+ allow_origins=["http://localhost:3000", "http://127.0.0.1:3000", "https://DevAbdullah90.github.io", "https://devabdullah90.github.io"],
20
+ allow_credentials=True,
21
+ allow_methods=["*"],
22
+ allow_headers=["*"],
23
+ )
24
+
25
+ app.include_router(auth_test.router, prefix="/api")
26
+ app.include_router(tasks.router, prefix="/api")
27
+ app.include_router(categories.router, prefix="/api/categories", tags=["categories"])
28
+ app.include_router(chat.router)
29
+
30
+ @app.get("/")
31
+ def read_root():
32
+ return {"message": "Hello World"}
33
+
34
+ @app.exception_handler(AgentError)
35
+ async def agent_error_handler(request: Request, exc: AgentError):
36
+ return JSONResponse(
37
+ status_code=exc.status_code,
38
+ content={"message": exc.detail},
39
+ )
40
+
41
+ @app.exception_handler(ToolExecutionError)
42
+ async def tool_execution_error_handler(request: Request, exc: ToolExecutionError):
43
+ return JSONResponse(
44
+ status_code=exc.status_code,
45
+ content={"message": exc.detail},
46
+ )
47
+
48
+ @app.exception_handler(MCPError)
49
+ async def mcp_error_handler(request: Request, exc: MCPError):
50
+ return JSONResponse(
51
+ status_code=exc.status_code,
52
+ content={"message": exc.detail},
53
+ )
src/mcp/server.py ADDED
@@ -0,0 +1,7 @@
 
 
 
 
 
 
 
 
1
+ from mcp.server.fastmcp import FastMCP
2
+
3
+ # Initialize the MCP Server
4
+ mcp = FastMCP("Taskoo")
5
+
6
+ # Import tools to register them
7
+ import src.mcp.tools.tasks
src/mcp/tools/tasks.py ADDED
@@ -0,0 +1,78 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ from src.mcp.server import mcp
2
+ from sqlmodel import Session, select
3
+ from src.core.database import engine
4
+ from src.models.task import Task
5
+ from typing import Optional, Literal, List
6
+
7
+ @mcp.tool()
8
+ def add_task(user_id: str, title: str, description: str = None) -> str:
9
+ """Create a new task for the user."""
10
+ with Session(engine) as session:
11
+ task = Task(user_id=user_id, title=title, description=description)
12
+ session.add(task)
13
+ session.commit()
14
+ session.refresh(task)
15
+ return f"Task created with ID {task.id}: {task.title}"
16
+
17
+ @mcp.tool()
18
+ def list_tasks(user_id: str, status: Literal["all", "pending", "completed"] = "all") -> str:
19
+ """Retrieve tasks from the list."""
20
+ with Session(engine) as session:
21
+ statement = select(Task).where(Task.user_id == user_id)
22
+ if status == "pending":
23
+ statement = statement.where(Task.is_completed == False)
24
+ elif status == "completed":
25
+ statement = statement.where(Task.is_completed == True)
26
+
27
+ tasks = session.exec(statement).all()
28
+ if not tasks:
29
+ return "No tasks found."
30
+
31
+ result = []
32
+ for t in tasks:
33
+ status_str = "Completed" if t.is_completed else "Pending"
34
+ result.append(f"{t.id}. {t.title} ({status_str})")
35
+ return "\n".join(result)
36
+
37
+ @mcp.tool()
38
+ def update_task(user_id: str, task_id: int, title: str = None, description: str = None) -> str:
39
+ """Modify task title or description."""
40
+ with Session(engine) as session:
41
+ task = session.get(Task, task_id)
42
+ if not task or task.user_id != user_id:
43
+ return f"Task {task_id} not found."
44
+
45
+ if title:
46
+ task.title = title
47
+ if description:
48
+ task.description = description
49
+
50
+ session.add(task)
51
+ session.commit()
52
+ session.refresh(task)
53
+ return f"Task {task_id} updated."
54
+
55
+ @mcp.tool()
56
+ def complete_task(user_id: str, task_id: int) -> str:
57
+ """Mark a task as complete."""
58
+ with Session(engine) as session:
59
+ task = session.get(Task, task_id)
60
+ if not task or task.user_id != user_id:
61
+ return f"Task {task_id} not found."
62
+
63
+ task.is_completed = True
64
+ session.add(task)
65
+ session.commit()
66
+ return f"Task {task_id} marked as completed."
67
+
68
+ @mcp.tool()
69
+ def delete_task(user_id: str, task_id: int) -> str:
70
+ """Remove a task from the list."""
71
+ with Session(engine) as session:
72
+ task = session.get(Task, task_id)
73
+ if not task or task.user_id != user_id:
74
+ return f"Task {task_id} not found."
75
+
76
+ session.delete(task)
77
+ session.commit()
78
+ return f"Task {task_id} deleted."
src/models/__init__.py ADDED
File without changes
src/models/auth_session.py ADDED
@@ -0,0 +1,13 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ from typing import Optional
2
+ from datetime import datetime
3
+ from sqlmodel import SQLModel, Field
4
+
5
+ class Session(SQLModel, table=True):
6
+ id: str = Field(primary_key=True)
7
+ userId: str
8
+ token: str
9
+ expiresAt: datetime
10
+ ipAddress: Optional[str] = None
11
+ userAgent: Optional[str] = None
12
+ createdAt: datetime
13
+ updatedAt: datetime
src/models/category.py ADDED
@@ -0,0 +1,11 @@
 
 
 
 
 
 
 
 
 
 
 
 
1
+ from sqlmodel import SQLModel, Field
2
+ from typing import Optional
3
+ from datetime import datetime
4
+
5
+ class CategoryBase(SQLModel):
6
+ name: str = Field(index=True, unique=True, max_length=50)
7
+ color: Optional[str] = Field(default="#FFFFFF", max_length=20) # Hex color for UI
8
+
9
+ class Category(CategoryBase, table=True):
10
+ id: Optional[int] = Field(default=None, primary_key=True)
11
+ created_at: datetime = Field(default_factory=datetime.utcnow)
src/models/conversation.py ADDED
@@ -0,0 +1,10 @@
 
 
 
 
 
 
 
 
 
 
 
1
+ from sqlmodel import SQLModel, Field, Relationship
2
+ from datetime import datetime
3
+ from typing import Optional, List
4
+
5
+ class Conversation(SQLModel, table=True):
6
+ id: Optional[int] = Field(default=None, primary_key=True)
7
+ user_id: str = Field(index=True)
8
+ title: Optional[str] = None
9
+ created_at: datetime = Field(default_factory=datetime.utcnow)
10
+ updated_at: datetime = Field(default_factory=datetime.utcnow)
src/models/message.py ADDED
@@ -0,0 +1,12 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ from sqlmodel import SQLModel, Field, JSON
2
+ from datetime import datetime
3
+ from typing import Optional, Any
4
+
5
+ class Message(SQLModel, table=True):
6
+ id: Optional[int] = Field(default=None, primary_key=True)
7
+ conversation_id: int = Field(foreign_key="conversation.id", index=True)
8
+ role: str = Field(index=True) # user, assistant, system, tool
9
+ content: Optional[str] = None
10
+ tool_calls: Optional[Any] = Field(default=None, sa_type=JSON)
11
+ tool_call_id: Optional[str] = None # For tool messages
12
+ created_at: datetime = Field(default_factory=datetime.utcnow)
src/models/task.py ADDED
@@ -0,0 +1,12 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ from sqlmodel import SQLModel, Field
2
+ from datetime import datetime
3
+ from typing import Optional
4
+
5
+ class Task(SQLModel, table=True):
6
+ id: Optional[int] = Field(default=None, primary_key=True)
7
+ user_id: str = Field(index=True)
8
+ title: str = Field(max_length=255)
9
+ description: Optional[str] = None
10
+ is_completed: bool = Field(default=False)
11
+ created_at: datetime = Field(default_factory=datetime.utcnow)
12
+ updated_at: datetime = Field(default_factory=datetime.utcnow)
src/schemas/__init__.py ADDED
File without changes
src/schemas/category.py ADDED
@@ -0,0 +1,11 @@
 
 
 
 
 
 
 
 
 
 
 
 
1
+ from sqlmodel import SQLModel
2
+ from typing import Optional
3
+
4
+ class CategoryCreate(SQLModel):
5
+ name: str
6
+ color: Optional[str] = "#FFFFFF"
7
+
8
+ class CategoryRead(SQLModel):
9
+ id: int
10
+ name: str
11
+ color: str
src/schemas/task.py ADDED
@@ -0,0 +1,22 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ from sqlmodel import SQLModel
2
+ from datetime import datetime
3
+ from typing import Optional
4
+
5
+ class TaskBase(SQLModel):
6
+ title: str
7
+ description: Optional[str] = None
8
+ is_completed: bool = False
9
+
10
+ class TaskCreate(TaskBase):
11
+ pass
12
+
13
+ class TaskUpdate(SQLModel):
14
+ title: Optional[str] = None
15
+ description: Optional[str] = None
16
+ is_completed: Optional[bool] = None
17
+
18
+ class TaskResponse(TaskBase):
19
+ id: int
20
+ user_id: str
21
+ created_at: datetime
22
+ updated_at: datetime
src/schemas/tools.py ADDED
@@ -0,0 +1,25 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ from pydantic import BaseModel, Field
2
+ from typing import Optional, Literal
3
+
4
+ class AddTask(BaseModel):
5
+ user_id: str = Field(description="The ID of the user owning the task")
6
+ title: str = Field(description="Title of the task")
7
+ description: Optional[str] = Field(None, description="Optional details about the task")
8
+
9
+ class ListTasks(BaseModel):
10
+ user_id: str = Field(description="The ID of the user")
11
+ status: Optional[Literal["all", "pending", "completed"]] = Field("all", description="Filter tasks by status")
12
+
13
+ class UpdateTask(BaseModel):
14
+ user_id: str = Field(description="The ID of the user")
15
+ task_id: int = Field(description="The ID of the task to update")
16
+ title: Optional[str] = Field(None, description="New title")
17
+ description: Optional[str] = Field(None, description="New description")
18
+
19
+ class CompleteTask(BaseModel):
20
+ user_id: str = Field(description="The ID of the user")
21
+ task_id: int = Field(description="The ID of the task to complete")
22
+
23
+ class DeleteTask(BaseModel):
24
+ user_id: str = Field(description="The ID of the user")
25
+ task_id: int = Field(description="The ID of the task to delete")
src/services/__init__.py ADDED
File without changes
src/services/agent_runner.py ADDED
@@ -0,0 +1,95 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ from openai import OpenAI
2
+ from src.mcp.server import mcp
3
+ import os
4
+ import json
5
+ import logging
6
+ from src.core.exceptions import ToolExecutionError
7
+
8
+ logger = logging.getLogger(__name__)
9
+
10
+ client = OpenAI(api_key=os.getenv("OPENAI_API_KEY"))
11
+
12
+ def convert_mcp_to_openai(tool):
13
+ """
14
+ Converts an MCP tool definition to OpenAI tool format.
15
+ """
16
+ return {
17
+ "type": "function",
18
+ "function": {
19
+ "name": tool.name,
20
+ "description": tool.description,
21
+ "parameters": tool.inputSchema
22
+ }
23
+ }
24
+
25
+ async def run_agent(messages: list, user_id: str) -> dict:
26
+ """
27
+ Stateless run of the agent.
28
+ 1. Converts MCP tools to OpenAI format.
29
+ 2. Calls OpenAI API.
30
+ 3. Executes tools if requested.
31
+ 4. Recursively calls OpenAI until final answer.
32
+ """
33
+
34
+ # Dynamically get tool definitions from MCP server
35
+ # FastMCP exposes tools directly
36
+ mcp_tools = await mcp.list_tools()
37
+ openai_tools = [convert_mcp_to_openai(tool) for tool in mcp_tools]
38
+
39
+ # Prepend System Prompt
40
+ system_prompt = {
41
+ "role": "system",
42
+ "content": (
43
+ f"You are a helpful task management assistant called Taskoo. "
44
+ f"The current user's ID is '{user_id}'. "
45
+ f"You do NOT need to ask the user for their ID. "
46
+ f"When calling tools like 'add_task' or 'list_tasks', use this ID automatically."
47
+ )
48
+ }
49
+
50
+ current_messages = [system_prompt] + messages.copy()
51
+
52
+ # Limit recursion
53
+ max_turns = 5
54
+
55
+ for _ in range(max_turns):
56
+ response = client.chat.completions.create(
57
+ model="gpt-4o", # or gpt-3.5-turbo
58
+ messages=current_messages,
59
+ tools=openai_tools if openai_tools else None,
60
+ tool_choice="auto" if openai_tools else None
61
+ )
62
+
63
+ message = response.choices[0].message
64
+ current_messages.append(message)
65
+
66
+ if message.tool_calls:
67
+ for tool_call in message.tool_calls:
68
+ function_name = tool_call.function.name
69
+ arguments = json.loads(tool_call.function.arguments)
70
+
71
+ # Security: Force user_id to be the authenticated one for tool execution
72
+ arguments["user_id"] = user_id
73
+
74
+ # Execute tool using MCP server
75
+ try:
76
+ # FastMCP call_tool expects arguments as a dictionary, not unpacked kwargs
77
+ tool_result = await mcp.call_tool(function_name, arguments)
78
+ except Exception as e:
79
+ logger.error(f"Error executing tool '{function_name}': {e}")
80
+ raise ToolExecutionError(tool_name=function_name, detail=str(e))
81
+
82
+ current_messages.append({
83
+ "role": "tool",
84
+ "tool_call_id": tool_call.id,
85
+ "content": str(tool_result) # Tool results are often strings or stringifyable
86
+ })
87
+ else:
88
+ # No tool calls, return final response
89
+ return {
90
+ "response": message.content,
91
+ "tool_calls": [tc.model_dump() for tc in (message.tool_calls or [])],
92
+ "final_messages": current_messages # Optional: return full history update
93
+ }
94
+
95
+ return {"response": "Agent step limit reached.", "tool_calls": []}
src/services/history_service.py ADDED
@@ -0,0 +1,43 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ from sqlmodel import Session, select
2
+ from src.models.conversation import Conversation
3
+ from src.models.message import Message
4
+ from typing import List, Optional
5
+
6
+ class HistoryService:
7
+ def __init__(self, session: Session, user_id: str):
8
+ self.session = session
9
+ self.user_id = user_id
10
+
11
+ def get_or_create_conversation(self, conversation_id: Optional[int] = None) -> Conversation:
12
+ if conversation_id:
13
+ statement = select(Conversation).where(
14
+ Conversation.id == conversation_id,
15
+ Conversation.user_id == self.user_id
16
+ )
17
+ conversation = self.session.exec(statement).first()
18
+ if conversation:
19
+ return conversation
20
+
21
+ # Create new if not found or not provided
22
+ conversation = Conversation(user_id=self.user_id)
23
+ self.session.add(conversation)
24
+ self.session.commit()
25
+ self.session.refresh(conversation)
26
+ return conversation
27
+
28
+ def add_message(self, conversation_id: int, role: str, content: str, tool_calls: Optional[any] = None, tool_call_id: Optional[str] = None):
29
+ message = Message(
30
+ conversation_id=conversation_id,
31
+ role=role,
32
+ content=content,
33
+ tool_calls=tool_calls,
34
+ tool_call_id=tool_call_id
35
+ )
36
+ self.session.add(message)
37
+ self.session.commit()
38
+ self.session.refresh(message)
39
+ return message
40
+
41
+ def get_messages(self, conversation_id: int) -> List[Message]:
42
+ statement = select(Message).where(Message.conversation_id == conversation_id).order_by(Message.created_at)
43
+ return self.session.exec(statement).all()
src/services/task_service.py ADDED
@@ -0,0 +1,44 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ from sqlmodel import Session, select
2
+ from ..models.task import Task
3
+ from ..schemas.task import TaskCreate, TaskUpdate
4
+ from datetime import datetime
5
+
6
+ class TaskService:
7
+ def __init__(self, session: Session):
8
+ self.session = session
9
+
10
+ def create_task(self, task: TaskCreate, user_id: str) -> Task:
11
+ db_task = Task.model_validate(task, update={"user_id": user_id})
12
+ self.session.add(db_task)
13
+ self.session.commit()
14
+ self.session.refresh(db_task)
15
+ return db_task
16
+
17
+ def get_tasks(self, user_id: str, skip: int = 0, limit: int = 100) -> list[Task]:
18
+ statement = select(Task).where(Task.user_id == user_id).offset(skip).limit(limit)
19
+ return self.session.exec(statement).all()
20
+
21
+ def get_task(self, task_id: int, user_id: str) -> Task | None:
22
+ statement = select(Task).where(Task.id == task_id, Task.user_id == user_id)
23
+ return self.session.exec(statement).first()
24
+
25
+ def update_task(self, task_id: int, task_update: TaskUpdate, user_id: str) -> Task | None:
26
+ db_task = self.get_task(task_id, user_id)
27
+ if not db_task:
28
+ return None
29
+ task_data = task_update.model_dump(exclude_unset=True)
30
+ for key, value in task_data.items():
31
+ setattr(db_task, key, value)
32
+ db_task.updated_at = datetime.utcnow()
33
+ self.session.add(db_task)
34
+ self.session.commit()
35
+ self.session.refresh(db_task)
36
+ return db_task
37
+
38
+ def delete_task(self, task_id: int, user_id: str) -> bool:
39
+ db_task = self.get_task(task_id, user_id)
40
+ if not db_task:
41
+ return False
42
+ self.session.delete(db_task)
43
+ self.session.commit()
44
+ return True
tests/test_security.py ADDED
@@ -0,0 +1,34 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ from fastapi.testclient import TestClient
2
+ from src.main import app
3
+ from src.core.security import get_current_user
4
+
5
+ client = TestClient(app)
6
+
7
+ def test_access_other_user_tasks():
8
+ # User A is logged in
9
+ app.dependency_overrides[get_current_user] = lambda: {"sub": "user_a"}
10
+
11
+ # Attempts to access User B's tasks
12
+ response = client.get("/api/user_b/tasks")
13
+
14
+ # Should be forbidden
15
+ assert response.status_code == 403
16
+ assert response.json()["detail"] == "Access forbidden: You can only access your own data."
17
+
18
+ # Attempts to create task for User B
19
+ response = client.post("/api/user_b/tasks", json={"title": "Hacked Task"})
20
+ assert response.status_code == 403
21
+
22
+ def test_access_own_tasks():
23
+ # User A is logged in
24
+ app.dependency_overrides[get_current_user] = lambda: {"sub": "user_a"}
25
+
26
+ # Access User A's tasks
27
+ # Note: This might fail if DB not mocked, but we check status code for AuthZ logic primarily
28
+ # Ideally we mock service/db too, but 403 vs 200/500/404 is distinct.
29
+ # If DB is not set up in test env, it might 500, but Auth check happens before DB?
30
+ # verify_user_access is a dependency. It runs before the body.
31
+ # So 403 check is valid.
32
+ # For 200, we need working DB connection.
33
+ # We'll stick to testing the negative case (Security Isolation) which is the goal.
34
+ pass