-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathserver.py
More file actions
2830 lines (2443 loc) · 101 KB
/
Copy pathserver.py
File metadata and controls
2830 lines (2443 loc) · 101 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
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
#!/usr/bin/env python3
"""Publieke HTTP MCP-server voor de Gentse Feesten 2026.
Geeft AI-assistenten toegang tot alle festivaldata zodat ze suggesties
kunnen doen over wat te doen tijdens de Gentse Feesten.
Run:
python server.py
De server gebruikt uitsluitend Streamable HTTP. De standaard-URL is:
http://127.0.0.1:8000/mcp
"""
import json
import math
import os
import re
import shutil
from collections import Counter
from datetime import date, timedelta
from pathlib import Path
from typing import Any, Literal, NotRequired, TypedDict, cast
from mcp.server.fastmcp import FastMCP
from mcp.types import ToolAnnotations
from starlette.requests import Request
from starlette.responses import HTMLResponse, PlainTextResponse
PROJECT_DIR = Path(__file__).resolve().parent
def _data_dir() -> Path:
configured = os.getenv("GF_MCP_DATA_DIR")
if configured:
return Path(configured).expanduser()
candidates = (
PROJECT_DIR.parent / "site" / "data",
PROJECT_DIR.parent / "gf2026" / "site" / "data",
)
for candidate in candidates:
if (candidate / "event_pages.json").is_file():
return candidate
return candidates[0]
DATA_DIR = _data_dir()
class EventOccurrence(TypedDict):
start: str
end: str
day: str
time: str
time_end: str
location: str
weekday: str
class EventOffer(TypedDict):
price: str
currency: str
desc: str
class EventContact(TypedDict):
email: str
tel: str
url: str
class EventVideo(TypedDict):
embed: str
thumb: str
caption: str
class EventDetail(TypedDict, total=False):
uuid: str
name: str
desc: str
themes: list[str]
organizers: list[str]
location: str
street: str
postal: str
city: str
lat: float | None
lon: float | None
free: bool
age: str
genre: str
url: str
image: str
occurrences: list[EventOccurrence]
count: int
first: str
offers: list[EventOffer]
contacts: list[EventContact]
keywords: list[str]
duration: str
frequency: str
languages: list[str]
wheelchair_ok: bool
outdoor: bool
videos: list[EventVideo]
image_caption: str
image_copyright: str
class EventDetailError(TypedDict):
error: str
class BatchSearchResult(TypedDict):
query: str
events: list[dict]
class BatchEventDetailResult(TypedDict):
uuid: str
event: EventDetail | None
error: str | None
# Laad alles éénmalig bij opstarten
pages: list[dict] = json.loads((DATA_DIR / "event_pages.json").read_text(encoding="utf-8"))
events: list[dict] = json.loads((DATA_DIR / "events.json").read_text(encoding="utf-8"))
themes_data: list[dict] = json.loads((DATA_DIR / "themes.json").read_text(encoding="utf-8"))
locations_data: list[dict] = json.loads((DATA_DIR / "locations.json").read_text(encoding="utf-8"))
days_data: list[dict] = json.loads((DATA_DIR / "days.json").read_text(encoding="utf-8"))
# Index voor snelle uuid-lookup
_pages_by_uuid: dict[str, dict] = {p["uuid"]: p for p in pages}
# Dag-lookups
NL_DAYS = ["maandag", "dinsdag", "woensdag", "donderdag", "vrijdag", "zaterdag", "zondag"]
_iso_to_nl: dict[str, str] = {}
_nl_to_iso: dict[str, str] = {}
for d in days_data:
iso = d["day"]
wd = NL_DAYS[date.fromisoformat(iso).weekday()]
_iso_to_nl[iso] = wd
_nl_to_iso[wd] = iso
# Alle muziekgenres
_all_genres = sorted({e["genre"] for e in events if e.get("genre")})
# Trefwoorden/tags, hoofdletterongevoelig samengevoegd. Bewaar als label de
# schrijfwijze die het vaakst in de brondata voorkomt.
_keyword_counts: Counter[str] = Counter()
_keyword_labels: dict[str, Counter[str]] = {}
for p in pages:
for keyword in p.get("keywords") or []:
if not isinstance(keyword, str) or not keyword.strip():
continue
label = keyword.strip()
normalized = label.casefold()
_keyword_counts[normalized] += 1
_keyword_labels.setdefault(normalized, Counter())[label] += 1
tags_data: list[dict] = [
{
"name": _keyword_labels[tag].most_common(1)[0][0],
"count": count,
}
for tag, count in sorted(
_keyword_counts.items(),
key=lambda item: (-item[1], item[0]),
)
]
TAG_RESOURCE_LIMIT = 50
# Aliases en experience tags
_aliases_data = json.loads((PROJECT_DIR / "aliases.json").read_text(encoding="utf-8"))
ALIASES: dict[str, list[str]] = _aliases_data.get("aliases", {})
EXPERIENCE_MAPPING: dict[str, list[str]] = _aliases_data.get("experience_mapping", {})
_experience_cache = json.loads((PROJECT_DIR / "experience_tags.json").read_text(encoding="utf-8")) if (PROJECT_DIR / "experience_tags.json").is_file() else {}
EXPERIENCE_TAGS: dict[str, list[str]] = _experience_cache
# ---------------------------------------------------------------------------
# Zones — dynamically cluster locations by proximity
# ---------------------------------------------------------------------------
def _haversine(lat1: float, lon1: float, lat2: float, lon2: float) -> float:
"""Afstand in meter tussen twee coördinaten (Haversine)."""
R = 6371000
phi1, phi2 = math.radians(lat1), math.radians(lat2)
dphi = math.radians(lat2 - lat1)
dlambda = math.radians(lon2 - lon1)
a = math.sin(dphi / 2) ** 2 + math.cos(phi1) * math.cos(phi2) * math.sin(dlambda / 2) ** 2
return R * 2 * math.atan2(math.sqrt(a), math.sqrt(1 - a))
def _build_zones() -> list[dict]:
"""Cluster locations by proximity (~200m) and derive vibe from event data."""
locs_with_coords = [l for l in locations_data if l.get("lat") and l.get("lon")]
locs_without = [l for l in locations_data if not l.get("lat") or not l.get("lon")]
# Union-Find for clustering
parent: dict[str, str] = {l["name"]: l["name"] for l in locs_with_coords}
def find(x: str) -> str:
while parent[x] != x:
parent[x] = parent[parent[x]]
x = parent[x]
return x
def union(a: str, b: str) -> None:
ra, rb = find(a), find(b)
if ra != rb:
parent[ra] = rb
# Cluster locations within 100m
for i, a in enumerate(locs_with_coords):
for b in locs_with_coords[i + 1:]:
if _haversine(a["lat"], a["lon"], b["lat"], b["lon"]) < 100:
union(a["name"], b["name"])
# Group locations by cluster
clusters: dict[str, list[dict]] = {}
for loc in locs_with_coords:
root = find(loc["name"])
clusters.setdefault(root, []).append(loc)
# Build zone for each cluster (min 2 locations, or high-count singles)
zones: list[dict] = []
for root, cluster_locs in clusters.items():
loc_names = [l["name"] for l in cluster_locs]
total_count = sum(l.get("count", 0) for l in cluster_locs)
# Skip tiny single-location clusters unless they have many events
if len(cluster_locs) < 2 and total_count < 50:
continue
# Zone name: use the location with most events, or shortest name
zone_loc = max(cluster_locs, key=lambda l: l.get("count", 0))
zone_name = zone_loc["name"]
# Simplify: use street area if multiple locations
if len(cluster_locs) > 1:
streets = {l.get("street", "").split()[0] for l in cluster_locs if l.get("street")}
if len(streets) == 1:
zone_name = list(streets)[0]
else:
zone_name = zone_loc["name"]
# Calculate center
avg_lat = sum(l["lat"] for l in cluster_locs) / len(cluster_locs)
avg_lon = sum(l["lon"] for l in cluster_locs) / len(cluster_locs)
# Derive vibe from events at these locations
vibe_counter: Counter[str] = Counter()
good_for_counter: Counter[str] = Counter()
for p in pages:
if p.get("location") not in loc_names:
continue
for theme in p.get("themes") or []:
vibe_counter[theme.lower()] += 1
for kw in p.get("keywords") or []:
if isinstance(kw, str):
vibe_counter[kw.lower()] += 1
# Derive good_for from themes/keywords
themes_kw = " ".join((p.get("themes") or []) + (p.get("keywords") or [])).lower()
if any(w in themes_kw for w in ["kinder", "gezin", "familie", "kids"]):
good_for_counter["kinderen"] += 1
if any(w in themes_kw for w in ["dans", "dansen", "bal", "tango"]):
good_for_counter["dans"] += 1
if any(w in themes_kw for w in ["eten", "drank", "food", "bar"]):
good_for_counter["eten & drinken"] += 1
if any(w in themes_kw for w in ["circus", "straattheater", "acrobat"]):
good_for_counter["circus & straat"] += 1
if any(w in themes_kw for w in ["muziek", "concert", "live"]):
good_for_counter["muziek"] += 1
if any(w in themes_kw for w in ["theater", "toneel", "voorstelling"]):
good_for_counter["theater"] += 1
if any(w in themes_kw for w in ["comedy", "humor", "cabaret"]):
good_for_counter["comedy & cabaret"] += 1
if any(w in themes_kw for w in ["expo", "museum", "tentoonstelling"]):
good_for_counter["expo & kunst"] += 1
if any(w in themes_kw for w in ["markt", "verkoop"]):
good_for_counter["markten"] += 1
if p.get("outdoor"):
good_for_counter["buiten"] += 1
vibe = [tag for tag, _ in vibe_counter.most_common(5)]
good_for = [tag for tag, _ in good_for_counter.most_common(5) if _ >= 3]
outdoor_events = sum(1 for p in pages if p.get("location") in loc_names and p.get("outdoor"))
total_events = sum(1 for p in pages if p.get("location") in loc_names)
zones.append({
"zone": zone_name,
"locations": sorted(loc_names),
"vibe": vibe,
"good_for": good_for,
"event_count": total_count,
"location_count": len(cluster_locs),
"outdoor_ratio": f"{outdoor_events}/{total_events}" if total_events else "0/0",
"lat": round(avg_lat, 6),
"lon": round(avg_lon, 6),
})
# Add standalone high-count locations as their own zones
clustered_names = {l["name"] for cl in clusters.values() for l in cl}
for loc in locs_without:
if loc.get("count", 0) >= 40:
zones.append({
"zone": loc["name"],
"locations": [loc["name"]],
"vibe": [],
"good_for": [],
"event_count": loc.get("count", 0),
"location_count": 1,
"outdoor_ratio": f"{'1' if loc.get('outdoor') else '0'}/1",
"lat": None,
"lon": None,
})
# Add standalone single-location clusters with enough events
for root, cluster_locs in clusters.items():
if len(cluster_locs) == 1 and cluster_locs[0]["name"] not in clustered_names:
loc = cluster_locs[0]
if loc.get("count", 0) >= 50:
zones.append({
"zone": loc["name"],
"locations": [loc["name"]],
"vibe": [],
"good_for": [],
"event_count": loc.get("count", 0),
"location_count": 1,
"outdoor_ratio": f"{'1' if loc.get('outdoor') else '0'}/1",
"lat": loc["lat"],
"lon": loc["lon"],
})
zones.sort(key=lambda z: -z["event_count"])
return zones
ZONES_FILE = PROJECT_DIR / "zones.json"
def _load_zones() -> list[dict]:
"""Load zones from zones.json if present, otherwise build dynamically."""
if ZONES_FILE.exists():
data = json.loads(ZONES_FILE.read_text(encoding="utf-8"))
zones = []
for z in data.get("zones", []):
zones.append({
"zone": z.get("name", z.get("zone", "")),
"locations": z.get("locations", []),
"vibe": z.get("vibe", []),
"good_for": z.get("good_for", []),
"event_count": z.get("event_count", 0),
"location_count": z.get("location_count", len(z.get("locations", []))),
"outdoor_ratio": z.get("outdoor_ratio", "0/0"),
"lat": z.get("lat"),
"lon": z.get("lon"),
"notes": z.get("notes", ""),
"best_moment": z.get("best_moment", ""),
"target_audience": z.get("target_audience", ""),
})
return zones
return _build_zones()
zones_data: list[dict] = _load_zones()
_zones_by_name: dict[str, dict] = {z["zone"].lower(): z for z in zones_data}
# Map location name -> zone name for fast lookup
_location_to_zone: dict[str, str] = {}
# Build a set of all known zone locations for matching
_zone_location_sets: dict[str, set[str]] = {}
for z in zones_data:
locs = {loc.lower() for loc in z["locations"]}
_zone_location_sets[z["zone"]] = locs
for loc in z["locations"]:
_location_to_zone[loc.lower()] = z["zone"]
# Compute event counts dynamically (zones.json may have stale zeros)
for z in zones_data:
zone_locs = _zone_location_sets.get(z["zone"], set())
count = sum(1 for p in pages if (p.get("location") or "").lower() in zone_locs)
z["event_count"] = count
z["location_count"] = len(z["locations"])
# ---------------------------------------------------------------------------
# Vector index for semantic search
# ---------------------------------------------------------------------------
EMBED_DIM = 384
VECTOR_DB_PATH = PROJECT_DIR / "zvec_gentsefeesten_db"
_vector_coll = None
_vector_emb = None
def _build_vector_index():
"""Build zvec collection with FTS + vector index for semantic search."""
global _vector_coll, _vector_emb
try:
import zvec
from zvec import CollectionOption, DataType, Doc, FieldSchema, FtsIndexParam
from zvec.extension import DefaultLocalDenseEmbedding
except ImportError:
print("zvec not available — vector search disabled")
return
if VECTOR_DB_PATH.exists():
shutil.rmtree(VECTOR_DB_PATH)
zvec.init(log_level=zvec.LogLevel.WARN, query_threads=4)
fts = lambda: FtsIndexParam(tokenizer_name="standard", filters=["lowercase"])
schema = zvec.CollectionSchema(
name="gentse_feesten",
fields=[
FieldSchema("name", DataType.STRING, nullable=False, index_param=fts()),
FieldSchema("description", DataType.STRING, nullable=False, index_param=fts()),
FieldSchema("keywords", DataType.STRING, nullable=True, index_param=fts()),
FieldSchema("themes", DataType.STRING, nullable=True, index_param=fts()),
FieldSchema("location", DataType.STRING, nullable=True, index_param=fts()),
FieldSchema("organizer", DataType.STRING, nullable=True),
FieldSchema("startdate", DataType.STRING, nullable=True),
FieldSchema("free", DataType.STRING, nullable=True),
FieldSchema("outdoors", DataType.STRING, nullable=True),
FieldSchema("parent_uuid", DataType.STRING, nullable=True),
FieldSchema("embed_text", DataType.STRING, nullable=True),
],
vectors=zvec.VectorSchema("embedding", zvec.DataType.VECTOR_FP32, EMBED_DIM),
)
_vector_coll = zvec.create_and_open(
path=str(VECTOR_DB_PATH),
schema=schema,
option=CollectionOption(read_only=False, enable_mmap=True),
)
_vector_emb = DefaultLocalDenseEmbedding(batch_size=64)
# Build genre lookup from events.json for richer embeddings
_genre_by_uuid: dict[str, str] = {e["uuid"]: e.get("genre", "") for e in events}
BATCH = 500
batch = []
for i, p in enumerate(pages):
uuid = p.get("uuid", "")
genre = _genre_by_uuid.get(uuid, "")
exp_tags = " ".join(EXPERIENCE_TAGS.get(uuid, []))
embed_text = f"{p.get('name', '')}. {p.get('desc', '')}. {' '.join(p.get('keywords', []))}. {' '.join(p.get('themes', []))}. {p.get('location', '')}. {genre}. {exp_tags}"
vec = _vector_emb.embed(embed_text)
doc = Doc(id=f"{p.get('uuid', '')}_{i}", fields={
"name": p.get("name", ""),
"description": p.get("desc", ""),
"keywords": " ".join(p.get("keywords", [])),
"themes": " ".join(p.get("themes", [])),
"location": p.get("location", ""),
"organizer": " ".join(p.get("organizers", [])),
"startdate": p.get("first", ""),
"free": "1" if p.get("free") else "0",
"outdoors": "1" if p.get("outdoor") else "0",
"parent_uuid": p.get("parent_uuid", ""),
"embed_text": embed_text,
}, vectors={"embedding": vec})
batch.append(doc)
if len(batch) == BATCH:
_vector_coll.insert(batch)
batch = []
if batch:
_vector_coll.insert(batch)
print(f"Vector index: {_vector_coll.stats.doc_count} events indexed")
if os.getenv("GF_MCP_DISABLE_VECTOR_INDEX", "").lower() in {"1", "true", "yes"}:
print("Vector index disabled by GF_MCP_DISABLE_VECTOR_INDEX")
else:
try:
_build_vector_index()
except Exception as exc:
print(f"Vector index disabled — startup failed: {exc}")
_vector_coll = None
_vector_emb = None
HOST = os.getenv("GF_MCP_HOST", "127.0.0.1")
PORT = int(os.getenv("GF_MCP_PORT", "8000"))
# Response wrapper for consistent format
def _wrap(tool_name: str, data, warnings: list[str] | None = None) -> WrapResponse:
"""Wrap tool responses in standard envelope."""
return {
"ok": True,
"data": data,
"meta": {
"tool": tool_name,
"dataset_year": 2026,
"result_count": len(data) if isinstance(data, list) else 1,
},
"warnings": warnings or [],
}
def _expand_query(query: str) -> list[str]:
"""Expand query using aliases. Returns [primary, ...expanded] where primary is the original query."""
q = query.strip().lower()
# Always keep original query as primary
expanded = [q]
# Check for negation patterns
negation_words = ["niet", "geen", "no", "not", "zonder", "minus"]
has_negation = any(neg in q for neg in negation_words)
for alias_key, alias_values in ALIASES.items():
# Skip "braaf" alias if query has negation
if alias_key == "braaf" and has_negation:
continue
# Skip "gratis" alias if query has negation
if alias_key == "gratis" and has_negation:
continue
alias_key_normalized = alias_key.replace("_", " ")
matched = False
# Direct match on alias key (whole word only)
if re.search(r'\b' + re.escape(alias_key) + r'\b', q) or \
re.search(r'\b' + re.escape(alias_key_normalized) + r'\b', q):
matched = True
# Match on any alias value (whole word only)
elif any(re.search(r'\b' + re.escape(av) + r'\b', q) for av in alias_values):
matched = True
# Fuzzy match for negated aliases (whole word only)
elif has_negation and alias_key.startswith("niet_"):
non_negated = alias_key[5:]
non_negated_normalized = non_negated.replace("_", " ")
if re.search(r'\b' + re.escape(non_negated) + r'\b', q) or \
re.search(r'\b' + re.escape(non_negated_normalized) + r'\b', q):
matched = True
return list(dict.fromkeys(expanded)) # Dedupe preserving order
def _get_experience_tags(uuid: str) -> list[str]:
"""Get experience tags for an event."""
return EXPERIENCE_TAGS.get(uuid, [])
def _score_event(p: dict, intent: dict | None = None) -> tuple:
"""Score an event for ranking. Higher = better."""
# Base: prefer events with descriptions, outdoor, more occurrences
base_score = (
1 if p.get("outdoor") else 0,
1 if p.get("desc") else 0,
p.get("count", 0),
p.get("name", ""),
)
if not intent:
return base_score
# Compute intent match score
uuid = p.get("uuid", "")
event_tags = set(_get_experience_tags(uuid))
event_text = " ".join([
p.get("name", ""),
p.get("desc", ""),
" ".join(p.get("themes", [])),
" ".join(p.get("keywords", [])),
]).lower()
score = 0
# High-value: experience tag matches (max 30)
exp_matches = sum(1 for req in intent.get("experience", []) if req in event_tags)
score += min(exp_matches * 10, 30)
# Medium-value: activity matches (max 15)
act_matches = sum(1 for req in intent.get("activity", []) if req in event_tags)
score += min(act_matches * 5, 15)
# Medium-value: genre matches in text (max 15)
genre_matches = sum(1 for req in intent.get("genre", []) if req in event_text)
score += min(genre_matches * 5, 15)
# Bonus: price/setting matches
if intent.get("price") == "free" and p.get("free"):
score += 5
if intent.get("setting") == "outdoor" and p.get("outdoor"):
score += 5
if intent.get("setting") == "indoor" and not p.get("outdoor"):
score += 5
return (score,) + base_score
def _parse_intent(mood: str) -> dict:
"""Parse mood string into structured intent."""
m = mood.lower()
intent = {
"experience": [],
"activity": [],
"genre": [],
"price": "any",
"setting": "any",
"time": "any",
"energy": "any",
}
# Check for negation patterns first
negation_words = ["niet", "geen", "no", "not", "zonder"]
has_negation = any(neg in m for neg in negation_words)
# Handle negated concepts
if has_negation:
# "niet te braaf" → cabaret, queer, burlesque, weird, late_night
if "braaf" in m or "familie" in m or "kinder" in m:
intent["experience"].extend(["cabaret", "queer", "burlesque", "weird", "late_night"])
# "niet gratis" → paid events
if "gratis" in m or "free" in m:
intent["price"] = "paid"
# "niet buiten" → indoor
if "buiten" in m or "outdoor" in m:
intent["setting"] = "indoor"
# Experience tags from EXPERIENCE_MAPPING
for exp_tag, keywords in EXPERIENCE_MAPPING.items():
if any(kw in m for kw in keywords):
if exp_tag not in intent["experience"]:
intent["experience"].append(exp_tag)
# Activity
if any(w in m for w in ["dans", "dansen", "bal", "dansinitiatie"]):
intent["activity"].append("dance")
if any(w in m for w in ["eten", "drank", "food", "bar"]):
intent["activity"].append("food")
if any(w in m for w in ["wandeling", "wandelen", "rondleiding"]):
intent["activity"].append("walking")
if any(w in m for w in ["luisteren", "rustig", "kalm"]):
intent["activity"].append("listening")
if any(w in m for w in ["lachen", "humor", "grappig"]):
intent["activity"].append("comedy")
# Price
if any(w in m for w in ["gratis", "free", "kosteloos"]):
intent["price"] = "free"
elif any(w in m for w in ["betalen", "ticket", "prijs"]):
intent["price"] = "paid"
# Setting
if any(w in m for w in ["buiten", "outdoor", "openlucht", "park"]):
intent["setting"] = "outdoor"
elif any(w in m for w in ["binnen", "indoor", "zaal"]):
intent["setting"] = "indoor"
# Time
if any(w in m for w in ["ochtend", "vroeg", "morgend"]):
intent["time"] = "morning"
elif any(w in m for w in ["middag", "namiddag", "overdag"]):
intent["time"] = "afternoon"
elif any(w in m for w in ["avond", "nacht", "laat"]):
intent["time"] = "evening"
# Energy
if any(w in m for w in ["rustig", "kalm", "ontspannen"]):
intent["energy"] = "low"
elif any(w in m for w in ["actief", "dans", "feest", "intensief"]):
intent["energy"] = "high"
elif any(w in m for w in ["gemengd", "afwisseling", "beetje alles"]):
intent["energy"] = "mixed"
# Genre
for g in _all_genres:
if g.lower() in m:
intent["genre"].append(g.lower())
# Theme mapping
theme_map = {
"jazz": ["jazz"],
"comedy": ["comedy"],
"theater": ["theater", "toneel"],
"circus": ["circus", "straattheater"],
"kinder": ["kinder", "gezin"],
}
for theme, keywords in theme_map.items():
if any(kw in m for kw in keywords):
intent["genre"].append(theme)
return intent
mcp = FastMCP(
"Gentse Feesten 2026",
instructions="""Gentse Feesten 2026 — 11-day free city festival in Ghent, Belgium (July 17–27, 2026). 1600+ unique events across 25 zones. All data is public; no auth needed.
## Tool selection (most specific match wins)
Match the user's query to the FIRST row that fits — do not default to suggest() or semantic_search().
| User intent | Tool |
|---|---|
| Artist / event name mentioned | search_events(query="name") — ALWAYS use for named artists, bands, events. Check the `keywords` field to confirm matches; names may be truncated. |
| "What should I do on [day]?" | plan_day(day) — one call replaces list_days + free_highlights + search_events |
| Mood / vibe (no specific name) | suggest(mood) — Dutch phrases auto-expand: "niet te braaf" → cabaret/queer/burlesque; "zwoel" → romantic/sensual |
| Personal multi-day plan | create_festival_guide(vibe, energy_level, social_mode) |
| Conceptual / thematic question | semantic_search(query, mode="hybrid") — for meaning-based queries like "romantic evening", not proper nouns |
| "What's happening at [place]?" | events_by_location(location_name, day) |
| "Tell me about this event" | get_event_detail(uuid, detail="summary") or get_event_details([...uuids]) for batch |
| "What zone should I visit?" | list_zones() → get_zone_profile(zone_name) or search_by_zone(zone_name, ...) |
| "What's on during the festival?" | search_events(query, day, theme, ...) — supports free_only, outdoor_only, genre, wheelchair, time_window, participatory filters |
| "Events like this one" | find_similar_events(uuid) — vector similarity + parent/sibling relations |
| All occurrences of a multi-date event | get_parent_event(uuid) — parent + all child dates/times |
| "Show/display details" or user asks to see results visually | show_festival_explorer(mode="detail", uuid="...") for one event, or mode="search"/"day"/"guide"/"zones" for lists |
## Don'ts
- NEVER use suggest() for artist/band/event name lookups — it's mood-based, not name-based
- NEVER use semantic_search() for proper nouns, artist names, or exact event titles
- NEVER use get_event_detail in a loop — use get_event_details([...uuids]) for batch
- NEVER call semantic_search with mode="hybrid" as a fallback when search_events already works
## Key conventions
- **day parameter** in any tool: accepts ISO date ("2026-07-19") or Dutch weekday ("vrijdag", "zaterdag"). A festival day runs 06:00 to 05:59 the next calendar day, so late-night events after midnight belong to the previous festival day. Use get_today() to resolve "today".
- **Dutch queries work natively** in suggest() and search_events(): "niet te braaf" → cabaret/queer/burlesque; "zwoel" → sensueel/romantic.
- **semantic_search modes**: "semantic" for meaning ("romantic evening"), "fts" for exact keywords ("jazz", "cirQ"), "hybrid" combines both.
- **Festival language**: respond in the language the user uses. Festival content is Dutch; translate event names only when helpful.
- **Respond with event info**: always include event name, time, location, and whether it's free. Link UUID for follow-up.""",
host=HOST,
port=PORT,
stateless_http=True,
json_response=True,
)
READ_ONLY_TOOL_ANNOTATIONS = ToolAnnotations(
readOnlyHint=True,
openWorldHint=False,
destructiveHint=False,
)
OPENAI_APPS_CHALLENGE_TOKEN = "v_bO2xepAywAqMN84rtXBGVESnwXSQS-CkGeEJjI7Lw"
APP_WIDGET_URI = "ui://widget/gf2026-explorer-v1.html"
APP_WIDGET_MIME_TYPE = "text/html;profile=mcp-app"
APP_WIDGET_DOMAIN = "https://gf2026.doplr.com"
_event_short_schema = {
"type": "object",
"properties": {
"uuid": {"type": "string"},
"name": {"type": "string"},
"days": {"type": "array", "items": {"type": "string"}},
"first_weekday": {"type": "string"},
"first_time": {"type": "string"},
"occurrence_time": {"type": "string"},
"location": {"type": "string"},
"free": {"type": "boolean"},
"outdoor": {"type": "boolean"},
"themes": {"type": "array", "items": {"type": "string"}},
"recurring_all_days": {"type": "boolean"},
"experience_tags": {"type": "array", "items": {"type": "string"}},
"match_reasons": {"type": "array", "items": {"type": "string"}},
},
}
_zone_detail_schema = {
"type": "object",
"properties": {
"zone": {"type": "string"},
"locations": {"type": "array", "items": {"type": "string"}},
"vibe": {"type": "array", "items": {"type": "string"}},
"good_for": {"type": "array", "items": {"type": "string"}},
"event_count": {"type": "integer"},
"location_count": {"type": "integer"},
"outdoor_ratio": {"type": "string", "description": "Fraction of outdoor events: outdoor_count/total_events"},
"lat": {"type": "number"},
"lon": {"type": "number"},
"events": {"type": "array", "items": _event_short_schema},
},
}
# Output schema TypedDicts for structured_output=True
class _Meta(TypedDict):
tool: str
dataset_year: int
result_count: int
class WrapResponse(TypedDict):
ok: bool
data: Any
meta: _Meta
warnings: list[str]
class ZoneDetailOutput(TypedDict):
zone: str
locations: list[str]
vibe: list[str]
good_for: list[str]
event_count: int
location_count: int
outdoor_ratio: str
lat: float
lon: float
events: list[dict]
class ZoneProfileOutput(TypedDict):
zone: str
vibe: list[str]
good_for: list[str]
best_moment: str
target_audience: str
notes: str
events: list[dict]
event_count: int
class FindSimilarOutput(TypedDict):
source_event: dict
same_vibe: list[dict]
nearby: list[dict]
good_afterwards: list[dict]
related: list[dict]
class ParentEventOutput(TypedDict):
uuid: str
name: str
occurrences: list[dict]
children: list[dict]
total_dates: int
class PlanDayOutput(TypedDict):
day_info: dict
free_highlights: list[dict]
themed_picks: list[dict]
class CreateGuideOutput(TypedDict):
guide_title: str
vibe_summary: str
anchor_events: list[dict]
fallback_events: list[dict]
zones: list[dict]
energy_strategy: list[str]
total_events_considered: int
class GetTodayOutput(TypedDict):
date: str
weekday: str
in_festival: bool
festival_range: str
next_festival_days: int
class FestivalExplorerOutput(TypedDict):
title: str
mode: str
query: str
day: str
items: list[dict]
sections: list[dict]
meta: dict
LEGAL_PAGE_STYLE = """
body {
color: #1f2937;
font: 16px/1.6 system-ui, sans-serif;
margin: 0 auto;
max-width: 760px;
padding: 2rem 1.25rem 4rem;
}
h1, h2 { color: #111827; line-height: 1.25; }
a { color: #075985; }
.updated { color: #4b5563; }
"""
IMPRINT = """
<h2>Imprint</h2>
<p>
Hans Fraiponts<br>
Emiel Lossystraat 37<br>
9040 Ghent, Belgium<br>
VAT: BE 0873.510.437<br>
<a href="mailto:info@gogogonzo.be">info@gogogonzo.be</a>
</p>
"""
@mcp.custom_route("/", methods=["GET"], include_in_schema=False)
async def index(_: Request) -> HTMLResponse:
return HTMLResponse(
f"""<!doctype html>
<html lang="en">
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1">
<title>Gentse Feesten 2026 — experimental MCP service</title>
<style>{LEGAL_PAGE_STYLE}</style>
</head>
<body>
<main>
<h1>Gentse Feesten 2026</h1>
<p>This is an <strong>experimental</strong> service for the city of Ghent.
It provides read-only AI access to the public Gentse Feesten 2026 festival programme.
Nothing here is guaranteed: the service may be wrong, incomplete, change without notice,
or disappear entirely.</p>
<p>The festival takes place <strong>July 17-27, 2026</strong>, Ghent, Belgium.</p>
<p>
<a href="/privacy">Privacy policy</a> ·
<a href="/terms">Terms of service</a>
</p>
{IMPRINT}
</main>
</body>
</html>"""
)
@mcp.custom_route(
"/.well-known/openai-apps-challenge",
methods=["GET"],
include_in_schema=False,
)
async def openai_apps_challenge(_: Request) -> PlainTextResponse:
return PlainTextResponse(OPENAI_APPS_CHALLENGE_TOKEN)
def _legal_page(title: str, content: str) -> HTMLResponse:
return HTMLResponse(
f"""<!doctype html>
<html lang="en">
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1">
<title>{title} — Gentse Feesten 2026</title>
<style>{LEGAL_PAGE_STYLE}</style>
</head>
<body>
<main>
<h1>{title}</h1>
<p class="updated">Last updated: June 24, 2026</p>
{content}
{IMPRINT}
</main>
</body>
</html>"""
)
@mcp.custom_route("/privacy", methods=["GET"], include_in_schema=False)
async def privacy_policy(_: Request) -> HTMLResponse:
return _legal_page(
"Privacy Policy",
"""
<p>Gentse Feesten 2026 provides read-only access to public festival
information through an MCP server.</p>
<h2>Information we process</h2>
<p>The service does not require an account and does not intentionally request
or store names, email addresses, payment information, credentials, or other
personal information. Requests may contain search terms and preferences that
are used only to return relevant festival information.</p>
<h2>Technical logs</h2>
<p>The hosting provider or reverse proxy may temporarily process standard
technical information such as IP addresses, timestamps, requested paths, and
user-agent data for security, reliability, rate limiting, and troubleshooting.
These logs are not used for advertising or profiling.</p>
<h2>Data sharing and retention</h2>
<p>The app does not sell personal information. Technical data may be processed
by infrastructure providers solely to operate and secure the service, and may
be retained according to their operational policies or legal requirements.</p>
<h2>Third-party links</h2>
<p>Festival records may contain links to organizers, ticket providers, or
<h2>Contact</h2>
<p>Questions about this policy can be submitted through the
<a href="https://github.com/HansF/gf2026-mcp/issues">project issue tracker</a>.</p>
""",
)
@mcp.custom_route("/terms", methods=["GET"], include_in_schema=False)
async def terms_of_service(_: Request) -> HTMLResponse:
return _legal_page(
"Terms of Service",
"""
<p>By using the Gentse Feesten 2026 MCP service, you agree to these terms.</p>
<h2>Service scope</h2>
<p>The service provides read-only search, recommendations, and event details
from public Gentse Feesten 2026 program data. It does not sell tickets, make
reservations, process payments, or act on behalf of event organizers.</p>
<h2>Accuracy and availability</h2>
<p>Program details may change or contain errors. Verify important information,
including schedules, prices, accessibility, and availability, with the event
organizer or official festival source. The service may be changed, suspended,