Files
FabledScribe/src/scribe/mcp/tools/events.py
T
bvandeusen b255a0f90e
CI & Build / Python lint (push) Successful in 3s
CI & Build / TypeScript typecheck (push) Successful in 35s
CI & Build / Python tests (push) Successful in 54s
CI & Build / Build & push image (push) Successful in 1m14s
refactor: rename package fabledassistant -> scribe (code-only)
Renames src/fabledassistant -> src/scribe and all imports, plus the
default DB name and DB user/password (fabled -> scribe) in config +
compose. 952 refs / 154 files. Reverses the old 'internal name stays
fabledassistant' convention.

Code-only: live databases are still physically named 'fabledassistant'.
Deployed environments must set POSTGRES_DB / POSTGRES_USER (or rename the
DB) since the defaults now resolve to 'scribe'. Repo (FabledScribe), git
host (fabledsword), MCP (fabled-git) and the image name (fabledscribe)
are intentionally unchanged.

ruff check src/ clean locally; CI (typecheck + pytest) is the gate.

Co-Authored-By: Claude Opus 4.8 (1M context) <noreply@anthropic.com>
2026-06-03 15:48:35 -04:00

172 lines
5.9 KiB
Python

"""Calendar event MCP tools — new in Phase 3.
Events were previously only an internal-LLM tool; the MCP surface didn't have
them. Wraps services/events.py.
Date/time inputs are split: start_date (YYYY-MM-DD) + start_time (HH:MM) get
combined into a naive datetime; the service layer interprets it in the user's
local timezone. duration_minutes=0 ⇒ point event (NULL duration). The
LLM-era expected_weekday verification check is intentionally not replicated —
Claude doesn't need it.
For update, sentinels:
- title="" / location="" / description="" → leave unchanged
- start_date="" / start_time="" → leave unchanged (both must be provided to
move the event)
- duration_minutes=-1 → leave unchanged; 0 means "set to point event"
"""
from __future__ import annotations
from datetime import datetime, timedelta, timezone
from scribe.mcp._context import current_user_id
from scribe.services import events as events_svc
from scribe.services import trash as trash_svc
def _combine(start_date: str, start_time: str) -> datetime:
"""Combine YYYY-MM-DD + HH:MM into a naive datetime.
The events service interprets naive datetimes for create/update against
the user's configured timezone, so we don't attach tzinfo here.
"""
t = start_time or "00:00"
return datetime.fromisoformat(f"{start_date}T{t}:00")
def _day_range_utc(date_from: str, date_to: str) -> tuple[datetime, datetime]:
"""Return a UTC datetime range [start_of_date_from, end_of_date_to).
Event.start_dt is stored timezone-aware in the DB; comparing it against a
naive datetime raises TypeError. We anchor the range in UTC, which is a
reasonable default — refining to the user's local timezone for the
range boundaries is a separate improvement.
"""
start = datetime.fromisoformat(date_from).replace(tzinfo=timezone.utc)
# `date_to` is inclusive at the day level — bump by 24h so events later
# on date_to are included.
end = (
datetime.fromisoformat(date_to).replace(tzinfo=timezone.utc)
+ timedelta(days=1)
)
return start, end
def _event_dict(event) -> dict:
"""Render an Event model to a dict, handling list_events (already dicts)."""
return event if isinstance(event, dict) else event.to_dict()
async def list_events(date_from: str, date_to: str) -> dict:
"""List events between date_from and date_to (YYYY-MM-DD, both inclusive at
the day level — `date_to` is interpreted as end-of-that-day).
Recurring events are expanded into individual occurrences within the range.
"""
uid = current_user_id()
start, end = _day_range_utc(date_from, date_to)
rows = await events_svc.list_events(uid, start, end)
return {"events": [_event_dict(e) for e in rows], "total": len(rows)}
async def create_event(
title: str,
start_date: str,
start_time: str = "00:00",
duration_minutes: int = 0,
all_day: bool = False,
location: str = "",
description: str = "",
) -> dict:
"""Create a calendar event.
Args:
title: Event title (required).
start_date: YYYY-MM-DD.
start_time: HH:MM (24-hour). Ignored when all_day=True.
duration_minutes: 0 for a point event (no duration); otherwise minutes.
all_day: True to make this an all-day event.
location: Optional location string.
description: Optional longer description.
"""
uid = current_user_id()
event = await events_svc.create_event(
uid,
title=title,
start_dt=_combine(start_date, start_time),
duration_minutes=duration_minutes or None,
all_day=all_day,
location=location,
description=description,
)
return event.to_dict()
async def get_event(event_id: int) -> dict:
"""Fetch a single event by ID."""
uid = current_user_id()
event = await events_svc.get_event(uid, event_id)
if event is None:
raise ValueError(f"event {event_id} not found")
return event.to_dict()
async def update_event(
event_id: int,
title: str = "",
start_date: str = "",
start_time: str = "",
duration_minutes: int = -1,
location: str = "",
description: str = "",
) -> dict:
"""Update an event. Only explicitly provided fields are changed.
Args:
event_id: ID of the event to update.
title: New title; omit to leave unchanged.
start_date / start_time: BOTH must be set to move the event. Omit either
to leave the start_dt unchanged.
duration_minutes: -1 leaves unchanged; 0 sets to point event; any
positive value sets the duration.
location / description: omit to leave unchanged.
"""
uid = current_user_id()
fields: dict = {}
if title:
fields["title"] = title
if location:
fields["location"] = location
if description:
fields["description"] = description
if start_date and start_time:
fields["start_dt"] = _combine(start_date, start_time)
if duration_minutes >= 0:
# 0 means point event (NULL); positive sets a real duration.
fields["duration_minutes"] = duration_minutes or None
event = await events_svc.update_event(uid, event_id, **fields)
if event is None:
raise ValueError(f"event {event_id} not found")
return event.to_dict()
async def delete_event(event_id: int) -> dict:
"""Move a calendar event to the trash (recoverable). Restore via restore(batch_id)."""
uid = current_user_id()
batch = await trash_svc.delete(uid, "event", event_id)
if batch is None:
raise ValueError(f"event {event_id} not found")
return {"deleted_batch_id": batch,
"message": f"Event {event_id} moved to trash. Restore with restore('{batch}')."}
def register(mcp) -> None:
for fn in (
list_events,
create_event,
get_event,
update_event,
delete_event,
):
mcp.tool(name=fn.__name__)(fn)