סקירה כללית

MCP Chatbot בנוי בארכיטקטורת שכבות (Layered Architecture) המפרידה בין הלוגיקה העסקית, שכבת הנתונים וממשק המשתמש. הארכיטקטורה מאפשרת הרחבה קלה והוספת פונקציות חדשות.

┌─────────────────────────────────────────────────────────────────────────────┐ │ USER INTERFACE │ │ ┌───────────────────────────────────────────────────────────────────────┐ │ │ │ mcp-chatbot.html │ mcp-chatbot-manager.js │ │ │ │ - Welcome Screen │ - MCPChatbotManager class │ │ │ │ - Chat Interface │ - Event handlers │ │ │ │ - Sidebar (History) │ - API calls │ │ │ │ - Settings Modal │ - UI rendering │ │ │ └───────────────────────────────────────────────────────────────────────┘ │ │ │ │ │ ▼ │ ├─────────────────────────────────────────────────────────────────────────────┤ │ API LAYER │ │ ┌───────────────────────────────────────────────────────────────────────┐ │ │ │ api_mcp_chatbot.py (Flask Blueprint) │ │ │ │ ├── /api/mcp-chatbot/conversations (GET, POST) │ │ │ │ ├── /api/mcp-chatbot/conversations/:id (GET, PUT, DELETE) │ │ │ │ ├── /api/mcp-chatbot/conversations/:id/messages (GET, POST) │ │ │ │ ├── /api/mcp-chatbot/chat (POST - Quick chat) │ │ │ │ ├── /api/mcp-chatbot/prompts (CRUD) │ │ │ │ ├── /api/mcp-chatbot/functions (GET) │ │ │ │ ├── /api/mcp-chatbot/knowledge (CRUD) │ │ │ │ └── /api/mcp-chatbot/stats (GET) │ │ │ └───────────────────────────────────────────────────────────────────────┘ │ │ │ │ │ ▼ │ ├─────────────────────────────────────────────────────────────────────────────┤ │ SERVICE LAYER │ │ ┌───────────────────────────────────────────────────────────────────────┐ │ │ │ mcp_chatbot_service.py (MCPChatbotService class) │ │ │ │ ┌─────────────────┬─────────────────┬─────────────────┐ │ │ │ │ │ Intent Detection│ Entity Extraction│ Function Exec │ │ │ │ │ │ _analyze_message│ - Phone numbers │ _execute_func │ │ │ │ │ │ - Keywords │ - Amounts (₪) │ - 15 handlers │ │ │ │ │ │ - Patterns │ - Invoice/Repair │ - Logging │ │ │ │ │ └─────────────────┴─────────────────┴─────────────────┘ │ │ │ │ │ │ │ │ ┌─────────────────────────────────────────────────────┐ │ │ │ │ │ Response Generation │ │ │ │ │ │ _generate_response() - Hebrew formatted output │ │ │ │ │ └─────────────────────────────────────────────────────┘ │ │ │ └───────────────────────────────────────────────────────────────────────┘ │ │ │ │ │ ▼ │ ├─────────────────────────────────────────────────────────────────────────────┤ │ DATA LAYER │ │ ┌───────────────────────────────────────────────────────────────────────┐ │ │ │ models_mcp_chatbot.py (SQLAlchemy Models) │ │ │ │ ├── MCPSystemPrompt - System prompts with module instructions │ │ │ │ ├── MCPConversation - Conversations with context linking │ │ │ │ ├── MCPMessage - Messages with function calling data │ │ │ │ ├── MCPFunction - Function definitions (OpenAI format) │ │ │ │ ├── MCPActionLog - Audit log for all actions │ │ │ │ └── MCPKnowledgeBase - FAQ, policies, procedures │ │ │ └───────────────────────────────────────────────────────────────────────┘ │ │ │ │ │ ▼ │ ├─────────────────────────────────────────────────────────────────────────────┤ │ EXTERNAL MODULES │ │ ┌─────────────┐ ┌─────────────┐ ┌─────────────┐ ┌─────────────┐ │ │ │ Customers │ │ Invoices │ │ Repairs │ │ Inventory │ │ │ │ LabCustomer│ │ Invoice │ │ LabRepair │ │ LabInventory│ │ │ └─────────────┘ └─────────────┘ └─────────────┘ └─────────────┘ │ └─────────────────────────────────────────────────────────────────────────────┘

מבנה קבצים

app/ ├── models_mcp_chatbot.py # 6 Database models + Enums (~600 lines) ├── api_mcp_chatbot.py # API routes (~650 lines) │ ├── services/ │ └── mcp_chatbot_service.py # Service layer (~2,000 lines) ⬆️ v2.0 │ ├── MCPChatbotService # Main service class │ ├── MCPValidator # Input validation class (NEW) │ ├── HEBREW_KEYWORDS # 16 categories, 200+ keywords │ └── log_function_call # Logging decorator │ ├── logs/ # Logging directory (NEW) │ ├── mcp_chatbot.log # General logs │ └── mcp_chatbot_errors.log # Error-only logs │ ├── templates/ │ └── mcp-chatbot.html # HTML template (~400 lines) │ └── static/ ├── js/modules/ │ └── mcp-chatbot-manager.js # JS Manager (~750 lines) │ ├── css/modules/ │ └── mcp-chatbot.css # Styles (~420 lines) │ └── docs/mcp-chatbot/ ├── index.html # Documentation ├── architecture.html ├── api-reference.html └── ...

שכבות המערכת

שכבת ממשק משתמש (UI Layer)

אחראית על הצגת הממשק והאינטראקציה עם המשתמש.

  • mcp-chatbot.html - תבנית HTML עם Bootstrap 5 RTL
  • mcp-chatbot-manager.js - מחלקת JavaScript לניהול הממשק
  • mcp-chatbot.css - עיצוב מותאם אישית
רכיבי UI:
  • Welcome Screen - מסך פתיחה עם פעולות מהירות
  • Chat Interface - ממשק שיחה עם בועות הודעות
  • Sidebar - היסטוריית שיחות
  • Settings Modal - הגדרות פרומפטים וידע

שכבת API

Flask Blueprint עם endpoints RESTful.

# api_mcp_chatbot.py

mcp_chatbot_bp = Blueprint('mcp_chatbot', __name__,
                           url_prefix='/api/mcp-chatbot')

@mcp_chatbot_bp.route('/conversations', methods=['GET', 'POST'])
@mcp_chatbot_bp.route('/conversations/<int:id>', methods=['GET', 'PUT', 'DELETE'])
@mcp_chatbot_bp.route('/conversations/<int:id>/messages', methods=['GET', 'POST'])
@mcp_chatbot_bp.route('/chat', methods=['POST'])  # Quick chat
@mcp_chatbot_bp.route('/prompts', methods=['GET', 'POST'])
@mcp_chatbot_bp.route('/functions/available', methods=['GET'])
@mcp_chatbot_bp.route('/knowledge', methods=['GET', 'POST'])
@mcp_chatbot_bp.route('/stats', methods=['GET'])

שכבת שירות (Service Layer) - v2.0

מכילה את הלוגיקה העסקית העיקרית עם שדרוגים משמעותיים.

תפקידים:
  • Intent Detection - זיהוי כוונות עם 16 קטגוריות ו-200+ מילות מפתח
  • Entity Extraction - חילוץ ישויות (טלפון, סכום, מספרי מסמכים)
  • Input Validation - MCPValidator לאימות קלט (טלפון ישראלי, סכומים)
  • Context Management - ניהול הקשר השיחה
  • Function Execution - ביצוע פעולות על המודולים
  • Response Generation - יצירת תשובות מעוצבות בעברית
  • Token Tracking - מעקב טוקנים נכנסים/יוצאים
  • Professional Logging - לוגים מקצועיים עם timestamps
מחלקות חדשות:
# MCPValidator - Input validation
class MCPValidator:
    @staticmethod
    def validate_phone(phone: str) -> Tuple[bool, str, str]
    @staticmethod
    def validate_invoice_number(inv_num: str) -> Tuple[bool, str, str]
    @staticmethod
    def validate_amount(amount: str) -> Tuple[bool, float, str]
    @staticmethod
    def sanitize_input(text: str) -> str  # XSS protection

# HEBREW_KEYWORDS - 16 categories
HEBREW_KEYWORDS = {
    'customer_lookup': [...],    # 16 keywords
    'customer_balance': [...],   # 21 keywords
    'invoice_status': [...],     # 13 keywords
    'repair_status': [...],      # 18 keywords
    'greeting': [...],           # 13 keywords (NEW)
    'thanks': [...],             # 11 keywords (NEW)
    # ... 10 more categories
}

שכבת נתונים (Data Layer)

מודלי SQLAlchemy לאחסון נתונים.

  • MCPSystemPrompt - פרומפטים עם הנחיות מודולריות
  • MCPConversation - שיחות עם קישור להקשר
  • MCPMessage - הודעות עם נתוני Function Calling
  • MCPFunction - הגדרות פונקציות
  • MCPActionLog - לוג פעולות
  • MCPKnowledgeBase - בסיס ידע

זרימת הודעה

תהליך עיבוד הודעת משתמש מקצה לקצה:

User Message: "מה היתרה של 050-1234567?" │ ▼ ┌───────────────────────────────┐ │ 1. API: POST /messages │ │ - Validate input │ │ - Get conversation │ └───────────────────────────────┘ │ ▼ ┌───────────────────────────────┐ │ 2. Intent Detection │ │ Keywords: יתרה, חוב │ │ Result: CUSTOMER_BALANCE │ └───────────────────────────────┘ │ ▼ ┌───────────────────────────────┐ │ 3. Entity Extraction │ │ Phone: 0501234567 │ │ Type: phone │ └───────────────────────────────┘ │ ▼ ┌───────────────────────────────┐ │ 4. Determine Functions │ │ Function: get_customer_ │ │ balance │ │ Args: {phone: "050..."} │ └───────────────────────────────┘ │ ▼ ┌───────────────────────────────┐ │ 5. Execute Function │ │ - Query LabCustomer │ │ - Query Invoices │ │ - Calculate balance │ └───────────────────────────────┘ │ ▼ ┌───────────────────────────────┐ │ 6. Generate Response │ │ Format Hebrew response │ │ Add emojis, formatting │ └───────────────────────────────┘ │ ▼ Response: "**יתרת הלקוח דוד כהן:** - יתרה: ₪1,234.00 - חשבוניות לא שולמו: 2 - סה״כ לתשלום: ₪1,234.00"

Design Patterns

Service Pattern

הלוגיקה העסקית מרוכזת במחלקת Service אחת.

class MCPChatbotService:
    def create_conversation(...)
    def process_message(...)
    def _analyze_message(...)
    def _execute_function(...)
    def _generate_response(...)
Strategy Pattern

פונקציות נבחרות דינמית לפי Intent.

handlers = {
    'get_customer_by_phone': self._fn_get_customer,
    'get_invoice_status': self._fn_get_invoice,
    'get_repair_status': self._fn_get_repair,
    ...
}
handler = handlers.get(func_name)
result = handler(**args)
Context Object

שיחה שומרת הקשר לישויות.

class MCPConversation:
    customer_id = ...  # Linked customer
    invoice_id = ...   # Linked invoice
    repair_id = ...    # Linked repair
    context_memory = {...}  # Extracted facts
    extracted_entities = [...]
Audit Log

כל פעולה נרשמת בלוג.

class MCPActionLog:
    action_type = ...    # query, create, update
    function_name = ...  # Function executed
    target_module = ...  # customer, invoice
    request_data = {...}
    response_data = {...}
    status = ...         # success, failed
התחלה מהירה זיהוי כוונות