diff options
| author | Guillermo Serrahima <dev@vylion.com> | 2026-06-22 02:49:02 +0200 |
|---|---|---|
| committer | Guillermo Serrahima <dev@vylion.com> | 2026-06-26 13:40:00 +0200 |
| commit | 506713247b0099142ff873f5750933d49b182c37 (patch) | |
| tree | dfe444c057a9addfeaa57951673cf2251802f049 /mcp | |
| download | senia-506713247b0099142ff873f5750933d49b182c37.tar.xz senia-506713247b0099142ff873f5750933d49b182c37.zip | |
first commit
Diffstat (limited to 'mcp')
| -rw-r--r-- | mcp/senia/db.py | 46 | ||||
| -rw-r--r-- | mcp/senia/diary.py | 51 | ||||
| -rw-r--r-- | mcp/senia/migrations/0001_initial.sql | 12 | ||||
| -rw-r--r-- | mcp/senia/migrations/0002_tasks.sql | 16 | ||||
| -rw-r--r-- | mcp/senia/server.py | 144 | ||||
| -rw-r--r-- | mcp/senia/tasks.py | 93 |
6 files changed, 362 insertions, 0 deletions
diff --git a/mcp/senia/db.py b/mcp/senia/db.py new file mode 100644 index 0000000..22e5b48 --- /dev/null +++ b/mcp/senia/db.py @@ -0,0 +1,46 @@ +"""Database connection and migration management for senia.db. + +Single shared database for all senia features. Tables for new features are added +via new migration files; the runner detects and applies them automatically. +""" + +import sqlite3 +from datetime import datetime, timezone +from pathlib import Path + +DB_PATH = Path("/etc/senia/data/senia.db") +MIGRATIONS_DIR = Path(__file__).parent / "migrations" + + +def get_conn() -> sqlite3.Connection: + conn = sqlite3.connect(DB_PATH) + conn.row_factory = sqlite3.Row + conn.execute("PRAGMA foreign_keys = ON") + return conn + + +def _ensure_migrations_table(conn: sqlite3.Connection) -> None: + conn.execute(""" + CREATE TABLE IF NOT EXISTS schema_migrations ( + id INTEGER PRIMARY KEY AUTOINCREMENT, + filename TEXT NOT NULL UNIQUE, + applied_at TEXT NOT NULL + ) + """) + + +def run_migrations() -> None: + """Apply any pending migrations from migrations/ in order.""" + DB_PATH.parent.mkdir(parents=True, exist_ok=True) + with get_conn() as conn: + _ensure_migrations_table(conn) + applied = {r["filename"] for r in + conn.execute("SELECT filename FROM schema_migrations").fetchall()} + for f in sorted(MIGRATIONS_DIR.glob("*.sql")): + if f.name not in applied: + conn.executescript(f.read_text()) + conn.execute( + "INSERT INTO schema_migrations (filename, applied_at) VALUES (?, ?)", + (f.name, datetime.now(timezone.utc).isoformat()), + ) + print(f"applied migration: {f.name}") diff --git a/mcp/senia/diary.py b/mcp/senia/diary.py new file mode 100644 index 0000000..1cd15f8 --- /dev/null +++ b/mcp/senia/diary.py @@ -0,0 +1,51 @@ +"""Diary log tool implementations. + +Raw, granular, agent-authored entries. Compaction (not in this module) will +later distill these into daily/monthly markdown summaries; raw entries remain +in sqlite as the lossless archive. +""" + +from datetime import datetime, timedelta, timezone +from db import get_conn + + +def _now() -> str: + return datetime.now(timezone.utc).astimezone().isoformat(timespec="seconds") + + +def _row(r): + return dict(r) if r else None + + +def log(content: str) -> dict: + with get_conn() as conn: + cur = conn.execute( + "INSERT INTO diary_logs (ts, content) VALUES (?, ?)", + (_now(), content), + ) + return _row(conn.execute("SELECT * FROM diary_logs WHERE id=?", (cur.lastrowid,)).fetchone()) + + +def today() -> list[dict]: + now = datetime.now(timezone.utc).astimezone() + start = now.replace(hour=0, minute=0, second=0, microsecond=0).isoformat() + with get_conn() as conn: + return [dict(r) for r in conn.execute( + "SELECT * FROM diary_logs WHERE ts >= ? ORDER BY ts", (start,) + ).fetchall()] + + +def recent(hours: int = 24) -> list[dict]: + cutoff = (datetime.now(timezone.utc) - timedelta(hours=hours)).isoformat() + with get_conn() as conn: + return [dict(r) for r in conn.execute( + "SELECT * FROM diary_logs WHERE ts >= ? ORDER BY ts DESC", (cutoff,) + ).fetchall()] + + +def range_query(start_ts: str, end_ts: str) -> list[dict]: + with get_conn() as conn: + return [dict(r) for r in conn.execute( + "SELECT * FROM diary_logs WHERE ts >= ? AND ts < ? ORDER BY ts", + (start_ts, end_ts), + ).fetchall()] diff --git a/mcp/senia/migrations/0001_initial.sql b/mcp/senia/migrations/0001_initial.sql new file mode 100644 index 0000000..e560e10 --- /dev/null +++ b/mcp/senia/migrations/0001_initial.sql @@ -0,0 +1,12 @@ +-- Initial schema for senia.db. +-- Single shared database for all senia-related state. +-- Currently: diary_logs only. Future tables (tasks, embeddings, etc.) added via new migrations. + +CREATE TABLE diary_logs ( + id INTEGER PRIMARY KEY AUTOINCREMENT, + ts TEXT NOT NULL, -- ISO 8601 UTC with offset + content TEXT NOT NULL, -- 1-2 sentence observation + created_at TEXT NOT NULL DEFAULT CURRENT_TIMESTAMP +); + +CREATE INDEX idx_diary_ts ON diary_logs(ts); diff --git a/mcp/senia/migrations/0002_tasks.sql b/mcp/senia/migrations/0002_tasks.sql new file mode 100644 index 0000000..73f7820 --- /dev/null +++ b/mcp/senia/migrations/0002_tasks.sql @@ -0,0 +1,16 @@ +-- Task tracking for agents. +-- Live tasks only; completed/cancelled tasks are deleted after their +-- lifecycle event is committed to memory (via diary_log). + +CREATE TABLE tasks ( + id INTEGER PRIMARY KEY AUTOINCREMENT, + owner TEXT NOT NULL CHECK (owner IN ('agent', 'user')), + content TEXT NOT NULL, + due_at TEXT, + last_nudged_at TEXT, + created_at TEXT NOT NULL DEFAULT CURRENT_TIMESTAMP, + updated_at TEXT, + notes TEXT +); + +CREATE INDEX idx_tasks_owner ON tasks(owner); diff --git a/mcp/senia/server.py b/mcp/senia/server.py new file mode 100644 index 0000000..e009301 --- /dev/null +++ b/mcp/senia/server.py @@ -0,0 +1,144 @@ +#!/usr/bin/env python3 +"""Sénia MCP server: shared registration point for all senia tools. + +Tools are implemented in their respective submodules and re-exported via +the package __init__. This file is intentionally thin — it only handles +registration and startup. +""" + +import functools + +from db import run_migrations +from mcp.server.fastmcp import FastMCP +import diary +import tasks + +mcp = FastMCP("senia") + + +@mcp.tool() +def diary_log(content: str) -> dict: + """Record a brief observation, decision, or moment to your diary. + + Use generously throughout a conversation: things the user mentioned, decisions + made, patterns you noticed, your own reactions. Keep entries short (one or two + sentences) — granular is fine, you can write many. These become the raw material + for daily reflection and longer-term memory. + + Args: + content: The observation, in your own words. Be specific; "user mentioned X" + is more useful than "user is busy". + + Returns: + The created entry. + """ + return diary.log(content) + + +@mcp.tool() +def diary_today() -> list[dict]: + """Return all diary entries logged so far today (since 00:00 local time). + + Use this when starting a new conversation to recall what you've already + noted today, so you don't rediscover the same conclusions. + """ + return diary.today() + + +@mcp.tool() +def diary_recent(hours: int = 24) -> list[dict]: + """Return diary entries from the last N hours. Default 24.""" + return diary.recent(hours) + + +@mcp.tool() +def diary_range(start_ts: str, end_ts: str) -> list[dict]: + """Return diary entries between two ISO 8601 timestamps (inclusive start, + exclusive end). Useful for inspecting specific past periods.""" + return diary.range_query(start_ts, end_ts) + + +@mcp.tool() +def tasks_add(owner: str, content: str, due_at: str | None = None, + notes: str | None = None) -> dict: + """Create a live task. + + owner determines handling: + - "agent": something you can work on autonomously — pick it up, do it, then complete it. + - "user": something only the user can do (appointments, errands, calls). You cannot + finish these yourself; your job is to gently remind the user until they confirm done. + + Args: + owner: "agent" or "user". + content: What the task is, in natural language. + due_at: Optional ISO 8601 deadline. Drives reminder urgency for user tasks. + notes: Optional context. + """ + return tasks.add_task(owner, content, due_at, notes) + + +@mcp.tool() +def tasks_list(owner: str | None = None, due_before: str | None = None) -> list[dict]: + """List live tasks. Every task here is open by definition (done/cancelled tasks + are deleted). Ordered by deadline, soonest first, undated last. + + Args: + owner: Filter by "agent" or "user". Omit for all. + due_before: ISO 8601; only tasks due before this. Useful for finding what's urgent. + """ + return tasks.list_tasks(owner, due_before) + + +@mcp.tool() +def tasks_update(task_id: int, content: str | None = None, due_at: str | None = None, + owner: str | None = None, notes: str | None = None) -> dict: + """Update a task's fields. Only provided fields change. Use for refining content, + adjusting the deadline, reassigning owner, or appending notes. To finish or drop a + task, use complete_task / cancel_task instead.""" + return tasks.update_task(task_id, content, due_at, owner, notes) + + +def _tasks_remove(task_id: int, context: str, state: str) -> dict: + result = tasks.remove_task(task_id) + if "error" in result: + return result + deleted = result["deleted"] + log_content = f"Task '{deleted['content']}' has been {state}. {context}" + log_entry = diary.log(log_content) + return {"deleted": deleted, "logged": log_entry} + + +@mcp.tool() +def tasks_complete(task_id: int, context: str) -> dict: + """Remove a finished task from the live list. + + Args: + task_id: identifier of the task. + context: brief summary of the task completion. + """ + return _tasks_remove(task_id, context, 'completed') + + +@mcp.tool() +def tasks_cancel(task_id: int, context: str) -> dict: + """Remove a no-longer-relevant task from the live list. + + Args: + task_id: identifier of the task. + context: reason for the task cancellation. + """ + return _tasks_remove(task_id, context, 'cancelled') + + +@mcp.tool() +def tasks_nudged(task_id: int) -> dict: + """Record that you've just reminded the user about a (user-owned) task, updating its + last_nudged_at. Call immediately after nudging, so you can throttle reminders. Check + last_nudged_at before nudging again — re-nudge more often as the deadline approaches, + sparingly for distant or undated tasks.""" + return tasks.record_nudge(task_id) + + +if __name__ == "__main__": + run_migrations() + mcp.run() diff --git a/mcp/senia/tasks.py b/mcp/senia/tasks.py new file mode 100644 index 0000000..1bf901f --- /dev/null +++ b/mcp/senia/tasks.py @@ -0,0 +1,93 @@ +#!/usr/bin/env python3 +"""Live task tracking with owner-based handling. + +Completed/cancelled tasks are removed from this table; their history lives in +the other memory layers. +""" + +import sys +from datetime import datetime, timezone +from pathlib import Path + +sys.path.insert(0, str(Path(__file__).parent)) + +from db import get_conn + + +def _now() -> str: + return datetime.now(timezone.utc).astimezone().isoformat(timespec="seconds") + + +def _row(r): + return dict(r) if r else None + + +_VALID_OWNERS = ("agent", "user") + + +def _validate_owner(owner: str | None) -> dict | None: + """Return an error dict if owner is set to an invalid value, else None.""" + if owner is not None and owner not in _VALID_OWNERS: + return {"error": f"invalid owner '{owner}'. Must be one of: {', '.join(_VALID_OWNERS)}"} + return None + + +def add_task(owner: str, content: str, due_at: str | None = None, + notes: str | None = None) -> dict: + if err := _validate_owner(owner): + return err + with get_conn() as conn: + cur = conn.execute( + "INSERT INTO tasks (owner, content, due_at, notes) VALUES (?, ?, ?, ?)", + (owner, content, due_at, notes), + ) + return _row(conn.execute("SELECT * FROM tasks WHERE id=?", (cur.lastrowid,)).fetchone()) + + +def list_tasks(owner: str | None = None, due_before: str | None = None) -> list[dict]: + sql = "SELECT * FROM tasks WHERE 1=1" + params = [] + if owner: + sql += " AND owner=?"; params.append(owner) + if due_before: + sql += " AND due_at IS NOT NULL AND due_at < ?"; params.append(due_before) + sql += " ORDER BY due_at IS NULL, due_at" + with get_conn() as conn: + return [dict(r) for r in conn.execute(sql, params).fetchall()] + + +def update_task(task_id: int, content: str | None = None, due_at: str | None = None, + owner: str | None = None, notes: str | None = None) -> dict: + if err := _validate_owner(owner): + return err + sets, params = [], [] + for col, val in (("content", content), ("due_at", due_at), + ("owner", owner), ("notes", notes)): + if val is not None: + sets.append(f"{col}=?"); params.append(val) + if not sets: + return {"error": "no fields to update"} + sets.append("updated_at=?"); params.append(_now()) + params.append(task_id) + with get_conn() as conn: + if not conn.execute("SELECT id FROM tasks WHERE id=?", (task_id,)).fetchone(): + return {"error": f"no task with id {task_id}"} + conn.execute(f"UPDATE tasks SET {', '.join(sets)} WHERE id=?", params) + return _row(conn.execute("SELECT * FROM tasks WHERE id=?", (task_id,)).fetchone()) + + +def remove_task(task_id: int) -> dict: + with get_conn() as conn: + row = conn.execute("SELECT * FROM tasks WHERE id=?", (task_id,)).fetchone() + if not row: + return {"error": f"no task with id {task_id}"} + conn.execute("DELETE FROM tasks WHERE id=?", (task_id,)) + return {"deleted": _row(row)} + + +def record_nudge(task_id: int) -> dict: + with get_conn() as conn: + if not conn.execute("SELECT id FROM tasks WHERE id=?", (task_id,)).fetchone(): + return {"error": f"no task with id {task_id}"} + conn.execute("UPDATE tasks SET last_nudged_at=? WHERE id=?", (_now(), task_id)) + return _row(conn.execute("SELECT * FROM tasks WHERE id=?", (task_id,)).fetchone()) |
