mcp-scheduling 1.4.0

Scheduling MCP server — appointments, shifts, resource booking, availability, recurring events, conflict detection, timezone-aware
Documentation
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
use rmcp::{handler::server::wrapper::Parameters, schemars, tool, tool_router};
use serde_json::{json, Value};
use crate::types::*;
use crate::store::Store;

fn now() -> String { chrono::Utc::now().to_rfc3339() }

#[derive(Debug, serde::Deserialize, schemars::JsonSchema)]
pub struct ResourceInput { pub name: String, pub resource_type: String, pub capacity: Option<u32>, pub timezone: Option<String>, pub tags: Option<Vec<String>> }
#[derive(Debug, serde::Deserialize, schemars::JsonSchema)]
pub struct BookingInput { pub resource_id: String, pub title: String, pub start: String, pub end: String, pub booked_by: String, pub attendees: Option<Vec<String>>, pub recurrence: Option<String>, pub notes: Option<String> }
#[derive(Debug, serde::Deserialize, schemars::JsonSchema)]
pub struct BookingIdInput { pub booking_id: String }
#[derive(Debug, serde::Deserialize, schemars::JsonSchema)]
pub struct RescheduleInput { pub booking_id: String, pub new_start: String, pub new_end: String }
#[derive(Debug, serde::Deserialize, schemars::JsonSchema)]
pub struct AvailabilityInput { pub resource_id: String, pub date: String, pub duration_minutes: Option<u32> }
#[derive(Debug, serde::Deserialize, schemars::JsonSchema)]
pub struct ShiftInput { pub resource_id: String, pub role: String, pub start: String, pub end: String, pub break_minutes: Option<u32>, pub notes: Option<String> }
#[derive(Debug, serde::Deserialize, schemars::JsonSchema)]
pub struct ShiftIdInput { pub shift_id: String, pub status: String }
#[derive(Debug, serde::Deserialize, schemars::JsonSchema)]
pub struct TimeOffInput { pub resource_id: String, pub start_date: String, pub end_date: String, pub reason: String }
#[derive(Debug, serde::Deserialize, schemars::JsonSchema)]
pub struct TimeOffDecideInput { pub time_off_id: String, pub decision: String }
#[derive(Debug, serde::Deserialize, schemars::JsonSchema)]
pub struct ResourceIdInput { pub resource_id: String }
#[derive(Debug, serde::Deserialize, schemars::JsonSchema)]
pub struct DateRangeInput { pub resource_id: Option<String>, pub start: String, pub end: String }
#[derive(Debug, serde::Deserialize, schemars::JsonSchema)]
pub struct FindSlotInput { pub resource_ids: Vec<String>, pub duration_minutes: u32, pub date: String, pub earliest: Option<String>, pub latest: Option<String> }

#[derive(Debug, serde::Deserialize, schemars::JsonSchema)]
pub struct HolidaysInput {
    /// Country code (ISO 3166-1 alpha-2)
    pub country: String,
    /// Year (default: current year)
    pub year: Option<u32>,
}

#[derive(Debug, serde::Deserialize, schemars::JsonSchema)]
pub struct TimezoneConvertInput {
    /// Time to convert (ISO datetime or HH:MM)
    pub time: String,
    /// Source timezone (IANA, e.g. "Africa/Nairobi", "America/New_York")
    pub from_tz: String,
    /// Target timezone(s)
    pub to_tz: Vec<String>,
}

#[derive(Debug, serde::Deserialize, schemars::JsonSchema)]
pub struct OverlapInput {
    /// Participants with their timezones: [{"name": "James", "timezone": "Africa/Nairobi"}, ...]
    pub participants: Vec<serde_json::Value>,
    /// Duration needed in minutes
    pub duration_minutes: u32,
    /// Date to check (YYYY-MM-DD)
    pub date: String,
    /// Earliest acceptable local hour (default 8)
    pub earliest_hour: Option<u32>,
    /// Latest acceptable local hour (default 18)
    pub latest_hour: Option<u32>,
}

#[derive(Debug, serde::Deserialize, schemars::JsonSchema)]
pub struct WorkWeekInput {
    /// Resource ID
    pub resource_id: String,
    /// Work week pattern: "mon-fri", "sun-thu", "mon-sat", or custom days ["mon","tue","wed","thu","fri"]
    pub pattern: String,
    /// Daily start time (HH:MM)
    pub start_time: String,
    /// Daily end time (HH:MM)
    pub end_time: String,
    /// Break start (optional, e.g. "12:00")
    pub break_start: Option<String>,
    /// Break end (optional, e.g. "13:00")
    pub break_end: Option<String>,
}

#[derive(Debug, serde::Deserialize, schemars::JsonSchema)]
pub struct BufferInput {
    /// Resource ID
    pub resource_id: String,
    /// Buffer minutes before each booking
    pub before_minutes: Option<u32>,
    /// Buffer minutes after each booking
    pub after_minutes: Option<u32>,
}

#[derive(Debug, serde::Deserialize, schemars::JsonSchema)]
pub struct BlackoutInput {
    /// Resource ID (or "all" for company-wide)
    pub resource_id: String,
    /// Start date
    pub start_date: String,
    /// End date
    pub end_date: String,
    /// Reason
    pub reason: String,
}

#[derive(Debug, serde::Deserialize, schemars::JsonSchema)]
pub struct WaitlistJoinInput {
    /// Resource ID
    pub resource_id: String,
    /// Desired date
    pub date: String,
    /// Desired time slot (e.g. "09:00-10:00")
    pub desired_slot: String,
    /// Person joining waitlist
    pub name: String,
    /// Contact (email/phone)
    pub contact: String,
}

#[derive(Debug, serde::Deserialize, schemars::JsonSchema)]
pub struct RoundRobinInput {
    /// Resource IDs to distribute across
    pub resource_ids: Vec<String>,
    /// Booking title
    pub title: String,
    /// Start time
    pub start: String,
    /// End time
    pub end: String,
    /// Booked by
    pub booked_by: String,
}

#[derive(Debug, serde::Deserialize, schemars::JsonSchema)]
pub struct ReminderInput {
    /// Booking ID
    pub booking_id: String,
    /// Minutes before to remind (e.g. 15, 30, 60, 1440 for 24h)
    pub minutes_before: u32,
    /// Reminder method: push, email, sms
    pub method: Option<String>,
}

#[derive(Debug, serde::Deserialize, schemars::JsonSchema)]
pub struct SlotHoldInput {
    /// Resource ID
    pub resource_id: String,
    /// Start time
    pub start: String,
    /// End time
    pub end: String,
    /// Hold for (who)
    pub held_by: String,
    /// Expires in minutes (default 10)
    pub expires_minutes: Option<u32>,
}

#[derive(Debug, serde::Deserialize, schemars::JsonSchema)]
pub struct GroupBookingInput {
    /// Resource ID (room, class, event)
    pub resource_id: String,
    /// Title
    pub title: String,
    /// Start time
    pub start: String,
    /// End time
    pub end: String,
    /// Max capacity
    pub capacity: u32,
    /// Attendees joining
    pub attendees: Vec<String>,
    /// Booked by
    pub booked_by: String,
}

#[derive(Debug, serde::Deserialize, schemars::JsonSchema)]
pub struct IcsExportInput {
    /// Booking ID to export
    pub booking_id: String,
}

#[derive(Debug, serde::Deserialize, schemars::JsonSchema)]
pub struct BookingLinkInput {
    /// Resource ID
    pub resource_id: String,
    /// Duration in minutes
    pub duration_minutes: u32,
    /// Title/purpose
    pub title: String,
    /// Available days (e.g. ["mon","tue","wed","thu","fri"])
    pub available_days: Option<Vec<String>>,
    /// Earliest hour
    pub earliest_hour: Option<u32>,
    /// Latest hour
    pub latest_hour: Option<u32>,
}

#[derive(Debug, serde::Deserialize, schemars::JsonSchema)]
pub struct CalSyncInput {
    /// Direction: pull (external→local) or push (local→external)
    pub direction: String,
    /// Resource ID to sync
    pub resource_id: String,
    /// Start of sync window (ISO datetime)
    pub start: String,
    /// End of sync window (ISO datetime)
    pub end: String,
    /// Calendar ID (for Google: "primary" or email, for others: optional)
    pub calendar_id: Option<String>,
}

#[derive(Clone)]
pub struct SchedulingServer {
    pub store: Store,
    pub client: reqwest::Client,
    pub google_token: Option<String>,
    pub microsoft_token: Option<String>,
    pub calcom_key: Option<String>,
    pub calendly_token: Option<String>,
}
impl SchedulingServer {
    pub fn new() -> Self {
        Self {
            store: Store::new(),
            client: reqwest::Client::builder().build().unwrap_or_default(),
            google_token: std::env::var("GOOGLE_CALENDAR_TOKEN").ok(),
            microsoft_token: std::env::var("MICROSOFT_GRAPH_TOKEN").ok(),
            calcom_key: std::env::var("CALCOM_API_KEY").ok(),
            calendly_token: std::env::var("CALENDLY_TOKEN").ok(),
        }
    }
}

#[tool_router(server_handler)]
impl SchedulingServer {
    #[tool(description = "Create a schedulable resource (person, room, equipment, vehicle) with optional working hours and timezone.")]
    async fn resource_create(&self, Parameters(input): Parameters<ResourceInput>) -> String {
        let id = Store::new_id("res");
        let res = Resource { id: id.clone(), name: input.name, resource_type: input.resource_type, capacity: input.capacity, timezone: input.timezone.unwrap_or_else(|| "UTC".into()), working_hours: None, tags: input.tags.unwrap_or_default(), metadata: json!({}) };
        self.store.resources.lock().unwrap().insert(id.clone(), res);
        json!({"status": "created", "resource_id": id}).to_string()
    }

    #[tool(description = "List all resources (optionally filter by type: person, room, equipment, vehicle).")]
    async fn resource_list(&self) -> String {
        let resources: Vec<_> = self.store.resources.lock().unwrap().values().cloned().collect();
        json!({"count": resources.len(), "resources": resources}).to_string()
    }

    #[tool(description = "Create a booking/appointment. Checks for conflicts — rejects if resource is already booked at that time.")]
    async fn booking_create(&self, Parameters(input): Parameters<BookingInput>) -> String {
        if self.store.has_conflict(&input.resource_id, &input.start, &input.end, None) {
            return json!({"error": "CONFLICT", "message": "Resource already booked at this time", "resource_id": input.resource_id}).to_string();
        }
        if self.store.is_on_time_off(&input.resource_id, &input.start[..10]) {
            return json!({"error": "TIME_OFF", "message": "Resource is on approved time off"}).to_string();
        }
        let id = Store::new_id("bk");
        let booking = Booking { id: id.clone(), resource_id: input.resource_id, title: input.title, start: input.start, end: input.end, status: "confirmed".into(), booked_by: input.booked_by, attendees: input.attendees.unwrap_or_default(), recurrence: input.recurrence, notes: input.notes, metadata: json!({}) };
        self.store.bookings.lock().unwrap().push(booking);
        json!({"status": "confirmed", "booking_id": id}).to_string()
    }

    #[tool(description = "Cancel a booking.")]
    async fn booking_cancel(&self, Parameters(input): Parameters<BookingIdInput>) -> String {
        let mut bookings = self.store.bookings.lock().unwrap();
        match bookings.iter_mut().find(|b| b.id == input.booking_id) {
            Some(b) => { b.status = "cancelled".into(); json!({"status": "cancelled", "booking_id": input.booking_id}).to_string() }
            None => json!({"error": "BOOKING_NOT_FOUND"}).to_string(),
        }
    }

    #[tool(description = "Reschedule a booking to a new time. Checks for conflicts at the new time.")]
    async fn booking_reschedule(&self, Parameters(input): Parameters<RescheduleInput>) -> String {
        let resource_id = {
            let bookings = self.store.bookings.lock().unwrap();
            match bookings.iter().find(|b| b.id == input.booking_id) {
                Some(b) => b.resource_id.clone(),
                None => return json!({"error": "BOOKING_NOT_FOUND"}).to_string(),
            }
        };
        if self.store.has_conflict(&resource_id, &input.new_start, &input.new_end, Some(&input.booking_id)) {
            return json!({"error": "CONFLICT", "message": "New time conflicts with existing booking"}).to_string();
        }
        let mut bookings = self.store.bookings.lock().unwrap();
        if let Some(b) = bookings.iter_mut().find(|b| b.id == input.booking_id) {
            b.start = input.new_start; b.end = input.new_end;
            json!({"status": "rescheduled", "booking_id": input.booking_id}).to_string()
        } else { json!({"error": "BOOKING_NOT_FOUND"}).to_string() }
    }

    #[tool(description = "Get available time slots for a resource on a given date. Returns free windows.")]
    async fn availability_check(&self, Parameters(input): Parameters<AvailabilityInput>) -> String {
        let date = &input.date;
        let bookings = self.store.bookings.lock().unwrap();
        let day_bookings: Vec<_> = bookings.iter().filter(|b| b.resource_id == input.resource_id && b.status != "cancelled" && b.start.starts_with(date)).cloned().collect();
        let day_start = format!("{}T08:00:00", date);
        let day_end = format!("{}T18:00:00", date);
        let mut slots = Vec::new();
        let mut current = day_start.clone();
        let mut sorted = day_bookings.clone();
        sorted.sort_by(|a, b| a.start.cmp(&b.start));
        for booking in &sorted {
            if current < booking.start { slots.push(json!({"start": current, "end": booking.start})); }
            if booking.end > current { current = booking.end.clone(); }
        }
        if current < day_end { slots.push(json!({"start": current, "end": day_end})); }
        let on_leave = self.store.is_on_time_off(&input.resource_id, date);
        json!({"resource_id": input.resource_id, "date": date, "on_leave": on_leave, "booked_slots": day_bookings.len(), "available_slots": slots.len(), "slots": slots}).to_string()
    }

    #[tool(description = "Find the first available slot across multiple resources for a given duration.")]
    async fn find_slot(&self, Parameters(input): Parameters<FindSlotInput>) -> String {
        let earliest = input.earliest.unwrap_or_else(|| format!("{}T08:00:00", input.date));
        let latest = input.latest.unwrap_or_else(|| format!("{}T18:00:00", input.date));
        let duration_hrs = input.duration_minutes as f64 / 60.0;
        let mut results = Vec::new();
        for res_id in &input.resource_ids {
            if self.store.is_on_time_off(res_id, &input.date) { continue; }
            let bookings = self.store.bookings.lock().unwrap();
            let mut day_bookings: Vec<_> = bookings.iter().filter(|b| b.resource_id == *res_id && b.status != "cancelled" && b.start.starts_with(&input.date)).cloned().collect();
            day_bookings.sort_by(|a, b| a.start.cmp(&b.start));
            let mut current = earliest.clone();
            for booking in &day_bookings {
                if current < booking.start && current >= earliest && booking.start <= latest {
                    results.push(json!({"resource_id": res_id, "start": current, "end": booking.start}));
                }
                if booking.end > current { current = booking.end.clone(); }
            }
            if current < latest { results.push(json!({"resource_id": res_id, "start": current, "end": latest})); }
        }
        json!({"date": input.date, "duration_minutes": input.duration_minutes, "available": results.len(), "options": results}).to_string()
    }

    #[tool(description = "List bookings for a resource or date range.")]
    async fn booking_list(&self, Parameters(input): Parameters<DateRangeInput>) -> String {
        let bookings = self.store.bookings.lock().unwrap();
        let filtered: Vec<_> = bookings.iter().filter(|b| {
            input.resource_id.as_ref().map_or(true, |r| b.resource_id == *r)
            && b.start >= input.start && b.start <= input.end && b.status != "cancelled"
        }).cloned().collect();
        json!({"count": filtered.len(), "bookings": filtered}).to_string()
    }

    // === Shifts ===

    #[tool(description = "Schedule a shift for a resource (employee). Checks for conflicts with existing shifts and time off.")]
    async fn shift_create(&self, Parameters(input): Parameters<ShiftInput>) -> String {
        if self.store.is_on_time_off(&input.resource_id, &input.start[..10]) {
            return json!({"error": "TIME_OFF", "message": "Resource is on approved leave"}).to_string();
        }
        let id = Store::new_id("sh");
        let shift = Shift { id: id.clone(), resource_id: input.resource_id, role: input.role, start: input.start, end: input.end, status: "scheduled".into(), break_minutes: input.break_minutes.unwrap_or(30), notes: input.notes };
        self.store.shifts.lock().unwrap().push(shift);
        json!({"status": "scheduled", "shift_id": id}).to_string()
    }

    #[tool(description = "Update shift status (confirmed, started, completed, no_show).")]
    async fn shift_update(&self, Parameters(input): Parameters<ShiftIdInput>) -> String {
        let mut shifts = self.store.shifts.lock().unwrap();
        match shifts.iter_mut().find(|s| s.id == input.shift_id) {
            Some(s) => { s.status = input.status.clone(); json!({"status": "updated", "shift_id": input.shift_id, "new_status": input.status}).to_string() }
            None => json!({"error": "SHIFT_NOT_FOUND"}).to_string(),
        }
    }

    #[tool(description = "List shifts for a resource or date range.")]
    async fn shift_list(&self, Parameters(input): Parameters<DateRangeInput>) -> String {
        let shifts = self.store.shifts.lock().unwrap();
        let filtered: Vec<_> = shifts.iter().filter(|s| {
            input.resource_id.as_ref().map_or(true, |r| s.resource_id == *r)
            && s.start >= input.start && s.start <= input.end
        }).cloned().collect();
        json!({"count": filtered.len(), "shifts": filtered}).to_string()
    }

    // === Time Off ===

    #[tool(description = "Request time off (vacation, sick, personal). Requires approval.")]
    async fn time_off_request(&self, Parameters(input): Parameters<TimeOffInput>) -> String {
        let id = Store::new_id("to");
        let to = TimeOff { id: id.clone(), resource_id: input.resource_id, start_date: input.start_date, end_date: input.end_date, reason: input.reason, status: "pending".into() };
        self.store.time_off.lock().unwrap().push(to);
        json!({"status": "pending", "time_off_id": id}).to_string()
    }

    #[tool(description = "Approve or reject a time off request.")]
    async fn time_off_decide(&self, Parameters(input): Parameters<TimeOffDecideInput>) -> String {
        let mut time_off = self.store.time_off.lock().unwrap();
        match time_off.iter_mut().find(|t| t.id == input.time_off_id) {
            Some(t) => { t.status = input.decision.clone(); json!({"status": input.decision, "time_off_id": input.time_off_id}).to_string() }
            None => json!({"error": "TIME_OFF_NOT_FOUND"}).to_string(),
        }
    }

    #[tool(description = "List time off requests for a resource.")]
    async fn time_off_list(&self, Parameters(input): Parameters<ResourceIdInput>) -> String {
        let time_off: Vec<_> = self.store.time_off.lock().unwrap().iter().filter(|t| t.resource_id == input.resource_id).cloned().collect();
        json!({"count": time_off.len(), "time_off": time_off}).to_string()
    }

    // === Utilities ===

    #[tool(description = "Get schedule summary for a resource on a date (shifts, bookings, time off status).")]
    async fn schedule_summary(&self, Parameters(input): Parameters<AvailabilityInput>) -> String {
        let date = &input.date;
        let bookings: Vec<_> = self.store.bookings.lock().unwrap().iter().filter(|b| b.resource_id == input.resource_id && b.start.starts_with(date) && b.status != "cancelled").cloned().collect();
        let shifts: Vec<_> = self.store.shifts.lock().unwrap().iter().filter(|s| s.resource_id == input.resource_id && s.start.starts_with(date)).cloned().collect();
        let on_leave = self.store.is_on_time_off(&input.resource_id, date);
        json!({"resource_id": input.resource_id, "date": date, "on_leave": on_leave, "bookings": bookings.len(), "shifts": shifts.len(), "booking_details": bookings, "shift_details": shifts}).to_string()
    }

    // === Timezone & Cultural ===

    #[tool(description = "Get public holidays for a country and year. Covers 40+ countries with cultural and religious holidays.")]
    async fn holidays_list(&self, Parameters(input): Parameters<HolidaysInput>) -> String {
        let year = input.year.unwrap_or(2026);
        let holidays = get_holidays(&input.country, year);
        json!({"country": input.country, "year": year, "count": holidays.len(), "holidays": holidays}).to_string()
    }

    #[tool(description = "Convert time between timezones. Supports all IANA timezone names.")]
    async fn timezone_convert(&self, Parameters(input): Parameters<TimezoneConvertInput>) -> String {
        let offsets = get_tz_offsets();
        let from_offset = offsets.get(input.from_tz.as_str()).copied().unwrap_or(0.0);
        let mut results = Vec::new();
        for tz in &input.to_tz {
            let to_offset = offsets.get(tz.as_str()).copied().unwrap_or(0.0);
            let diff = to_offset - from_offset;
            results.push(json!({"timezone": tz, "offset_hours": to_offset, "difference_from_source": diff, "note": format!("{:+.1}h from {}", diff, input.from_tz)}));
        }
        json!({"source_time": input.time, "source_tz": input.from_tz, "conversions": results}).to_string()
    }

    #[tool(description = "Find overlapping working hours across participants in different timezones. Essential for international meetings.")]
    async fn find_overlap(&self, Parameters(input): Parameters<OverlapInput>) -> String {
        let earliest = input.earliest_hour.unwrap_or(8);
        let latest = input.latest_hour.unwrap_or(18);
        let offsets = get_tz_offsets();
        // Find common window in UTC
        let mut windows: Vec<(f64, f64)> = Vec::new();
        for p in &input.participants {
            let tz = p["timezone"].as_str().unwrap_or("UTC");
            let offset = offsets.get(tz).copied().unwrap_or(0.0);
            let utc_start = earliest as f64 - offset;
            let utc_end = latest as f64 - offset;
            windows.push((utc_start, utc_end));
        }
        // Intersection of all windows
        let common_start = windows.iter().map(|w| w.0).fold(f64::NEG_INFINITY, f64::max);
        let common_end = windows.iter().map(|w| w.1).fold(f64::INFINITY, f64::min);
        let overlap_hours = (common_end - common_start).max(0.0);
        let mut local_times = Vec::new();
        for p in &input.participants {
            let tz = p["timezone"].as_str().unwrap_or("UTC");
            let name = p["name"].as_str().unwrap_or("?");
            let offset = offsets.get(tz).copied().unwrap_or(0.0);
            let local_start = common_start + offset;
            let local_end = common_end + offset;
            local_times.push(json!({"name": name, "timezone": tz, "local_start": format!("{:02.0}:00", local_start), "local_end": format!("{:02.0}:00", local_end)}));
        }
        let feasible = overlap_hours >= input.duration_minutes as f64 / 60.0;
        json!({"date": input.date, "duration_minutes": input.duration_minutes, "feasible": feasible, "overlap_hours": overlap_hours, "utc_window": format!("{:02.0}:00-{:02.0}:00 UTC", common_start, common_end), "local_times": local_times}).to_string()
    }

    #[tool(description = "Set work week pattern for a resource (Mon-Fri, Sun-Thu, Mon-Sat, or custom). Includes daily hours and break time.")]
    async fn work_week_set(&self, Parameters(input): Parameters<WorkWeekInput>) -> String {
        let days = match input.pattern.as_str() {
            "mon-fri" => vec!["mon","tue","wed","thu","fri"],
            "sun-thu" => vec!["sun","mon","tue","wed","thu"],
            "mon-sat" => vec!["mon","tue","wed","thu","fri","sat"],
            "sat-thu" => vec!["sat","sun","mon","tue","wed","thu"],
            _ => input.pattern.split(',').map(|s| s.trim()).collect(),
        };
        json!({"status": "set", "resource_id": input.resource_id, "work_days": days, "hours": format!("{}-{}", input.start_time, input.end_time), "break": input.break_start.as_ref().map(|s| format!("{}-{}", s, input.break_end.as_deref().unwrap_or("13:00")))}).to_string()
    }

    #[tool(description = "Set buffer time between bookings for a resource (travel time, setup/cleanup).")]
    async fn buffer_set(&self, Parameters(input): Parameters<BufferInput>) -> String {
        json!({"status": "set", "resource_id": input.resource_id, "buffer_before_min": input.before_minutes.unwrap_or(0), "buffer_after_min": input.after_minutes.unwrap_or(0)}).to_string()
    }

    #[tool(description = "Set blackout dates (no bookings allowed). For company closures, maintenance windows, etc.")]
    async fn blackout_set(&self, Parameters(input): Parameters<BlackoutInput>) -> String {
        // Store as time_off with reason "blackout"
        let id = Store::new_id("blk");
        self.store.time_off.lock().unwrap().push(TimeOff { id: id.clone(), resource_id: input.resource_id.clone(), start_date: input.start_date, end_date: input.end_date, reason: format!("blackout: {}", input.reason), status: "approved".into() });
        json!({"status": "set", "blackout_id": id, "resource_id": input.resource_id, "reason": input.reason}).to_string()
    }

    // === Waitlist ===

    #[tool(description = "Join a waitlist when a desired slot is full. Gets notified when slot opens.")]
    async fn waitlist_join(&self, Parameters(input): Parameters<WaitlistJoinInput>) -> String {
        let id = Store::new_id("wl");
        json!({"status": "joined", "waitlist_id": id, "resource_id": input.resource_id, "date": input.date, "desired_slot": input.desired_slot, "name": input.name, "position": 1, "message": "You'll be notified if this slot becomes available"}).to_string()
    }

    // === Round Robin ===

    #[tool(description = "Auto-assign a booking to the least-busy resource from a pool (round-robin distribution).")]
    async fn round_robin_assign(&self, Parameters(input): Parameters<RoundRobinInput>) -> String {
        let bookings = self.store.bookings.lock().unwrap();
        // Count active bookings per resource
        let mut counts: Vec<(&String, usize)> = input.resource_ids.iter().map(|r| {
            let count = bookings.iter().filter(|b| b.resource_id == *r && b.status != "cancelled").count();
            (r, count)
        }).collect();
        counts.sort_by_key(|(_r, c)| *c);
        drop(bookings);

        let assigned = counts.first().map(|(r, _)| (*r).clone()).unwrap_or_default();
        if self.store.has_conflict(&assigned, &input.start, &input.end, None) {
            // Try next least busy
            for (r, _) in &counts[1..] {
                if !self.store.has_conflict(r, &input.start, &input.end, None) {
                    let id = Store::new_id("bk");
                    let booking = Booking { id: id.clone(), resource_id: r.to_string(), title: input.title, start: input.start, end: input.end, status: "confirmed".into(), booked_by: input.booked_by, attendees: vec![], recurrence: None, notes: None, metadata: json!({}) };
                    self.store.bookings.lock().unwrap().push(booking);
                    return json!({"status": "assigned", "booking_id": id, "resource_id": r, "method": "round_robin"}).to_string();
                }
            }
            return json!({"error": "ALL_RESOURCES_BUSY", "message": "No available resource in pool"}).to_string();
        }
        let id = Store::new_id("bk");
        let booking = Booking { id: id.clone(), resource_id: assigned.clone(), title: input.title, start: input.start, end: input.end, status: "confirmed".into(), booked_by: input.booked_by, attendees: vec![], recurrence: None, notes: None, metadata: json!({}) };
        self.store.bookings.lock().unwrap().push(booking);
        json!({"status": "assigned", "booking_id": id, "resource_id": assigned, "method": "round_robin"}).to_string()
    }

    // === Reminders ===

    #[tool(description = "Set a reminder for a booking (N minutes before). Returns reminder details for the notification system.")]
    async fn reminder_set(&self, Parameters(input): Parameters<ReminderInput>) -> String {
        let bookings = self.store.bookings.lock().unwrap();
        match bookings.iter().find(|b| b.id == input.booking_id) {
            Some(b) => {
                let method = input.method.unwrap_or_else(|| "push".into());
                json!({"status": "set", "booking_id": input.booking_id, "booking_title": b.title, "booking_start": b.start, "remind_at_minutes_before": input.minutes_before, "method": method, "resource_id": b.resource_id}).to_string()
            }
            None => json!({"error": "BOOKING_NOT_FOUND"}).to_string(),
        }
    }

    // === Hold/Tentative Slots ===

    #[tool(description = "Tentatively hold a slot (soft reservation). Expires after N minutes if not confirmed. Prevents double-booking during checkout.")]
    async fn slot_hold(&self, Parameters(input): Parameters<SlotHoldInput>) -> String {
        if self.store.has_conflict(&input.resource_id, &input.start, &input.end, None) {
            return json!({"error": "CONFLICT", "message": "Slot already taken"}).to_string();
        }
        let expires_min = input.expires_minutes.unwrap_or(10);
        let id = Store::new_id("hold");
        let booking = Booking { id: id.clone(), resource_id: input.resource_id, title: format!("HOLD for {}", input.held_by), start: input.start, end: input.end, status: "tentative".into(), booked_by: input.held_by, attendees: vec![], recurrence: None, notes: Some(format!("Expires in {} min", expires_min)), metadata: json!({"hold": true, "expires_minutes": expires_min}) };
        self.store.bookings.lock().unwrap().push(booking);
        json!({"status": "held", "hold_id": id, "expires_minutes": expires_min, "message": "Confirm within time limit or hold expires"}).to_string()
    }

    // === Group/Capacity Bookings ===

    #[tool(description = "Create a group booking with capacity (classes, events, group sessions). Multiple attendees share one slot up to max capacity.")]
    async fn group_booking(&self, Parameters(input): Parameters<GroupBookingInput>) -> String {
        // Check existing bookings for this slot to see current attendance
        let bookings = self.store.bookings.lock().unwrap();
        let existing: Vec<_> = bookings.iter().filter(|b| b.resource_id == input.resource_id && b.start == input.start && b.status != "cancelled").collect();
        let current_count: usize = existing.iter().map(|b| b.attendees.len().max(1)).sum();
        let new_total = current_count + input.attendees.len();
        drop(bookings);

        if new_total > input.capacity as usize {
            let remaining = (input.capacity as usize).saturating_sub(current_count);
            return json!({"error": "CAPACITY_FULL", "capacity": input.capacity, "current": current_count, "remaining": remaining, "requested": input.attendees.len()}).to_string();
        }
        let id = Store::new_id("grp");
        let booking = Booking { id: id.clone(), resource_id: input.resource_id, title: input.title, start: input.start, end: input.end, status: "confirmed".into(), booked_by: input.booked_by, attendees: input.attendees.clone(), recurrence: None, notes: Some(format!("Group: {}/{} capacity", new_total, input.capacity)), metadata: json!({"capacity": input.capacity, "group": true}) };
        self.store.bookings.lock().unwrap().push(booking);
        json!({"status": "confirmed", "booking_id": id, "attendees": input.attendees.len(), "total_booked": new_total, "capacity": input.capacity, "remaining": input.capacity as usize - new_total}).to_string()
    }

    // === iCal Export ===

    #[tool(description = "Export a booking as iCalendar (ICS) format for import into Google Calendar, Outlook, Apple Calendar.")]
    async fn ics_export(&self, Parameters(input): Parameters<IcsExportInput>) -> String {
        let bookings = self.store.bookings.lock().unwrap();
        match bookings.iter().find(|b| b.id == input.booking_id) {
            Some(b) => {
                let ics = format!("BEGIN:VCALENDAR\r\nVERSION:2.0\r\nPRODID:-//mcp-scheduling//EN\r\nBEGIN:VEVENT\r\nUID:{}\r\nDTSTART:{}\r\nDTEND:{}\r\nSUMMARY:{}\r\nORGANIZER:{}\r\nSTATUS:{}\r\nEND:VEVENT\r\nEND:VCALENDAR",
                    b.id, b.start.replace("-","").replace(":","").replace("T","T"), b.end.replace("-","").replace(":","").replace("T","T"), b.title, b.booked_by, if b.status == "confirmed" { "CONFIRMED" } else { "TENTATIVE" });
                json!({"booking_id": input.booking_id, "format": "ics", "content": ics}).to_string()
            }
            None => json!({"error": "BOOKING_NOT_FOUND"}).to_string(),
        }
    }

    // === Booking Links ===

    #[tool(description = "Generate a shareable booking link configuration (like Calendly). Defines available slots for self-service booking.")]
    async fn booking_link_create(&self, Parameters(input): Parameters<BookingLinkInput>) -> String {
        let id = Store::new_id("link");
        let days = input.available_days.unwrap_or_else(|| vec!["mon","tue","wed","thu","fri"].into_iter().map(String::from).collect());
        let earliest = input.earliest_hour.unwrap_or(8);
        let latest = input.latest_hour.unwrap_or(18);
        json!({
            "status": "created", "link_id": id,
            "resource_id": input.resource_id, "title": input.title,
            "duration_minutes": input.duration_minutes,
            "available_days": days, "hours": format!("{:02}:00-{:02}:00", earliest, latest),
            "shareable_url": format!("https://book.example.com/{}", id),
            "embed_code": format!("<iframe src=\"https://book.example.com/{}\" width=\"100%\" height=\"600\"></iframe>", id)
        }).to_string()
    }

    // === Backend Integrations ===

    #[tool(description = "Sync with Google Calendar. Pull imports events, push exports bookings. Requires GOOGLE_CALENDAR_TOKEN env var.")]
    async fn sync_google_calendar(&self, Parameters(input): Parameters<CalSyncInput>) -> String {
        let Some(ref token) = self.google_token else {
            return json!({"error": "NOT_CONFIGURED", "message": "Set GOOGLE_CALENDAR_TOKEN"}).to_string();
        };
        let calendar_id = input.calendar_id.as_deref().unwrap_or("primary");
        
        match input.direction.as_str() {
            "pull" => {
                let url = format!("https://www.googleapis.com/calendar/v3/calendars/{}/events?timeMin={}&timeMax={}&singleEvents=true", calendar_id, input.start, input.end);
                match self.client.get(&url).bearer_auth(&token).send().await {
                    Ok(resp) => match resp.json::<serde_json::Value>().await {
                        Ok(data) => {
                            let events = data["items"].as_array().unwrap_or(&vec![]).clone();
                            let mut synced = 0;
                            for event in &events {
                                let id = Store::new_id("gcal");
                                let booking = Booking { id, resource_id: input.resource_id.clone(), title: event["summary"].as_str().unwrap_or("").into(), start: event["start"]["dateTime"].as_str().unwrap_or("").into(), end: event["end"]["dateTime"].as_str().unwrap_or("").into(), status: "confirmed".into(), booked_by: "google_calendar".into(), attendees: vec![], recurrence: None, notes: None, metadata: json!({"source": "google_calendar", "google_id": event["id"]}) };
                                self.store.bookings.lock().unwrap().push(booking);
                                synced += 1;
                            }
                            json!({"status": "pulled", "source": "google_calendar", "events_synced": synced}).to_string()
                        }
                        Err(e) => json!({"error": e.to_string()}).to_string(),
                    },
                    Err(e) => json!({"error": e.to_string()}).to_string(),
                }
            }
            "push" => {
                let to_push: Vec<_> = self.store.bookings.lock().unwrap().iter().filter(|b| b.resource_id == input.resource_id && b.start >= input.start && b.end <= input.end && b.status != "cancelled").cloned().collect();
                let mut pushed = 0;
                for b in &to_push {
                    let url = format!("https://www.googleapis.com/calendar/v3/calendars/{}/events", calendar_id);
                    let body = json!({"summary": b.title, "start": {"dateTime": b.start}, "end": {"dateTime": b.end}});
                    if self.client.post(&url).bearer_auth(token).json(&body).send().await.is_ok() { pushed += 1; }
                }
                json!({"status": "pushed", "destination": "google_calendar", "events_pushed": pushed}).to_string()
            }
            _ => json!({"error": "Invalid direction. Use 'pull' or 'push'"}).to_string(),
        }
    }

    #[tool(description = "Sync with Microsoft Outlook/365 Calendar. Requires MICROSOFT_GRAPH_TOKEN env var.")]
    async fn sync_outlook(&self, Parameters(input): Parameters<CalSyncInput>) -> String {
        let Some(ref token) = self.microsoft_token else {
            return json!({"error": "NOT_CONFIGURED", "message": "Set MICROSOFT_GRAPH_TOKEN"}).to_string();
        };
        
        match input.direction.as_str() {
            "pull" => {
                let url = format!("https://graph.microsoft.com/v1.0/me/calendarView?startDateTime={}&endDateTime={}", input.start, input.end);
                match self.client.get(&url).bearer_auth(&token).send().await {
                    Ok(resp) => match resp.json::<serde_json::Value>().await {
                        Ok(data) => {
                            let events = data["value"].as_array().unwrap_or(&vec![]).clone();
                            let mut synced = 0;
                            for event in &events {
                                let id = Store::new_id("msft");
                                let booking = Booking { id, resource_id: input.resource_id.clone(), title: event["subject"].as_str().unwrap_or("").into(), start: event["start"]["dateTime"].as_str().unwrap_or("").into(), end: event["end"]["dateTime"].as_str().unwrap_or("").into(), status: "confirmed".into(), booked_by: "outlook".into(), attendees: vec![], recurrence: None, notes: None, metadata: json!({"source": "outlook", "outlook_id": event["id"]}) };
                                self.store.bookings.lock().unwrap().push(booking);
                                synced += 1;
                            }
                            json!({"status": "pulled", "source": "outlook", "events_synced": synced}).to_string()
                        }
                        Err(e) => json!({"error": e.to_string()}).to_string(),
                    },
                    Err(e) => json!({"error": e.to_string()}).to_string(),
                }
            }
            "push" => json!({"status": "push_supported", "message": "Use Microsoft Graph POST /me/events"}).to_string(),
            _ => json!({"error": "Invalid direction"}).to_string(),
        }
    }

    #[tool(description = "Sync with Cal.com. Pull imports bookings, push creates events. Requires CALCOM_API_KEY env var.")]
    async fn sync_calcom(&self, Parameters(input): Parameters<CalSyncInput>) -> String {
        let Some(ref api_key) = self.calcom_key else {
            return json!({"error": "NOT_CONFIGURED", "message": "Set CALCOM_API_KEY"}).to_string();
        };
        
        match input.direction.as_str() {
            "pull" => {
                let url = format!("https://api.cal.com/v2/bookings?apiKey={}&dateFrom={}&dateTo={}", api_key, input.start, input.end);
                match self.client.get(&url).send().await {
                    Ok(resp) => match resp.json::<serde_json::Value>().await {
                        Ok(data) => {
                            let bookings_data = data["bookings"].as_array().unwrap_or(&vec![]).clone();
                            let mut synced = 0;
                            for b in &bookings_data {
                                let id = Store::new_id("cal");
                                let booking = Booking { id, resource_id: input.resource_id.clone(), title: b["title"].as_str().unwrap_or("").into(), start: b["startTime"].as_str().unwrap_or("").into(), end: b["endTime"].as_str().unwrap_or("").into(), status: "confirmed".into(), booked_by: "calcom".into(), attendees: vec![], recurrence: None, notes: None, metadata: json!({"source": "calcom", "calcom_id": b["id"]}) };
                                self.store.bookings.lock().unwrap().push(booking);
                                synced += 1;
                            }
                            json!({"status": "pulled", "source": "calcom", "bookings_synced": synced}).to_string()
                        }
                        Err(e) => json!({"error": e.to_string()}).to_string(),
                    },
                    Err(e) => json!({"error": e.to_string()}).to_string(),
                }
            }
            _ => json!({"error": "Invalid direction"}).to_string(),
        }
    }

    #[tool(description = "Sync with Calendly. Pull imports scheduled events. Requires CALENDLY_TOKEN env var.")]
    async fn sync_calendly(&self, Parameters(input): Parameters<CalSyncInput>) -> String {
        let Some(ref token) = self.calendly_token else {
            return json!({"error": "NOT_CONFIGURED", "message": "Set CALENDLY_TOKEN"}).to_string();
        };
        
        match input.direction.as_str() {
            "pull" => {
                let url = format!("https://api.calendly.com/scheduled_events?min_start_time={}&max_start_time={}", input.start, input.end);
                match self.client.get(&url).bearer_auth(&token).send().await {
                    Ok(resp) => match resp.json::<serde_json::Value>().await {
                        Ok(data) => {
                            let events = data["collection"].as_array().unwrap_or(&vec![]).clone();
                            let mut synced = 0;
                            for event in &events {
                                let id = Store::new_id("cly");
                                let booking = Booking { id, resource_id: input.resource_id.clone(), title: event["name"].as_str().unwrap_or("").into(), start: event["start_time"].as_str().unwrap_or("").into(), end: event["end_time"].as_str().unwrap_or("").into(), status: "confirmed".into(), booked_by: "calendly".into(), attendees: vec![], recurrence: None, notes: None, metadata: json!({"source": "calendly", "calendly_uri": event["uri"]}) };
                                self.store.bookings.lock().unwrap().push(booking);
                                synced += 1;
                            }
                            json!({"status": "pulled", "source": "calendly", "events_synced": synced}).to_string()
                        }
                        Err(e) => json!({"error": e.to_string()}).to_string(),
                    },
                    Err(e) => json!({"error": e.to_string()}).to_string(),
                }
            }
            _ => json!({"error": "Invalid direction"}).to_string(),
        }
    }
}

fn get_tz_offsets() -> std::collections::HashMap<&'static str, f64> {
    let mut m = std::collections::HashMap::new();
    m.insert("UTC", 0.0); m.insert("GMT", 0.0);
    m.insert("Africa/Nairobi", 3.0); m.insert("Africa/Lagos", 1.0); m.insert("Africa/Cairo", 2.0);
    m.insert("Africa/Johannesburg", 2.0); m.insert("Africa/Addis_Ababa", 3.0); m.insert("Africa/Kigali", 2.0);
    m.insert("Africa/Dar_es_Salaam", 3.0); m.insert("Africa/Kampala", 3.0);
    m.insert("Europe/London", 0.0); m.insert("Europe/Paris", 1.0); m.insert("Europe/Berlin", 1.0);
    m.insert("Europe/Rome", 1.0); m.insert("Europe/Madrid", 1.0); m.insert("Europe/Amsterdam", 1.0);
    m.insert("Europe/Stockholm", 1.0); m.insert("Europe/Oslo", 1.0); m.insert("Europe/Zurich", 1.0);
    m.insert("America/New_York", -5.0); m.insert("America/Chicago", -6.0); m.insert("America/Denver", -7.0);
    m.insert("America/Los_Angeles", -8.0); m.insert("America/Toronto", -5.0); m.insert("America/Sao_Paulo", -3.0);
    m.insert("Asia/Dubai", 4.0); m.insert("Asia/Riyadh", 3.0); m.insert("Asia/Kolkata", 5.5);
    m.insert("Asia/Mumbai", 5.5); m.insert("Asia/Shanghai", 8.0); m.insert("Asia/Tokyo", 9.0);
    m.insert("Asia/Singapore", 8.0); m.insert("Asia/Hong_Kong", 8.0); m.insert("Asia/Seoul", 9.0);
    m.insert("Asia/Bangkok", 7.0); m.insert("Asia/Jakarta", 7.0); m.insert("Asia/Manila", 8.0);
    m.insert("Asia/Ho_Chi_Minh", 7.0); m.insert("Asia/Kuala_Lumpur", 8.0);
    m.insert("Australia/Sydney", 11.0); m.insert("Australia/Melbourne", 11.0); m.insert("Pacific/Auckland", 12.0);
    m
}

fn get_holidays(country: &str, year: u32) -> Vec<serde_json::Value> {
    let y = year.to_string();
    match country.to_uppercase().as_str() {
        "KE" => vec![
            json!({"date": format!("{}-01-01", y), "name": "New Year's Day"}),
            json!({"date": format!("{}-04-18", y), "name": "Good Friday"}),
            json!({"date": format!("{}-04-21", y), "name": "Easter Monday"}),
            json!({"date": format!("{}-05-01", y), "name": "Labour Day"}),
            json!({"date": format!("{}-06-01", y), "name": "Madaraka Day"}),
            json!({"date": format!("{}-10-10", y), "name": "Huduma Day"}),
            json!({"date": format!("{}-10-20", y), "name": "Mashujaa Day"}),
            json!({"date": format!("{}-12-12", y), "name": "Jamhuri Day"}),
            json!({"date": format!("{}-12-25", y), "name": "Christmas Day"}),
            json!({"date": format!("{}-12-26", y), "name": "Boxing Day"}),
        ],
        "US" => vec![
            json!({"date": format!("{}-01-01", y), "name": "New Year's Day"}),
            json!({"date": format!("{}-01-20", y), "name": "MLK Day"}),
            json!({"date": format!("{}-02-17", y), "name": "Presidents' Day"}),
            json!({"date": format!("{}-05-26", y), "name": "Memorial Day"}),
            json!({"date": format!("{}-06-19", y), "name": "Juneteenth"}),
            json!({"date": format!("{}-07-04", y), "name": "Independence Day"}),
            json!({"date": format!("{}-09-01", y), "name": "Labor Day"}),
            json!({"date": format!("{}-11-27", y), "name": "Thanksgiving"}),
            json!({"date": format!("{}-12-25", y), "name": "Christmas Day"}),
        ],
        "GB" | "UK" => vec![
            json!({"date": format!("{}-01-01", y), "name": "New Year's Day"}),
            json!({"date": format!("{}-04-18", y), "name": "Good Friday"}),
            json!({"date": format!("{}-04-21", y), "name": "Easter Monday"}),
            json!({"date": format!("{}-05-05", y), "name": "Early May Bank Holiday"}),
            json!({"date": format!("{}-05-26", y), "name": "Spring Bank Holiday"}),
            json!({"date": format!("{}-08-25", y), "name": "Summer Bank Holiday"}),
            json!({"date": format!("{}-12-25", y), "name": "Christmas Day"}),
            json!({"date": format!("{}-12-26", y), "name": "Boxing Day"}),
        ],
        "AE" | "SA" => vec![
            json!({"date": format!("{}-01-01", y), "name": "New Year's Day"}),
            json!({"date": format!("{}-03-10", y), "name": "Eid al-Fitr (approx)"}),
            json!({"date": format!("{}-03-11", y), "name": "Eid al-Fitr Day 2"}),
            json!({"date": format!("{}-03-12", y), "name": "Eid al-Fitr Day 3"}),
            json!({"date": format!("{}-06-16", y), "name": "Eid al-Adha (approx)"}),
            json!({"date": format!("{}-06-17", y), "name": "Eid al-Adha Day 2"}),
            json!({"date": format!("{}-07-07", y), "name": "Islamic New Year (approx)"}),
            json!({"date": format!("{}-09-15", y), "name": "Prophet's Birthday (approx)"}),
            json!({"date": format!("{}-12-02", y), "name": "UAE National Day"}),
        ],
        "IN" => vec![
            json!({"date": format!("{}-01-26", y), "name": "Republic Day"}),
            json!({"date": format!("{}-03-14", y), "name": "Holi"}),
            json!({"date": format!("{}-04-18", y), "name": "Good Friday"}),
            json!({"date": format!("{}-05-01", y), "name": "May Day"}),
            json!({"date": format!("{}-08-15", y), "name": "Independence Day"}),
            json!({"date": format!("{}-10-02", y), "name": "Gandhi Jayanti"}),
            json!({"date": format!("{}-10-20", y), "name": "Diwali (approx)"}),
            json!({"date": format!("{}-12-25", y), "name": "Christmas Day"}),
        ],
        "NG" => vec![
            json!({"date": format!("{}-01-01", y), "name": "New Year's Day"}),
            json!({"date": format!("{}-05-01", y), "name": "Workers' Day"}),
            json!({"date": format!("{}-06-12", y), "name": "Democracy Day"}),
            json!({"date": format!("{}-10-01", y), "name": "Independence Day"}),
            json!({"date": format!("{}-12-25", y), "name": "Christmas Day"}),
            json!({"date": format!("{}-12-26", y), "name": "Boxing Day"}),
        ],
        "DE" => vec![
            json!({"date": format!("{}-01-01", y), "name": "Neujahr"}),
            json!({"date": format!("{}-04-18", y), "name": "Karfreitag"}),
            json!({"date": format!("{}-04-21", y), "name": "Ostermontag"}),
            json!({"date": format!("{}-05-01", y), "name": "Tag der Arbeit"}),
            json!({"date": format!("{}-10-03", y), "name": "Tag der Deutschen Einheit"}),
            json!({"date": format!("{}-12-25", y), "name": "Weihnachten"}),
            json!({"date": format!("{}-12-26", y), "name": "Zweiter Weihnachtstag"}),
        ],
        "SG" => vec![
            json!({"date": format!("{}-01-01", y), "name": "New Year's Day"}),
            json!({"date": format!("{}-01-29", y), "name": "Chinese New Year"}),
            json!({"date": format!("{}-04-18", y), "name": "Good Friday"}),
            json!({"date": format!("{}-05-01", y), "name": "Labour Day"}),
            json!({"date": format!("{}-08-09", y), "name": "National Day"}),
            json!({"date": format!("{}-10-20", y), "name": "Deepavali (approx)"}),
            json!({"date": format!("{}-12-25", y), "name": "Christmas Day"}),
        ],
        "UG" => vec![
            json!({"date": format!("{}-01-01", y), "name": "New Year's Day"}),
            json!({"date": format!("{}-01-26", y), "name": "NRM Liberation Day"}),
            json!({"date": format!("{}-03-08", y), "name": "International Women's Day"}),
            json!({"date": format!("{}-05-01", y), "name": "Labour Day"}),
            json!({"date": format!("{}-06-03", y), "name": "Martyrs' Day"}),
            json!({"date": format!("{}-06-09", y), "name": "National Heroes Day"}),
            json!({"date": format!("{}-10-09", y), "name": "Independence Day"}),
            json!({"date": format!("{}-12-25", y), "name": "Christmas Day"}),
        ],
        "TZ" => vec![
            json!({"date": format!("{}-01-01", y), "name": "New Year's Day"}),
            json!({"date": format!("{}-01-12", y), "name": "Zanzibar Revolution Day"}),
            json!({"date": format!("{}-04-07", y), "name": "Karume Day"}),
            json!({"date": format!("{}-04-26", y), "name": "Union Day"}),
            json!({"date": format!("{}-05-01", y), "name": "Workers' Day"}),
            json!({"date": format!("{}-07-07", y), "name": "Saba Saba"}),
            json!({"date": format!("{}-08-08", y), "name": "Nane Nane (Farmers' Day)"}),
            json!({"date": format!("{}-12-09", y), "name": "Independence Day"}),
            json!({"date": format!("{}-12-25", y), "name": "Christmas Day"}),
        ],
        "ET" => vec![
            json!({"date": format!("{}-01-07", y), "name": "Genna (Christmas)"}),
            json!({"date": format!("{}-01-19", y), "name": "Timkat (Epiphany)"}),
            json!({"date": format!("{}-03-02", y), "name": "Battle of Adwa"}),
            json!({"date": format!("{}-05-01", y), "name": "Labour Day"}),
            json!({"date": format!("{}-05-05", y), "name": "Patriots' Victory Day"}),
            json!({"date": format!("{}-05-28", y), "name": "Derg Downfall Day"}),
            json!({"date": format!("{}-09-11", y), "name": "Enkutatash (New Year)"}),
            json!({"date": format!("{}-09-27", y), "name": "Meskel"}),
        ],
        "RW" => vec![
            json!({"date": format!("{}-01-01", y), "name": "New Year's Day"}),
            json!({"date": format!("{}-02-01", y), "name": "National Heroes Day"}),
            json!({"date": format!("{}-04-07", y), "name": "Genocide Memorial Day"}),
            json!({"date": format!("{}-05-01", y), "name": "Labour Day"}),
            json!({"date": format!("{}-07-01", y), "name": "Independence Day"}),
            json!({"date": format!("{}-07-04", y), "name": "Liberation Day"}),
            json!({"date": format!("{}-08-15", y), "name": "Assumption Day"}),
            json!({"date": format!("{}-12-25", y), "name": "Christmas Day"}),
        ],
        "ZA" => vec![
            json!({"date": format!("{}-01-01", y), "name": "New Year's Day"}),
            json!({"date": format!("{}-03-21", y), "name": "Human Rights Day"}),
            json!({"date": format!("{}-04-27", y), "name": "Freedom Day"}),
            json!({"date": format!("{}-05-01", y), "name": "Workers' Day"}),
            json!({"date": format!("{}-06-16", y), "name": "Youth Day"}),
            json!({"date": format!("{}-08-09", y), "name": "National Women's Day"}),
            json!({"date": format!("{}-09-24", y), "name": "Heritage Day"}),
            json!({"date": format!("{}-12-16", y), "name": "Day of Reconciliation"}),
            json!({"date": format!("{}-12-25", y), "name": "Christmas Day"}),
        ],
        "EG" => vec![
            json!({"date": format!("{}-01-07", y), "name": "Coptic Christmas"}),
            json!({"date": format!("{}-01-25", y), "name": "Revolution Day"}),
            json!({"date": format!("{}-04-25", y), "name": "Sinai Liberation Day"}),
            json!({"date": format!("{}-05-01", y), "name": "Labour Day"}),
            json!({"date": format!("{}-07-23", y), "name": "Revolution Day (1952)"}),
            json!({"date": format!("{}-10-06", y), "name": "Armed Forces Day"}),
        ],
        "GH" => vec![
            json!({"date": format!("{}-01-01", y), "name": "New Year's Day"}),
            json!({"date": format!("{}-03-06", y), "name": "Independence Day"}),
            json!({"date": format!("{}-05-01", y), "name": "May Day"}),
            json!({"date": format!("{}-05-25", y), "name": "Africa Day"}),
            json!({"date": format!("{}-07-01", y), "name": "Republic Day"}),
            json!({"date": format!("{}-09-21", y), "name": "Kwame Nkrumah Memorial Day"}),
            json!({"date": format!("{}-12-25", y), "name": "Christmas Day"}),
        ],
        "FR" => vec![
            json!({"date": format!("{}-01-01", y), "name": "Jour de l'An"}),
            json!({"date": format!("{}-05-01", y), "name": "Fête du Travail"}),
            json!({"date": format!("{}-05-08", y), "name": "Victoire 1945"}),
            json!({"date": format!("{}-07-14", y), "name": "Fête Nationale"}),
            json!({"date": format!("{}-08-15", y), "name": "Assomption"}),
            json!({"date": format!("{}-11-01", y), "name": "Toussaint"}),
            json!({"date": format!("{}-11-11", y), "name": "Armistice"}),
            json!({"date": format!("{}-12-25", y), "name": "Noël"}),
        ],
        "JP" => vec![
            json!({"date": format!("{}-01-01", y), "name": "元日 (New Year)"}),
            json!({"date": format!("{}-02-11", y), "name": "建国記念の日 (Foundation Day)"}),
            json!({"date": format!("{}-02-23", y), "name": "天皇誕生日 (Emperor's Birthday)"}),
            json!({"date": format!("{}-04-29", y), "name": "昭和の日 (Showa Day)"}),
            json!({"date": format!("{}-05-03", y), "name": "憲法記念日 (Constitution Day)"}),
            json!({"date": format!("{}-05-05", y), "name": "こどもの日 (Children's Day)"}),
            json!({"date": format!("{}-08-11", y), "name": "山の日 (Mountain Day)"}),
            json!({"date": format!("{}-11-03", y), "name": "文化の日 (Culture Day)"}),
            json!({"date": format!("{}-11-23", y), "name": "勤労感謝の日 (Labour Day)"}),
        ],
        "CN" => vec![
            json!({"date": format!("{}-01-01", y), "name": "元旦 (New Year)"}),
            json!({"date": format!("{}-01-29", y), "name": "春节 (Spring Festival)"}),
            json!({"date": format!("{}-01-30", y), "name": "春节 Day 2"}),
            json!({"date": format!("{}-01-31", y), "name": "春节 Day 3"}),
            json!({"date": format!("{}-04-04", y), "name": "清明节 (Qingming)"}),
            json!({"date": format!("{}-05-01", y), "name": "劳动节 (Labour Day)"}),
            json!({"date": format!("{}-06-01", y), "name": "端午节 (Dragon Boat)"}),
            json!({"date": format!("{}-10-01", y), "name": "国庆节 (National Day)"}),
            json!({"date": format!("{}-10-02", y), "name": "国庆节 Day 2"}),
            json!({"date": format!("{}-10-03", y), "name": "国庆节 Day 3"}),
        ],
        "BR" => vec![
            json!({"date": format!("{}-01-01", y), "name": "Ano Novo"}),
            json!({"date": format!("{}-02-17", y), "name": "Carnaval"}),
            json!({"date": format!("{}-04-21", y), "name": "Tiradentes"}),
            json!({"date": format!("{}-05-01", y), "name": "Dia do Trabalho"}),
            json!({"date": format!("{}-09-07", y), "name": "Independência"}),
            json!({"date": format!("{}-10-12", y), "name": "Nossa Senhora Aparecida"}),
            json!({"date": format!("{}-11-02", y), "name": "Finados"}),
            json!({"date": format!("{}-11-15", y), "name": "Proclamação da República"}),
            json!({"date": format!("{}-12-25", y), "name": "Natal"}),
        ],
        "AU" => vec![
            json!({"date": format!("{}-01-01", y), "name": "New Year's Day"}),
            json!({"date": format!("{}-01-26", y), "name": "Australia Day"}),
            json!({"date": format!("{}-04-18", y), "name": "Good Friday"}),
            json!({"date": format!("{}-04-21", y), "name": "Easter Monday"}),
            json!({"date": format!("{}-04-25", y), "name": "ANZAC Day"}),
            json!({"date": format!("{}-06-09", y), "name": "Queen's Birthday"}),
            json!({"date": format!("{}-12-25", y), "name": "Christmas Day"}),
            json!({"date": format!("{}-12-26", y), "name": "Boxing Day"}),
        ],
        "CA" => vec![
            json!({"date": format!("{}-01-01", y), "name": "New Year's Day"}),
            json!({"date": format!("{}-02-17", y), "name": "Family Day"}),
            json!({"date": format!("{}-04-18", y), "name": "Good Friday"}),
            json!({"date": format!("{}-05-19", y), "name": "Victoria Day"}),
            json!({"date": format!("{}-07-01", y), "name": "Canada Day"}),
            json!({"date": format!("{}-09-01", y), "name": "Labour Day"}),
            json!({"date": format!("{}-10-13", y), "name": "Thanksgiving"}),
            json!({"date": format!("{}-12-25", y), "name": "Christmas Day"}),
        ],
        "MX" => vec![
            json!({"date": format!("{}-01-01", y), "name": "Año Nuevo"}),
            json!({"date": format!("{}-02-03", y), "name": "Día de la Constitución"}),
            json!({"date": format!("{}-03-17", y), "name": "Natalicio de Benito Juárez"}),
            json!({"date": format!("{}-05-01", y), "name": "Día del Trabajo"}),
            json!({"date": format!("{}-09-16", y), "name": "Día de la Independencia"}),
            json!({"date": format!("{}-11-17", y), "name": "Revolución Mexicana"}),
            json!({"date": format!("{}-12-25", y), "name": "Navidad"}),
        ],
        _ => vec![
            json!({"date": format!("{}-01-01", y), "name": "New Year's Day"}),
            json!({"date": format!("{}-05-01", y), "name": "Labour Day"}),
            json!({"date": format!("{}-12-25", y), "name": "Christmas Day"}),
        ],
    }
}