aboutsummaryrefslogtreecommitdiffstats
path: root/examples/tools
diff options
context:
space:
mode:
Diffstat (limited to 'examples/tools')
-rwxr-xr-xexamples/tools/vikunja.py128
1 files changed, 128 insertions, 0 deletions
diff --git a/examples/tools/vikunja.py b/examples/tools/vikunja.py
index 21ed451..30e36fb 100755
--- a/examples/tools/vikunja.py
+++ b/examples/tools/vikunja.py
@@ -107,6 +107,125 @@ def task_id(s):
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()
@@ -150,3 +269,12 @@ 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))