forked from homeassistant-ai/ha-mcp
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathtools_calendar.py
More file actions
490 lines (432 loc) · 17.9 KB
/
Copy pathtools_calendar.py
File metadata and controls
490 lines (432 loc) · 17.9 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
"""
Calendar event management tools for Home Assistant MCP server.
This module provides tools for managing calendar events in Home Assistant,
including retrieving events, creating events, and deleting events.
Use ha_search_entities(query='calendar', domain_filter='calendar') to find calendar entities.
"""
import logging
from datetime import datetime, timedelta
from typing import Annotated, Any
from fastmcp.exceptions import ToolError
from fastmcp.tools import tool
from pydantic import Field
from ..errors import ErrorCode, create_error_response
from .auto_backup import with_auto_backup
from .helpers import (
exception_to_structured_error,
log_tool_usage,
raise_tool_error,
register_tool_methods,
validate_identifier_not_empty,
)
logger = logging.getLogger(__name__)
class CalendarTools:
"""Calendar event management tools for Home Assistant."""
def __init__(self, client: Any) -> None:
self._client = client
@tool(
name="ha_config_get_calendar_events",
tags={"Calendar"},
annotations={
"idempotentHint": True,
"readOnlyHint": True,
"title": "Get Calendar Events",
},
)
@log_tool_usage
async def ha_config_get_calendar_events(
self,
entity_id: Annotated[
str, Field(description="Calendar entity ID (e.g., 'calendar.family')")
],
start: Annotated[
str | None,
Field(
description="Start datetime in ISO format (default: now)", default=None
),
] = None,
end: Annotated[
str | None,
Field(
description="End datetime in ISO format (default: 7 days from start)",
default=None,
),
] = None,
max_results: Annotated[
int,
Field(description="Maximum number of events to return", default=20),
] = 20,
) -> dict[str, Any]:
"""
Retrieve calendar events from a calendar entity.
Retrieves calendar events within a specified time range.
**Parameters:**
- entity_id: Calendar entity ID (e.g., 'calendar.family')
- start: Start datetime in ISO format (default: now)
- end: End datetime in ISO format (default: 7 days from start)
- max_results: Maximum number of events to return (default: 20)
**Example Usage:**
```python
# Get events for the next week
events = ha_config_get_calendar_events("calendar.family")
# Get events for a specific date range
events = ha_config_get_calendar_events(
"calendar.work",
start="2024-01-01T00:00:00",
end="2024-01-31T23:59:59"
)
```
**Note:** To find calendar entities, use ha_search_entities(query='calendar', domain_filter='calendar')
**Returns:**
- List of calendar events with summary, start, end, description, location
"""
try:
# Validate entity_id
if not entity_id.startswith("calendar."):
raise_tool_error(
create_error_response(
ErrorCode.VALIDATION_INVALID_PARAMETER,
f"Invalid calendar entity ID: {entity_id}. Must start with 'calendar.'",
context={"entity_id": entity_id},
suggestions=[
"Use ha_search_entities(query='calendar', domain_filter='calendar') to find calendar entities",
"Calendar entity IDs start with 'calendar.' prefix",
],
)
)
# Set default time range if not provided
now = datetime.now()
if start is None:
start = now.isoformat()
if end is None:
end_date = now + timedelta(days=7)
end = end_date.isoformat()
# Build the API endpoint for calendar events
# Home Assistant uses: GET /api/calendars/{entity_id}?start=...&end=...
params = {"start": start, "end": end}
# Use the REST client to fetch calendar events
# The endpoint is /calendars/{entity_id} (note: without /api prefix as client adds it)
response = await self._client._request(
"GET", f"/calendars/{entity_id}", params=params
)
# Response is a list of events
events = response if isinstance(response, list) else []
# Limit results
limited_events = events[:max_results]
return {
"success": True,
"entity_id": entity_id,
"events": limited_events,
"count": len(limited_events),
"total_available": len(events),
"time_range": {
"start": start,
"end": end,
},
"message": f"Retrieved {len(limited_events)} event(s) from {entity_id}",
}
except ToolError:
raise
except Exception as error:
logger.error(f"Failed to get calendar events for {entity_id}: {error}")
# Provide helpful error messages
suggestions = [
f"Verify calendar entity '{entity_id}' exists using ha_search_entities(query='calendar', domain_filter='calendar')",
"Check start/end datetime format (ISO 8601)",
"Ensure calendar integration supports event retrieval",
]
error_str = str(error)
if "404" in error_str or "not found" in error_str.lower():
suggestions.insert(0, f"Calendar entity '{entity_id}' not found")
exception_to_structured_error(
error, context={"entity_id": entity_id}, suggestions=suggestions
)
@tool(
name="ha_config_set_calendar_event",
tags={"Calendar"},
annotations={
"destructiveHint": True,
"title": "Create or Update Calendar Event",
},
)
@with_auto_backup(
domain="calendar_event",
# Skip on missing entity_id or uid; falsy "" beats the truthy
# "::" shape that would hit the fetch with no record to find.
id_fn=lambda kw: (
f"{kw['entity_id']}::{kw['uid']}"
if kw.get("entity_id") and kw.get("uid")
else ""
),
)
@log_tool_usage
async def ha_config_set_calendar_event(
self,
entity_id: Annotated[
str, Field(description="Calendar entity ID (e.g., 'calendar.family')")
],
summary: Annotated[str, Field(description="Event title/summary")],
start: Annotated[str, Field(description="Event start datetime in ISO format")],
end: Annotated[str, Field(description="Event end datetime in ISO format")],
description: Annotated[
str | None,
Field(description="Optional event description", default=None),
] = None,
location: Annotated[
str | None, Field(description="Optional event location", default=None)
] = None,
) -> dict[str, Any]:
"""
Create a new event in a calendar.
Creates a calendar event using the calendar.create_event service.
**Parameters:**
- entity_id: Calendar entity ID (e.g., 'calendar.family')
- summary: Event title/summary
- start: Event start datetime in ISO format
- end: Event end datetime in ISO format
- description: Optional event description
- location: Optional event location
**Example Usage:**
```python
# Create a simple event
result = ha_config_set_calendar_event(
"calendar.family",
summary="Doctor appointment",
start="2024-01-15T14:00:00",
end="2024-01-15T15:00:00"
)
# Create an event with details
result = ha_config_set_calendar_event(
"calendar.work",
summary="Team meeting",
start="2024-01-16T10:00:00",
end="2024-01-16T11:00:00",
description="Weekly sync meeting",
location="Conference Room A"
)
```
**Returns:**
- Success status and event details
"""
try:
# Validate entity_id
if not entity_id.startswith("calendar."):
raise_tool_error(
create_error_response(
ErrorCode.VALIDATION_INVALID_PARAMETER,
f"Invalid calendar entity ID: {entity_id}. Must start with 'calendar.'",
context={"entity_id": entity_id},
suggestions=[
"Use ha_search_entities(query='calendar', domain_filter='calendar') to find calendar entities",
"Calendar entity IDs start with 'calendar.' prefix",
],
)
)
# Build service data
service_data: dict[str, Any] = {
"entity_id": entity_id,
"summary": summary,
"start_date_time": start,
"end_date_time": end,
}
if description:
service_data["description"] = description
if location:
service_data["location"] = location
# Call the calendar.create_event service
result = await self._client.call_service(
"calendar", "create_event", service_data
)
return {
"success": True,
"entity_id": entity_id,
"event": {
"summary": summary,
"start": start,
"end": end,
"description": description,
"location": location,
},
"result": result,
"message": f"Successfully created event '{summary}' in {entity_id}",
}
except ToolError:
raise
except Exception as error:
logger.error(f"Failed to create calendar event in {entity_id}: {error}")
suggestions = [
f"Verify calendar entity '{entity_id}' exists and supports event creation",
"Check datetime format (ISO 8601)",
"Ensure end time is after start time",
"Some calendar integrations may be read-only",
]
error_str = str(error)
if "404" in error_str or "not found" in error_str.lower():
suggestions.insert(0, f"Calendar entity '{entity_id}' not found")
if "not supported" in error_str.lower():
suggestions.insert(0, "This calendar does not support event creation")
exception_to_structured_error(
error, context={"entity_id": entity_id}, suggestions=suggestions
)
@tool(
name="ha_config_remove_calendar_event",
tags={"Calendar"},
annotations={
"destructiveHint": True,
"idempotentHint": True,
"title": "Remove Calendar Event",
},
)
@with_auto_backup(
domain="calendar_event",
# Skip on missing entity_id or uid; falsy "" beats the truthy
# "::" shape that would hit the fetch with no record to find.
id_fn=lambda kw: (
f"{kw['entity_id']}::{kw['uid']}"
if kw.get("entity_id") and kw.get("uid")
else ""
),
)
@log_tool_usage
async def ha_config_remove_calendar_event(
self,
entity_id: Annotated[
str, Field(description="Calendar entity ID (e.g., 'calendar.family')")
],
uid: Annotated[
str, Field(description="Unique identifier of the event to delete")
],
recurrence_id: Annotated[
str | None,
Field(
description="Optional recurrence ID for recurring events", default=None
),
] = None,
recurrence_range: Annotated[
str | None,
Field(
description="Optional recurrence range ('THIS_AND_FUTURE' to delete this and future occurrences)",
default=None,
),
] = None,
) -> dict[str, Any]:
"""
Delete an event from a calendar.
Deletes a calendar event via the WebSocket ``calendar/event/delete``
command. HA's calendar component only registers ``create_event`` and
``get_events`` as REST services — delete and update live on the
WebSocket API only.
**Parameters:**
- entity_id: Calendar entity ID (e.g., 'calendar.family')
- uid: Unique identifier of the event to delete
- recurrence_id: Optional recurrence ID for recurring events
- recurrence_range: Optional recurrence range ('THIS_AND_FUTURE' to delete this and future occurrences)
**Example Usage:**
```python
# Delete a single event
result = ha_config_remove_calendar_event(
"calendar.family",
uid="event-12345"
)
# Delete a recurring event instance and future occurrences
result = ha_config_remove_calendar_event(
"calendar.work",
uid="recurring-event-67890",
recurrence_id="20240115T100000",
recurrence_range="THIS_AND_FUTURE"
)
```
**Note:**
To get the event UID, first use ha_config_get_calendar_events() to list events.
The UID is returned in each event's data.
**Returns:**
- Success status and deletion confirmation
"""
try:
# Validate entity_id
if not entity_id.startswith("calendar."):
raise_tool_error(
create_error_response(
ErrorCode.VALIDATION_INVALID_PARAMETER,
f"Invalid calendar entity ID: {entity_id}. Must start with 'calendar.'",
context={"entity_id": entity_id},
suggestions=[
"Use ha_search_entities(query='calendar', domain_filter='calendar') to find calendar entities",
"Calendar entity IDs start with 'calendar.' prefix",
],
)
)
# entity_id format-check above does not cover the ``uid`` parameter.
# Empty/whitespace uid would flow through to the WS command and HA
# returns a misleading "event not found".
validate_identifier_not_empty(
uid,
"uid",
suggestions=[
"Use ha_config_get_calendar_events() to list events and obtain valid UIDs",
],
context={"entity_id": entity_id},
)
# ``calendar.delete_event`` is NOT a REST service — HA only
# registers ``calendar.create_event`` and ``calendar.get_events``.
# Delete is exposed exclusively via the WebSocket command
# ``calendar/event/delete`` (see HA Core
# ``homeassistant/components/calendar/__init__.py``).
ws_message: dict[str, Any] = {
"type": "calendar/event/delete",
"entity_id": entity_id,
"uid": uid,
}
if recurrence_id:
ws_message["recurrence_id"] = recurrence_id
if recurrence_range:
ws_message["recurrence_range"] = recurrence_range
result = await self._client.send_websocket_message(ws_message)
if not result.get("success"):
ws_error = result.get("error", "Failed to delete calendar event")
raise_tool_error(
create_error_response(
ErrorCode.SERVICE_CALL_FAILED,
str(ws_error),
context={"entity_id": entity_id, "uid": uid},
suggestions=[
f"Verify event with UID '{uid}' exists in {entity_id}",
"Use ha_config_get_calendar_events() to find the correct event UID",
"Some calendar integrations may not support event deletion",
],
)
)
return {
"success": True,
"entity_id": entity_id,
"uid": uid,
"recurrence_id": recurrence_id,
"recurrence_range": recurrence_range,
"result": result,
"message": f"Successfully deleted event '{uid}' from {entity_id}",
}
except ToolError:
raise
except Exception as error:
logger.error(f"Failed to delete calendar event from {entity_id}: {error}")
suggestions = [
f"Verify calendar entity '{entity_id}' exists",
f"Verify event with UID '{uid}' exists in the calendar",
"Use ha_config_get_calendar_events() to find the correct event UID",
"Some calendar integrations may not support event deletion",
]
error_str = str(error)
if "404" in error_str or "not found" in error_str.lower():
suggestions.insert(
0, f"Calendar entity '{entity_id}' or event '{uid}' not found"
)
if "not supported" in error_str.lower():
suggestions.insert(0, "This calendar does not support event deletion")
exception_to_structured_error(
error,
context={"entity_id": entity_id, "uid": uid},
suggestions=suggestions,
)
def register_calendar_tools(mcp: Any, client: Any, **kwargs: Any) -> None:
"""Register calendar management tools with the MCP server."""
register_tool_methods(mcp, CalendarTools(client))