backlog-tiny-mcp 0.35.0__py3-none-any.whl
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- backlog_mcp/__init__.py +29 -0
- backlog_mcp/__main__.py +10 -0
- backlog_mcp/auth.py +199 -0
- backlog_mcp/backlog.py +696 -0
- backlog_mcp/cli.py +2046 -0
- backlog_mcp/client.py +320 -0
- backlog_mcp/computer.py +33 -0
- backlog_mcp/database.py +80 -0
- backlog_mcp/embeddings.py +900 -0
- backlog_mcp/global_rules.md +126 -0
- backlog_mcp/guidance.py +11 -0
- backlog_mcp/guide/index.md +11 -0
- backlog_mcp/guide/memory.md +27 -0
- backlog_mcp/guide/projects.md +16 -0
- backlog_mcp/guide/search.md +72 -0
- backlog_mcp/guide/tasks.md +40 -0
- backlog_mcp/guide/workflow.md +22 -0
- backlog_mcp/httpd.py +270 -0
- backlog_mcp/migrate.py +113 -0
- backlog_mcp/migrations/0001-initial.sql +194 -0
- backlog_mcp/migrations/0002-task-assignment.sql +2 -0
- backlog_mcp/migrations/0003-task-edit-claims.sql +5 -0
- backlog_mcp/migrations/0004-memory-visibility.sql +42 -0
- backlog_mcp/model/CITATION.bib +9 -0
- backlog_mcp/model/LICENSE +202 -0
- backlog_mcp/model/README.md +12 -0
- backlog_mcp/model/UPSTREAM.md +2053 -0
- backlog_mcp/model/config.json +12 -0
- backlog_mcp/model/model.safetensors +4 -0
- backlog_mcp/model/modules.json +14 -0
- backlog_mcp/model/provenance.json +16 -0
- backlog_mcp/model/tokenizer.json +1 -0
- backlog_mcp/models.py +581 -0
- backlog_mcp/names.py +35 -0
- backlog_mcp/paths.py +53 -0
- backlog_mcp/protocol_storage.py +104 -0
- backlog_mcp/queries.py +7 -0
- backlog_mcp/queries.sql +531 -0
- backlog_mcp/records.py +215 -0
- backlog_mcp/render.py +479 -0
- backlog_mcp/server.py +2864 -0
- backlog_mcp/skills/autopilot/SKILL.md +96 -0
- backlog_mcp/skills/planning/SKILL.md +106 -0
- backlog_mcp/skills/planning/references/splitting.md +45 -0
- backlog_mcp/skills/triage/SKILL.md +104 -0
- backlog_mcp/skills/triage/references/conventions.md +43 -0
- backlog_mcp/skills.py +56 -0
- backlog_mcp/static/agent-config.js +20 -0
- backlog_mcp/static/app.css +1950 -0
- backlog_mcp/static/app.js +1301 -0
- backlog_mcp/static/assignments.js +96 -0
- backlog_mcp/static/breadcrumbs.js +54 -0
- backlog_mcp/static/comment-composer.js +95 -0
- backlog_mcp/static/connect.css +98 -0
- backlog_mcp/static/connect.html +74 -0
- backlog_mcp/static/connect.js +160 -0
- backlog_mcp/static/credentials.js +72 -0
- backlog_mcp/static/diagrams.js +128 -0
- backlog_mcp/static/dom.js +162 -0
- backlog_mcp/static/editor-claim.js +104 -0
- backlog_mcp/static/editor.js +355 -0
- backlog_mcp/static/index.html +137 -0
- backlog_mcp/static/markdown.css +33 -0
- backlog_mcp/static/markdown.js +72 -0
- backlog_mcp/static/mcp.js +177 -0
- backlog_mcp/static/memory-append.js +34 -0
- backlog_mcp/static/memory-editor.js +173 -0
- backlog_mcp/static/memory.js +279 -0
- backlog_mcp/static/package.json +1 -0
- backlog_mcp/static/project-form.js +71 -0
- backlog_mcp/static/project-settings.js +225 -0
- backlog_mcp/static/scope.js +90 -0
- backlog_mcp/static/statistics.js +87 -0
- backlog_mcp/static/task-browser.js +100 -0
- backlog_mcp/static/task-pagination.js +94 -0
- backlog_mcp/static/task-picker.js +164 -0
- backlog_mcp/static/task-table.js +74 -0
- backlog_mcp/static/vendor/README.md +12 -0
- backlog_mcp/static/vendor/dompurify-LICENSE +202 -0
- backlog_mcp/static/vendor/highlight-LICENSE +29 -0
- backlog_mcp/static/vendor/highlight-dark.css +118 -0
- backlog_mcp/static/vendor/highlight-light.css +118 -0
- backlog_mcp/static/vendor/highlight.min.js +1262 -0
- backlog_mcp/static/vendor/marked-LICENSE +44 -0
- backlog_mcp/static/vendor/marked.esm.js +80 -0
- backlog_mcp/static/vendor/marked.esm.js.map +7 -0
- backlog_mcp/static/vendor/mermaid-LICENSE +21 -0
- backlog_mcp/static/vendor/mermaid.min.js +4376 -0
- backlog_mcp/static/vendor/purify.es.mjs +2722 -0
- backlog_mcp/static/vendor/purify.es.mjs.map +1 -0
- backlog_mcp/transaction.py +47 -0
- backlog_mcp/version.py +79 -0
- backlog_mcp/webui.py +63 -0
- backlog_tiny_mcp-0.35.0.dist-info/METADATA +84 -0
- backlog_tiny_mcp-0.35.0.dist-info/RECORD +97 -0
- backlog_tiny_mcp-0.35.0.dist-info/WHEEL +4 -0
- backlog_tiny_mcp-0.35.0.dist-info/entry_points.txt +4 -0
backlog_mcp/cli.py
ADDED
|
@@ -0,0 +1,2046 @@
|
|
|
1
|
+
"""The command line: serve MCP, or connect to it over HTTP or local stdio."""
|
|
2
|
+
|
|
3
|
+
from __future__ import annotations
|
|
4
|
+
|
|
5
|
+
import argparse
|
|
6
|
+
import asyncio
|
|
7
|
+
import contextlib
|
|
8
|
+
import dataclasses
|
|
9
|
+
import json
|
|
10
|
+
import logging
|
|
11
|
+
import os
|
|
12
|
+
import re
|
|
13
|
+
import shlex
|
|
14
|
+
import subprocess
|
|
15
|
+
import sys
|
|
16
|
+
import tempfile
|
|
17
|
+
from collections.abc import AsyncGenerator, Mapping, Sequence
|
|
18
|
+
from pathlib import Path
|
|
19
|
+
from typing import Any, cast
|
|
20
|
+
|
|
21
|
+
import argclass
|
|
22
|
+
import rtoml
|
|
23
|
+
from aiohttp import ClientError as HTTPClientError
|
|
24
|
+
from aiohttp_tiny_mcp import ClientError, elicit_accept
|
|
25
|
+
from rich.prompt import Confirm, Prompt
|
|
26
|
+
from yarl import URL
|
|
27
|
+
|
|
28
|
+
from . import embeddings, httpd, paths, skills
|
|
29
|
+
from .auth import (
|
|
30
|
+
BCRYPT_COST,
|
|
31
|
+
bcrypt_account,
|
|
32
|
+
normalize_accounts,
|
|
33
|
+
user_identity,
|
|
34
|
+
validate_account,
|
|
35
|
+
validate_bcrypt_cost,
|
|
36
|
+
)
|
|
37
|
+
from .backlog import Backlog, UnknownProject, slugify
|
|
38
|
+
from .client import Connection, Registration, ToolError, bind_directory, connect, directory_project
|
|
39
|
+
from .models import (
|
|
40
|
+
OPEN_STATUSES,
|
|
41
|
+
CommentOut,
|
|
42
|
+
Comments,
|
|
43
|
+
Deleted,
|
|
44
|
+
Event,
|
|
45
|
+
FullNotes,
|
|
46
|
+
FullTasks,
|
|
47
|
+
Identity,
|
|
48
|
+
LinkChange,
|
|
49
|
+
NoteOut,
|
|
50
|
+
Priority,
|
|
51
|
+
ProjectDeleted,
|
|
52
|
+
ProjectOut,
|
|
53
|
+
Relation,
|
|
54
|
+
Status,
|
|
55
|
+
TaskDetails,
|
|
56
|
+
TaskOut,
|
|
57
|
+
Tasks,
|
|
58
|
+
)
|
|
59
|
+
from .models import (
|
|
60
|
+
Projects as ProjectList,
|
|
61
|
+
)
|
|
62
|
+
from .models import (
|
|
63
|
+
Stats as StatsOut,
|
|
64
|
+
)
|
|
65
|
+
from .names import default_user, principal_label
|
|
66
|
+
from .records import NOTE_LIMIT, Note, Task, check_note
|
|
67
|
+
from .render import (
|
|
68
|
+
board_panel,
|
|
69
|
+
comment_panel,
|
|
70
|
+
comments_table,
|
|
71
|
+
console,
|
|
72
|
+
errors,
|
|
73
|
+
event_line,
|
|
74
|
+
fail,
|
|
75
|
+
fields,
|
|
76
|
+
note,
|
|
77
|
+
note_panel,
|
|
78
|
+
notes_table,
|
|
79
|
+
projects_table,
|
|
80
|
+
skill_panel,
|
|
81
|
+
skills_table,
|
|
82
|
+
stats_view,
|
|
83
|
+
task_panel,
|
|
84
|
+
tasks_table,
|
|
85
|
+
warn,
|
|
86
|
+
)
|
|
87
|
+
from .server import (
|
|
88
|
+
NOTE_CHANGED,
|
|
89
|
+
PROJECT_CHANGED,
|
|
90
|
+
TASK_CHANGED,
|
|
91
|
+
VERSION,
|
|
92
|
+
bound,
|
|
93
|
+
registry,
|
|
94
|
+
use,
|
|
95
|
+
)
|
|
96
|
+
|
|
97
|
+
log = logging.getLogger("backlog_mcp")
|
|
98
|
+
|
|
99
|
+
LOG_FORMAT = "%(asctime)s %(levelname)-7s %(name)s: %(message)s"
|
|
100
|
+
|
|
101
|
+
STATUSES = tuple(item.value for item in Status)
|
|
102
|
+
PRIORITIES = tuple(item.value for item in Priority)
|
|
103
|
+
|
|
104
|
+
FORM = """\
|
|
105
|
+
Title: {title}
|
|
106
|
+
Status: {status}
|
|
107
|
+
Priority: {priority}
|
|
108
|
+
Tags: {tags}
|
|
109
|
+
|
|
110
|
+
{body}
|
|
111
|
+
|
|
112
|
+
# Everything above the blank line sets a field; everything below it is the description.
|
|
113
|
+
# Lines starting with '#' are dropped. An empty title cancels the task.
|
|
114
|
+
"""
|
|
115
|
+
|
|
116
|
+
HEADERS = ("title", "status", "priority", "tags")
|
|
117
|
+
|
|
118
|
+
#: The hints sit on top: the body is markdown, so a '#' line below the headers is a heading.
|
|
119
|
+
NOTE_FORM = """\
|
|
120
|
+
# Everything above the blank line sets a field; everything below it is the note, in markdown.
|
|
121
|
+
# Shared: yes makes the note visible to members of this project. An empty title cancels the note.
|
|
122
|
+
# A note is a short fact: the body holds at most {limit} characters.
|
|
123
|
+
Title: {title}
|
|
124
|
+
Tags: {tags}
|
|
125
|
+
Shared: {shared}
|
|
126
|
+
|
|
127
|
+
{body}
|
|
128
|
+
"""
|
|
129
|
+
|
|
130
|
+
NOTE_HEADERS = ("title", "tags", "shared")
|
|
131
|
+
|
|
132
|
+
YES = ("yes", "y", "true", "1")
|
|
133
|
+
|
|
134
|
+
|
|
135
|
+
def repeated(*aliases: str, help: str, choices: tuple[str, ...] | None = None) -> list[str]:
|
|
136
|
+
"""A flag that may be repeated, such as `-t one -t two`. Every value is kept."""
|
|
137
|
+
settings: dict[str, Any] = {
|
|
138
|
+
"action": "append",
|
|
139
|
+
"type": str,
|
|
140
|
+
"nargs": None,
|
|
141
|
+
"default": [],
|
|
142
|
+
"help": help,
|
|
143
|
+
}
|
|
144
|
+
if choices is not None:
|
|
145
|
+
settings["choices"] = choices
|
|
146
|
+
return cast(list[str], argclass.Argument(*aliases, **settings))
|
|
147
|
+
|
|
148
|
+
|
|
149
|
+
def account_value(value: str) -> str:
|
|
150
|
+
"""Require an account marker before converting a list of account values."""
|
|
151
|
+
if ":" not in value and not value.startswith("bcrypt|"):
|
|
152
|
+
raise ValueError("Use username:password or bcrypt|username|<hash> for Basic accounts")
|
|
153
|
+
return value
|
|
154
|
+
|
|
155
|
+
|
|
156
|
+
def account_values(value: str | Sequence[str]) -> list[str]:
|
|
157
|
+
"""Read a shell-quoted environment string or an account sequence."""
|
|
158
|
+
return shlex.split(value) if isinstance(value, str) else list(value)
|
|
159
|
+
|
|
160
|
+
|
|
161
|
+
def secret_accounts(value: str | Sequence[str], cost: int = BCRYPT_COST) -> list[str]:
|
|
162
|
+
"""Hash plaintext account values and keep every account masked in repr."""
|
|
163
|
+
return [argclass.SecretString(item) for item in normalize_accounts(account_values(value), cost)]
|
|
164
|
+
|
|
165
|
+
|
|
166
|
+
class BasicAccountsAction(argparse.Action):
|
|
167
|
+
"""Extend nargs values, including string defaults supplied by the environment."""
|
|
168
|
+
|
|
169
|
+
def __call__(
|
|
170
|
+
self,
|
|
171
|
+
parser: argparse.ArgumentParser,
|
|
172
|
+
namespace: argparse.Namespace,
|
|
173
|
+
values: Any,
|
|
174
|
+
option_string: str | None = None,
|
|
175
|
+
) -> None:
|
|
176
|
+
accounts = account_values(getattr(namespace, self.dest, []) or [])
|
|
177
|
+
setattr(
|
|
178
|
+
namespace,
|
|
179
|
+
self.dest,
|
|
180
|
+
[argclass.SecretString(item) for item in [*accounts, *account_values(values)]],
|
|
181
|
+
)
|
|
182
|
+
|
|
183
|
+
|
|
184
|
+
def build(options: CLI) -> Backlog:
|
|
185
|
+
"""The backlog the global options describe."""
|
|
186
|
+
principal = "local"
|
|
187
|
+
auth = options.mcp.auth
|
|
188
|
+
authorized_http = options.mcp.protocol == "http" and (
|
|
189
|
+
auth.basic or auth.jwt.public_key or auth.jwt.pre_shared_key
|
|
190
|
+
)
|
|
191
|
+
configured_user = (
|
|
192
|
+
options.mcp.default_user_override
|
|
193
|
+
if options.mcp.default_user_override is not None
|
|
194
|
+
else options.default_user
|
|
195
|
+
)
|
|
196
|
+
if authorized_http and configured_user is not None:
|
|
197
|
+
raise ValueError("HTTP --default-user cannot be combined with authentication")
|
|
198
|
+
if not authorized_http:
|
|
199
|
+
username = default_user(configured_user)
|
|
200
|
+
principal = user_identity(username)
|
|
201
|
+
return Backlog(
|
|
202
|
+
options.database or paths.database_path(),
|
|
203
|
+
cwd=options.root,
|
|
204
|
+
project=options.project,
|
|
205
|
+
computer=options.computer,
|
|
206
|
+
principal=principal,
|
|
207
|
+
)
|
|
208
|
+
|
|
209
|
+
|
|
210
|
+
def editor() -> list[str]:
|
|
211
|
+
"""The editor to open, from `VISUAL`, then `EDITOR`, then `vi`."""
|
|
212
|
+
chosen = os.environ.get("VISUAL") or os.environ.get("EDITOR") or "vi"
|
|
213
|
+
return chosen.split()
|
|
214
|
+
|
|
215
|
+
|
|
216
|
+
def compose(text: str) -> str | None:
|
|
217
|
+
"""Open the editor on this text and return what came back, or `None` when nothing changed."""
|
|
218
|
+
with tempfile.NamedTemporaryFile("w+", suffix=".backlog.md", delete=False) as handle:
|
|
219
|
+
handle.write(text)
|
|
220
|
+
name = handle.name
|
|
221
|
+
try:
|
|
222
|
+
subprocess.call([*editor(), name])
|
|
223
|
+
written = Path(name).read_text(encoding="utf-8")
|
|
224
|
+
finally:
|
|
225
|
+
Path(name).unlink(missing_ok=True)
|
|
226
|
+
return None if written.strip() == text.strip() else written
|
|
227
|
+
|
|
228
|
+
|
|
229
|
+
def split_form(
|
|
230
|
+
text: str, headers: tuple[str, ...], *, markdown: bool = False
|
|
231
|
+
) -> tuple[dict[str, str], str]:
|
|
232
|
+
"""Split an edited form into its `Key: value` headers and the text below them.
|
|
233
|
+
|
|
234
|
+
Lines starting with '#' are hints and are dropped. A markdown body keeps them: they are its
|
|
235
|
+
headings, so only the hints above the body go.
|
|
236
|
+
"""
|
|
237
|
+
lines = text.splitlines()
|
|
238
|
+
if not markdown:
|
|
239
|
+
lines = [line for line in lines if not line.startswith("#")]
|
|
240
|
+
while lines and not lines[0].strip():
|
|
241
|
+
lines.pop(0)
|
|
242
|
+
found: dict[str, str] = {}
|
|
243
|
+
rest = len(lines)
|
|
244
|
+
for index, line in enumerate(lines):
|
|
245
|
+
if markdown and line.startswith("#"):
|
|
246
|
+
continue
|
|
247
|
+
key, separator, value = line.partition(":")
|
|
248
|
+
name = key.strip().lower()
|
|
249
|
+
if not separator or name not in headers:
|
|
250
|
+
rest = index
|
|
251
|
+
break
|
|
252
|
+
found[name] = value.strip()
|
|
253
|
+
return found, "\n".join(lines[rest:]).strip()
|
|
254
|
+
|
|
255
|
+
|
|
256
|
+
def split_list(text: str) -> list[str]:
|
|
257
|
+
return [item.strip() for item in text.split(",") if item.strip()]
|
|
258
|
+
|
|
259
|
+
|
|
260
|
+
def parse_form(text: str) -> dict[str, Any]:
|
|
261
|
+
"""Read the edited task form back: the headers at the top, the description below them."""
|
|
262
|
+
headers, body = split_form(text, HEADERS)
|
|
263
|
+
return {
|
|
264
|
+
"title": headers.get("title", ""),
|
|
265
|
+
"body": body,
|
|
266
|
+
"status": Status(headers.get("status", "").lower() or Status.TODO),
|
|
267
|
+
"priority": Priority(headers.get("priority", "").lower() or Priority.NORMAL),
|
|
268
|
+
"tags": split_list(headers.get("tags", "")),
|
|
269
|
+
}
|
|
270
|
+
|
|
271
|
+
|
|
272
|
+
def parse_note_form(text: str) -> dict[str, Any]:
|
|
273
|
+
"""Read the edited note form back: title, tags and the shared flag, then the markdown."""
|
|
274
|
+
headers, body = split_form(text, NOTE_HEADERS, markdown=True)
|
|
275
|
+
return {
|
|
276
|
+
"title": headers.get("title", ""),
|
|
277
|
+
"body": body,
|
|
278
|
+
"tags": split_list(headers.get("tags", "")),
|
|
279
|
+
"shared": headers.get("shared", "").lower() in YES,
|
|
280
|
+
}
|
|
281
|
+
|
|
282
|
+
|
|
283
|
+
def form_of(task: Task | TaskOut | None = None) -> str:
|
|
284
|
+
"""The form to edit: empty for a new task, filled in for one that exists."""
|
|
285
|
+
if task is None:
|
|
286
|
+
return FORM.format(
|
|
287
|
+
title="", status=Status.TODO.value, priority=Priority.NORMAL.value, tags="", body=""
|
|
288
|
+
)
|
|
289
|
+
return FORM.format(
|
|
290
|
+
title=task.title,
|
|
291
|
+
status=task.status.value,
|
|
292
|
+
priority=task.priority.value,
|
|
293
|
+
tags=", ".join(task.tags),
|
|
294
|
+
body=task.body,
|
|
295
|
+
)
|
|
296
|
+
|
|
297
|
+
|
|
298
|
+
def note_form_of(existing: Note | NoteOut | None = None) -> str:
|
|
299
|
+
"""The note form to edit: empty for a new note, filled in for one that exists."""
|
|
300
|
+
if existing is None:
|
|
301
|
+
return NOTE_FORM.format(title="", tags="", shared="no", body="", limit=NOTE_LIMIT)
|
|
302
|
+
return NOTE_FORM.format(
|
|
303
|
+
limit=NOTE_LIMIT,
|
|
304
|
+
title=existing.title,
|
|
305
|
+
tags=", ".join(existing.tags),
|
|
306
|
+
shared="yes" if existing.shared else "no",
|
|
307
|
+
body=existing.body,
|
|
308
|
+
)
|
|
309
|
+
|
|
310
|
+
|
|
311
|
+
class ConfigTemplate(argclass.TOMLConfigGenerator):
|
|
312
|
+
"""The TOML the config files are read as, with the log level written as a lowercase name.
|
|
313
|
+
|
|
314
|
+
Only the root options and the tables in `TABLES` are written: the other commands take
|
|
315
|
+
their options on the command line. A log level given on the command line or in the
|
|
316
|
+
environment arrives as an integer. `--log-level` accepts names only, so an integer would
|
|
317
|
+
not read back.
|
|
318
|
+
"""
|
|
319
|
+
|
|
320
|
+
#: The subcommands whose options a config file may set.
|
|
321
|
+
TABLES = frozenset({"mcp"})
|
|
322
|
+
|
|
323
|
+
def render(self, fields: Sequence[argclass.ConfigField]) -> str:
|
|
324
|
+
cost = validate_bcrypt_cost(
|
|
325
|
+
next(
|
|
326
|
+
(
|
|
327
|
+
field.value
|
|
328
|
+
for field in fields
|
|
329
|
+
if field.attr_path == ("mcp", "auth", "bcrypt_cost")
|
|
330
|
+
),
|
|
331
|
+
BCRYPT_COST,
|
|
332
|
+
)
|
|
333
|
+
)
|
|
334
|
+
kept = [
|
|
335
|
+
self.named(field, cost)
|
|
336
|
+
for field in fields
|
|
337
|
+
if not field.attr_path[:-1] or field.attr_path[0] in self.TABLES
|
|
338
|
+
]
|
|
339
|
+
return super().render(kept)
|
|
340
|
+
|
|
341
|
+
@staticmethod
|
|
342
|
+
def named(field: argclass.ConfigField, cost: int = BCRYPT_COST) -> argclass.ConfigField:
|
|
343
|
+
if field.attr_path == ("mcp", "auth", "basic") and field.value is not None:
|
|
344
|
+
return dataclasses.replace(field, value=secret_accounts(field.value, cost))
|
|
345
|
+
if field.key == "allowed_origin" and field.value is not None:
|
|
346
|
+
return dataclasses.replace(field, value=[str(origin) for origin in field.value])
|
|
347
|
+
if field.key != "log_level" or field.value is None:
|
|
348
|
+
return field
|
|
349
|
+
value = field.value
|
|
350
|
+
if isinstance(value, int):
|
|
351
|
+
value = logging.getLevelName(value)
|
|
352
|
+
return dataclasses.replace(field, value=str(value).lower())
|
|
353
|
+
|
|
354
|
+
|
|
355
|
+
class Command(argclass.Parser):
|
|
356
|
+
"""One subcommand, using the MCP connection opened by the root parser."""
|
|
357
|
+
|
|
358
|
+
def options(self) -> CLI:
|
|
359
|
+
"""The root parser, however deep this command is nested."""
|
|
360
|
+
parent = self.__parent__
|
|
361
|
+
while isinstance(parent, Command):
|
|
362
|
+
parent = parent.__parent__
|
|
363
|
+
assert isinstance(parent, CLI), "a command runs under the root parser"
|
|
364
|
+
return parent
|
|
365
|
+
|
|
366
|
+
def reference(self) -> str | None:
|
|
367
|
+
"""The project this command works on: the `--project` of the root parser."""
|
|
368
|
+
return self.options().project
|
|
369
|
+
|
|
370
|
+
def listing(self) -> dict[str, Any]:
|
|
371
|
+
return {
|
|
372
|
+
"project": self.reference(),
|
|
373
|
+
"all_projects": bool(getattr(self, "all_projects", False)),
|
|
374
|
+
"computer": getattr(self, "at", None) or None,
|
|
375
|
+
"all_computers": bool(getattr(self, "all_computers", False)),
|
|
376
|
+
}
|
|
377
|
+
|
|
378
|
+
@property
|
|
379
|
+
def connection(self) -> Connection:
|
|
380
|
+
return self.options().connection
|
|
381
|
+
|
|
382
|
+
async def ask(self, request: Mapping[str, Any]) -> Mapping[str, Any]:
|
|
383
|
+
params = request.get("params") or request
|
|
384
|
+
message = str(params.get("message", "Confirm this operation?"))
|
|
385
|
+
accepted = bool(getattr(self, "yes", False)) or Confirm.ask(message, default=False)
|
|
386
|
+
return elicit_accept({"ok": accepted})
|
|
387
|
+
|
|
388
|
+
def registration(self, computer: str, root: Path, projects: list[ProjectOut]) -> Registration:
|
|
389
|
+
return prompt_registration(computer, root, projects)
|
|
390
|
+
|
|
391
|
+
async def task(self, task_id: int) -> TaskDetails:
|
|
392
|
+
task = await self.connection.call(TaskDetails, "task_get", id=task_id)
|
|
393
|
+
if task.status == Status.DELETED:
|
|
394
|
+
raise ToolError(f"no task #{task_id}")
|
|
395
|
+
return task
|
|
396
|
+
|
|
397
|
+
def label(self, result: FullTasks | FullNotes | embeddings.Matches | StatsOut) -> str:
|
|
398
|
+
if result.project:
|
|
399
|
+
return result.project
|
|
400
|
+
if getattr(self, "all_computers", False):
|
|
401
|
+
return "every project on every computer"
|
|
402
|
+
computer = getattr(self, "at", None) or result.computer
|
|
403
|
+
return f"every project on {computer}"
|
|
404
|
+
|
|
405
|
+
def show_help(self) -> int:
|
|
406
|
+
"""Print the help of this command, the way `--help` after it does.
|
|
407
|
+
|
|
408
|
+
Only the root parser renders a subparser's help, so this asks it to parse `--help`
|
|
409
|
+
behind the words that lead here, and swallows the exit that argparse then raises.
|
|
410
|
+
"""
|
|
411
|
+
words: list[str] = []
|
|
412
|
+
parser: argclass.Parser = self
|
|
413
|
+
while isinstance(parser, Command):
|
|
414
|
+
parent = parser.__parent__
|
|
415
|
+
assert isinstance(parent, argclass.Parser), "a command runs under the root parser"
|
|
416
|
+
words[:0] = [name for name, item in parent.__subparsers__.items() if item is parser]
|
|
417
|
+
parser = parent
|
|
418
|
+
with contextlib.suppress(SystemExit):
|
|
419
|
+
parser.parse_args([*words, "--help"])
|
|
420
|
+
return 0
|
|
421
|
+
|
|
422
|
+
async def __call__(self) -> int:
|
|
423
|
+
raise NotImplementedError
|
|
424
|
+
|
|
425
|
+
|
|
426
|
+
class HTTPOptions(argclass.Group):
|
|
427
|
+
"""HTTP listener and browser access settings."""
|
|
428
|
+
|
|
429
|
+
listen: str = argclass.Argument(default="127.0.0.1", help="Address to listen on, HTTP only")
|
|
430
|
+
port: int = argclass.Argument(default=3009, help="Port to listen on, HTTP only")
|
|
431
|
+
no_console: bool = argclass.Argument(
|
|
432
|
+
default=False, help="Do not serve the bundled MCP console at /console"
|
|
433
|
+
)
|
|
434
|
+
allowed_origin: frozenset[URL] = argclass.Argument(
|
|
435
|
+
default=[],
|
|
436
|
+
type=URL,
|
|
437
|
+
converter=frozenset,
|
|
438
|
+
help="Additional exact browser Origin accepted by the HTTP endpoint",
|
|
439
|
+
nargs=argclass.Nargs.ZERO_OR_MORE,
|
|
440
|
+
)
|
|
441
|
+
trust_proxy: bool = argclass.Argument(
|
|
442
|
+
default=False,
|
|
443
|
+
help=(
|
|
444
|
+
"Behind a TLS-terminating reverse proxy: skip the Origin check of the endpoint, "
|
|
445
|
+
"the proxy validates origins instead"
|
|
446
|
+
),
|
|
447
|
+
)
|
|
448
|
+
|
|
449
|
+
|
|
450
|
+
class JWTOptions(argclass.Group):
|
|
451
|
+
"""Independent JWT verification keys and common claim requirements."""
|
|
452
|
+
|
|
453
|
+
public_key: str = argclass.Argument(
|
|
454
|
+
default="", help="JWT PEM public key or path to its file; algorithms follow the key type"
|
|
455
|
+
)
|
|
456
|
+
pre_shared_key: str = argclass.Secret(
|
|
457
|
+
default="",
|
|
458
|
+
help="JWT HS256 pre-shared key, at least 32 bytes; independent of public-key JWT",
|
|
459
|
+
)
|
|
460
|
+
issuer: str = argclass.Argument(
|
|
461
|
+
default="", help="Required JWT issuer; empty accepts any issuer"
|
|
462
|
+
)
|
|
463
|
+
audience: str = argclass.Argument(
|
|
464
|
+
default="", help="Required JWT audience; empty disables the audience check"
|
|
465
|
+
)
|
|
466
|
+
|
|
467
|
+
|
|
468
|
+
class AuthOptions(argclass.Group):
|
|
469
|
+
"""Credentials accepted by the HTTP server."""
|
|
470
|
+
|
|
471
|
+
# Argclass converts fields in declaration order, so the cost must precede the accounts.
|
|
472
|
+
bcrypt_cost: int = argclass.Argument(
|
|
473
|
+
default=BCRYPT_COST,
|
|
474
|
+
type=validate_bcrypt_cost,
|
|
475
|
+
help="Bcrypt cost for plaintext account conversion (4–31); existing hashes are unchanged",
|
|
476
|
+
)
|
|
477
|
+
|
|
478
|
+
basic: list[str] = argclass.Secret(
|
|
479
|
+
action=BasicAccountsAction,
|
|
480
|
+
nargs="+",
|
|
481
|
+
type=account_value,
|
|
482
|
+
converter=secret_accounts,
|
|
483
|
+
default=[],
|
|
484
|
+
metavar="USERNAME:PASSWORD",
|
|
485
|
+
help=(
|
|
486
|
+
"Basic accounts, HTTP only; use username:password or bcrypt|username|<hash>; "
|
|
487
|
+
"accepts multiple values or repeated flags alongside JWT"
|
|
488
|
+
),
|
|
489
|
+
)
|
|
490
|
+
|
|
491
|
+
jwt = JWTOptions(title="JWT authentication")
|
|
492
|
+
|
|
493
|
+
def convert_accounts(self, value: str | Sequence[str]) -> list[str]:
|
|
494
|
+
return secret_accounts(value, cost=self.bcrypt_cost)
|
|
495
|
+
|
|
496
|
+
|
|
497
|
+
class HashPassword(Command):
|
|
498
|
+
"""Prompt for Basic credentials and print one bcrypt account entry."""
|
|
499
|
+
|
|
500
|
+
bcrypt_cost: int = argclass.Argument(
|
|
501
|
+
default=BCRYPT_COST,
|
|
502
|
+
type=validate_bcrypt_cost,
|
|
503
|
+
help="Bcrypt cost for the generated password hash (4–31)",
|
|
504
|
+
)
|
|
505
|
+
|
|
506
|
+
async def __call__(self) -> int:
|
|
507
|
+
username = Prompt.ask("Username", console=errors)
|
|
508
|
+
password = Prompt.ask("Password", password=True, console=errors)
|
|
509
|
+
validate_account(username, password)
|
|
510
|
+
hashed = await asyncio.to_thread(bcrypt_account, f"{username}:{password}", self.bcrypt_cost)
|
|
511
|
+
print(hashed)
|
|
512
|
+
return 0
|
|
513
|
+
|
|
514
|
+
|
|
515
|
+
class Serve(Command):
|
|
516
|
+
"""Run the MCP server: on stdio by default, or over HTTP with `--protocol=http`.
|
|
517
|
+
|
|
518
|
+
Groups map to `[mcp.http]`, `[mcp.auth]` and `[mcp.auth.jwt]` in TOML.
|
|
519
|
+
Environment variables use the same group prefixes after `BACKLOG_MCP_`.
|
|
520
|
+
"""
|
|
521
|
+
|
|
522
|
+
@property
|
|
523
|
+
def backlog(self) -> Backlog:
|
|
524
|
+
return bound()
|
|
525
|
+
|
|
526
|
+
protocol: str = argclass.Argument(
|
|
527
|
+
default="stdio",
|
|
528
|
+
choices=("stdio", "http"),
|
|
529
|
+
help="stdio speaks MCP on stdin and stdout; http serves the endpoint and the console",
|
|
530
|
+
)
|
|
531
|
+
default_user_override: str | None = argclass.Argument(
|
|
532
|
+
"--default-user",
|
|
533
|
+
default=None,
|
|
534
|
+
type=str,
|
|
535
|
+
help="Username for stdio or HTTP without authorizers (default: global option, then $USER)",
|
|
536
|
+
)
|
|
537
|
+
http = HTTPOptions(title="HTTP transport")
|
|
538
|
+
auth = AuthOptions(title="HTTP authentication")
|
|
539
|
+
generate_config: str = argclass.Argument(
|
|
540
|
+
action=argclass.GenerateConfigAction,
|
|
541
|
+
generator=ConfigTemplate,
|
|
542
|
+
metavar="FILE",
|
|
543
|
+
help=(
|
|
544
|
+
"Write a TOML config file with these options in its [mcp] tables and exit; '-' "
|
|
545
|
+
"prints it. Options given before this flag are written active, the rest as "
|
|
546
|
+
"commented-out defaults"
|
|
547
|
+
),
|
|
548
|
+
)
|
|
549
|
+
|
|
550
|
+
async def stdio(self) -> int:
|
|
551
|
+
"""MCP on stdin and stdout, the transport every client starts by itself."""
|
|
552
|
+
from aiohttp_tiny_mcp import run_stdio
|
|
553
|
+
|
|
554
|
+
from .server import ACTIVE_REGISTRY, persistent_registry
|
|
555
|
+
|
|
556
|
+
backlog = self.backlog
|
|
557
|
+
log.info("serving %s on stdio, database %s", registry.info.name, backlog.database.path)
|
|
558
|
+
|
|
559
|
+
configured, storage = persistent_registry(backlog)
|
|
560
|
+
token = ACTIVE_REGISTRY.set(configured)
|
|
561
|
+
try:
|
|
562
|
+
await storage.open()
|
|
563
|
+
await storage.sweep()
|
|
564
|
+
await run_stdio(configured)
|
|
565
|
+
finally:
|
|
566
|
+
ACTIVE_REGISTRY.reset(token)
|
|
567
|
+
await storage.close()
|
|
568
|
+
await backlog.close()
|
|
569
|
+
return 0
|
|
570
|
+
|
|
571
|
+
async def __call__(self) -> int:
|
|
572
|
+
match self.protocol:
|
|
573
|
+
case "http":
|
|
574
|
+
await httpd.serve(
|
|
575
|
+
self.backlog,
|
|
576
|
+
address=self.http.listen,
|
|
577
|
+
port=self.http.port,
|
|
578
|
+
basic=[str(account) for account in self.auth.basic],
|
|
579
|
+
jwt_public_key=self.auth.jwt.public_key,
|
|
580
|
+
jwt_pre_shared_key=str(self.auth.jwt.pre_shared_key),
|
|
581
|
+
jwt_issuer=self.auth.jwt.issuer,
|
|
582
|
+
jwt_audience=self.auth.jwt.audience,
|
|
583
|
+
console=not self.http.no_console,
|
|
584
|
+
allowed_origins=self.http.allowed_origin,
|
|
585
|
+
trust_proxy=self.http.trust_proxy,
|
|
586
|
+
)
|
|
587
|
+
case _:
|
|
588
|
+
await self.stdio()
|
|
589
|
+
return 0
|
|
590
|
+
|
|
591
|
+
|
|
592
|
+
class Whoami(Command):
|
|
593
|
+
"""Show the identity used by this connection without registering a project."""
|
|
594
|
+
|
|
595
|
+
async def __call__(self) -> int:
|
|
596
|
+
identity = await self.connection.call(Identity, "whoami")
|
|
597
|
+
console.print(
|
|
598
|
+
fields(
|
|
599
|
+
[
|
|
600
|
+
("principal", principal_label(identity.principal, identity.computer)),
|
|
601
|
+
("auth_type", identity.auth_type),
|
|
602
|
+
("handle", identity.handle),
|
|
603
|
+
("assigned_tasks", str(identity.assigned_tasks)),
|
|
604
|
+
]
|
|
605
|
+
)
|
|
606
|
+
)
|
|
607
|
+
return 0
|
|
608
|
+
|
|
609
|
+
|
|
610
|
+
class Board(Command):
|
|
611
|
+
"""Show project context, counts and ready/claimed tasks."""
|
|
612
|
+
|
|
613
|
+
project: str | None = argclass.Argument(
|
|
614
|
+
"project",
|
|
615
|
+
nargs="?",
|
|
616
|
+
default=None,
|
|
617
|
+
type=str,
|
|
618
|
+
help="Project reference; omit for this checkout",
|
|
619
|
+
)
|
|
620
|
+
|
|
621
|
+
async def __call__(self) -> int:
|
|
622
|
+
console.print(board_panel(await self.connection.board(self.project)))
|
|
623
|
+
return 0
|
|
624
|
+
|
|
625
|
+
|
|
626
|
+
def matching_projects(name: str, projects: list[ProjectOut]) -> list[ProjectOut]:
|
|
627
|
+
exact = [project for project in projects if project.full_name == name or project.slug == name]
|
|
628
|
+
return exact or [
|
|
629
|
+
project
|
|
630
|
+
for project in projects
|
|
631
|
+
if project.name.casefold() == name.casefold() or project.slug == slugify(name)
|
|
632
|
+
]
|
|
633
|
+
|
|
634
|
+
|
|
635
|
+
def prompt_registration(computer: str, root: Path, projects: list[ProjectOut]) -> Registration:
|
|
636
|
+
"""Collect registration details before any project or task is written."""
|
|
637
|
+
if not sys.stdin.isatty():
|
|
638
|
+
raise ToolError(
|
|
639
|
+
f"no project registered for {root} on {computer!r}; "
|
|
640
|
+
"run `backlog init NAME` or `backlog init --existing SLUG` first"
|
|
641
|
+
)
|
|
642
|
+
try:
|
|
643
|
+
while True:
|
|
644
|
+
value = Prompt.ask("Input project directory", default=str(root), console=errors)
|
|
645
|
+
directory = Path(value.strip()).expanduser()
|
|
646
|
+
directory = (root / directory).resolve()
|
|
647
|
+
if directory.is_dir():
|
|
648
|
+
root = directory
|
|
649
|
+
break
|
|
650
|
+
errors.print(f"No such directory: {directory}", markup=False)
|
|
651
|
+
if existing := directory_project(computer, root, projects):
|
|
652
|
+
errors.print(f"This directory belongs to {existing.full_name!r}.", markup=False)
|
|
653
|
+
if not Confirm.ask("Use this project?", default=True, console=errors):
|
|
654
|
+
raise ToolError("registration cancelled")
|
|
655
|
+
return Registration(project=existing.full_name, computer=computer, root=root)
|
|
656
|
+
name = ""
|
|
657
|
+
while not name:
|
|
658
|
+
name = Prompt.ask(
|
|
659
|
+
"Input project name", default=root.name or "project", console=errors
|
|
660
|
+
).strip()
|
|
661
|
+
matches = matching_projects(name, projects)
|
|
662
|
+
if matches:
|
|
663
|
+
if len(matches) > 1:
|
|
664
|
+
slug = Prompt.ask(
|
|
665
|
+
"Input existing project slug",
|
|
666
|
+
choices=[item.full_name for item in matches],
|
|
667
|
+
console=errors,
|
|
668
|
+
)
|
|
669
|
+
existing = next(item for item in matches if item.full_name == slug)
|
|
670
|
+
else:
|
|
671
|
+
existing = matches[0]
|
|
672
|
+
errors.print(f"Existing project: {existing.name} ({existing.full_name})", markup=False)
|
|
673
|
+
computers = ", ".join(sorted({item.computer for item in existing.roots})) or "none"
|
|
674
|
+
errors.print(f"Registered computers: {computers}", markup=False)
|
|
675
|
+
if not Confirm.ask(
|
|
676
|
+
"Bind this directory to the existing project?", default=True, console=errors
|
|
677
|
+
):
|
|
678
|
+
raise ToolError(
|
|
679
|
+
"registration cancelled; choose another name to create a new project"
|
|
680
|
+
)
|
|
681
|
+
return Registration(project=existing.full_name, computer=computer, root=root)
|
|
682
|
+
description = Prompt.ask(
|
|
683
|
+
"Input project description", default="", show_default=False, console=errors
|
|
684
|
+
)
|
|
685
|
+
if not Confirm.ask("Register this project?", default=True, console=errors):
|
|
686
|
+
raise ToolError("registration cancelled")
|
|
687
|
+
return Registration(name=name, description=description, computer=computer, root=root)
|
|
688
|
+
except EOFError:
|
|
689
|
+
raise ToolError("registration cancelled") from None
|
|
690
|
+
|
|
691
|
+
|
|
692
|
+
class Init(Command):
|
|
693
|
+
"""Register the current checkout, interactively or with explicit arguments."""
|
|
694
|
+
|
|
695
|
+
project_name: str = argclass.Argument(
|
|
696
|
+
"project_name", nargs="?", default="", help="New project name"
|
|
697
|
+
)
|
|
698
|
+
details: str = argclass.Argument("--description", default="", help="New project description")
|
|
699
|
+
existing: str = argclass.Argument(
|
|
700
|
+
default="", help="Bind this checkout to an existing project slug"
|
|
701
|
+
)
|
|
702
|
+
|
|
703
|
+
def registration(self, computer: str, root: Path, projects: list[ProjectOut]) -> Registration:
|
|
704
|
+
if self.project_name and self.existing:
|
|
705
|
+
raise ToolError("choose a new project name or --existing, not both")
|
|
706
|
+
if self.existing:
|
|
707
|
+
return Registration(project=self.existing)
|
|
708
|
+
if self.project_name:
|
|
709
|
+
name = self.project_name.strip()
|
|
710
|
+
if not name:
|
|
711
|
+
raise ToolError("project name must not be empty")
|
|
712
|
+
if matches := matching_projects(name, [p for p in projects if p.role == "owner"]):
|
|
713
|
+
raise ToolError(
|
|
714
|
+
f"project already exists; use `backlog init --existing {matches[0].full_name}` "
|
|
715
|
+
"to bind this directory, or choose a different name"
|
|
716
|
+
)
|
|
717
|
+
return Registration(name=name, description=self.details)
|
|
718
|
+
return super().registration(computer, root, projects)
|
|
719
|
+
|
|
720
|
+
async def __call__(self) -> int:
|
|
721
|
+
if self.project_name and self.existing:
|
|
722
|
+
raise ToolError("choose a new project name or --existing, not both")
|
|
723
|
+
if self.project_name and not self.project_name.strip():
|
|
724
|
+
raise ToolError("project name must not be empty")
|
|
725
|
+
if self.existing:
|
|
726
|
+
known = await self.connection.call(
|
|
727
|
+
ProjectList, "project_list", archived=True, all_computers=True
|
|
728
|
+
)
|
|
729
|
+
matches = [
|
|
730
|
+
item
|
|
731
|
+
for item in known.items
|
|
732
|
+
if self.existing in {item.full_name, item.slug, f"#{item.id}"}
|
|
733
|
+
]
|
|
734
|
+
if not matches:
|
|
735
|
+
raise ToolError(f"no project {self.existing!r}")
|
|
736
|
+
if len(matches) > 1:
|
|
737
|
+
names = ", ".join(item.full_name for item in matches)
|
|
738
|
+
raise ToolError(f"ambiguous project {self.existing!r}; use its full name: {names}")
|
|
739
|
+
self.existing = matches[0].full_name
|
|
740
|
+
project = await bind_directory(self.connection, self.registration)
|
|
741
|
+
if self.existing and self.existing != project.full_name:
|
|
742
|
+
raise ToolError(f"this directory already belongs to {project.slug!r}")
|
|
743
|
+
if self.project_name and not matching_projects(self.project_name, [project]):
|
|
744
|
+
raise ToolError(f"this directory already belongs to {project.slug!r}")
|
|
745
|
+
note(f"registered {project.full_name!r} on {self.connection.computer}")
|
|
746
|
+
return 0
|
|
747
|
+
|
|
748
|
+
|
|
749
|
+
def computer_options() -> tuple[str, bool]:
|
|
750
|
+
"""The two arguments that widen a listing to another computer, or to all of them.
|
|
751
|
+
|
|
752
|
+
The class annotations do not reach here, so the type and the action are explicit.
|
|
753
|
+
"""
|
|
754
|
+
at: str = argclass.Argument(
|
|
755
|
+
"--computer",
|
|
756
|
+
type=str,
|
|
757
|
+
default="",
|
|
758
|
+
help="Every project on that computer instead of this one",
|
|
759
|
+
)
|
|
760
|
+
all_computers: bool = argclass.Argument(
|
|
761
|
+
"--all-computers",
|
|
762
|
+
action=argclass.Actions.STORE_TRUE,
|
|
763
|
+
default=False,
|
|
764
|
+
help="Every project on every computer",
|
|
765
|
+
)
|
|
766
|
+
return at, all_computers
|
|
767
|
+
|
|
768
|
+
|
|
769
|
+
class ProjectDelete(Command):
|
|
770
|
+
"""Delete a project with every task and note on its board."""
|
|
771
|
+
|
|
772
|
+
target: str = argclass.Argument("target", help="Project slug, or a path inside it")
|
|
773
|
+
yes: bool = argclass.Argument("-y", "--yes", default=False, help="Delete without asking")
|
|
774
|
+
|
|
775
|
+
async def __call__(self) -> int:
|
|
776
|
+
result = await self.connection.call(ProjectDeleted, "project_delete", project=self.target)
|
|
777
|
+
if not result.deleted:
|
|
778
|
+
warn("nothing deleted")
|
|
779
|
+
return 1
|
|
780
|
+
note(
|
|
781
|
+
f"deleted project {result.full_name!r}: {result.tasks} task(s), {result.memory} note(s)"
|
|
782
|
+
)
|
|
783
|
+
return 0
|
|
784
|
+
|
|
785
|
+
|
|
786
|
+
class ProjectUpdate(Command):
|
|
787
|
+
"""Set or clear the language for project work and task text."""
|
|
788
|
+
|
|
789
|
+
target: str = argclass.Argument("target", help="Project slug, or a path inside it")
|
|
790
|
+
preferred_language: str | None = argclass.Argument(
|
|
791
|
+
type=str, default=None, help="Language for project work and task text, such as ru or en"
|
|
792
|
+
)
|
|
793
|
+
clear_preferred_language: bool = argclass.Argument(
|
|
794
|
+
default=False, help="Clear the project language preference"
|
|
795
|
+
)
|
|
796
|
+
|
|
797
|
+
async def __call__(self) -> int:
|
|
798
|
+
if (self.preferred_language is not None) == self.clear_preferred_language:
|
|
799
|
+
raise ToolError("choose --preferred-language or --clear-preferred-language")
|
|
800
|
+
project = await self.connection.call(
|
|
801
|
+
ProjectOut,
|
|
802
|
+
"project_save",
|
|
803
|
+
exclude_none=False,
|
|
804
|
+
project=self.target,
|
|
805
|
+
preferred_language=self.preferred_language,
|
|
806
|
+
)
|
|
807
|
+
note(f"{project.full_name}: preferred language = {project.preferred_language or 'none'}")
|
|
808
|
+
return 0
|
|
809
|
+
|
|
810
|
+
|
|
811
|
+
class Projects(Command):
|
|
812
|
+
"""List the registered projects of this computer, or of another, or of all."""
|
|
813
|
+
|
|
814
|
+
archived: bool = argclass.Argument(default=False, help="Include archived projects")
|
|
815
|
+
at, all_computers = computer_options()
|
|
816
|
+
update = ProjectUpdate(aliases=["pu"], help="Set or clear the project language preference")
|
|
817
|
+
delete = ProjectDelete(
|
|
818
|
+
aliases=["pd"],
|
|
819
|
+
help="Delete a project for good",
|
|
820
|
+
description=(
|
|
821
|
+
"Delete a project with every task and note on its board, and free its directories "
|
|
822
|
+
"for a new registration. Asks first unless --yes is given. Prefer archiving through "
|
|
823
|
+
"the MCP tool project_save when the history should stay."
|
|
824
|
+
),
|
|
825
|
+
)
|
|
826
|
+
|
|
827
|
+
async def __call__(self) -> int:
|
|
828
|
+
found = await self.connection.call(
|
|
829
|
+
ProjectList,
|
|
830
|
+
"project_list",
|
|
831
|
+
archived=self.archived,
|
|
832
|
+
computer=self.at or None,
|
|
833
|
+
all_computers=self.all_computers,
|
|
834
|
+
)
|
|
835
|
+
console.print(projects_table(found.items, computer=self.connection.computer))
|
|
836
|
+
return 0
|
|
837
|
+
|
|
838
|
+
|
|
839
|
+
class List(Command):
|
|
840
|
+
"""List tasks, open ones first, of this project or of every project."""
|
|
841
|
+
|
|
842
|
+
all_projects: bool = argclass.Argument(
|
|
843
|
+
"-a", "--all-projects", default=False, help="List tasks of every project on this computer"
|
|
844
|
+
)
|
|
845
|
+
at, all_computers = computer_options()
|
|
846
|
+
status: list[str] = repeated(
|
|
847
|
+
"--status",
|
|
848
|
+
choices=STATUSES,
|
|
849
|
+
help="Status to show. Repeat for more (default: the open ones)",
|
|
850
|
+
)
|
|
851
|
+
every: bool = argclass.Argument("--every", default=False, help="Show closed tasks as well")
|
|
852
|
+
tag: str = argclass.Argument(default="", help="Only tasks carrying this tag")
|
|
853
|
+
priority: str = argclass.Argument(default="", choices=("", *PRIORITIES), help="Only this one")
|
|
854
|
+
limit: int = argclass.Argument(default=50, help="Most tasks to print")
|
|
855
|
+
|
|
856
|
+
def wanted(self) -> list[Status] | None:
|
|
857
|
+
if self.status:
|
|
858
|
+
return [Status(item) for item in self.status]
|
|
859
|
+
return None if self.every else list(OPEN_STATUSES)
|
|
860
|
+
|
|
861
|
+
async def __call__(self) -> int:
|
|
862
|
+
found = await self.connection.call(
|
|
863
|
+
FullTasks,
|
|
864
|
+
"task_list",
|
|
865
|
+
**self.listing(),
|
|
866
|
+
status=self.wanted() or [item for item in Status if item != Status.DELETED],
|
|
867
|
+
tag=self.tag or None,
|
|
868
|
+
priority=self.priority or None,
|
|
869
|
+
limit=self.limit,
|
|
870
|
+
full=True,
|
|
871
|
+
)
|
|
872
|
+
console.print(
|
|
873
|
+
tasks_table(
|
|
874
|
+
found.items,
|
|
875
|
+
title=f"{len(found.items)} task(s) of {self.label(found)}",
|
|
876
|
+
wide=found.project is None,
|
|
877
|
+
computer=self.connection.computer,
|
|
878
|
+
)
|
|
879
|
+
)
|
|
880
|
+
return 0
|
|
881
|
+
|
|
882
|
+
|
|
883
|
+
class Search(Command):
|
|
884
|
+
"""FTS and semantic search across projects, tasks, comments, and memory."""
|
|
885
|
+
|
|
886
|
+
kind: list[str] = repeated(
|
|
887
|
+
"--kind",
|
|
888
|
+
choices=("tasks", "comments", "memory", "projects"),
|
|
889
|
+
help="Content to search; repeat for several kinds (default: all)",
|
|
890
|
+
)
|
|
891
|
+
query: list[str] = argclass.Argument("query", nargs="+", help="Words or meaning to search for")
|
|
892
|
+
all_projects: bool = argclass.Argument(
|
|
893
|
+
"-a", "--all-projects", default=False, help="Search every project on this computer"
|
|
894
|
+
)
|
|
895
|
+
at, all_computers = computer_options()
|
|
896
|
+
tag: str = argclass.Argument(
|
|
897
|
+
default="", help="Filter by task or note tags; comments use their task tags"
|
|
898
|
+
)
|
|
899
|
+
limit: int = argclass.Argument(default=20, help="Most matches to print, of each kind")
|
|
900
|
+
min_score: float | None = argclass.Argument(
|
|
901
|
+
default=None,
|
|
902
|
+
help="Minimum vector similarity (-1 to 1), default 0.15; does not filter text matches",
|
|
903
|
+
)
|
|
904
|
+
|
|
905
|
+
async def __call__(self) -> int:
|
|
906
|
+
text = " ".join(self.query)
|
|
907
|
+
matches = await self.connection.call(
|
|
908
|
+
embeddings.Matches,
|
|
909
|
+
"search",
|
|
910
|
+
**self.listing(),
|
|
911
|
+
query=[text],
|
|
912
|
+
kinds=self.kind or None,
|
|
913
|
+
tag=self.tag or None,
|
|
914
|
+
limit=self.limit,
|
|
915
|
+
min_score=self.min_score,
|
|
916
|
+
)
|
|
917
|
+
where = self.label(matches)
|
|
918
|
+
if not self.kind or "tasks" in self.kind:
|
|
919
|
+
console.print(
|
|
920
|
+
tasks_table(
|
|
921
|
+
matches.tasks,
|
|
922
|
+
title=f"{len(matches.tasks)} task match(es) for {text!r} in {where}",
|
|
923
|
+
wide=matches.project is None,
|
|
924
|
+
computer=self.connection.computer,
|
|
925
|
+
)
|
|
926
|
+
)
|
|
927
|
+
if matches.projects or "projects" in self.kind:
|
|
928
|
+
table = projects_table(matches.projects, computer=self.connection.computer)
|
|
929
|
+
table.title = f"{len(matches.projects)} project match(es) for {text!r} in {where}"
|
|
930
|
+
console.print(table)
|
|
931
|
+
if matches.comments or "comments" in self.kind:
|
|
932
|
+
console.print(
|
|
933
|
+
comments_table(
|
|
934
|
+
matches.comments,
|
|
935
|
+
title=f"{len(matches.comments)} comment match(es) for {text!r} in {where}",
|
|
936
|
+
)
|
|
937
|
+
)
|
|
938
|
+
if matches.memory or "memory" in self.kind:
|
|
939
|
+
console.print(
|
|
940
|
+
notes_table(
|
|
941
|
+
matches.memory,
|
|
942
|
+
title=f"{len(matches.memory)} note match(es) for {text!r} in {where}",
|
|
943
|
+
wide=matches.project is None
|
|
944
|
+
or any(n.project != matches.project for n in matches.memory),
|
|
945
|
+
computer=self.connection.computer,
|
|
946
|
+
)
|
|
947
|
+
)
|
|
948
|
+
return 0
|
|
949
|
+
|
|
950
|
+
|
|
951
|
+
class Show(Command):
|
|
952
|
+
"""Print one task in full."""
|
|
953
|
+
|
|
954
|
+
id: int = argclass.Argument("id", type=int, help="Task id")
|
|
955
|
+
|
|
956
|
+
async def __call__(self) -> int:
|
|
957
|
+
console.print(task_panel(await self.task(self.id), computer=self.connection.computer))
|
|
958
|
+
return 0
|
|
959
|
+
|
|
960
|
+
|
|
961
|
+
class Assigned(Command):
|
|
962
|
+
"""List assigned tasks across accessible projects, including closed tasks."""
|
|
963
|
+
|
|
964
|
+
prefix: str | None = argclass.Argument(
|
|
965
|
+
default=None, type=str, help="Assignment prefix; omit for your principal"
|
|
966
|
+
)
|
|
967
|
+
limit: int = argclass.Argument(default=50, type=int, help="Maximum tasks to return")
|
|
968
|
+
offset: int = argclass.Argument(default=0, type=int, help="Skip this many matching tasks")
|
|
969
|
+
|
|
970
|
+
async def __call__(self) -> int:
|
|
971
|
+
result = await self.connection.call(
|
|
972
|
+
Tasks, "task_assigned", prefix=self.prefix, limit=self.limit, offset=self.offset
|
|
973
|
+
)
|
|
974
|
+
console.print(
|
|
975
|
+
tasks_table(
|
|
976
|
+
[TaskOut(**item.model_dump()) for item in result.items],
|
|
977
|
+
title=f"{result.count} assigned task(s)",
|
|
978
|
+
wide=True,
|
|
979
|
+
)
|
|
980
|
+
)
|
|
981
|
+
return 0
|
|
982
|
+
|
|
983
|
+
|
|
984
|
+
class Claim(Command):
|
|
985
|
+
"""Replace a task assignment only when its current value matches --expected."""
|
|
986
|
+
|
|
987
|
+
id: int = argclass.Argument("id", type=int, metavar="TASK", help="Task id")
|
|
988
|
+
expected: str = argclass.Argument(
|
|
989
|
+
required=True, help="Current username@computer:marker, or null"
|
|
990
|
+
)
|
|
991
|
+
assigned: str = argclass.Argument(
|
|
992
|
+
required=True, help="New username@computer:marker, or null to release"
|
|
993
|
+
)
|
|
994
|
+
|
|
995
|
+
async def __call__(self) -> int:
|
|
996
|
+
result = await self.connection.call(
|
|
997
|
+
TaskOut,
|
|
998
|
+
"task_claim",
|
|
999
|
+
exclude_none=False,
|
|
1000
|
+
task=self.id,
|
|
1001
|
+
expected=None if self.expected == "null" else self.expected,
|
|
1002
|
+
assigned=None if self.assigned == "null" else self.assigned,
|
|
1003
|
+
)
|
|
1004
|
+
console.print(task_panel(result, computer=self.connection.computer))
|
|
1005
|
+
return 0
|
|
1006
|
+
|
|
1007
|
+
|
|
1008
|
+
class Link(Command):
|
|
1009
|
+
"""Create a relation and its inverse, or change their reason."""
|
|
1010
|
+
|
|
1011
|
+
source: int = argclass.Argument("source", type=int, metavar="TASK", help="Source task id")
|
|
1012
|
+
relation: str = argclass.Argument("relation", choices=[item.value for item in Relation])
|
|
1013
|
+
target: int = argclass.Argument("target", type=int, help="Target task id")
|
|
1014
|
+
reason: str | None = argclass.Argument(
|
|
1015
|
+
default=None, type=str, help="Explanation; omit to preserve it, pass empty text to clear"
|
|
1016
|
+
)
|
|
1017
|
+
|
|
1018
|
+
async def __call__(self) -> int:
|
|
1019
|
+
result = await self.connection.call(
|
|
1020
|
+
LinkChange,
|
|
1021
|
+
"task_link",
|
|
1022
|
+
task=self.source,
|
|
1023
|
+
relation=self.relation,
|
|
1024
|
+
target=self.target,
|
|
1025
|
+
reason=self.reason,
|
|
1026
|
+
)
|
|
1027
|
+
note("link saved" if result.changed else "link unchanged")
|
|
1028
|
+
return 0
|
|
1029
|
+
|
|
1030
|
+
|
|
1031
|
+
class Unlink(Command):
|
|
1032
|
+
"""Remove a relation and its inverse."""
|
|
1033
|
+
|
|
1034
|
+
source: int = argclass.Argument("source", type=int, metavar="TASK", help="Source task id")
|
|
1035
|
+
relation: str = argclass.Argument("relation", choices=[item.value for item in Relation])
|
|
1036
|
+
target: int = argclass.Argument("target", type=int, help="Target task id")
|
|
1037
|
+
|
|
1038
|
+
async def __call__(self) -> int:
|
|
1039
|
+
result = await self.connection.call(
|
|
1040
|
+
LinkChange,
|
|
1041
|
+
"task_unlink",
|
|
1042
|
+
task=self.source,
|
|
1043
|
+
relation=self.relation,
|
|
1044
|
+
target=self.target,
|
|
1045
|
+
)
|
|
1046
|
+
note("link removed" if result.changed else "link absent")
|
|
1047
|
+
return 0
|
|
1048
|
+
|
|
1049
|
+
|
|
1050
|
+
class CommentAdd(Command):
|
|
1051
|
+
"""Add a Markdown comment without changing the task description."""
|
|
1052
|
+
|
|
1053
|
+
id: int = argclass.Argument("id", type=int, help="Task id")
|
|
1054
|
+
body: list[str] = argclass.Argument("body", nargs="+", help="Comment text")
|
|
1055
|
+
|
|
1056
|
+
async def __call__(self) -> int:
|
|
1057
|
+
comment = await self.connection.call(
|
|
1058
|
+
CommentOut,
|
|
1059
|
+
"task_comment_add",
|
|
1060
|
+
task_id=self.id,
|
|
1061
|
+
body=" ".join(self.body),
|
|
1062
|
+
)
|
|
1063
|
+
console.print(comment_panel(comment))
|
|
1064
|
+
return 0
|
|
1065
|
+
|
|
1066
|
+
|
|
1067
|
+
class CommentList(Command):
|
|
1068
|
+
"""Read all comments and history in chronological order."""
|
|
1069
|
+
|
|
1070
|
+
id: int = argclass.Argument("id", type=int, help="Task id")
|
|
1071
|
+
|
|
1072
|
+
async def __call__(self) -> int:
|
|
1073
|
+
result = await self.connection.call(
|
|
1074
|
+
Comments,
|
|
1075
|
+
"task_comment_list",
|
|
1076
|
+
task_id=self.id,
|
|
1077
|
+
)
|
|
1078
|
+
for item in result.items:
|
|
1079
|
+
console.print(comment_panel(item))
|
|
1080
|
+
note(f"{result.count} comments and history entries")
|
|
1081
|
+
return 0
|
|
1082
|
+
|
|
1083
|
+
|
|
1084
|
+
class Add(Command):
|
|
1085
|
+
"""Add a task from the command line, without opening an editor."""
|
|
1086
|
+
|
|
1087
|
+
title: list[str] = argclass.Argument("title", nargs="+", help="Title of the task")
|
|
1088
|
+
body: str = argclass.Argument("-b", "--body", default="", help="Description")
|
|
1089
|
+
status: str = argclass.Argument("-s", "--status", default=Status.TODO.value, choices=STATUSES)
|
|
1090
|
+
priority: str = argclass.Argument(default=Priority.NORMAL.value, choices=PRIORITIES)
|
|
1091
|
+
tag: list[str] = repeated("-t", "--tag", help="Tag to attach. Repeat for more than one")
|
|
1092
|
+
|
|
1093
|
+
async def __call__(self) -> int:
|
|
1094
|
+
task = await self.connection.call(
|
|
1095
|
+
TaskOut,
|
|
1096
|
+
"task_add",
|
|
1097
|
+
project=self.reference(),
|
|
1098
|
+
title=" ".join(self.title),
|
|
1099
|
+
body=self.body,
|
|
1100
|
+
status=self.status,
|
|
1101
|
+
priority=self.priority,
|
|
1102
|
+
tags=self.tag,
|
|
1103
|
+
)
|
|
1104
|
+
note(f"added #{task.id} to {task.project}")
|
|
1105
|
+
console.print(task_panel(task, computer=self.connection.computer))
|
|
1106
|
+
return 0
|
|
1107
|
+
|
|
1108
|
+
|
|
1109
|
+
class Create(Command):
|
|
1110
|
+
"""Write a task in `$EDITOR`, from a filled-in form."""
|
|
1111
|
+
|
|
1112
|
+
async def __call__(self) -> int:
|
|
1113
|
+
written = compose(form_of())
|
|
1114
|
+
if written is None:
|
|
1115
|
+
warn("nothing written, no task added")
|
|
1116
|
+
return 1
|
|
1117
|
+
fields = parse_form(written)
|
|
1118
|
+
if not fields["title"]:
|
|
1119
|
+
warn("the title is empty, no task added")
|
|
1120
|
+
return 1
|
|
1121
|
+
task = await self.connection.call(TaskOut, "task_add", project=self.reference(), **fields)
|
|
1122
|
+
note(f"added #{task.id} to {task.project}")
|
|
1123
|
+
console.print(task_panel(task, computer=self.connection.computer))
|
|
1124
|
+
return 0
|
|
1125
|
+
|
|
1126
|
+
|
|
1127
|
+
class Edit(Command):
|
|
1128
|
+
"""Edit a task in `$EDITOR`."""
|
|
1129
|
+
|
|
1130
|
+
id: int = argclass.Argument("id", type=int, help="Task id")
|
|
1131
|
+
|
|
1132
|
+
async def __call__(self) -> int:
|
|
1133
|
+
task = await self.task(self.id)
|
|
1134
|
+
written = compose(form_of(task))
|
|
1135
|
+
if written is None:
|
|
1136
|
+
warn("nothing changed")
|
|
1137
|
+
return 0
|
|
1138
|
+
fields = parse_form(written)
|
|
1139
|
+
if not fields["title"]:
|
|
1140
|
+
warn("the title is empty, nothing changed")
|
|
1141
|
+
return 1
|
|
1142
|
+
changed = await self.connection.call(TaskOut, "task_update", id=task.id, **fields)
|
|
1143
|
+
note(f"updated #{changed.id}")
|
|
1144
|
+
console.print(task_panel(changed, computer=self.connection.computer))
|
|
1145
|
+
return 0
|
|
1146
|
+
|
|
1147
|
+
|
|
1148
|
+
class Transition(Command):
|
|
1149
|
+
"""Base of the commands that only move a task from one status to another."""
|
|
1150
|
+
|
|
1151
|
+
ids: list[int] = argclass.Argument("ids", type=int, nargs="+", help="Task ids")
|
|
1152
|
+
target = Status.DONE
|
|
1153
|
+
|
|
1154
|
+
async def __call__(self) -> int:
|
|
1155
|
+
failed = 0
|
|
1156
|
+
for task_id in self.ids:
|
|
1157
|
+
try:
|
|
1158
|
+
task = await self.connection.call(
|
|
1159
|
+
TaskOut, "task_update", id=task_id, status=self.target
|
|
1160
|
+
)
|
|
1161
|
+
except ToolError as error:
|
|
1162
|
+
fail(str(error))
|
|
1163
|
+
failed += 1
|
|
1164
|
+
continue
|
|
1165
|
+
note(f"#{task.id} is {task.status.value}: {task.title}")
|
|
1166
|
+
return 1 if failed else 0
|
|
1167
|
+
|
|
1168
|
+
|
|
1169
|
+
class Close(Transition):
|
|
1170
|
+
"""Mark tasks done."""
|
|
1171
|
+
|
|
1172
|
+
target = Status.DONE
|
|
1173
|
+
|
|
1174
|
+
|
|
1175
|
+
class Cancel(Transition):
|
|
1176
|
+
"""Mark tasks cancelled: kept, but closed."""
|
|
1177
|
+
|
|
1178
|
+
target = Status.CANCELLED
|
|
1179
|
+
|
|
1180
|
+
|
|
1181
|
+
class Start(Transition):
|
|
1182
|
+
"""Mark tasks in progress."""
|
|
1183
|
+
|
|
1184
|
+
target = Status.DOING
|
|
1185
|
+
|
|
1186
|
+
|
|
1187
|
+
class Reopen(Transition):
|
|
1188
|
+
"""Put tasks back on the pile."""
|
|
1189
|
+
|
|
1190
|
+
target = Status.TODO
|
|
1191
|
+
|
|
1192
|
+
|
|
1193
|
+
class Block(Transition):
|
|
1194
|
+
"""Mark tasks blocked."""
|
|
1195
|
+
|
|
1196
|
+
target = Status.BLOCKED
|
|
1197
|
+
|
|
1198
|
+
|
|
1199
|
+
class Move(Command):
|
|
1200
|
+
"""Move a task into another project."""
|
|
1201
|
+
|
|
1202
|
+
id: int = argclass.Argument("id", type=int, help="Task id")
|
|
1203
|
+
destination: str = argclass.Argument("destination", help="Project slug, or a path inside it")
|
|
1204
|
+
|
|
1205
|
+
async def __call__(self) -> int:
|
|
1206
|
+
existing = await self.task(self.id)
|
|
1207
|
+
task = await self.connection.call(
|
|
1208
|
+
TaskOut, "task_move", id=self.id, project=self.destination
|
|
1209
|
+
)
|
|
1210
|
+
if existing.project == task.project:
|
|
1211
|
+
note(f"#{task.id} already belongs to {task.project}")
|
|
1212
|
+
else:
|
|
1213
|
+
note(f"#{task.id} now belongs to {task.project}")
|
|
1214
|
+
return 0
|
|
1215
|
+
|
|
1216
|
+
|
|
1217
|
+
class Delete(Command):
|
|
1218
|
+
"""Delete a task for good."""
|
|
1219
|
+
|
|
1220
|
+
id: int = argclass.Argument("id", type=int, help="Task id")
|
|
1221
|
+
yes: bool = argclass.Argument(
|
|
1222
|
+
"-y",
|
|
1223
|
+
"--yes",
|
|
1224
|
+
default=False,
|
|
1225
|
+
help="Confirm deletion from another project",
|
|
1226
|
+
)
|
|
1227
|
+
|
|
1228
|
+
async def __call__(self) -> int:
|
|
1229
|
+
task = await self.task(self.id)
|
|
1230
|
+
current = (await self.connection.board()).project
|
|
1231
|
+
if (
|
|
1232
|
+
task.project != current.full_name
|
|
1233
|
+
and not self.yes
|
|
1234
|
+
and not Confirm.ask(
|
|
1235
|
+
f"delete task #{task.id} {task.title!r} from {task.project!r}?",
|
|
1236
|
+
default=False,
|
|
1237
|
+
)
|
|
1238
|
+
):
|
|
1239
|
+
warn("nothing deleted")
|
|
1240
|
+
return 1
|
|
1241
|
+
await self.connection.call(Deleted, "task_delete", id=self.id)
|
|
1242
|
+
note(f"deleted #{self.id}")
|
|
1243
|
+
return 0
|
|
1244
|
+
|
|
1245
|
+
|
|
1246
|
+
class Stats(Command):
|
|
1247
|
+
"""Open tasks, closed tasks, notes, and detailed task counts."""
|
|
1248
|
+
|
|
1249
|
+
all_projects: bool = argclass.Argument(
|
|
1250
|
+
"-a", "--all-projects", default=False, help="Count every project on this computer together"
|
|
1251
|
+
)
|
|
1252
|
+
at, all_computers = computer_options()
|
|
1253
|
+
|
|
1254
|
+
async def __call__(self) -> int:
|
|
1255
|
+
result = await self.connection.call(StatsOut, "stats", **self.listing())
|
|
1256
|
+
console.print(stats_view(result, where=self.label(result)))
|
|
1257
|
+
return 0
|
|
1258
|
+
|
|
1259
|
+
|
|
1260
|
+
class NoteList(Command):
|
|
1261
|
+
"""List your personal and shared notes in the selected project, or across projects."""
|
|
1262
|
+
|
|
1263
|
+
all_projects: bool = argclass.Argument(
|
|
1264
|
+
"-a", "--all-projects", default=False, help="List notes of every project on this computer"
|
|
1265
|
+
)
|
|
1266
|
+
at, all_computers = computer_options()
|
|
1267
|
+
tag: str = argclass.Argument(default="", help="Only notes carrying this tag")
|
|
1268
|
+
shared: bool = argclass.Argument("--shared", default=False, help="Only shared notes")
|
|
1269
|
+
limit: int = argclass.Argument(default=50, help="Most notes to print")
|
|
1270
|
+
|
|
1271
|
+
async def __call__(self) -> int:
|
|
1272
|
+
found = await self.connection.call(
|
|
1273
|
+
FullNotes,
|
|
1274
|
+
"memory_list",
|
|
1275
|
+
**self.listing(),
|
|
1276
|
+
tag=self.tag or None,
|
|
1277
|
+
shared=True if self.shared else None,
|
|
1278
|
+
limit=self.limit,
|
|
1279
|
+
full=True,
|
|
1280
|
+
)
|
|
1281
|
+
console.print(
|
|
1282
|
+
notes_table(
|
|
1283
|
+
found.items,
|
|
1284
|
+
title=f"{len(found.items)} note(s) of {self.label(found)}",
|
|
1285
|
+
wide=found.project is None or any(n.project != found.project for n in found.items),
|
|
1286
|
+
computer=self.connection.computer,
|
|
1287
|
+
)
|
|
1288
|
+
)
|
|
1289
|
+
return 0
|
|
1290
|
+
|
|
1291
|
+
|
|
1292
|
+
class NoteShow(Command):
|
|
1293
|
+
"""Print one note in full."""
|
|
1294
|
+
|
|
1295
|
+
id: int = argclass.Argument("id", type=int, help="Note id")
|
|
1296
|
+
|
|
1297
|
+
async def __call__(self) -> int:
|
|
1298
|
+
found = await self.connection.call(NoteOut, "memory_get", id=self.id)
|
|
1299
|
+
console.print(note_panel(found, computer=self.connection.computer))
|
|
1300
|
+
return 0
|
|
1301
|
+
|
|
1302
|
+
|
|
1303
|
+
class NoteAdd(Command):
|
|
1304
|
+
"""Save a note: create it, or replace the body of the one with that title."""
|
|
1305
|
+
|
|
1306
|
+
title: list[str] = argclass.Argument("title", nargs="+", help="Title of the note")
|
|
1307
|
+
body: str = argclass.Argument(
|
|
1308
|
+
"-b", "--body", default="", help=f"The note, in markdown, at most {NOTE_LIMIT} characters"
|
|
1309
|
+
)
|
|
1310
|
+
tag: list[str] = repeated("-t", "--tag", help="Tag to attach. Repeat for more than one")
|
|
1311
|
+
shared: bool = argclass.Argument(
|
|
1312
|
+
"--shared", default=False, help="Share the note with members of this project"
|
|
1313
|
+
)
|
|
1314
|
+
|
|
1315
|
+
async def __call__(self) -> int:
|
|
1316
|
+
title = " ".join(self.title)
|
|
1317
|
+
check_note(self.body)
|
|
1318
|
+
existing: NoteOut | None = None
|
|
1319
|
+
try:
|
|
1320
|
+
existing = await self.connection.call(
|
|
1321
|
+
NoteOut,
|
|
1322
|
+
"memory_get",
|
|
1323
|
+
title=title,
|
|
1324
|
+
project=self.reference(),
|
|
1325
|
+
)
|
|
1326
|
+
except ToolError as error:
|
|
1327
|
+
if not str(error).startswith("no note"):
|
|
1328
|
+
raise
|
|
1329
|
+
saved = await self.connection.call(
|
|
1330
|
+
NoteOut,
|
|
1331
|
+
"memory_save",
|
|
1332
|
+
project=self.reference(),
|
|
1333
|
+
title=title,
|
|
1334
|
+
body=self.body,
|
|
1335
|
+
tags=self.tag or None,
|
|
1336
|
+
shared=self.shared or None,
|
|
1337
|
+
)
|
|
1338
|
+
if existing is not None and existing.id == saved.id:
|
|
1339
|
+
note(f"replaced note #{saved.id} in {saved.project}")
|
|
1340
|
+
else:
|
|
1341
|
+
note(f"added note #{saved.id} to {saved.project}")
|
|
1342
|
+
console.print(note_panel(saved, computer=self.connection.computer))
|
|
1343
|
+
return 0
|
|
1344
|
+
|
|
1345
|
+
|
|
1346
|
+
class NoteAppend(Command):
|
|
1347
|
+
"""Add a paragraph at the end of a note."""
|
|
1348
|
+
|
|
1349
|
+
id: int = argclass.Argument("id", type=int, help="Note id")
|
|
1350
|
+
text: list[str] = argclass.Argument("text", nargs="+", help="The paragraph to add")
|
|
1351
|
+
|
|
1352
|
+
async def __call__(self) -> int:
|
|
1353
|
+
updated = await self.connection.call(
|
|
1354
|
+
NoteOut, "memory_append", id=self.id, text=" ".join(self.text)
|
|
1355
|
+
)
|
|
1356
|
+
note(f"appended to note #{updated.id}")
|
|
1357
|
+
console.print(note_panel(updated, computer=self.connection.computer))
|
|
1358
|
+
return 0
|
|
1359
|
+
|
|
1360
|
+
|
|
1361
|
+
class NoteEdit(Command):
|
|
1362
|
+
"""Edit a note in `$EDITOR`."""
|
|
1363
|
+
|
|
1364
|
+
id: int = argclass.Argument("id", type=int, help="Note id")
|
|
1365
|
+
|
|
1366
|
+
async def __call__(self) -> int:
|
|
1367
|
+
found = await self.connection.call(NoteOut, "memory_get", id=self.id)
|
|
1368
|
+
written = compose(note_form_of(found))
|
|
1369
|
+
if written is None:
|
|
1370
|
+
warn("nothing changed")
|
|
1371
|
+
return 0
|
|
1372
|
+
fields = parse_note_form(written)
|
|
1373
|
+
if not fields["title"]:
|
|
1374
|
+
warn("the title is empty, nothing changed")
|
|
1375
|
+
return 1
|
|
1376
|
+
check_note(fields["body"])
|
|
1377
|
+
updated = await self.connection.call(NoteOut, "memory_save", id=found.id, **fields)
|
|
1378
|
+
note(f"updated note #{updated.id}")
|
|
1379
|
+
console.print(note_panel(updated, computer=self.connection.computer))
|
|
1380
|
+
return 0
|
|
1381
|
+
|
|
1382
|
+
|
|
1383
|
+
class NoteDelete(Command):
|
|
1384
|
+
"""Delete a note for good."""
|
|
1385
|
+
|
|
1386
|
+
id: int = argclass.Argument("id", type=int, help="Note id")
|
|
1387
|
+
yes: bool = argclass.Argument(
|
|
1388
|
+
"-y",
|
|
1389
|
+
"--yes",
|
|
1390
|
+
default=False,
|
|
1391
|
+
help="Confirm deletion from another project",
|
|
1392
|
+
)
|
|
1393
|
+
|
|
1394
|
+
async def __call__(self) -> int:
|
|
1395
|
+
result = await self.connection.call(Deleted, "memory_delete", id=self.id)
|
|
1396
|
+
if not result.deleted:
|
|
1397
|
+
warn("nothing deleted")
|
|
1398
|
+
return 1
|
|
1399
|
+
note(f"deleted note #{self.id}")
|
|
1400
|
+
return 0
|
|
1401
|
+
|
|
1402
|
+
|
|
1403
|
+
class Notes(Command):
|
|
1404
|
+
"""Lasting user context unavailable from other sources."""
|
|
1405
|
+
|
|
1406
|
+
list = NoteList(
|
|
1407
|
+
aliases=["nl"],
|
|
1408
|
+
help="List your personal and shared notes in this project",
|
|
1409
|
+
description=(
|
|
1410
|
+
"Print your personal notes and project-shared notes, most recently "
|
|
1411
|
+
"changed first. --tag keeps one tag, --shared keeps the shared notes only, and "
|
|
1412
|
+
"--all-projects lists every board."
|
|
1413
|
+
),
|
|
1414
|
+
)
|
|
1415
|
+
show = NoteShow(
|
|
1416
|
+
aliases=["ns"],
|
|
1417
|
+
help="Print one note in full",
|
|
1418
|
+
description="Print a note by id: its tags, whether it is shared, and the markdown body.",
|
|
1419
|
+
)
|
|
1420
|
+
add = NoteAdd(
|
|
1421
|
+
aliases=["na"],
|
|
1422
|
+
help="Write a note, or replace the one with that title",
|
|
1423
|
+
description=(
|
|
1424
|
+
"Save a note from the command line. Titles are unique within each audience: a new "
|
|
1425
|
+
"title creates the note, a known one replaces its body and tags. --shared makes "
|
|
1426
|
+
"the note visible to members of this project. Keep secrets out; write where they live."
|
|
1427
|
+
),
|
|
1428
|
+
)
|
|
1429
|
+
append = NoteAppend(
|
|
1430
|
+
aliases=["np"],
|
|
1431
|
+
help="Add a paragraph at the end of a note",
|
|
1432
|
+
description=(
|
|
1433
|
+
"Extend a note by id without rewriting it. The text lands after a blank line, so "
|
|
1434
|
+
"one fact per call keeps the note readable. `backlog search` finds notes as well."
|
|
1435
|
+
),
|
|
1436
|
+
)
|
|
1437
|
+
edit = NoteEdit(
|
|
1438
|
+
aliases=["ne"],
|
|
1439
|
+
help="Edit a note in $EDITOR",
|
|
1440
|
+
description=(
|
|
1441
|
+
"Open a note in the editor as a form: the title, the tags and the shared flag on "
|
|
1442
|
+
"top, the markdown body below. Nothing changes when the file comes back unchanged."
|
|
1443
|
+
),
|
|
1444
|
+
)
|
|
1445
|
+
delete = NoteDelete(
|
|
1446
|
+
aliases=["nd"],
|
|
1447
|
+
help="Delete a note for good",
|
|
1448
|
+
description=(
|
|
1449
|
+
"Delete a note permanently. Ask first only for another project, unless --yes is given. "
|
|
1450
|
+
"Tasks that link the note as `note #id` keep the dead link."
|
|
1451
|
+
),
|
|
1452
|
+
)
|
|
1453
|
+
|
|
1454
|
+
async def __call__(self) -> int:
|
|
1455
|
+
return self.show_help()
|
|
1456
|
+
|
|
1457
|
+
|
|
1458
|
+
class Skills(Command):
|
|
1459
|
+
"""The written skills this server offers to MCP clients."""
|
|
1460
|
+
|
|
1461
|
+
skill: str = argclass.Argument("skill", nargs="?", default=None, help="Skill to print in full")
|
|
1462
|
+
|
|
1463
|
+
async def __call__(self) -> int:
|
|
1464
|
+
found = await self.connection.skills()
|
|
1465
|
+
if self.skill is None:
|
|
1466
|
+
if not found:
|
|
1467
|
+
warn("no skills")
|
|
1468
|
+
return 1
|
|
1469
|
+
console.print(skills_table(found))
|
|
1470
|
+
return 0
|
|
1471
|
+
one = next((item for item in found if item.name == self.skill), None)
|
|
1472
|
+
if one is None:
|
|
1473
|
+
fail(f"no skill {self.skill!r}")
|
|
1474
|
+
return 1
|
|
1475
|
+
content = await self.connection.read(one.uri)
|
|
1476
|
+
one.instructions = skills.body(content.text)
|
|
1477
|
+
console.print(skill_panel(one))
|
|
1478
|
+
return 0
|
|
1479
|
+
|
|
1480
|
+
|
|
1481
|
+
class Watch(Command):
|
|
1482
|
+
"""Print each change of a backlog server as it happens."""
|
|
1483
|
+
|
|
1484
|
+
endpoint: str = argclass.Argument(
|
|
1485
|
+
"endpoint",
|
|
1486
|
+
nargs="?",
|
|
1487
|
+
default="",
|
|
1488
|
+
help="The MCP endpoint of a running server, e.g. https://host/mcp?computer=laptop",
|
|
1489
|
+
)
|
|
1490
|
+
auth_user: str = argclass.Argument("-u", "--user", default="", help="Basic auth user")
|
|
1491
|
+
auth_password: str = argclass.Secret("--password", default="", help="Basic auth password")
|
|
1492
|
+
count: int = argclass.Argument(
|
|
1493
|
+
"-n",
|
|
1494
|
+
"--count",
|
|
1495
|
+
default=0,
|
|
1496
|
+
help="Stop after this many events; 0 watches until interrupted",
|
|
1497
|
+
)
|
|
1498
|
+
|
|
1499
|
+
async def __call__(self) -> int:
|
|
1500
|
+
from aiohttp_tiny_mcp import MethodFilter
|
|
1501
|
+
|
|
1502
|
+
project = self.reference()
|
|
1503
|
+
if project:
|
|
1504
|
+
selected = (await self.connection.board()).project
|
|
1505
|
+
project = selected.full_name
|
|
1506
|
+
methods: list[str | MethodFilter] = [
|
|
1507
|
+
MethodFilter(method=method, topics=[project]) if project else method
|
|
1508
|
+
for method in (TASK_CHANGED, NOTE_CHANGED)
|
|
1509
|
+
]
|
|
1510
|
+
methods.append(PROJECT_CHANGED)
|
|
1511
|
+
seen = 0
|
|
1512
|
+
listening = cast(
|
|
1513
|
+
AsyncGenerator[dict[str, Any]], self.connection.client.listen(methods=methods)
|
|
1514
|
+
)
|
|
1515
|
+
async with contextlib.aclosing(listening) as changes:
|
|
1516
|
+
async for frame in changes:
|
|
1517
|
+
event = Event.model_validate(frame.get("params") or {})
|
|
1518
|
+
if project and event.project != project:
|
|
1519
|
+
continue
|
|
1520
|
+
console.print(event_line(event), highlight=False)
|
|
1521
|
+
seen += 1
|
|
1522
|
+
if self.count and seen >= self.count:
|
|
1523
|
+
break
|
|
1524
|
+
return 0
|
|
1525
|
+
|
|
1526
|
+
|
|
1527
|
+
class Install(Command):
|
|
1528
|
+
"""Register this server with the MCP clients on this machine."""
|
|
1529
|
+
|
|
1530
|
+
name: str = argclass.Argument(default="backlog", help="Name the clients will show")
|
|
1531
|
+
claude: bool = argclass.Argument(default=False, help="Only Claude Code")
|
|
1532
|
+
codex: bool = argclass.Argument(default=False, help="Only Codex")
|
|
1533
|
+
force: bool = argclass.Argument(default=False, help="Replace an entry that is already there")
|
|
1534
|
+
|
|
1535
|
+
def wanted(self) -> tuple[bool, bool]:
|
|
1536
|
+
"""Both clients unless one was named."""
|
|
1537
|
+
return (True, True) if not (self.claude or self.codex) else (self.claude, self.codex)
|
|
1538
|
+
|
|
1539
|
+
async def __call__(self) -> int:
|
|
1540
|
+
claude, codex = self.wanted()
|
|
1541
|
+
if not re.fullmatch(r"[A-Za-z0-9_-]+", self.name):
|
|
1542
|
+
fail("server name must contain only letters, digits, underscores, or hyphens")
|
|
1543
|
+
return 1
|
|
1544
|
+
command, arguments = server_command()
|
|
1545
|
+
failed = 0
|
|
1546
|
+
if claude:
|
|
1547
|
+
failed += install_claude(self.name, command, arguments, force=self.force)
|
|
1548
|
+
if codex:
|
|
1549
|
+
failed += install_codex(self.name, command, arguments, force=self.force)
|
|
1550
|
+
return 1 if failed else 0
|
|
1551
|
+
|
|
1552
|
+
|
|
1553
|
+
def server_command() -> tuple[str, list[str]]:
|
|
1554
|
+
"""How another program should start this server."""
|
|
1555
|
+
found = Path(sys.argv[0]).resolve()
|
|
1556
|
+
if found.name.startswith("backlog") and os.access(found, os.X_OK):
|
|
1557
|
+
return str(found), ["mcp"]
|
|
1558
|
+
return sys.executable, ["-m", "backlog_mcp", "mcp"]
|
|
1559
|
+
|
|
1560
|
+
|
|
1561
|
+
def run(command: Sequence[str]) -> bool:
|
|
1562
|
+
"""Run a client's own CLI. False when it is missing or refuses."""
|
|
1563
|
+
try:
|
|
1564
|
+
done = subprocess.run(command, capture_output=True, text=True, check=False)
|
|
1565
|
+
except OSError:
|
|
1566
|
+
return False
|
|
1567
|
+
if done.returncode:
|
|
1568
|
+
log.debug("%s failed: %s", command[0], done.stderr.strip())
|
|
1569
|
+
return done.returncode == 0
|
|
1570
|
+
|
|
1571
|
+
|
|
1572
|
+
def client_json(path: Path) -> dict[str, Any]:
|
|
1573
|
+
"""Read a client JSON object without discarding unrelated settings."""
|
|
1574
|
+
found = json.loads(path.read_text(encoding="utf-8")) if path.exists() else {}
|
|
1575
|
+
if not isinstance(found, dict):
|
|
1576
|
+
raise ValueError(f"{path} must contain a JSON object")
|
|
1577
|
+
return found
|
|
1578
|
+
|
|
1579
|
+
|
|
1580
|
+
def config_table(parent: dict[str, Any], key: str) -> dict[str, Any]:
|
|
1581
|
+
value = parent.setdefault(key, {})
|
|
1582
|
+
if not isinstance(value, dict):
|
|
1583
|
+
raise ValueError(f"{key} must be a configuration table")
|
|
1584
|
+
return value
|
|
1585
|
+
|
|
1586
|
+
|
|
1587
|
+
def write_client_config(path: Path, text: str) -> None:
|
|
1588
|
+
"""Replace a complete configuration atomically, preserving existing file permissions."""
|
|
1589
|
+
path = path.resolve()
|
|
1590
|
+
path.parent.mkdir(parents=True, exist_ok=True)
|
|
1591
|
+
temporary: Path | None = None
|
|
1592
|
+
try:
|
|
1593
|
+
with tempfile.NamedTemporaryFile(
|
|
1594
|
+
mode="w", encoding="utf-8", dir=path.parent, delete=False
|
|
1595
|
+
) as stream:
|
|
1596
|
+
temporary = Path(stream.name)
|
|
1597
|
+
stream.write(text)
|
|
1598
|
+
if path.exists():
|
|
1599
|
+
temporary.chmod(path.stat().st_mode & 0o777)
|
|
1600
|
+
temporary.replace(path)
|
|
1601
|
+
finally:
|
|
1602
|
+
if temporary is not None:
|
|
1603
|
+
temporary.unlink(missing_ok=True)
|
|
1604
|
+
|
|
1605
|
+
|
|
1606
|
+
def install_claude(name: str, command: str, arguments: list[str], *, force: bool) -> int:
|
|
1607
|
+
"""Register the server and allow its tools in Claude's user settings."""
|
|
1608
|
+
config = Path.home() / ".claude.json"
|
|
1609
|
+
settings = Path.home() / ".claude" / "settings.json"
|
|
1610
|
+
try:
|
|
1611
|
+
found = client_json(config)
|
|
1612
|
+
servers = config_table(found, "mcpServers")
|
|
1613
|
+
preferences = client_json(settings)
|
|
1614
|
+
permissions = config_table(preferences, "permissions")
|
|
1615
|
+
allowed = permissions.setdefault("allow", [])
|
|
1616
|
+
if not isinstance(allowed, list) or not all(isinstance(item, str) for item in allowed):
|
|
1617
|
+
raise ValueError("permissions.allow must be a list of strings")
|
|
1618
|
+
rule = f"mcp__{name}__*"
|
|
1619
|
+
if rule not in allowed:
|
|
1620
|
+
allowed.append(rule)
|
|
1621
|
+
if name in servers and not force:
|
|
1622
|
+
warn(f"claude: {name} is already registered, --force replaces it")
|
|
1623
|
+
elif run(["claude", "mcp", "add", "--scope", "user", name, "--", command, *arguments]):
|
|
1624
|
+
note(f"claude: {name} registered")
|
|
1625
|
+
else:
|
|
1626
|
+
servers[name] = {"type": "stdio", "command": command, "args": arguments, "env": {}}
|
|
1627
|
+
write_client_config(config, json.dumps(found, indent=2) + "\n")
|
|
1628
|
+
note(f"claude: {name} written to {config}")
|
|
1629
|
+
write_client_config(settings, json.dumps(preferences, indent=2) + "\n")
|
|
1630
|
+
except (OSError, ValueError) as error:
|
|
1631
|
+
fail(f"claude: cannot configure {name}: {error}")
|
|
1632
|
+
return 1
|
|
1633
|
+
note(f"claude: {name} tools auto-approved in {settings}")
|
|
1634
|
+
return 0
|
|
1635
|
+
|
|
1636
|
+
|
|
1637
|
+
def install_codex(name: str, command: str, arguments: list[str], *, force: bool) -> int:
|
|
1638
|
+
"""Approve this server's tools and disable the Codex sandbox in user configuration."""
|
|
1639
|
+
config = Path.home() / ".codex" / "config.toml"
|
|
1640
|
+
try:
|
|
1641
|
+
found = rtoml.loads(config.read_text(encoding="utf-8")) if config.exists() else {}
|
|
1642
|
+
servers = config_table(found, "mcp_servers")
|
|
1643
|
+
if name in servers and not force:
|
|
1644
|
+
warn(f"codex: {name} is already registered, --force replaces it")
|
|
1645
|
+
else:
|
|
1646
|
+
registered = run(["codex", "mcp", "add", name, "--", command, *arguments])
|
|
1647
|
+
if registered:
|
|
1648
|
+
found = rtoml.loads(config.read_text(encoding="utf-8")) if config.exists() else {}
|
|
1649
|
+
servers = config_table(found, "mcp_servers")
|
|
1650
|
+
note(f"codex: {name} registered")
|
|
1651
|
+
if not registered or name not in servers:
|
|
1652
|
+
servers[name] = {"command": command, "args": arguments}
|
|
1653
|
+
server = config_table(servers, name)
|
|
1654
|
+
server["default_tools_approval_mode"] = "approve"
|
|
1655
|
+
overrides = server.get("tools", {})
|
|
1656
|
+
if not isinstance(overrides, dict):
|
|
1657
|
+
raise ValueError("tools must be a configuration table")
|
|
1658
|
+
for tool in overrides:
|
|
1659
|
+
config_table(overrides, tool)["approval_mode"] = "approve"
|
|
1660
|
+
found["sandbox_mode"] = "danger-full-access"
|
|
1661
|
+
write_client_config(config, rtoml.dumps(found))
|
|
1662
|
+
except (OSError, ValueError) as error:
|
|
1663
|
+
fail(f"codex: cannot configure {name}: {error}")
|
|
1664
|
+
return 1
|
|
1665
|
+
note(f"codex: {name} written to {config}; tools auto-approved, user sandbox disabled")
|
|
1666
|
+
return 0
|
|
1667
|
+
|
|
1668
|
+
|
|
1669
|
+
class TaskCommands(Command):
|
|
1670
|
+
"""Tasks, their status, and their comment history."""
|
|
1671
|
+
|
|
1672
|
+
list = List(
|
|
1673
|
+
aliases=["ls"],
|
|
1674
|
+
help="List tasks of this project, or of all",
|
|
1675
|
+
description=(
|
|
1676
|
+
"List tasks, most important first, open ones (todo, doing, blocked) before the "
|
|
1677
|
+
"rest. --status narrows to named statuses and may be repeated, --every adds the "
|
|
1678
|
+
"closed ones, and --all-projects reaches every board at once."
|
|
1679
|
+
),
|
|
1680
|
+
)
|
|
1681
|
+
|
|
1682
|
+
link = Link(aliases=["lk"], help="Create a typed relation and its inverse")
|
|
1683
|
+
claim = Claim(aliases=["ck"], help="Atomically claim, release or reassign a task")
|
|
1684
|
+
assigned = Assigned(aliases=["as"], help="List tasks by assignment prefix")
|
|
1685
|
+
unlink = Unlink(aliases=["ul"], help="Remove a relation and its inverse")
|
|
1686
|
+
comment = CommentAdd(aliases=["co"], help="Add a task comment")
|
|
1687
|
+
|
|
1688
|
+
comments = CommentList(aliases=["cm"], help="Read task comments and history")
|
|
1689
|
+
|
|
1690
|
+
show = Show(
|
|
1691
|
+
aliases=["sh"],
|
|
1692
|
+
help="Print one task in full",
|
|
1693
|
+
description="Print the title, body, status, priority, tags and timestamps of one task.",
|
|
1694
|
+
)
|
|
1695
|
+
|
|
1696
|
+
add = Add(
|
|
1697
|
+
aliases=["ad"],
|
|
1698
|
+
help="Add a task from the command line",
|
|
1699
|
+
description=(
|
|
1700
|
+
"Add a task without opening an editor. The title is the positional argument; "
|
|
1701
|
+
"--body, --status, --priority and repeated --tag flags set the rest."
|
|
1702
|
+
),
|
|
1703
|
+
)
|
|
1704
|
+
|
|
1705
|
+
create = Create(
|
|
1706
|
+
aliases=["cr"],
|
|
1707
|
+
help="Write a task in $EDITOR",
|
|
1708
|
+
description=(
|
|
1709
|
+
"Open $VISUAL, else $EDITOR, else vi on a form. The headers at the top set the "
|
|
1710
|
+
"title, status, priority and tags; everything under the blank line is the "
|
|
1711
|
+
"description. An empty title cancels the task."
|
|
1712
|
+
),
|
|
1713
|
+
)
|
|
1714
|
+
|
|
1715
|
+
edit = Edit(
|
|
1716
|
+
aliases=["ed"],
|
|
1717
|
+
help="Edit a task in $EDITOR",
|
|
1718
|
+
description=(
|
|
1719
|
+
"Edit the task fields and description. "
|
|
1720
|
+
"Use `backlog task comment` for progress updates. "
|
|
1721
|
+
"Leaving the file unchanged changes nothing."
|
|
1722
|
+
),
|
|
1723
|
+
)
|
|
1724
|
+
|
|
1725
|
+
start = Start(
|
|
1726
|
+
aliases=["st"],
|
|
1727
|
+
help="Mark tasks in progress",
|
|
1728
|
+
description="Move one or more tasks to the doing status.",
|
|
1729
|
+
)
|
|
1730
|
+
|
|
1731
|
+
block = Block(
|
|
1732
|
+
aliases=["bl"],
|
|
1733
|
+
help="Mark tasks blocked",
|
|
1734
|
+
description="Move one or more tasks to the blocked status. They stay open.",
|
|
1735
|
+
)
|
|
1736
|
+
|
|
1737
|
+
close = Close(
|
|
1738
|
+
aliases=["cl"],
|
|
1739
|
+
help="Mark tasks done",
|
|
1740
|
+
description="Move one or more tasks to the done status, which stamps the closing time.",
|
|
1741
|
+
)
|
|
1742
|
+
|
|
1743
|
+
cancel = Cancel(
|
|
1744
|
+
aliases=["ca"],
|
|
1745
|
+
help="Mark tasks cancelled",
|
|
1746
|
+
description=(
|
|
1747
|
+
"Move one or more tasks to the cancelled status: kept and searchable, but closed. "
|
|
1748
|
+
"Prefer this to `backlog task delete` for work that was dropped."
|
|
1749
|
+
),
|
|
1750
|
+
)
|
|
1751
|
+
|
|
1752
|
+
reopen = Reopen(
|
|
1753
|
+
aliases=["re"],
|
|
1754
|
+
help="Put tasks back on the pile",
|
|
1755
|
+
description="Move one or more tasks back to the todo status and clear the closing time.",
|
|
1756
|
+
)
|
|
1757
|
+
|
|
1758
|
+
move = Move(
|
|
1759
|
+
aliases=["mv"],
|
|
1760
|
+
help="Move a task into another project",
|
|
1761
|
+
description=(
|
|
1762
|
+
"Give a task to another board. The destination is a project slug or any path "
|
|
1763
|
+
"inside the project. The task keeps its id."
|
|
1764
|
+
),
|
|
1765
|
+
)
|
|
1766
|
+
|
|
1767
|
+
delete = Delete(
|
|
1768
|
+
aliases=["rm"],
|
|
1769
|
+
help="Delete a task for good",
|
|
1770
|
+
description=(
|
|
1771
|
+
"Delete a task permanently. Ask first only for another project, unless --yes is given. "
|
|
1772
|
+
"`backlog task cancel` keeps the record instead."
|
|
1773
|
+
),
|
|
1774
|
+
)
|
|
1775
|
+
|
|
1776
|
+
async def __call__(self) -> int:
|
|
1777
|
+
return self.show_help()
|
|
1778
|
+
|
|
1779
|
+
|
|
1780
|
+
class CLI(argclass.Parser):
|
|
1781
|
+
"""Defaults come from the config files, then `BACKLOG_MCP_*`, then these arguments.
|
|
1782
|
+
|
|
1783
|
+
The options of `backlog mcp` read the `[mcp]` table of the same files and the same
|
|
1784
|
+
environment prefix. `--generate-config` here, or on `mcp`, writes both back. The options
|
|
1785
|
+
of the other commands are command-line only.
|
|
1786
|
+
"""
|
|
1787
|
+
|
|
1788
|
+
def __init__(self, *args: Any, **kwargs: Any) -> None:
|
|
1789
|
+
super().__init__(*args, **kwargs)
|
|
1790
|
+
auth = self.mcp.auth
|
|
1791
|
+
# Bind the converter to this parser's cloned group, not the shared class prototype.
|
|
1792
|
+
auth.__arguments__ = {
|
|
1793
|
+
**auth.__arguments__,
|
|
1794
|
+
"basic": auth.__arguments__["basic"].copy(converter=auth.convert_accounts),
|
|
1795
|
+
}
|
|
1796
|
+
|
|
1797
|
+
log_level: int = argclass.LogLevel
|
|
1798
|
+
|
|
1799
|
+
url: str = argclass.Argument(
|
|
1800
|
+
"--url",
|
|
1801
|
+
default="",
|
|
1802
|
+
help="MCP HTTP endpoint; unset starts a local stdio server",
|
|
1803
|
+
)
|
|
1804
|
+
user: str = argclass.Argument("--user", default="", help="MCP HTTP Basic auth user")
|
|
1805
|
+
password: str = argclass.Secret("--password", default="", help="MCP HTTP Basic auth password")
|
|
1806
|
+
token: str = argclass.Secret(
|
|
1807
|
+
"--token", default="", help="MCP HTTP Bearer token; mutually exclusive with Basic auth"
|
|
1808
|
+
)
|
|
1809
|
+
default_user: str | None = argclass.Argument(
|
|
1810
|
+
default=None,
|
|
1811
|
+
type=str,
|
|
1812
|
+
help="Default username for stdio or HTTP without authorizers (default: $USER)",
|
|
1813
|
+
)
|
|
1814
|
+
timeout: float = argclass.Argument(default=120.0, help="MCP request timeout in seconds")
|
|
1815
|
+
|
|
1816
|
+
database: Path = argclass.Argument(
|
|
1817
|
+
"-d",
|
|
1818
|
+
"--database",
|
|
1819
|
+
type=Path,
|
|
1820
|
+
default=None,
|
|
1821
|
+
help=(
|
|
1822
|
+
"SQLite file holding every project "
|
|
1823
|
+
"(default: $XDG_DATA_HOME/backlog-mcp/backlog.sqlite3)"
|
|
1824
|
+
),
|
|
1825
|
+
)
|
|
1826
|
+
root: Path = argclass.Argument(
|
|
1827
|
+
"-r",
|
|
1828
|
+
"--root",
|
|
1829
|
+
type=Path,
|
|
1830
|
+
default=None,
|
|
1831
|
+
help="Directory to scope to (default: the working directory)",
|
|
1832
|
+
)
|
|
1833
|
+
project: str = argclass.Argument(
|
|
1834
|
+
"-p",
|
|
1835
|
+
"--project",
|
|
1836
|
+
default=None,
|
|
1837
|
+
help="Work on this project whatever the directory says: a slug, or a path inside it",
|
|
1838
|
+
)
|
|
1839
|
+
computer: str = argclass.Argument(
|
|
1840
|
+
"--computer",
|
|
1841
|
+
default=None,
|
|
1842
|
+
help=(
|
|
1843
|
+
"Name of this computer, the one the projects of this directory tree belong to "
|
|
1844
|
+
"(default: the short host name)"
|
|
1845
|
+
),
|
|
1846
|
+
)
|
|
1847
|
+
generate_config: str = argclass.Argument(
|
|
1848
|
+
action=argclass.GenerateConfigAction,
|
|
1849
|
+
generator=ConfigTemplate,
|
|
1850
|
+
metavar="FILE",
|
|
1851
|
+
help=(
|
|
1852
|
+
"Write these options and the [mcp] tables as a TOML config file and exit; '-' "
|
|
1853
|
+
"prints it. Options given before this flag are written active, the rest as "
|
|
1854
|
+
"commented-out defaults"
|
|
1855
|
+
),
|
|
1856
|
+
)
|
|
1857
|
+
|
|
1858
|
+
mcp = Serve(
|
|
1859
|
+
aliases=["mc"],
|
|
1860
|
+
help="Serve MCP, on stdio or over HTTP",
|
|
1861
|
+
description=(
|
|
1862
|
+
"Run the MCP server on the same backlog the other commands use. stdio is the "
|
|
1863
|
+
"transport clients start by themselves; --protocol=http serves the endpoint at "
|
|
1864
|
+
"/mcp and the bundled console at /console. The http group configures the listener; "
|
|
1865
|
+
"the auth group configures Basic accounts and JWT verification. `backlog-mcp` is "
|
|
1866
|
+
"the same command without the word mcp. Over HTTP, "
|
|
1867
|
+
"?computer=<name>&project=<slug> on the endpoint URL serves a client as another "
|
|
1868
|
+
"computer."
|
|
1869
|
+
),
|
|
1870
|
+
#: The same prefix as the root, so the port is BACKLOG_MCP_HTTP_PORT, not _MCP_MCP_.
|
|
1871
|
+
auto_env_var_prefix="BACKLOG_MCP_",
|
|
1872
|
+
#: `--config` after `mcp` as well, so `backlog-mcp --config FILE` works.
|
|
1873
|
+
config_argument="--config",
|
|
1874
|
+
config_parser_class=argclass.TOMLDefaultsParser,
|
|
1875
|
+
)
|
|
1876
|
+
hash_password = HashPassword(
|
|
1877
|
+
aliases=["hash-password", "pwhash", "pw", "hash"],
|
|
1878
|
+
help="Prompt for credentials and print a bcrypt account entry",
|
|
1879
|
+
)
|
|
1880
|
+
whoami = Whoami(aliases=["wi"], help="Show the current principal and computer")
|
|
1881
|
+
board = Board(aliases=["bo"], help="Show a project board with ready and claimed tasks")
|
|
1882
|
+
init = Init(
|
|
1883
|
+
aliases=["in"],
|
|
1884
|
+
help="Register this checkout or bind it to an existing project",
|
|
1885
|
+
description=(
|
|
1886
|
+
"Register the current computer and checkout through MCP. Without arguments, ask "
|
|
1887
|
+
"for the computer, directory, name, and description. NAME creates a project without "
|
|
1888
|
+
"prompts; "
|
|
1889
|
+
"--existing SLUG binds the directory to an existing project."
|
|
1890
|
+
),
|
|
1891
|
+
)
|
|
1892
|
+
projects = Projects(
|
|
1893
|
+
aliases=["pr"],
|
|
1894
|
+
help="List the registered projects",
|
|
1895
|
+
description=(
|
|
1896
|
+
"Print the projects of this computer with their root directory and their open and "
|
|
1897
|
+
"total task counts; --computer shows another computer's, --all-computers all. "
|
|
1898
|
+
"Archived projects are hidden until --archived asks for them. `backlog projects "
|
|
1899
|
+
"delete <slug>` removes a project with everything on its board."
|
|
1900
|
+
),
|
|
1901
|
+
)
|
|
1902
|
+
task = TaskCommands(aliases=["ta"], help="Manage tasks and comments")
|
|
1903
|
+
search = Search(
|
|
1904
|
+
aliases=["se"],
|
|
1905
|
+
help="FTS and semantic search over projects, tasks, comments, and memory",
|
|
1906
|
+
description=(
|
|
1907
|
+
"Quoted expressions search text; unquoted words search vectors. "
|
|
1908
|
+
"Mixed queries use both. "
|
|
1909
|
+
"--min-score filters semantic matches only. --all-projects searches every board."
|
|
1910
|
+
),
|
|
1911
|
+
)
|
|
1912
|
+
stats = Stats(
|
|
1913
|
+
aliases=["ss"],
|
|
1914
|
+
help="Count open tasks, closed tasks, and notes",
|
|
1915
|
+
description=(
|
|
1916
|
+
"Show open tasks, closed tasks, and notes, followed by status and priority counts "
|
|
1917
|
+
"and tags. Notes include shared notes. --all-projects counts every board together."
|
|
1918
|
+
),
|
|
1919
|
+
)
|
|
1920
|
+
memory = Notes(
|
|
1921
|
+
aliases=["mm"],
|
|
1922
|
+
help="Lasting user context: preferences, agreements, and constraints",
|
|
1923
|
+
description=(
|
|
1924
|
+
"Code changes; notes remain. Keep lasting user context unavailable elsewhere, not "
|
|
1925
|
+
"implementation details or documentation summaries. `memory add` creates a note "
|
|
1926
|
+
"or replaces the one with that title, `memory append` adds a paragraph, and `backlog "
|
|
1927
|
+
"search` finds notes as well as tasks. A note has an id for good, so a task body "
|
|
1928
|
+
"can say `#note3`."
|
|
1929
|
+
),
|
|
1930
|
+
)
|
|
1931
|
+
skills = Skills(
|
|
1932
|
+
aliases=["sk"],
|
|
1933
|
+
help="Show the skills this server offers to MCP clients",
|
|
1934
|
+
description=(
|
|
1935
|
+
"Print the written skills served over MCP: their names, what each one is for, and "
|
|
1936
|
+
"how many files it carries. Name a skill to read its instructions in full. Skills "
|
|
1937
|
+
"are text: a client reads them, then calls the tools."
|
|
1938
|
+
),
|
|
1939
|
+
)
|
|
1940
|
+
watch = Watch(
|
|
1941
|
+
aliases=["wa"],
|
|
1942
|
+
help="Print the changes of a backlog server as they happen",
|
|
1943
|
+
description=(
|
|
1944
|
+
"Listen to a running server over HTTP and print one line per change: tasks, notes "
|
|
1945
|
+
"and projects added, updated, moved or deleted, by any client. --project keeps one "
|
|
1946
|
+
"board. The server sends these as MCP notifications of the backlog-mcp/events "
|
|
1947
|
+
"extension; agents do not see them, this command and dashboards do."
|
|
1948
|
+
),
|
|
1949
|
+
)
|
|
1950
|
+
install = Install(
|
|
1951
|
+
aliases=["is"],
|
|
1952
|
+
help="Register this server with Claude Code and Codex",
|
|
1953
|
+
description=(
|
|
1954
|
+
"Add this backlog as an MCP server to the clients on this machine. Their own CLIs "
|
|
1955
|
+
"write the entry when they are installed; otherwise ~/.claude.json and "
|
|
1956
|
+
"~/.codex/config.toml are edited directly. Auto-approve this server's tools in both "
|
|
1957
|
+
"clients and disable the Codex sandbox in user configuration. "
|
|
1958
|
+
"--claude or --codex picks one client."
|
|
1959
|
+
),
|
|
1960
|
+
)
|
|
1961
|
+
|
|
1962
|
+
async def __call__(self) -> int:
|
|
1963
|
+
"""Serve locally, or run a command over one MCP connection."""
|
|
1964
|
+
command = self.current_subparser
|
|
1965
|
+
if not isinstance(command, Command):
|
|
1966
|
+
self.print_help()
|
|
1967
|
+
return 0
|
|
1968
|
+
try:
|
|
1969
|
+
if isinstance(command, Serve):
|
|
1970
|
+
backlog = build(self)
|
|
1971
|
+
use(backlog)
|
|
1972
|
+
try:
|
|
1973
|
+
await backlog.open()
|
|
1974
|
+
return await command()
|
|
1975
|
+
finally:
|
|
1976
|
+
await backlog.close()
|
|
1977
|
+
if isinstance(command, (HashPassword, Install, Notes, TaskCommands)):
|
|
1978
|
+
return await command()
|
|
1979
|
+
if isinstance(command, Watch):
|
|
1980
|
+
self.url = command.endpoint or self.url
|
|
1981
|
+
self.user = command.auth_user or self.user
|
|
1982
|
+
self.password = command.auth_password or self.password
|
|
1983
|
+
scoped = isinstance(
|
|
1984
|
+
command,
|
|
1985
|
+
(Board, List, Search, Add, Create, Delete, Stats, NoteList, NoteAdd, NoteDelete),
|
|
1986
|
+
)
|
|
1987
|
+
if (
|
|
1988
|
+
(isinstance(command, Board) and command.project is not None)
|
|
1989
|
+
or getattr(command, "all_projects", False)
|
|
1990
|
+
or getattr(command, "all_computers", False)
|
|
1991
|
+
or getattr(command, "at", None)
|
|
1992
|
+
):
|
|
1993
|
+
scoped = False
|
|
1994
|
+
async with connect(
|
|
1995
|
+
self, on_ask=command.ask, on_register=command.registration, scope_directory=scoped
|
|
1996
|
+
) as connection:
|
|
1997
|
+
self.connection = connection
|
|
1998
|
+
return await command()
|
|
1999
|
+
except ToolError as error:
|
|
2000
|
+
fail(str(error))
|
|
2001
|
+
return error.exit_code
|
|
2002
|
+
except UnknownProject as error:
|
|
2003
|
+
fail(str(error))
|
|
2004
|
+
return 2
|
|
2005
|
+
except HTTPClientError as error:
|
|
2006
|
+
fail(f"MCP connection failed: {type(error).__name__}")
|
|
2007
|
+
return 1
|
|
2008
|
+
except (ClientError, OSError, TimeoutError, ValueError) as error:
|
|
2009
|
+
fail(str(error) or "MCP request timed out")
|
|
2010
|
+
return 1
|
|
2011
|
+
|
|
2012
|
+
|
|
2013
|
+
def main(argv: Sequence[str] | None = None) -> int:
|
|
2014
|
+
"""Entry point. stdout carries the MCP protocol, so every log line goes to stderr."""
|
|
2015
|
+
parser = CLI(
|
|
2016
|
+
config_files=paths.config_files(),
|
|
2017
|
+
config_parser_class=argclass.TOMLDefaultsParser,
|
|
2018
|
+
config_argument="--config",
|
|
2019
|
+
auto_env_var_prefix="BACKLOG_MCP_",
|
|
2020
|
+
description=f"backlog {VERSION}: projects and tasks, on the command line and over MCP",
|
|
2021
|
+
#: argparse obeys FORCE_COLOR like rich does; a pipe gets plain help text.
|
|
2022
|
+
color=sys.stdout.isatty(),
|
|
2023
|
+
)
|
|
2024
|
+
parser.parse_args(list(argv) if argv is not None else None)
|
|
2025
|
+
logging.basicConfig(level=parser.log_level, stream=sys.stderr, format=LOG_FORMAT)
|
|
2026
|
+
try:
|
|
2027
|
+
return asyncio.run(parser())
|
|
2028
|
+
except KeyboardInterrupt:
|
|
2029
|
+
return 130
|
|
2030
|
+
|
|
2031
|
+
|
|
2032
|
+
def server_main(argv: Sequence[str] | None = None) -> int:
|
|
2033
|
+
"""The `backlog-mcp` entry point: the server, with no subcommand to type."""
|
|
2034
|
+
return main(["mcp", *(argv if argv is not None else sys.argv[1:])])
|
|
2035
|
+
|
|
2036
|
+
|
|
2037
|
+
__all__ = [
|
|
2038
|
+
"CLI",
|
|
2039
|
+
"Command",
|
|
2040
|
+
"Transition",
|
|
2041
|
+
"build",
|
|
2042
|
+
"main",
|
|
2043
|
+
"parse_form",
|
|
2044
|
+
"parse_note_form",
|
|
2045
|
+
"server_main",
|
|
2046
|
+
]
|