-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathserver.py
More file actions
618 lines (508 loc) · 25.3 KB
/
server.py
File metadata and controls
618 lines (508 loc) · 25.3 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
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
#!/usr/bin/env python3
"""
Regulatory Update Webhook — MEOK AI Labs. Monitor regulatory changes, notify subscribers."""
import sys, os
from auth_middleware import check_access
import json, os, hashlib, time, requests
from datetime import datetime, timezone
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": f"Limit {FREE_DAILY_LIMIT}/day"})
_usage[c].append(now)
return None
mcp = FastMCP(
"regulatory-webhook",
instructions="MEOK AI Labs — Monitor regulatory changes. Subscribe to updates. Get notified when laws change.",
)
_subscribers = defaultdict(list)
_webhooks = []
_updates_cache = []
REGULATORY_CHANGES = [
{
"date": "2026-04-14",
"framework": "EU AI Act",
"change": "Digital Omnibus: Annex III deadline moved to Dec 2027",
"impact": "high",
"source": "EU Commission",
},
{
"date": "2026-04-10",
"framework": "NIST AI RMF 2.0",
"change": "Version 2.0 released with new governance structures",
"impact": "high",
"source": "NIST",
},
{
"date": "2026-04-01",
"framework": "UK AI Security Institute",
"change": "Rebranded to UK AISI",
"impact": "medium",
"source": "UK Government",
},
{
"date": "2026-03-20",
"framework": "ISO 42001",
"change": "First AI management system standard published",
"impact": "high",
"source": "ISO",
},
{
"date": "2026-03-15",
"framework": "Singapore Model AI Governance",
"change": "Updated версия 2.0 released",
"impact": "medium",
"source": "IMDA",
},
]
@mcp.tool()
def subscribe(
email: str, frameworks: str = "all", webhook_url: str = "", api_key: str = ""
) -> str:
"""Subscribe to regulatory update notifications for specific frameworks.
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.
Args:
email (str): The email to analyze or process.
frameworks (str): The frameworks to analyze or process.
webhook_url (str): The webhook url 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
sub_id = hashlib.sha256(f"{email}{time.time()}".encode()).hexdigest()[:12]
frameworks_list = [f.strip() for f in frameworks.split(",")]
sub = {
"id": sub_id,
"email": email,
"frameworks": frameworks_list,
"webhook_url": webhook_url,
"subscribed_at": datetime.now(timezone.utc).isoformat(),
"status": "active",
}
_subscribers[email] = sub
if webhook_url:
_webhooks.append({"url": webhook_url, "sub_id": sub_id})
return {
"subscribed": True,
"sub_id": sub_id,
"email": email,
"frameworks": frameworks_list,
}
@mcp.tool()
def unsubscribe(email: str, api_key: str = "") -> str:
"""Unsubscribe from regulatory updates.
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.
Args:
email (str): The email 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
if email in _subscribers:
_subscribers[email]["status"] = "inactive"
return {"unsubscribed": True, "email": email}
return {"error": "Not subscribed"}
@mcp.tool()
def get_recent_changes(
framework: str = "all", days: int = 90, api_key: str = ""
) -> str:
"""Get recent regulatory changes for specified frameworks.
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.
Args:
framework (str): The framework to analyze or process.
days (int): The days 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
cutoff = datetime.now(timezone.utc) - timedelta(days=days)
filtered = [
c
for c in REGULATORY_CHANGES
if datetime.fromisoformat(c["date"].replace("-", "/")) >= cutoff
]
if framework != "all":
filtered = [c for c in filtered if framework.lower() in c["framework"].lower()]
return {"changes": filtered, "total": len(filtered), "framework": framework}
@mcp.tool()
def check_for_updates(
frameworks: str = "eu_ai_act,nist,iso_42001", api_key: str = ""
) -> str:
"""Check if monitored frameworks have recent updates.
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.
Args:
frameworks (str): The frameworks to analyze or process.
nist: The nist to analyze or process.
iso_42001": The iso 42001" 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
fw_list = [f.strip() for f in frameworks.split(",")]
updates = []
for fw in fw_list:
for change in REGULATORY_CHANGES:
if fw.lower().replace("_", " ") in change["framework"].lower():
updates.append(change)
return {
"has_updates": len(updates) > 0,
"updates": updates,
"checked": datetime.now(timezone.utc).isoformat(),
}
@mcp.tool()
def register_webhook(
url: str, events: str = "regulatory_change", api_key: str = ""
) -> str:
"""Register a webhook for regulatory notifications.
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.
Args:
url (str): The url to analyze or process.
events (str): The events 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
webhook_id = hashlib.sha256(f"{url}{time.time()}".encode()).hexdigest()[:12]
webhook = {
"id": webhook_id,
"url": url,
"events": [e.strip() for e in events.split(",")],
"registered_at": datetime.now(timezone.utc).isoformat(),
"status": "active",
}
_webhooks.append(webhook)
return {"registered": True, "webhook_id": webhook_id, "url": url}
@mcp.tool()
def trigger_webhook(webhook_id: str, payload: dict, api_key: str = "") -> str:
"""Manually trigger a webhook with payload.
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.
Args:
webhook_id (str): The webhook id to analyze or process.
payload (dict): The payload 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
webhook = next((w for w in _webhooks if w["id"] == webhook_id), None)
if not webhook:
return {"error": "Webhook not found"}
try:
response = requests.post(webhook["url"], json=payload, timeout=10)
return {
"triggered": True,
"status_code": response.status_code,
"response": response.text[:200],
}
except Exception as e:
return {"triggered": False, "error": str(e)}
@mcp.tool()
def get_subscribers(api_key: str = "") -> str:
"""List all webhook subscribers (admin only).
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.
Args:
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 tier not in ["pro", "enterprise"]:
return {"error": "Admin access required"}
return {"subscribers": list(_subscribers.values()), "total": len(_subscribers)}
@mcp.tool()
def list_webhooks(api_key: str = "") -> str:
"""List all registered webhooks.
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.
Args:
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"}
return {"webhooks": _webhooks, "total": len(_webhooks)}
@mcp.tool()
def get_framework_newsletter_summary(api_key: str = "") -> str:
"""Get a newsletter-ready summary of recent regulatory changes.
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.
Args:
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
high_impact = [c for c in REGULATORY_CHANGES if c.get("impact") == "high"]
return {
"summary": {
"total_changes": len(REGULATORY_CHANGES),
"high_impact_count": len(high_impact),
"frameworks_covered": list(set(c["framework"] for c in REGULATORY_CHANGES)),
"high_impact_items": high_impact,
},
"generated_at": 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}