#!/usr/bin/env python3 # desktop-assistant tool: the user's Vikunja tasks, through Vikunja's MCP server. # Copyright (C) 2026 Danilo M. # # This program is free software; you can redistribute it and/or modify it # under the terms of the GNU General Public License version 2 as published # by the Free Software Foundation. # # This program is distributed in the hope that it will be useful, but # WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General # Public License for more details. # # You should have received a copy of the GNU General Public License along # with this program; if not, write to the Free Software Foundation, Inc., # 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA. """vikunja.py ACTION ARGS...: the user's Vikunja tasks. list QUERY PROJECT DUE_BEFORE ALL ID add TITLE DESCRIPTION DUE PROJECT edit ID TITLE DESCRIPTION DUE PROJECT DONE delete ID Every argument is present and empty means not given. Dates are local time, YYYY-MM-DD (23:59 that day) or YYYY-MM-DD HH:MM; "none" clears a due date in edit. VIKUNJA_MCP_URL is the MCP endpoint, VIKUNJA_TOKEN_CMD prints the bearer token on its first line (run without a shell). --test runs the self-check. """ import functools import json import os import shlex import subprocess import sys import time import urllib.error import urllib.request from datetime import datetime, timezone NO_DATE = "0001-01-01T00:00:00Z" # Vikunja's "no due date" FIELDS = ["id", "title", "done", "due_date", "project_id"] def parse_due(s): # Local "YYYY-MM-DD" (23:59 that day) or "YYYY-MM-DD HH:MM" to UTC ISO; # "none" to None. s = s.strip() if s.lower() == "none": return None for fmt in ("%Y-%m-%d %H:%M", "%Y-%m-%d"): try: d = datetime.strptime(s, fmt) except ValueError: continue if fmt == "%Y-%m-%d": d = d.replace(hour=23, minute=59) return d.astimezone(timezone.utc).strftime("%Y-%m-%dT%H:%M:%SZ") raise ValueError(f"bad date {s!r}: use YYYY-MM-DD or YYYY-MM-DD HH:MM") def when(iso): # Vikunja date to an aware datetime, None for "no date". if not iso or iso.startswith("0001-"): return None return datetime.fromisoformat(iso.replace("Z", "+00:00")) def show_due(iso): # Local time with the weekday: the model gets weekdays wrong from dates. d = when(iso) return d.astimezone().strftime("%a %d %b %Y %H:%M") if d else "" def paths(projects): # id -> "parent/title", so nested projects read unambiguously. by = {p["id"]: p for p in projects} def path(p): parent = by.get(p.get("parent_project_id")) return f"{path(parent)}/{p['title']}" if parent else p["title"] return {i: path(p) for i, p in by.items()} def find_project(name, ps): # By full path or by own title, case-insensitive; exactly one match. n = name.strip().lower() hits = [i for i, p in ps.items() if n in (p.lower(), p.rsplit("/", 1)[-1].lower())] if len(hits) == 1: return hits[0] raise ValueError(f"{'ambiguous' if hits else 'no'} project {name.strip()!r}; " "projects: " + ", ".join(sorted(ps.values()))) def line(t, ps): s = f"#{t['id']} [{ps.get(t['project_id'], '?')}] {t['title']}" if d := show_due(t.get("due_date")): s += f", due {d}" return s + (" (done)" if t.get("done") else "") def task_id(s): try: return int(str(s).strip().lstrip("#")) except ValueError: raise ValueError(f"bad task id {s!r}") from None @functools.cache def token(): try: r = subprocess.run(shlex.split(os.environ["VIKUNJA_TOKEN_CMD"]), capture_output=True, text=True, stdin=subprocess.DEVNULL, timeout=10) except (OSError, ValueError, subprocess.TimeoutExpired) as e: sys.exit(f"token command failed ({type(e).__name__})") if r.returncode or not r.stdout.strip(): last = r.stderr.strip().splitlines()[-1:] sys.exit(last[0] if last else "token command printed nothing") return r.stdout.splitlines()[0].strip() def call(tool, **args): # One stateless JSON-RPC tools/call; Vikunja needs no initialize. url = os.environ["VIKUNJA_MCP_URL"] body = json.dumps({"jsonrpc": "2.0", "id": 1, "method": "tools/call", "params": {"name": tool, "arguments": args}}).encode() req = urllib.request.Request(url, body, { "Authorization": f"Bearer {token()}", "Content-Type": "application/json", "Accept": "application/json, text/event-stream"}) try: with urllib.request.urlopen(req, timeout=15) as r: raw = r.read().decode() except urllib.error.HTTPError as e: sys.exit("Vikunja token expired: make a new one in Vikunja, Settings > MCP" if e.code == 401 else f"Vikunja answered HTTP {e.code}") except OSError: # URLError, timeout, refused sys.exit(f"Vikunja unreachable at {url}") # SSE (one data: line) or plain JSON, whichever the server picked. msg = json.loads(next((l[5:] for l in raw.splitlines() if l.startswith("data:")), raw)) if "error" in msg: sys.exit(msg["error"].get("message", "MCP error")) res = msg["result"] if res.get("isError"): sys.exit(res["content"][0]["text"]) return res.get("structuredContent") def projects(): return paths(call("projects_list", per_page=200, fields=["id", "title", "parent_project_id"])["items"]) def read(n, ps, full=False): t = call("tasks_read", task=n, format="markdown", fields=FIELDS + (["description"] if full else [])) out = line(t, ps) if full and (t.get("description") or "").strip(): out += "\n\n" + t["description"].strip() return out def do_list(query, project, due_before, all_, id_): ps = projects() if id_: return read(task_id(id_), ps, full=True) f = [] if all_.strip() == "1" else ["done = false"] if query.strip(): f.append("title like '%" + query.strip().replace("'", "") + "%'") if project.strip(): f.append(f"project = {find_project(project, ps)}") if due_before.strip(): f.append(f"due_date < {parse_due(due_before) or NO_DATE}") args = {"per_page": 50, "fields": FIELDS} if f: args["filter"] = " && ".join(f) # ponytail: first 50 matches sorted here; with more open tasks than that, # the soonest due can be missed. Server-side sort_by if it happens. items = call("tasks_list", **args)["items"] far = datetime.max.replace(tzinfo=timezone.utc) items.sort(key=lambda t: (when(t["due_date"]) or far, t["id"])) return "\n".join(line(t, ps) for t in items) or "no tasks" def do_add(title, description, due, project): if not title.strip(): raise ValueError("title is required") ps = projects() args = {"project": find_project(project or "Inbox", ps), "title": title.strip(), "format": "markdown"} if description.strip(): args["description"] = description.strip() if due.strip() and (d := parse_due(due)): args["due_date"] = d return line(call("tasks_create", **args), ps) def do_edit(id_, title, description, due, project, done): n, ps, args = task_id(id_), projects(), {} if title.strip(): args["title"] = title.strip() if description.strip(): args["description"] = description.strip() if due.strip(): args["due_date"] = parse_due(due) # None clears it if project.strip(): args["project_id"] = find_project(project, ps) if done.strip(): args["done"] = done.strip().lower() in ("1", "true", "yes") if not args: raise ValueError("nothing to change") # The update answers {"ok": true, "unchanged": true} when nothing changed, # not the task: read it back either way. call("tasks_update", task=n, format="markdown", **args) return read(n, ps) def do_delete(id_): n = task_id(id_) title = call("tasks_read", task=n, fields=["title"])["title"] call("tasks_delete", task=n) return f'deleted #{n} "{title}"' ACTIONS = {"list": (do_list, 5), "add": (do_add, 4), "edit": (do_edit, 6), "delete": (do_delete, 1)} def test(): os.environ["TZ"] = "Europe/Rome" time.tzset() assert parse_due("2026-11-28") == "2026-11-28T22:59:00Z" assert parse_due("2026-07-01 09:30") == "2026-07-01T07:30:00Z" # summer time assert parse_due(" None ") is None for bad in ("28/11/2026", "2026-11-28 25:00", "tomorrow", ""): try: parse_due(bad) except ValueError: continue raise AssertionError(bad) assert show_due("2026-11-28T22:59:00Z") == "Sat 28 Nov 2026 23:59" assert show_due("2026-11-28T23:59:00+01:00") == "Sat 28 Nov 2026 23:59" assert show_due(NO_DATE) == "" and show_due(None) == "" ps = paths([{"id": 1, "title": "Inbox", "parent_project_id": 0}, {"id": 9, "title": "dev", "parent_project_id": 0}, {"id": 12, "title": "quickshell", "parent_project_id": 9}]) assert ps == {1: "Inbox", 9: "dev", 12: "dev/quickshell"} assert find_project("QuickShell", ps) == 12 == find_project("dev/quickshell", ps) try: find_project("nope", ps) raise AssertionError("unknown project") except ValueError as e: assert "dev/quickshell" in str(e) assert line({"id": 42, "title": "Fix lamp", "done": False, "project_id": 12, "due_date": "2026-11-28T23:59:00+01:00"}, ps) \ == "#42 [dev/quickshell] Fix lamp, due Sat 28 Nov 2026 23:59" assert line({"id": 7, "title": "x", "done": True, "project_id": 1, "due_date": NO_DATE}, ps) == "#7 [Inbox] x (done)" assert task_id("#42") == 42 == task_id(" 42 ") try: task_id("forty") raise AssertionError("bad id") except ValueError: pass print("ok") if __name__ == "__main__": if sys.argv[1:] == ["--test"]: test() sys.exit() fn, n = ACTIONS.get(sys.argv[1] if len(sys.argv) > 1 else "", (None, 0)) if fn is None or len(sys.argv) != n + 2: sys.exit("usage: vikunja.py list|add|edit|delete ARGS... (see the docstring)") if not (os.environ.get("VIKUNJA_MCP_URL") and os.environ.get("VIKUNJA_TOKEN_CMD")): sys.exit("VIKUNJA_MCP_URL / VIKUNJA_TOKEN_CMD not set in config [env]") try: print(fn(*sys.argv[2:])) except ValueError as e: sys.exit(str(e))