-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathserver.py
More file actions
314 lines (273 loc) · 15.1 KB
/
server.py
File metadata and controls
314 lines (273 loc) · 15.1 KB
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
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
"""
SQL Builder AI MCP Server
SQL query building and analysis tools powered by MEOK AI Labs.
"""
import sys, os
sys.path.insert(0, os.path.expanduser('~/clawd/meok-labs-engine/shared'))
from auth_middleware import check_access
import re
import time
from collections import defaultdict
from mcp.server.fastmcp import FastMCP
mcp = FastMCP("sql-builder-ai", instructions="MEOK AI Labs MCP Server")
_call_counts: dict[str, list[float]] = defaultdict(list)
FREE_TIER_LIMIT = 50
WINDOW = 86400
def _check_rate_limit(tool_name: str) -> None:
now = time.time()
_call_counts[tool_name] = [t for t in _call_counts[tool_name] if now - t < WINDOW]
if len(_call_counts[tool_name]) >= FREE_TIER_LIMIT:
raise ValueError(f"Rate limit exceeded for {tool_name}. Free tier: {FREE_TIER_LIMIT}/day. Upgrade at https://meok.ai/pricing")
_call_counts[tool_name].append(now)
def _quote_id(name: str) -> str:
return f'"{name}"' if not name.isidentifier() or name.upper() in SQL_KEYWORDS else name
SQL_KEYWORDS = {"SELECT", "FROM", "WHERE", "INSERT", "UPDATE", "DELETE", "JOIN", "ON",
"ORDER", "GROUP", "BY", "HAVING", "LIMIT", "OFFSET", "TABLE", "INDEX",
"CREATE", "DROP", "ALTER", "AND", "OR", "NOT", "IN", "BETWEEN", "LIKE", "AS"}
@mcp.tool()
def build_select(
table: str, columns: list[str] | None = None, where: dict | None = None,
order_by: str = "", limit: int = 0, joins: list[dict] | None = None
, api_key: str = "") -> dict:
"""Build a SELECT SQL query from structured parameters.
Args:
table: Main table name
columns: List of column names (default: *)
where: Dict of column:value conditions (AND-joined)
order_by: Column to order by (prefix with - for DESC)
limit: LIMIT clause (0 = no limit)
joins: List of dicts with keys: table, on, type (LEFT/INNER/RIGHT)
Behavior:
This tool generates structured output without modifying external systems.
Output is deterministic for identical inputs. No side effects.
Free tier: 10/day rate limit. Pro tier: unlimited.
No authentication required for basic usage.
When to use:
Use this tool when you need structured analysis or classification
of inputs against established frameworks or standards.
When NOT to use:
Not suitable for real-time production decision-making without
human review of results.
Behavioral Transparency:
- Side Effects: This tool is read-only and produces no side effects. It does not modify
any external state, databases, or files. All output is computed in-memory and returned
directly to the caller.
- Authentication: No authentication required for basic usage. Pro/Enterprise tiers
require a valid MEOK API key passed via the MEOK_API_KEY environment variable.
- Rate Limits: Free tier: 10 calls/day. Pro tier: unlimited. Rate limit headers are
included in responses (X-RateLimit-Remaining, X-RateLimit-Reset).
- Error Handling: Returns structured error objects with 'error' key on failure.
Never raises unhandled exceptions. Invalid inputs return descriptive validation errors.
- Idempotency: Fully idempotent — calling with the same inputs always produces the
same output. Safe to retry on timeout or transient failure.
- Data Privacy: No input data is stored, logged, or transmitted to external services.
All processing happens locally within the MCP server process.
"""
allowed, msg, tier = check_access(api_key)
if not allowed:
return {"error": msg, "upgrade_url": "https://meok.ai/pricing"}
_check_rate_limit("build_select")
cols = ", ".join(columns) if columns else "*"
sql = f"SELECT {cols}\nFROM {table}"
params = []
if joins:
for j in joins:
jtype = j.get("type", "LEFT").upper()
sql += f"\n{jtype} JOIN {j['table']} ON {j['on']}"
if where:
conditions = []
for col, val in where.items():
if val is None:
conditions.append(f"{col} IS NULL")
elif isinstance(val, list):
placeholders = ", ".join(["%s"] * len(val))
conditions.append(f"{col} IN ({placeholders})")
params.extend(val)
else:
conditions.append(f"{col} = %s")
params.append(val)
if conditions:
sql += "\nWHERE " + " AND ".join(conditions)
if order_by:
direction = "DESC" if order_by.startswith("-") else "ASC"
col = order_by.lstrip("-")
sql += f"\nORDER BY {col} {direction}"
if limit > 0:
sql += f"\nLIMIT {limit}"
return {"sql": sql + ";", "params": params, "type": "SELECT"}
@mcp.tool()
def build_insert(table: str, rows: list[dict], on_conflict: str = "", api_key: str = "") -> dict:
"""Build an INSERT SQL query from a list of row dicts.
Args:
table: Target table name
rows: List of dicts (each dict is a row, keys are column names)
on_conflict: Conflict resolution: '' (none), 'ignore', 'update'
Behavior:
This tool generates structured output without modifying external systems.
Output is deterministic for identical inputs. No side effects.
Free tier: 10/day rate limit. Pro tier: unlimited.
No authentication required for basic usage.
When to use:
Use this tool when you need structured analysis or classification
of inputs against established frameworks or standards.
When NOT to use:
Not suitable for real-time production decision-making without
human review of results.
Behavioral Transparency:
- Side Effects: This tool is read-only and produces no side effects. It does not modify
any external state, databases, or files. All output is computed in-memory and returned
directly to the caller.
- Authentication: No authentication required for basic usage. Pro/Enterprise tiers
require a valid MEOK API key passed via the MEOK_API_KEY environment variable.
- Rate Limits: Free tier: 10 calls/day. Pro tier: unlimited. Rate limit headers are
included in responses (X-RateLimit-Remaining, X-RateLimit-Reset).
- Error Handling: Returns structured error objects with 'error' key on failure.
Never raises unhandled exceptions. Invalid inputs return descriptive validation errors.
- Idempotency: Fully idempotent — calling with the same inputs always produces the
same output. Safe to retry on timeout or transient failure.
- Data Privacy: No input data is stored, logged, or transmitted to external services.
All processing happens locally within the MCP server process.
"""
allowed, msg, tier = check_access(api_key)
if not allowed:
return {"error": msg, "upgrade_url": "https://meok.ai/pricing"}
_check_rate_limit("build_insert")
if not rows:
return {"error": "No rows provided"}
columns = list(rows[0].keys())
placeholders = ", ".join(["%s"] * len(columns))
cols_str = ", ".join(columns)
sql = f"INSERT INTO {table} ({cols_str})\nVALUES"
all_params = []
value_rows = []
for row in rows:
vals = [row.get(c) for c in columns]
value_rows.append(f"({placeholders})")
all_params.extend(vals)
sql += "\n" + ",\n".join(value_rows)
if on_conflict == "ignore":
sql += "\nON CONFLICT DO NOTHING"
elif on_conflict == "update":
updates = ", ".join(f"{c} = EXCLUDED.{c}" for c in columns)
sql += f"\nON CONFLICT DO UPDATE SET {updates}"
return {"sql": sql + ";", "params": all_params, "type": "INSERT", "row_count": len(rows)}
@mcp.tool()
def explain_query(sql: str, api_key: str = "") -> dict:
"""Analyze and explain a SQL query's structure and components.
Args:
sql: SQL query string to analyze
Behavior:
This tool is read-only and stateless — it produces analysis output
without modifying any external systems, databases, or files.
Safe to call repeatedly with identical inputs (idempotent).
Free tier: 10/day rate limit. Pro tier: unlimited.
No authentication required for basic usage.
When to use:
Use this tool when you need structured analysis or classification
of inputs against established frameworks or standards.
When NOT to use:
Not suitable for real-time production decision-making without
human review of results.
Behavioral Transparency:
- Side Effects: This tool is read-only and produces no side effects. It does not modify
any external state, databases, or files. All output is computed in-memory and returned
directly to the caller.
- Authentication: No authentication required for basic usage. Pro/Enterprise tiers
require a valid MEOK API key passed via the MEOK_API_KEY environment variable.
- Rate Limits: Free tier: 10 calls/day. Pro tier: unlimited. Rate limit headers are
included in responses (X-RateLimit-Remaining, X-RateLimit-Reset).
- Error Handling: Returns structured error objects with 'error' key on failure.
Never raises unhandled exceptions. Invalid inputs return descriptive validation errors.
- Idempotency: Fully idempotent — calling with the same inputs always produces the
same output. Safe to retry on timeout or transient failure.
- Data Privacy: No input data is stored, logged, or transmitted to external services.
All processing happens locally within the MCP server process.
"""
allowed, msg, tier = check_access(api_key)
if not allowed:
return {"error": msg, "upgrade_url": "https://meok.ai/pricing"}
_check_rate_limit("explain_query")
sql_upper = sql.upper().strip()
query_type = "UNKNOWN"
for t in ("SELECT", "INSERT", "UPDATE", "DELETE", "CREATE", "DROP", "ALTER"):
if sql_upper.startswith(t):
query_type = t
break
components = {"type": query_type}
tables = re.findall(r'\bFROM\s+(\w+)', sql, re.IGNORECASE)
tables += re.findall(r'\bJOIN\s+(\w+)', sql, re.IGNORECASE)
tables += re.findall(r'\bINTO\s+(\w+)', sql, re.IGNORECASE)
tables += re.findall(r'\bUPDATE\s+(\w+)', sql, re.IGNORECASE)
components["tables"] = list(set(tables))
if re.search(r'\bWHERE\b', sql, re.IGNORECASE):
where = re.search(r'\bWHERE\b(.+?)(?:\bORDER\b|\bGROUP\b|\bLIMIT\b|\bHAVING\b|;|$)', sql, re.IGNORECASE | re.DOTALL)
components["where_clause"] = where.group(1).strip() if where else ""
joins = re.findall(r'((?:LEFT|RIGHT|INNER|OUTER|CROSS|FULL)\s+)?JOIN\s+(\w+)\s+ON\s+([^)]+?)(?=\s+(?:LEFT|RIGHT|INNER|WHERE|ORDER|GROUP|LIMIT|$))', sql, re.IGNORECASE)
if joins:
components["joins"] = [{"type": j[0].strip() or "INNER", "table": j[1], "condition": j[2].strip()} for j in joins]
has_subquery = "(" in sql and "SELECT" in sql_upper.split("(", 1)[-1] if "(" in sql else False
components["has_subquery"] = has_subquery
components["complexity"] = "simple" if len(tables) <= 1 and not has_subquery else "moderate" if len(tables) <= 3 else "complex"
return components
@mcp.tool()
def optimize_query_hints(sql: str, api_key: str = "") -> dict:
"""Suggest optimizations for a SQL query.
Args:
sql: SQL query string to analyze for optimizations
Behavior:
This tool is read-only and stateless — it produces analysis output
without modifying any external systems, databases, or files.
Safe to call repeatedly with identical inputs (idempotent).
Free tier: 10/day rate limit. Pro tier: unlimited.
No authentication required for basic usage.
When to use:
Use this tool when you need structured analysis or classification
of inputs against established frameworks or standards.
When NOT to use:
Not suitable for real-time production decision-making without
human review of results.
Behavioral Transparency:
- Side Effects: This tool is read-only and produces no side effects. It does not modify
any external state, databases, or files. All output is computed in-memory and returned
directly to the caller.
- Authentication: No authentication required for basic usage. Pro/Enterprise tiers
require a valid MEOK API key passed via the MEOK_API_KEY environment variable.
- Rate Limits: Free tier: 10 calls/day. Pro tier: unlimited. Rate limit headers are
included in responses (X-RateLimit-Remaining, X-RateLimit-Reset).
- Error Handling: Returns structured error objects with 'error' key on failure.
Never raises unhandled exceptions. Invalid inputs return descriptive validation errors.
- Idempotency: Fully idempotent — calling with the same inputs always produces the
same output. Safe to retry on timeout or transient failure.
- Data Privacy: No input data is stored, logged, or transmitted to external services.
All processing happens locally within the MCP server process.
"""
allowed, msg, tier = check_access(api_key)
if not allowed:
return {"error": msg, "upgrade_url": "https://meok.ai/pricing"}
_check_rate_limit("optimize_query_hints")
hints = []
sql_upper = sql.upper()
if "SELECT *" in sql_upper:
hints.append({"hint": "Avoid SELECT * - specify only needed columns", "severity": "warning", "category": "performance"})
if "WHERE" not in sql_upper and "SELECT" in sql_upper:
hints.append({"hint": "No WHERE clause - may scan entire table", "severity": "warning", "category": "performance"})
if re.search(r'WHERE.*\bLIKE\s+["\']%', sql, re.IGNORECASE):
hints.append({"hint": "Leading wildcard in LIKE prevents index usage", "severity": "warning", "category": "index"})
if re.search(r'WHERE.*\bOR\b', sql, re.IGNORECASE):
hints.append({"hint": "OR conditions may prevent index usage - consider UNION", "severity": "info", "category": "index"})
if "DISTINCT" in sql_upper:
hints.append({"hint": "DISTINCT can be expensive - ensure it's necessary", "severity": "info", "category": "performance"})
if "ORDER BY" in sql_upper and "LIMIT" not in sql_upper:
hints.append({"hint": "ORDER BY without LIMIT sorts all results", "severity": "info", "category": "performance"})
if sql_upper.count("SELECT") > 1:
hints.append({"hint": "Subquery detected - consider using JOINs or CTEs instead", "severity": "info", "category": "readability"})
if re.search(r'WHERE.*(?:FUNCTION|UPPER|LOWER|CAST|CONVERT)\s*\(', sql, re.IGNORECASE):
hints.append({"hint": "Function in WHERE clause prevents index usage", "severity": "warning", "category": "index"})
tables = re.findall(r'\bFROM\s+(\w+)', sql, re.IGNORECASE) + re.findall(r'\bJOIN\s+(\w+)', sql, re.IGNORECASE)
idx_suggestions = []
for col_match in re.finditer(r'WHERE\s+(\w+)\s*=', sql, re.IGNORECASE):
idx_suggestions.append(f"Consider index on {col_match.group(1)}")
return {"hints": hints, "hint_count": len(hints), "index_suggestions": idx_suggestions,
"tables_referenced": list(set(tables))}
if __name__ == "__main__":
mcp.run()