-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathserver.py
More file actions
435 lines (374 loc) · 22.1 KB
/
server.py
File metadata and controls
435 lines (374 loc) · 22.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
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
#!/usr/bin/env python3
"""
Generate realistic fake test data for development and testing. — MEOK AI Labs."""
import sys, os
from auth_middleware import check_access
import json, random, string, hashlib
from datetime import datetime, timezone, timedelta
from collections import defaultdict
from mcp.server.fastmcp import FastMCP
FREE_DAILY_LIMIT = 30
_usage = defaultdict(list)
def _rl(c="anon"):
now = datetime.now(timezone.utc)
_usage[c] = [t for t in _usage[c] if (now-t).total_seconds() < 86400]
if len(_usage[c]) >= FREE_DAILY_LIMIT: return json.dumps({"error": "Limit {0}/day. Upgrade: meok.ai".format(FREE_DAILY_LIMIT)})
_usage[c].append(now); return None
mcp = FastMCP("faker-ai", instructions="MEOK AI Labs — Generate realistic fake test data for development and testing.")
FIRST_NAMES = {
"en": ["James", "Emma", "Oliver", "Sophie", "William", "Charlotte", "Harry", "Amelia", "Thomas", "Isabella",
"George", "Mia", "Alexander", "Ella", "Daniel", "Grace", "Matthew", "Chloe", "Samuel", "Lily"],
"de": ["Lukas", "Anna", "Felix", "Marie", "Paul", "Sophie", "Leon", "Emilia", "Maximilian", "Hannah"],
"fr": ["Lucas", "Emma", "Louis", "Jade", "Gabriel", "Louise", "Raphael", "Alice", "Arthur", "Chloe"],
"es": ["Hugo", "Lucia", "Martin", "Sofia", "Carlos", "Maria", "Pablo", "Valeria", "Daniel", "Carmen"],
}
LAST_NAMES = {
"en": ["Smith", "Johnson", "Williams", "Brown", "Jones", "Davis", "Miller", "Wilson", "Moore", "Taylor",
"Anderson", "Thomas", "Jackson", "White", "Harris", "Martin", "Thompson", "Garcia", "Robinson", "Clark"],
"de": ["Mueller", "Schmidt", "Schneider", "Fischer", "Weber", "Meyer", "Wagner", "Becker", "Schulz", "Hoffmann"],
"fr": ["Martin", "Bernard", "Dubois", "Thomas", "Robert", "Petit", "Richard", "Durand", "Leroy", "Moreau"],
"es": ["Garcia", "Rodriguez", "Martinez", "Lopez", "Gonzalez", "Hernandez", "Perez", "Sanchez", "Ramirez", "Torres"],
}
STREETS = ["High Street", "Main Street", "Oak Avenue", "Park Lane", "Church Road", "Mill Lane",
"Station Road", "Victoria Street", "Queen Street", "King Street", "Elm Drive", "Cedar Court"]
CITIES = {"en": ["London", "Manchester", "Birmingham", "Leeds", "Bristol", "Edinburgh", "Glasgow", "Liverpool"],
"us": ["New York", "Los Angeles", "Chicago", "Houston", "Phoenix", "Philadelphia", "San Antonio"],
"de": ["Berlin", "Munich", "Hamburg", "Frankfurt", "Cologne", "Stuttgart"],
"fr": ["Paris", "Lyon", "Marseille", "Toulouse", "Nice", "Nantes"]}
DOMAINS = ["example.com", "test.org", "sample.net", "demo.io", "fakeco.com", "testmail.dev"]
INDUSTRIES = ["Technology", "Healthcare", "Finance", "Education", "Retail", "Manufacturing",
"Consulting", "Energy", "Media", "Transportation", "Real Estate", "Legal"]
COMPANY_SUFFIXES = ["Ltd", "Inc", "Corp", "Group", "Solutions", "Technologies", "Partners", "Global", "Labs"]
def _random_date(start_year: int = 1960, end_year: int = 2005) -> str:
start = datetime(start_year, 1, 1)
end = datetime(end_year, 12, 31)
delta = (end - start).days
rand_date = start + timedelta(days=random.randint(0, delta))
return rand_date.strftime("%Y-%m-%d")
def _luhn_checksum(partial: str) -> str:
digits = [int(d) for d in partial]
odd_sum = sum(digits[-1::-2])
even_sum = sum(sum(divmod(2 * d, 10)) for d in digits[-2::-2])
check = (10 - (odd_sum + even_sum) % 10) % 10
return partial + str(check)
@mcp.tool()
def generate_fake_data(data_type: str = "person", count: int = 1, locale: str = "en",
api_key: str = "") -> str:
"""Generate fake data of a specified type (person, company, address, email, phone). Returns 1-50 records.
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.
Args:
data_type (str): The data type to analyze or process.
count (int): The count to analyze or process.
locale (str): The locale to analyze or process.
api_key (str): The api key to analyze or process.
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://councilof.ai"}
if err := _rl(): return err
count = max(1, min(count, 50))
results = []
for _ in range(count):
if data_type == "person":
first = random.choice(FIRST_NAMES.get(locale, FIRST_NAMES["en"]))
last = random.choice(LAST_NAMES.get(locale, LAST_NAMES["en"]))
results.append({"name": f"{first} {last}", "email": f"{first.lower()}.{last.lower()}@{random.choice(DOMAINS)}",
"phone": f"+44 {''.join(random.choices(string.digits, k=10))}",
"dob": _random_date(), "gender": random.choice(["male", "female"])})
elif data_type == "email":
first = random.choice(FIRST_NAMES.get(locale, FIRST_NAMES["en"])).lower()
last = random.choice(LAST_NAMES.get(locale, LAST_NAMES["en"])).lower()
results.append({"email": f"{first}.{last}{random.randint(1,99)}@{random.choice(DOMAINS)}"})
elif data_type == "phone":
code = random.choice(["+44", "+1", "+49", "+33", "+34"])
results.append({"phone": f"{code} {''.join(random.choices(string.digits, k=10))}"})
elif data_type == "address":
city_pool = CITIES.get(locale, CITIES["en"])
results.append({"street": f"{random.randint(1,200)} {random.choice(STREETS)}",
"city": random.choice(city_pool), "postcode": "".join(random.choices(string.ascii_uppercase, k=2)) + str(random.randint(1,20)) + " " + str(random.randint(1,9)) + "".join(random.choices(string.ascii_uppercase, k=2))})
else:
results.append({"type": data_type, "value": "".join(random.choices(string.ascii_letters + string.digits, k=16))})
return {"data_type": data_type, "locale": locale, "count": len(results), "data": results,
"timestamp": datetime.now(timezone.utc).isoformat()}
@mcp.tool()
def generate_profile(locale: str = "en", include_avatar: bool = False, api_key: str = "") -> str:
"""Generate a complete fake user profile with name, contact, address, employment, and bio.
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.
Args:
locale (str): The locale to analyze or process.
include_avatar (bool): The include avatar to analyze or process.
api_key (str): The api key to analyze or process.
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://councilof.ai"}
if err := _rl(): return err
first = random.choice(FIRST_NAMES.get(locale, FIRST_NAMES["en"]))
last = random.choice(LAST_NAMES.get(locale, LAST_NAMES["en"]))
city_pool = CITIES.get(locale, CITIES["en"])
uid = hashlib.md5(f"{first}{last}{random.random()}".encode()).hexdigest()[:8]
profile = {
"uid": uid,
"name": {"first": first, "last": last, "full": f"{first} {last}"},
"email": f"{first.lower()}.{last.lower()}@{random.choice(DOMAINS)}",
"phone": f"+44 {''.join(random.choices(string.digits, k=10))}",
"dob": _random_date(),
"gender": random.choice(["male", "female"]),
"address": {"street": f"{random.randint(1,200)} {random.choice(STREETS)}",
"city": random.choice(city_pool), "country": locale.upper()},
"employment": {"company": f"{random.choice(LAST_NAMES['en'])} {random.choice(COMPANY_SUFFIXES)}",
"title": random.choice(["Engineer", "Manager", "Analyst", "Designer", "Developer", "Director"]),
"industry": random.choice(INDUSTRIES)},
"bio": f"{first} is a professional based in {random.choice(city_pool)}.",
}
if include_avatar:
profile["avatar_url"] = f"https://api.dicebear.com/7.x/personas/svg?seed={uid}"
profile["timestamp"] = datetime.now(timezone.utc).isoformat()
return profile
@mcp.tool()
def generate_address(locale: str = "en", count: int = 1, api_key: str = "") -> str:
"""Generate realistic fake addresses with street, city, postcode, and country.
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.
Args:
locale (str): The locale to analyze or process.
count (int): The count to analyze or process.
api_key (str): The api key to analyze or process.
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://councilof.ai"}
if err := _rl(): return err
count = max(1, min(count, 50))
city_pool = CITIES.get(locale, CITIES["en"])
country_map = {"en": "United Kingdom", "us": "United States", "de": "Germany", "fr": "France", "es": "Spain"}
addresses = []
for _ in range(count):
addresses.append({
"street": f"{random.randint(1, 300)} {random.choice(STREETS)}",
"city": random.choice(city_pool),
"postcode": "".join(random.choices(string.ascii_uppercase, k=2)) + str(random.randint(1, 20)) + " " + str(random.randint(1, 9)) + "".join(random.choices(string.ascii_uppercase, k=2)),
"country": country_map.get(locale, "Unknown"),
"latitude": round(random.uniform(49.0, 58.0), 6),
"longitude": round(random.uniform(-6.0, 2.0), 6),
})
return {"locale": locale, "count": len(addresses), "addresses": addresses,
"timestamp": datetime.now(timezone.utc).isoformat()}
@mcp.tool()
def generate_company(locale: str = "en", api_key: str = "") -> str:
"""Generate a fake company with name, industry, address, registration, and financial details.
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.
Args:
locale (str): The locale to analyze or process.
api_key (str): The api key to analyze or process.
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://councilof.ai"}
if err := _rl(): return err
name = f"{random.choice(LAST_NAMES.get(locale, LAST_NAMES['en']))} {random.choice(COMPANY_SUFFIXES)}"
city_pool = CITIES.get(locale, CITIES["en"])
reg_number = "".join(random.choices(string.digits, k=8))
employees = random.choice([5, 10, 25, 50, 100, 250, 500, 1000, 5000])
return {
"name": name,
"registration_number": reg_number,
"industry": random.choice(INDUSTRIES),
"founded": random.randint(1970, 2024),
"employees": employees,
"revenue_estimate": f"${employees * random.randint(50, 200)}k",
"address": {"street": f"{random.randint(1, 100)} {random.choice(STREETS)}",
"city": random.choice(city_pool)},
"website": f"https://www.{name.lower().replace(' ', '')}.com",
"phone": f"+44 {''.join(random.choices(string.digits, k=10))}",
"email": f"info@{name.lower().replace(' ', '')}.com",
"vat_number": f"GB{''.join(random.choices(string.digits, k=9))}",
"timestamp": datetime.now(timezone.utc).isoformat(),
}
@mcp.tool()
def generate_dataset(rows: int = 10, columns: str = "name,email,age", locale: str = "en",
api_key: str = "") -> str:
"""Generate a tabular fake dataset with specified columns. Supports: name, email, age, phone, city, company, date, amount.
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.
Args:
rows (int): The rows to analyze or process.
columns (str): The columns to analyze or process.
email: The email to analyze or process.
age": The age" to analyze or process.
locale (str): The locale to analyze or process.
api_key (str): The api key to analyze or process.
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://councilof.ai"}
if err := _rl(): return err
rows = max(1, min(rows, 100))
cols = [c.strip().lower() for c in columns.split(",") if c.strip()]
city_pool = CITIES.get(locale, CITIES["en"])
data = []
for _ in range(rows):
row = {}
for col in cols:
if col == "name":
first = random.choice(FIRST_NAMES.get(locale, FIRST_NAMES["en"]))
last = random.choice(LAST_NAMES.get(locale, LAST_NAMES["en"]))
row["name"] = f"{first} {last}"
elif col == "email":
row["email"] = f"{''.join(random.choices(string.ascii_lowercase, k=6))}@{random.choice(DOMAINS)}"
elif col == "age":
row["age"] = random.randint(18, 85)
elif col == "phone":
row["phone"] = f"+44 {''.join(random.choices(string.digits, k=10))}"
elif col == "city":
row["city"] = random.choice(city_pool)
elif col == "company":
row["company"] = f"{random.choice(LAST_NAMES['en'])} {random.choice(COMPANY_SUFFIXES)}"
elif col == "date":
row["date"] = _random_date(2020, 2026)
elif col == "amount":
row["amount"] = round(random.uniform(10.0, 10000.0), 2)
elif col == "id":
row["id"] = "".join(random.choices(string.ascii_uppercase + string.digits, k=8))
elif col == "boolean":
row["boolean"] = random.choice([True, False])
else:
row[col] = "".join(random.choices(string.ascii_letters, k=10))
data.append(row)
return {"columns": cols, "rows": len(data), "data": data,
"timestamp": datetime.now(timezone.utc).isoformat()}
def main():
mcp.run()
if __name__ == '__main__':
main()
# ── MEOK monetization layer (Stripe upgrade · PAYG · pricing) ──────────
# Free tier is zero-config. Upgrade to Pro (unlimited) or pay-as-you-go per call.
import os as _meok_os
MEOK_STRIPE_UPGRADE = "https://buy.stripe.com/5kQ6oJ0xS3ce8sl7ew8k91j" # Pro (unlimited)
MEOK_PAYG_KEY = _meok_os.environ.get("MEOK_PAYG_KEY", "") # set to enable PAYG (x402 / ~GBP0.05 per call)
MEOK_PRICING = "https://meok.ai/pricing"
def meok_upsell(tier: str = "free") -> dict:
"""Monetization options for free-tier callers: Pro upgrade, PAYG, or pricing page."""
if tier != "free":
return {}
return {"upgrade_url": MEOK_STRIPE_UPGRADE,
"payg_enabled": bool(MEOK_PAYG_KEY),
"pricing": MEOK_PRICING}