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
|
#!/usr/bin/env python3
# desktop-assistant tool: the user's Vikunja tasks, through Vikunja's MCP server.
# Copyright (C) 2026 Danilo M. <danix@danix.xyz>
#
# 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))
|