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
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
|
"""TaskWarrior MCP Server implementation."""
import asyncio
import json
import logging
import os
import sys
from typing import Any
from mcp.server.fastmcp import FastMCP
# reconfigure UnicodeEncodeError prone default (i.e. windows-1252) to utf-8
if sys.platform == "win32" and os.environ.get("PYTHONIOENCODING") is None:
sys.stdin.reconfigure(encoding="utf-8")
sys.stdout.reconfigure(encoding="utf-8")
sys.stderr.reconfigure(encoding="utf-8")
logger = logging.getLogger("mcp_taskwarrior_server")
class TaskWarriorError(Exception):
"""Base exception for TaskWarrior operations."""
pass
class TaskWarriorServer:
"""Server class for TaskWarrior MCP operations."""
def __init__(self) -> None:
"""Initialize the TaskWarrior server."""
self._check_taskwarrior_installed()
def _check_taskwarrior_installed(self) -> None:
"""Check if TaskWarrior is installed and accessible."""
# This will be checked on first command execution
pass
async def _run_task_command(
self, *args: str, input_text: str | None = None
) -> tuple[str, str, int]:
"""Execute a TaskWarrior command and return stdout, stderr, return code.
Args:
*args: Command arguments to pass to task command
input_text: Optional input text to send to stdin
Returns:
Tuple of (stdout, stderr, return_code)
Raises:
TaskWarriorError: If taskwarrior is not installed or command fails
"""
try:
# Use rc.confirmation:off to avoid interactive prompts
# Use rc.bulk:0 to avoid bulk operation confirmations
cmd = ["task", "rc.confirmation:off", "rc.bulk:0"] + list(args)
process = await asyncio.create_subprocess_exec(
*cmd,
stdout=asyncio.subprocess.PIPE,
stderr=asyncio.subprocess.PIPE,
stdin=asyncio.subprocess.PIPE if input_text else None,
)
stdout_bytes, stderr_bytes = await process.communicate(
input_text.encode() if input_text else None
)
stdout = stdout_bytes.decode("utf-8", errors="replace")
stderr = stderr_bytes.decode("utf-8", errors="replace")
return_code = process.returncode
if return_code != 0:
error_msg = stderr.strip() or stdout.strip() or "Unknown error"
# Check if taskwarrior is not installed
error_lower = error_msg.lower()
if "command not found" in error_lower or "not found" in error_lower:
raise TaskWarriorError(
"TaskWarrior is not installed or not in PATH. "
"Please install TaskWarrior to use this server."
)
raise TaskWarriorError(f"TaskWarrior command failed: {error_msg}")
return stdout, stderr, return_code
except FileNotFoundError:
raise TaskWarriorError(
"TaskWarrior is not installed or not in PATH. "
"Please install TaskWarrior to use this server."
) from None
except Exception as e:
if isinstance(e, TaskWarriorError):
raise
raise TaskWarriorError(
f"Error executing TaskWarrior command: {str(e)}"
) from e
async def list_tasks(self, filter_expr: str | None = None) -> list[dict[str, Any]]:
"""List tasks matching the optional filter.
Args:
filter_expr: Optional filter expression (e.g., "project:Home", "+work")
Returns:
List of task dictionaries from JSON export
"""
args = []
if filter_expr:
args.append(filter_expr)
args.append("export")
stdout, _, _ = await self._run_task_command(*args)
# Parse JSON output
try:
# TaskWarrior export outputs JSON array, but may have trailing newlines
stdout = stdout.strip()
if not stdout:
return []
tasks = json.loads(stdout)
if not isinstance(tasks, list):
return [tasks] if tasks else []
return tasks
except json.JSONDecodeError as e:
logger.error(f"Failed to parse TaskWarrior JSON output: {e}")
logger.debug(f"Output was: {stdout}")
raise TaskWarriorError(
f"Failed to parse TaskWarrior output: {str(e)}"
) from e
async def add_task(
self,
description: str,
project: str | None = None,
priority: str | None = None,
due: str | None = None,
tags: list[str] | None = None,
) -> dict[str, Any]:
"""Add a new task to TaskWarrior.
Args:
description: Task description (required)
project: Optional project name
priority: Optional priority (H, M, or L)
due: Optional due date (ISO format or TaskWarrior date format)
tags: Optional list of tags
Returns:
Dictionary with task information including UUID
"""
args = ["add", description]
if project:
args.append(f"project:{project}")
if priority:
if priority.upper() not in ["H", "M", "L"]:
raise ValueError(f"Priority must be H, M, or L, got: {priority}")
args.append(f"priority:{priority.upper()}")
if due:
args.append(f"due:{due}")
if tags:
for tag in tags:
args.append(f"+{tag}")
stdout, stderr, _ = await self._run_task_command(*args)
# Extract UUID from output
# TaskWarrior output format: "Created task 123.\n\nUUID: <uuid>"
uuid = None
for line in stdout.split("\n"):
if line.startswith("UUID:"):
uuid = line.split(":", 1)[1].strip()
break
# If UUID not found in stdout, try to get it by listing the newest task
if not uuid:
# Get the newest task to find the UUID
tasks = await self.list_tasks("status:pending")
if tasks:
# Sort by entry date (most recent first)
tasks.sort(key=lambda t: t.get("entry", ""), reverse=True)
uuid = tasks[0].get("uuid")
return {
"description": description,
"uuid": uuid,
"project": project,
"priority": priority.upper() if priority else None,
"due": due,
"tags": tags or [],
"output": stdout.strip(),
}
async def add_tasks(
self,
tasks: list[dict[str, Any]],
) -> list[dict[str, Any]]:
"""Add multiple tasks to TaskWarrior.
Args:
tasks: List of task definitions, each with:
- description (required): Task description
- project (optional): Project name
- priority (optional): H, M, or L
- due (optional): Due date
- tags (optional): List of tags
Returns:
List of dictionaries with task information including UUIDs
"""
results = []
for task in tasks:
result = await self.add_task(
description=task["description"],
project=task.get("project"),
priority=task.get("priority"),
due=task.get("due"),
tags=task.get("tags"),
)
results.append(result)
return results
async def done_task(self, uuids: list[str]) -> dict[str, Any]:
"""Mark one or more tasks as completed.
Args:
uuids: List of task UUIDs (stable identifiers) to mark as done
Returns:
Dictionary with completion information including all UUIDs
Raises:
ValueError: If the uuids list is empty
"""
if not uuids:
raise ValueError("At least one UUID is required")
stdout, stderr, _ = await self._run_task_command(*uuids, "done")
return {
"uuids": uuids,
"status": "completed",
"output": stdout.strip(),
}
async def delete_task(self, uuids: list[str]) -> dict[str, Any]:
"""Delete one or more tasks.
Args:
uuids: List of task UUIDs (stable identifiers) to delete
Returns:
Dictionary with deletion information including all UUIDs
Raises:
ValueError: If the uuids list is empty
"""
if not uuids:
raise ValueError("At least one UUID is required")
stdout, stderr, _ = await self._run_task_command(*uuids, "delete")
return {
"uuids": uuids,
"status": "deleted",
"output": stdout.strip(),
}
async def modify_task(
self,
filter_expr: str,
project: str | None = None,
priority: str | None = None,
due: str | None = None,
description: str | None = None,
tags: list[str] | None = None,
) -> dict[str, Any]:
"""Modify one or more tasks matching the filter expression.
Args:
filter_expr: Filter expression to identify tasks to modify
(e.g., "uuid:abc123", "+work", "project:Home status:pending")
project: New project name (use empty string "" to clear project)
priority: New priority (H, M, L, or empty string "" to clear)
due: New due date (ISO format or TaskWarrior format like "tomorrow",
or empty string "" to clear)
description: New description text
tags: List of tags with +/- prefixes (e.g., ["+newtag", "-oldtag"])
Returns:
Dictionary with modification information
Raises:
ValueError: If no modification parameters provided, invalid priority,
or invalid tag format
"""
# Validate that at least one modification parameter is provided
if not any(
[
project is not None,
priority is not None,
due is not None,
description is not None,
tags,
]
):
raise ValueError(
"At least one modification parameter must be provided "
"(project, priority, due, description, or tags)"
)
# Validate priority if provided
if priority is not None:
priority_upper = priority.upper() if priority else ""
if priority_upper and priority_upper not in ["H", "M", "L"]:
raise ValueError(f"Priority must be H, M, or L, got: {priority}")
# Validate tags format if provided
if tags:
for tag in tags:
if not tag.startswith(("+", "-")):
raise ValueError(f"Tags must start with + or -, got: {tag}")
# Build command: task <filter_expr> modify <modifications>
args = [filter_expr, "modify"]
if project is not None:
if project == "":
args.append("project:")
else:
args.append(f"project:{project}")
if priority is not None:
if priority == "":
args.append("priority:")
else:
args.append(f"priority:{priority.upper()}")
if due is not None:
if due == "":
args.append("due:")
else:
args.append(f"due:{due}")
if description is not None:
args.append(f"description:{description}")
if tags:
args.extend(tags)
stdout, stderr, _ = await self._run_task_command(*args)
return {
"filter_expr": filter_expr,
"modifications": {
"project": project if project is not None else None,
"priority": priority.upper() if priority and priority != "" else None,
"due": due if due != "" else None,
"description": description,
"tags": tags,
},
"output": stdout.strip(),
}
async def manage_context(
self, action: str, name: str | None = None
) -> dict[str, Any]:
"""Manage TaskWarrior contexts.
Args:
action: One of "set", "list", "show", "none"
name: Context name (required for "set" action)
Returns:
Dictionary with context information
"""
if action not in ["set", "list", "show", "none"]:
raise ValueError(
f"Action must be one of: set, list, show, none. Got: {action}"
)
if action == "set" and not name:
raise ValueError("Context name is required for 'set' action")
args = ["context"]
if action == "set":
args.append(name)
elif action == "none":
args.append("none")
else:
args.append(action)
stdout, stderr, _ = await self._run_task_command(*args)
result: dict[str, Any] = {
"action": action,
"output": stdout.strip(),
}
if action == "set" and name:
result["context"] = name
elif action == "show":
# Parse the context show output to extract context name
lines = stdout.strip().split("\n")
for line in lines:
if line.startswith("Context '") and "'" in line:
context_name = line.split("'")[1]
result["context"] = context_name
break
elif action == "list":
# Parse context list output
contexts = []
for line in stdout.strip().split("\n"):
if line.strip() and not line.startswith("Name"):
parts = line.split()
if len(parts) >= 2:
ctx_name = parts[0]
if ctx_name not in [c.get("name") for c in contexts]:
contexts.append({"name": ctx_name})
result["contexts"] = contexts
return result
def create_server(host: str = "127.0.0.1", port: int = 8080) -> FastMCP:
"""Create and configure the FastMCP server.
Args:
host: Host to bind to for remote transport
port: Port to bind to for remote transport
Returns:
Configured FastMCP server instance
"""
mcp = FastMCP("TaskWarrior", host=host, port=port)
# Create a TaskWarriorServer instance
taskwarrior = TaskWarriorServer()
@mcp.tool()
async def list_tasks(filter_expr: str | None = None) -> str:
"""List tasks with optional filter.
Args:
filter_expr: Optional filter expression
(e.g., "project:Home", "+work", "status:pending")
Returns:
JSON string of tasks matching the filter
"""
try:
tasks = await taskwarrior.list_tasks(filter_expr)
return json.dumps(tasks, indent=2)
except Exception as e:
logger.error(f"Error listing tasks: {e}")
return json.dumps({"error": str(e)})
@mcp.tool()
async def add_task(
description: str,
project: str | None = None,
priority: str | None = None,
due: str | None = None,
tags: list[str] | None = None,
) -> str:
"""Add a new task to TaskWarrior.
Args:
description: Task description (required)
project: Optional project name
priority: Optional priority (H, M, or L)
due: Optional due date (ISO format or TaskWarrior date format
like "tomorrow", "2024-12-25")
tags: Optional list of tags
Returns:
JSON string with task information including UUID
"""
try:
result = await taskwarrior.add_task(
description=description,
project=project,
priority=priority,
due=due,
tags=tags,
)
return json.dumps(result, indent=2)
except Exception as e:
logger.error(f"Error adding task: {e}")
return json.dumps({"error": str(e)})
@mcp.tool()
async def add_tasks(
tasks: list[dict[str, Any]],
) -> str:
"""Add multiple tasks to TaskWarrior in one call.
Args:
tasks: List of task definitions. Each task should have:
- description (required): Task description
- project (optional): Project name
- priority (optional): Priority (H, M, or L)
- due (optional): Due date
- tags (optional): List of tags
Returns:
JSON string with list of created task information
"""
try:
results = await taskwarrior.add_tasks(tasks)
return json.dumps(results, indent=2)
except Exception as e:
logger.error(f"Error adding tasks: {e}")
return json.dumps({"error": str(e)})
@mcp.tool()
async def done_task(uuids: list[str]) -> str:
"""Mark one or more tasks as completed.
Args:
uuids: List of task UUIDs (stable identifiers, not numeric IDs)
Returns:
JSON string with completion information for all tasks
"""
try:
result = await taskwarrior.done_task(uuids)
return json.dumps(result, indent=2)
except Exception as e:
logger.error(f"Error marking task as done: {e}")
return json.dumps({"error": str(e)})
@mcp.tool()
async def delete_task(uuids: list[str]) -> str:
"""Delete one or more tasks.
Args:
uuids: List of task UUIDs (stable identifiers, not numeric IDs)
Returns:
JSON string with deletion information for all tasks
"""
try:
result = await taskwarrior.delete_task(uuids)
return json.dumps(result, indent=2)
except Exception as e:
logger.error(f"Error deleting task: {e}")
return json.dumps({"error": str(e)})
@mcp.tool()
async def modify_task(
filter_expr: str,
project: str | None = None,
priority: str | None = None,
due: str | None = None,
description: str | None = None,
tags: list[str] | None = None,
) -> str:
"""Modify one or more tasks matching the filter expression.
Args:
filter_expr: Filter expression to identify tasks to modify
(e.g., "uuid:abc123", "+work", "project:Home status:pending")
project: New project name (use empty string "" to clear project)
priority: New priority (H, M, L, or empty string "" to clear)
due: New due date (ISO format or TaskWarrior format like "tomorrow",
or empty string "" to clear)
description: New description text
tags: List of tags with +/- prefixes (e.g., ["+newtag", "-oldtag"])
Returns:
JSON string with modification information
"""
try:
result = await taskwarrior.modify_task(
filter_expr=filter_expr,
project=project,
priority=priority,
due=due,
description=description,
tags=tags,
)
return json.dumps(result, indent=2)
except Exception as e:
logger.error(f"Error modifying task: {e}")
return json.dumps({"error": str(e)})
@mcp.tool()
async def context(action: str, name: str | None = None) -> str:
"""Manage TaskWarrior contexts.
Args:
action: One of "set", "list", "show", "none"
name: Context name (required for "set" action, optional otherwise)
Returns:
JSON string with context information
"""
try:
result = await taskwarrior.manage_context(action, name)
return json.dumps(result, indent=2)
except Exception as e:
logger.error(f"Error managing context: {e}")
return json.dumps({"error": str(e)})
return mcp
async def main(transport_type: str, host: str, port: int) -> None:
"""Start the server with the specified transport.
Args:
transport_type: Transport type ("stdio" or "remote")
host: Host to bind to for remote transport
port: Port to bind to for remote transport
"""
logger.info("Starting MCP TaskWarrior Server")
logger.info(f"Starting TaskWarrior MCP Server with {transport_type} transport")
# Create the server with host and port
mcp = create_server(host=host, port=port)
# Run the server with the appropriate transport
if transport_type == "stdio":
logger.info("Server running with stdio transport")
await mcp.run_stdio_async()
else: # remote transport
logger.info(f"Server running with remote transport on {host}:{port}")
await mcp.run_sse_async()
|