File size: 2,121 Bytes
8f7f7d7
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
# server.py

import sqlite3
from fastmcp import FastMCP

# Initialize MCP server
mcp = FastMCP(
    name="SQLiteMCPServer",
    port=8000,
    transport="streamable-http",
    instructions="Tools: add_data(query) and read_data(query)."
)

# --- Database Setup ---
DB_PATH = "demo.db"
_conn = sqlite3.connect(DB_PATH, check_same_thread=False)
_cursor = _conn.cursor()

print("🔧 Connecting to SQLite DB:", DB_PATH)

# Create tables
print("🛠️ Ensuring table 'people' exists…")
_cursor.execute("""
    CREATE TABLE IF NOT EXISTS people (
        id INTEGER PRIMARY KEY AUTOINCREMENT,
        name TEXT NOT NULL,
        age INTEGER NOT NULL,
        profession TEXT NOT NULL
    )
""")

print("🛠️ Ensuring table 'interactions' exists…")
_cursor.execute("""
    CREATE TABLE IF NOT EXISTS interactions (
        id INTEGER PRIMARY KEY AUTOINCREMENT,
        prompt TEXT NOT NULL,
        response TEXT NOT NULL,
        time_taken_sec REAL NOT NULL,
        timestamp DATETIME DEFAULT CURRENT_TIMESTAMP
    )
""")

_conn.commit()
print("✅ Tables are ready.")


# --- Tool: Add Record ---
@mcp.tool(name="add_data", description="Insert a record via SQL")
def add_data(query: str) -> bool:
    print(f"📥 [add_data] Executing query:\n{query}")
    try:
        _cursor.execute(query)
        _conn.commit()
        print("✅ Inserted successfully.")
        return True
    except Exception as e:
        print(f"❌ Insert error: {e}")
        return False


# --- Tool: Read Records ---
@mcp.tool(name="read_data", description="Query records via SQL")
def read_data(query: str = "SELECT * FROM people") -> list:
    print(f"📤 [read_data] Executing query:\n{query}")
    try:
        _cursor.execute(query)
        results = _cursor.fetchall()
        print(f"✅ Retrieved {len(results)} rows.")
        return results
    except Exception as e:
        print(f"❌ Read error: {e}")
        return []


# --- Run the Server ---
if __name__ == "__main__":
    print("🚀 Starting SQLite MCP server on http://127.0.0.1:8000 …")
    mcp.run(transport="streamable-http", host="127.0.0.1", port=8000)