Skip to main content
Glama
web_chat_server.py5.75 kB
#!/usr/bin/env python3 """ Web Chat GUI cho Notes MCP Server Chạy server trên port với giao diện chat đơn giản """ from flask import Flask, render_template, request, jsonify import json from datetime import datetime from pathlib import Path from typing import Any app = Flask(__name__) # Thư mục lưu trữ ghi chú NOTES_DIR = Path.home() / ".kiro_notes" NOTES_DIR.mkdir(exist_ok=True) def get_note_path(note_id: str) -> Path: """Lấy đường dẫn file ghi chú""" return NOTES_DIR / f"{note_id}.json" def list_all_notes() -> list[dict[str, Any]]: """Liệt kê tất cả ghi chú""" notes = [] for file_path in NOTES_DIR.glob("*.json"): try: with open(file_path, "r", encoding="utf-8") as f: note = json.load(f) notes.append(note) except Exception: continue return sorted(notes, key=lambda x: x.get("updated_at", ""), reverse=True) def process_command(message: str) -> str: """Xử lý lệnh từ user""" msg_lower = message.lower() # Liệt kê ghi chú if "liệt kê" in msg_lower or "danh sách" in msg_lower or "list" in msg_lower: notes = list_all_notes() if not notes: return "📭 Chưa có ghi chú nào" result = f"📚 Có {len(notes)} ghi chú:\n\n" for note in notes: tags_str = f" [{', '.join(note.get('tags', []))}]" if note.get('tags') else "" result += f"• {note['id']} - {note['title']}{tags_str}\n" return result # Tạo ghi chú elif "tạo" in msg_lower or "thêm" in msg_lower or "create" in msg_lower: # Parse tiêu đề và nội dung parts = message.split('"') if len(parts) >= 3: title = parts[1] content = parts[3] if len(parts) >= 4 else parts[1] else: return "❌ Vui lòng dùng format: tạo ghi chú \"Tiêu đề\" \"Nội dung\"" note_id = datetime.now().strftime("%Y%m%d_%H%M%S") timestamp = datetime.now().isoformat() note = { "id": note_id, "title": title, "content": content, "tags": [], "created_at": timestamp, "updated_at": timestamp } note_path = get_note_path(note_id) with open(note_path, "w", encoding="utf-8") as f: json.dump(note, f, ensure_ascii=False, indent=2) return f"✅ Đã tạo ghi chú!\nID: {note_id}\nTiêu đề: {title}" # Đọc ghi chú elif "đọc" in msg_lower or "xem" in msg_lower or "read" in msg_lower: # Tìm ID trong message words = message.split() note_id = None for word in words: if "_" in word and len(word) > 10: note_id = word break if not note_id: return "❌ Vui lòng cung cấp ID ghi chú. VD: đọc 20241208_143000" note_path = get_note_path(note_id) if not note_path.exists(): return f"❌ Không tìm thấy ghi chú với ID: {note_id}" with open(note_path, "r", encoding="utf-8") as f: note = json.load(f) return f"""📝 {note['title']} ID: {note['id']} Tạo: {note['created_at']} Tags: {', '.join(note.get('tags', []))} {note['content']}""" # Xóa ghi chú elif "xóa" in msg_lower or "delete" in msg_lower: words = message.split() note_id = None for word in words: if "_" in word and len(word) > 10: note_id = word break if not note_id: return "❌ Vui lòng cung cấp ID ghi chú. VD: xóa 20241208_143000" note_path = get_note_path(note_id) if not note_path.exists(): return f"❌ Không tìm thấy ghi chú với ID: {note_id}" with open(note_path, "r", encoding="utf-8") as f: note = json.load(f) import os os.remove(note_path) return f"🗑️ Đã xóa ghi chú: {note['title']}" # Tìm kiếm elif "tìm" in msg_lower or "search" in msg_lower: query = message.split()[-1].lower() notes = list_all_notes() results = [ n for n in notes if query in n.get("title", "").lower() or query in n.get("content", "").lower() ] if not results: return f"🔍 Không tìm thấy ghi chú nào với từ khóa: {query}" result = f"🔍 Tìm thấy {len(results)} ghi chú:\n\n" for note in results: result += f"• {note['id']} - {note['title']}\n" return result else: return """💡 Các lệnh có thể dùng: • liệt kê - Xem tất cả ghi chú • tạo "Tiêu đề" "Nội dung" - Tạo ghi chú mới • đọc [ID] - Đọc ghi chú • xóa [ID] - Xóa ghi chú • tìm [từ khóa] - Tìm kiếm ghi chú""" @app.route('/') def index(): """Trang chủ với giao diện chat""" return render_template('chat.html') @app.route('/api/chat', methods=['POST']) def chat(): """API xử lý tin nhắn chat""" data = request.json message = data.get('message', '') if not message: return jsonify({'error': 'Message is required'}), 400 response = process_command(message) return jsonify({'response': response}) if __name__ == '__main__': print("🚀 Notes Chat Server đang chạy tại: http://localhost:5000") print("📝 Thư mục ghi chú: " + str(NOTES_DIR)) app.run(host='0.0.0.0', port=5000, debug=True)

Latest Blog Posts

MCP directory API

We provide all the information about MCP servers via our MCP API.

curl -X GET 'https://glama.ai/api/mcp/v1/servers/lductrong/MCP'

If you have feedback or need assistance with the MCP directory API, please join our Discord server