backlog-tiny-mcp 0.34.2__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.
Files changed (97) hide show
  1. backlog_mcp/__init__.py +29 -0
  2. backlog_mcp/__main__.py +10 -0
  3. backlog_mcp/auth.py +199 -0
  4. backlog_mcp/backlog.py +696 -0
  5. backlog_mcp/cli.py +2046 -0
  6. backlog_mcp/client.py +320 -0
  7. backlog_mcp/computer.py +33 -0
  8. backlog_mcp/database.py +80 -0
  9. backlog_mcp/embeddings.py +900 -0
  10. backlog_mcp/global_rules.md +126 -0
  11. backlog_mcp/guidance.py +11 -0
  12. backlog_mcp/guide/index.md +11 -0
  13. backlog_mcp/guide/memory.md +27 -0
  14. backlog_mcp/guide/projects.md +16 -0
  15. backlog_mcp/guide/search.md +72 -0
  16. backlog_mcp/guide/tasks.md +40 -0
  17. backlog_mcp/guide/workflow.md +22 -0
  18. backlog_mcp/httpd.py +270 -0
  19. backlog_mcp/migrate.py +113 -0
  20. backlog_mcp/migrations/0001-initial.sql +194 -0
  21. backlog_mcp/migrations/0002-task-assignment.sql +2 -0
  22. backlog_mcp/migrations/0003-task-edit-claims.sql +5 -0
  23. backlog_mcp/migrations/0004-memory-visibility.sql +42 -0
  24. backlog_mcp/model/CITATION.bib +9 -0
  25. backlog_mcp/model/LICENSE +202 -0
  26. backlog_mcp/model/README.md +12 -0
  27. backlog_mcp/model/UPSTREAM.md +2053 -0
  28. backlog_mcp/model/config.json +12 -0
  29. backlog_mcp/model/model.safetensors +4 -0
  30. backlog_mcp/model/modules.json +14 -0
  31. backlog_mcp/model/provenance.json +16 -0
  32. backlog_mcp/model/tokenizer.json +1 -0
  33. backlog_mcp/models.py +581 -0
  34. backlog_mcp/names.py +35 -0
  35. backlog_mcp/paths.py +53 -0
  36. backlog_mcp/protocol_storage.py +104 -0
  37. backlog_mcp/queries.py +7 -0
  38. backlog_mcp/queries.sql +531 -0
  39. backlog_mcp/records.py +215 -0
  40. backlog_mcp/render.py +479 -0
  41. backlog_mcp/server.py +2864 -0
  42. backlog_mcp/skills/autopilot/SKILL.md +96 -0
  43. backlog_mcp/skills/planning/SKILL.md +106 -0
  44. backlog_mcp/skills/planning/references/splitting.md +45 -0
  45. backlog_mcp/skills/triage/SKILL.md +104 -0
  46. backlog_mcp/skills/triage/references/conventions.md +43 -0
  47. backlog_mcp/skills.py +56 -0
  48. backlog_mcp/static/agent-config.js +20 -0
  49. backlog_mcp/static/app.css +1950 -0
  50. backlog_mcp/static/app.js +1301 -0
  51. backlog_mcp/static/assignments.js +96 -0
  52. backlog_mcp/static/breadcrumbs.js +54 -0
  53. backlog_mcp/static/comment-composer.js +95 -0
  54. backlog_mcp/static/connect.css +98 -0
  55. backlog_mcp/static/connect.html +74 -0
  56. backlog_mcp/static/connect.js +160 -0
  57. backlog_mcp/static/credentials.js +72 -0
  58. backlog_mcp/static/diagrams.js +128 -0
  59. backlog_mcp/static/dom.js +162 -0
  60. backlog_mcp/static/editor-claim.js +104 -0
  61. backlog_mcp/static/editor.js +355 -0
  62. backlog_mcp/static/index.html +137 -0
  63. backlog_mcp/static/markdown.css +33 -0
  64. backlog_mcp/static/markdown.js +72 -0
  65. backlog_mcp/static/mcp.js +177 -0
  66. backlog_mcp/static/memory-append.js +34 -0
  67. backlog_mcp/static/memory-editor.js +173 -0
  68. backlog_mcp/static/memory.js +279 -0
  69. backlog_mcp/static/package.json +1 -0
  70. backlog_mcp/static/project-form.js +71 -0
  71. backlog_mcp/static/project-settings.js +225 -0
  72. backlog_mcp/static/scope.js +90 -0
  73. backlog_mcp/static/statistics.js +87 -0
  74. backlog_mcp/static/task-browser.js +100 -0
  75. backlog_mcp/static/task-pagination.js +94 -0
  76. backlog_mcp/static/task-picker.js +164 -0
  77. backlog_mcp/static/task-table.js +74 -0
  78. backlog_mcp/static/vendor/README.md +12 -0
  79. backlog_mcp/static/vendor/dompurify-LICENSE +202 -0
  80. backlog_mcp/static/vendor/highlight-LICENSE +29 -0
  81. backlog_mcp/static/vendor/highlight-dark.css +118 -0
  82. backlog_mcp/static/vendor/highlight-light.css +118 -0
  83. backlog_mcp/static/vendor/highlight.min.js +1262 -0
  84. backlog_mcp/static/vendor/marked-LICENSE +44 -0
  85. backlog_mcp/static/vendor/marked.esm.js +80 -0
  86. backlog_mcp/static/vendor/marked.esm.js.map +7 -0
  87. backlog_mcp/static/vendor/mermaid-LICENSE +21 -0
  88. backlog_mcp/static/vendor/mermaid.min.js +4376 -0
  89. backlog_mcp/static/vendor/purify.es.mjs +2722 -0
  90. backlog_mcp/static/vendor/purify.es.mjs.map +1 -0
  91. backlog_mcp/transaction.py +47 -0
  92. backlog_mcp/version.py +79 -0
  93. backlog_mcp/webui.py +63 -0
  94. backlog_tiny_mcp-0.34.2.dist-info/METADATA +84 -0
  95. backlog_tiny_mcp-0.34.2.dist-info/RECORD +97 -0
  96. backlog_tiny_mcp-0.34.2.dist-info/WHEEL +4 -0
  97. backlog_tiny_mcp-0.34.2.dist-info/entry_points.txt +4 -0
@@ -0,0 +1,126 @@
1
+ <!-- BACKLOG_START -->
2
+ ## Backlog workflow
3
+
4
+ Read `backlog://guide` for the topic index and `backlog://guide/workflow` for the
5
+ workflow. Use MCP `resources/read`, or `mcp_resources_read(uri=...)` when the HTTP
6
+ connection uses `resources=tool`. Discover URIs with `resources/list` and
7
+ `resources/templates/list`, or `mcp_resources_list` in tool mode.
8
+ Read `backlog://guide/tasks` for task rules, `backlog://guide/memory` for memory,
9
+ `backlog://guide/search` for search syntax, and `backlog://guide/projects` for scope
10
+ and registration.
11
+
12
+ ### 1. Check project registration first
13
+
14
+ The simplest way to find a project is to read its board by absolute local path.
15
+ At session start or when changing projects or directories, first call
16
+ `project_board(project=<absolute local project path>)`.
17
+ Compare the returned principal (`user@computer`) and project roots with the
18
+ actual local workspace. For HTTP connections, the server cwd is not the local cwd.
19
+ If the binding matches, use the returned `full_name` for subsequent calls.
20
+ No `project_list` or `project_save` call is needed for a correct binding.
21
+ If the project is not found or the binding is wrong, use `project_list`;
22
+ use `all_computers=true` to find an existing logical project on another computer.
23
+ Use `whoami` when the authenticated principal needs clarification.
24
+ If the local binding is missing or wrong, call
25
+ `project_save(project=<existing full_name>, root=<absolute local project root>)`.
26
+ Create a project only if no matching logical project exists.
27
+ Leave correct bindings unchanged. Do not access paths that belong to another computer.
28
+ Complete this check before searching context, managing tasks, or investigating code.
29
+ Use owner-qualified names (`owner/slug`) to avoid ambiguous project references.
30
+ The board provides project context, counts, ready tasks, and tasks claimed by
31
+ this principal on this computer.
32
+ Follow `preferred_language` for task titles, descriptions, and progress updates.
33
+ A null value means no language preference.
34
+ Registration and board reads do not select a project for other calls.
35
+ Pass `project=` explicitly on unscoped HTTP connections.
36
+
37
+ ### 2. Search context before decisions
38
+
39
+ Read all `global_memory` entries returned by `project_board` in full before work.
40
+ They are mandatory context, regardless of search relevance or list pagination.
41
+
42
+ After the registration check, first call
43
+ `memory_list(project=<returned full_name>)` for project memory.
44
+ Keep the default compact result and use `memory_get` for relevant entries.
45
+ The list includes personal entries and entries shared with this project.
46
+ Use topic-specific `search` for other projects only when needed.
47
+ Use `search` before investigating a problem,
48
+ choosing an approach, creating tasks or memory, or asking about prior agreements.
49
+ Use natural-language queries that describe the problem or question.
50
+ Search again when a new question arises. Read relevant matches with `task_get`
51
+ or `memory_get` when more detail is needed. Check memory before guessing user
52
+ preferences or project conventions.
53
+ Use targeted search for topics, filtered lists for board reviews, and `stats`
54
+ for counts. Search can match task descriptions and comments separately.
55
+ Verify current technical facts in code or documentation.
56
+ Use available code-search tools to locate implementations.
57
+
58
+ ### 3. Track work through tasks
59
+
60
+ Use backlog as the persistent task record. Reuse a relevant task or create one
61
+ with `task_add` before substantive work, including investigation and verification.
62
+ Define one verifiable outcome per task. A brief answer with no separate work
63
+ does not need a new task.
64
+ Read the task before claiming it; a board result does not reserve it.
65
+ Before starting work, call `task_claim(task=<id>, expected=null,
66
+ assigned=<principal>:<marker>)` for an unassigned task.
67
+ Use the principal from `whoami` and a distinct URL-safe marker per agent run.
68
+ Both `expected` and `assigned` are required. If the claim conflicts, do not start work.
69
+ Set `doing` when work starts. Use `task_comment_add(task_id=<id>, body=...)`
70
+ for progress, review feedback, findings, hypotheses, questions, suggestions, proposed
71
+ requirement changes, decisions, checks, blockers, remaining work, and relevant commit
72
+ hashes or deployment state. Send only new update text.
73
+ Use `task_update` for task fields and status.
74
+ The task body is the agreed definition: goal, scope, requirements, constraints,
75
+ and acceptance criteria. Do not use it as a work log or for unapproved requirements.
76
+ Use `task_update(body=...)` only on an explicit user request to change the definition,
77
+ or to reflect explicitly agreed requirements that make the current body incorrect
78
+ or outdated. It replaces the entire description; it does not append history.
79
+ For every body edit, add a separate comment explaining the reason and the user request
80
+ or agreement that authorized it. New information alone does not authorize a body edit.
81
+ Read comments with `task_get` or `task_comment_list`.
82
+ If scope must be replaced, close the old task and create a successor referencing it.
83
+ Set `done` only when the outcome is verified, `blocked` with the blocker and next
84
+ step, or `cancelled` when the work is abandoned.
85
+ Status changes do not release assignments. When finished or handing off work,
86
+ release with `task_claim(task=<id>, expected=<current assignment>, assigned=null)`.
87
+ Use `task_assigned` to find existing assignments when needed.
88
+ Before ending a turn, leave the task status, assignment, and history accurate.
89
+ Keep all task tracking in backlog. Never create or maintain task lists, work
90
+ plans, progress logs, or task checklists in files, in any directory or format.
91
+ This also applies when backlog is unavailable.
92
+
93
+ Write task descriptions in Markdown for users reading them in the Web UI.
94
+ Use headings, lists, and tables when they improve clarity. Put code in
95
+ triple-backtick fenced blocks with a language label for syntax highlighting.
96
+ Use fenced blocks labelled `mermaid` when a diagram clarifies a flow or relationship.
97
+ The Web UI renders Markdown, code highlighting, and Mermaid diagrams.
98
+ Keep explanatory prose so the task also makes sense as plain text through MCP.
99
+ Use `#{ID}` for task references and `#note{ID}` for memory notes.
100
+
101
+ ### 4. Keep lasting agreements in memory
102
+
103
+ Proactively save user preferences, constraints, and decisions with `memory_save`
104
+ or `memory_append`. Search first and update an existing record when appropriate.
105
+ Use the selected project's memory first; read full entries only when relevant.
106
+ Use `shared=true` to share an entry with members of this project.
107
+ Use `shared=false` for entries visible only to the entry author.
108
+ Choose by who needs the fact: "my dev server" is personal; "team dev servers catalog"
109
+ is shared because the team needs it. `global_scope=true` extends the entry to all projects
110
+ without changing its audience. Use `memory_sharing` to set shared and global_scope.
111
+ If the project, audience or global scope is unclear, ask the user before saving or
112
+ changing sharing. Do not guess or use defaults to resolve uncertainty.
113
+ Use task comments for temporary findings, bugs, and implementation progress.
114
+ Do not save code or documentation snapshots as lasting memory.
115
+ `memory_save(body=...)` replaces the body; `memory_append` adds related context.
116
+ Keep each record within 1024 characters. Never store secrets or unconfirmed guesses.
117
+ After a user correction, save the lasting agreement that prevents recurrence.
118
+
119
+ ### 5. Handle backlog outages explicitly
120
+
121
+ If backlog or a required tool is unavailable, report the failure and continue
122
+ authorized work that does not require missing context. Use an available CLI
123
+ equivalent when it accesses the same server and authenticated principal.
124
+ Keep pending task and memory updates in the conversation and save them when
125
+ access returns. Do not claim that a write succeeded unless the tool confirmed it.
126
+ <!-- BACKLOG_END -->
@@ -0,0 +1,11 @@
1
+ """Packaged Markdown for MCP resources and the Web UI."""
2
+
3
+ from importlib.resources import files
4
+
5
+ TOPICS = ("workflow", "tasks", "memory", "search", "projects")
6
+
7
+
8
+ def read(topic: str | None = None) -> str:
9
+ if topic is not None and topic not in TOPICS:
10
+ raise ValueError(f"Unknown guide topic {topic!r}. Topics: {', '.join(TOPICS)}")
11
+ return files("backlog_mcp").joinpath("guide", f"{topic or 'index'}.md").read_text()
@@ -0,0 +1,11 @@
1
+ # Backlog guide
2
+
3
+ - [workflow](backlog://guide/workflow): entry point, task lifecycle and verification.
4
+ - [tasks](backlog://guide/tasks): statuses, relations, assignments and CAS.
5
+ - [memory](backlog://guide/memory): lasting agreements and corrections.
6
+ - [search](backlog://guide/search): text, vector and mixed queries with examples.
7
+ - [projects](backlog://guide/projects): connection scope, roots and sharing.
8
+
9
+ Read these URIs with `resources/read`, or `mcp_resources_read(uri=...)` in tool mode.
10
+ Use `resources/list` and `resources/templates/list`, or `mcp_resources_list`, to find URIs.
11
+ For HTTP clients without native resource access, add `resources=tool` to the MCP URL.
@@ -0,0 +1,27 @@
1
+ # Memory
2
+
3
+ Read all `global_memory` entries returned by `project_board` before work. They are
4
+ mandatory context, returned in full regardless of list pagination or search relevance.
5
+ Then call `memory_list(project=<full_name>)` for project memory.
6
+ Keep the default compact result; use `memory_get` to read relevant entries in full.
7
+ Include your personal entries and entries shared with this project.
8
+ Search other projects only when the task needs that context.
9
+ Keep it small. Store lasting agreements, preferences and invariants stated by the user.
10
+ Update a matching entry by id instead of adding a near-duplicate.
11
+
12
+ A correction replaces the body through `memory_save` with the current truth.
13
+ Do not append historical corrections. A supplied body replaces the whole body,
14
+ at most 1024 characters. Before closing a task, update memory it made obsolete.
15
+
16
+ Put task status, progress, findings and verification in tasks and comments.
17
+ Do not store secrets, guesses, code snapshots or documentation summaries.
18
+ Use shared=true to share an entry with members of this project.
19
+ Personal entries (shared=false) are visible only to the entry author.
20
+ If the project, audience or global scope is unclear, ask the user before saving or
21
+ changing sharing. Do not guess or use defaults to resolve uncertainty.
22
+ Choose by audience: `my dev server` is personal; `team dev servers catalog` is shared
23
+ because the team needs it. `global_scope=true` makes an entry available in every project
24
+ to the same audience; source-project membership is still required.
25
+ Use `memory_sharing(id, shared, global_scope)` to change visibility.
26
+ Shared=false does not select a project. Existing entries remain shared within their project.
27
+ Delete memory only when the user requests it.
@@ -0,0 +1,16 @@
1
+ # Projects
2
+
3
+ Use owner/slug names. A connection can have project scope through `?project=` in HTTP
4
+ or `--project` on stdio. Pass project explicitly when no connection scope exists.
5
+ Local connections can resolve a registered working directory.
6
+ Board reads and registration never change connection scope.
7
+
8
+ Begin with `project_board(project=<absolute local path>)`. Verify principal and roots.
9
+ If the binding is missing or wrong, use project_list, including all_computers=true,
10
+ before registering an existing logical project with project_save(project, root).
11
+ Do not access paths belonging to another computer.
12
+
13
+ Projects are private until shared. Owners manage sharing and deletion;
14
+ editors change content; readers read. project_members shows roles and roots.
15
+ Shared memory does not bypass membership. Archive to retain history.
16
+ Project deletion is irreversible and requires user confirmation.
@@ -0,0 +1,72 @@
1
+ # Search
2
+
3
+ Without double quotes, search uses vectors to find related meanings only.
4
+ Quoted expressions alone search text only. Add unquoted words to search both:
5
+ text search receives only the quoted expressions; vector search receives the whole query
6
+ with double quotes removed. Mixed results show text matches first, then vector matches,
7
+ without duplicates. Quoted expressions in a mixed query are combined with AND.
8
+
9
+ ## Multiple formulations
10
+
11
+ `query` requires a list of 1–5 strings, even for one formulation. Use 2–5 short rephrasings of the
12
+ same intent, for example in both languages, to improve recall:
13
+
14
+ ```json
15
+ {"query": ["recover account access", "восстановить доступ к аккаунту"], "kinds": ["tasks", "memory"]}
16
+ ```
17
+
18
+ One formulation uses cosine ranking. Multiple semantic formulations
19
+ use equal-weight reciprocal rank fusion (RRF, k=60). Each record appears once;
20
+ `limit` applies after fusion. The response echoes the formulations in `queries`.
21
+ Semantic `score` is cosine similarity for one formulation and an RRF sum for a
22
+ multi-formulation request. `min_score` filters cosine matches before fusion.
23
+
24
+ Quote rules apply separately to each formulation. Text matches remain first with
25
+ `match: "fts"` and no score; they do not enter semantic RRF. Semantic results use
26
+ `match: "semantic"`. Exact matches are deduplicated across formulations in input order.
27
+
28
+ Vector search represents each record by its full text, heading, and body paragraphs.
29
+ Short paragraphs remain separate. The record's cosine score is its best passage
30
+ score. Results remain records, not separate passages.
31
+
32
+ ## Query syntax
33
+
34
+ | Query | Finds |
35
+ | --- | --- |
36
+ | `token` | Related meanings, using vector similarity. |
37
+ | `"token" reset "production"` | Text: token AND production; vector: token reset production |
38
+ | `"token"` | Only the word token, without prefixes or related meanings. |
39
+ | `"token*"` | Only the word token. A star inside quotes does not enable prefixes. |
40
+ | `"token"*` | Words starting with token, including tokens and tokenizer. |
41
+ | `"refresh token"` | The adjacent words refresh token, in this order. |
42
+ | `"refresh token"*` | The word refresh followed by a word starting with token. |
43
+ | `"token" "refresh"` | Both words, anywhere in the same field set. |
44
+ | `"token" AND "refresh"` | Both words, like the previous example. |
45
+ | `"token" OR "password"` | Either word, or both. |
46
+ | `"token" NOT "legacy"` | The word token, excluding records with legacy. |
47
+ | `("token" OR "password") AND "reset"` | Either token or password, and also reset. |
48
+ | `"refresh" + "token"` | The phrase refresh token, like quoted adjacent words. |
49
+ | `NEAR("refresh" "token", 5)` | Both words, either order; at most five words between them. |
50
+ | `NEAR("refresh" "token")` | The same proximity search with a default distance of ten words. |
51
+ | `^"token"` | A field starting with the word token. |
52
+ | `title:"token"` | The word token in the title field. |
53
+ | `title:("token" OR "password")` | Either word in the title field. |
54
+ | `{title body}:"token"` | The word token in title or body. |
55
+ | `-tags:"token"` | The word token in fields other than tags. |
56
+ | `tags:"web-ui"` | The adjacent words web ui in tags; punctuation is a separator. |
57
+ | `"say ""hello"" now"` | The phrase say hello now. Double an inner quote to escape it. |
58
+
59
+ **Fields:** Tasks and Memory support `title`, `body`, `tags`; Comments support `body`;
60
+ Projects support `slug`, `name`, `description`. Select compatible content types before
61
+ using a field filter. An unknown field or incomplete expression produces an error.
62
+
63
+ Words are case-insensitive; punctuation separates words. Quotes match words, not an entire
64
+ field or punctuation. Use uppercase `AND`, `OR`, `NOT`, and `NEAR`.
65
+ Use parentheses to make grouping explicit.
66
+ A trailing star outside quotes is a word-prefix operator; leading and middle wildcards
67
+ are not supported. To match punctuation-containing text, put it in double quotes.
68
+
69
+ **Filters:** Use the Tag filter (`tag` in MCP) for an exact tag, such as `web-ui`.
70
+ Choose content types with `kinds`, task statuses with `status`, and scope with `project`,
71
+ `all_projects`, `computer`, or `all_computers`. `limit` is 1–200 results per content type.
72
+ `min_score` is -1–1 and filters semantic matches only; it never filters text matches.
@@ -0,0 +1,40 @@
1
+ # Tasks
2
+
3
+ ## Task body and comments
4
+
5
+ `task.body` is the agreed task definition: goal, scope, requirements, constraints,
6
+ and acceptance criteria. It is not a work log.
7
+
8
+ Use `task_comment_add` for progress, review feedback, findings, research results,
9
+ hypotheses, questions, suggestions, blockers, and verification. Proposed requirement
10
+ changes also belong in comments until the user explicitly agrees to them.
11
+ New information alone does not authorize a body edit.
12
+
13
+ Use `task_update(body=...)` only when the user explicitly requests a definition change,
14
+ or explicitly agrees to requirements that make the current body incorrect or outdated.
15
+ The supplied body replaces the entire description; an empty string clears it.
16
+ For every body edit, add a separate comment explaining the reason and the user request
17
+ or agreement that authorized it. Do not put review feedback, progress, or unapproved
18
+ requirements into body edits.
19
+
20
+ For example, a review that finds a missing requirement produces a comment proposing
21
+ that requirement. Update the body only after the user agrees, then comment on why it changed.
22
+
23
+ ## Status and relationships
24
+
25
+ Use todo for planned work, doing for active work, done for verified outcomes,
26
+ cancelled for abandoned work, and blocked for external blockers explained in a comment.
27
+ Use `task_link(task, relation, target)` for relationships:
28
+ - part_of: task belongs to a parent; inverse contains.
29
+ - depends_on: task waits for a prerequisite; inverse blocks.
30
+ - caused_by: task results from another task; inverse causes.
31
+ - related_to: symmetric association.
32
+
33
+ Dependencies belong in links, not blocked status or prose. Board ready tasks are
34
+ unassigned open tasks whose direct dependencies are closed.
35
+
36
+ Assignments are advisory. Any editor can take over through CAS:
37
+ `task_claim(task, expected=<observed value>, assigned=<principal>:<marker>)`.
38
+ Both nullable values are required. On conflict, reread before retrying.
39
+ Closing does not release assignment. Use assigned=null to release.
40
+ Temporary UI edit claims protect writes until restored; see task_claim parameters.
@@ -0,0 +1,22 @@
1
+ # Workflow
2
+
3
+ 1. Call `project_board(project=<absolute local path>)`. Verify principal and roots;
4
+ then use the returned owner/slug. Read every `global_memory` entry in full before
5
+ work; it is mandatory context. Leave correct bindings unchanged.
6
+ 2. First call `memory_list(project=<full_name>)` for project memory.
7
+ Keep the compact result; read relevant entries with `memory_get`.
8
+ Use topic-specific `search` for related tasks and agreements.
9
+ Include project-shared entries; do not load unrelated project memory. Verify technical facts in code.
10
+ 3. For work spanning multiple steps or sessions, reuse or create a task.
11
+ Read it with `task_get`, then claim through `task_claim` before starting.
12
+ 4. Set doing. Use `task_comment_add` for progress, review, findings, checks, questions,
13
+ and proposed requirement changes. The task body is the agreed definition.
14
+ Edit it only on an explicit user request or to reflect explicitly agreed requirements
15
+ that make it incorrect or outdated. Add a separate comment explaining every body edit.
16
+ New findings alone do not authorize changes to the body.
17
+ 5. Verify the outcome, update obsolete memory, close the task, and release
18
+ through `task_claim(expected=<your claim>, assigned=null)`.
19
+
20
+ Follow preferred_language. A brief answer needs no task. Keep tracking in backlog,
21
+ not files. On outages, report the failure, continue independent authorized work,
22
+ and keep pending updates in the conversation. Never claim an unconfirmed write.
backlog_mcp/httpd.py ADDED
@@ -0,0 +1,270 @@
1
+ """The optional HTTP front end: the same MCP surface, plus the bundled console."""
2
+
3
+ from __future__ import annotations
4
+
5
+ import asyncio
6
+ import json
7
+ import logging
8
+ import signal
9
+ from collections.abc import AsyncIterator, Awaitable, Callable, Collection, Sequence
10
+ from typing import Any
11
+
12
+ from aiohttp import web
13
+ from aiohttp.typedefs import Middleware
14
+ from aiohttp_tiny_mcp import Authentication, Endpoint, Principal, Registry, Unauthorized
15
+ from aiohttp_tiny_mcp.auth.jwt import HMACJWTVerifier, PublicKeyJWTVerifier
16
+ from aiohttp_tiny_mcp.console import Console
17
+ from aiohttp_tiny_mcp.storage.namespaces import namespace
18
+ from aiohttp_tiny_mcp.storage.sqlite import SqliteStorage
19
+ from yarl import URL
20
+
21
+ from . import webui
22
+ from .auth import (
23
+ VERIFIED,
24
+ BasicAuthentication,
25
+ JWTAuthentication,
26
+ normalize_accounts,
27
+ user_identity,
28
+ )
29
+ from .backlog import Backlog, register
30
+ from .server import ACTIVE_REGISTRY, VERSION, persistent_registry, use
31
+
32
+ log = logging.getLogger(__name__)
33
+
34
+ Handler = Callable[[web.Request], Awaitable[web.StreamResponse]]
35
+
36
+ ENDPOINT_PATH = "/mcp"
37
+ CONSOLE_PATH = "/console"
38
+ PRINCIPAL = web.RequestKey("backlog_principal", Principal)
39
+ STORAGE = web.AppKey("backlog_storage", SqliteStorage)
40
+
41
+ CONSOLE_ABOUT = (
42
+ "Projects and tasks of this backlog. Tools work on one project at a time; "
43
+ "list and search tools reach every project with all_projects, and every computer with "
44
+ "all_computers. Connect as another computer with ?computer=<name>&project=<slug>."
45
+ )
46
+
47
+
48
+ def bind(backlog: Backlog, configured: Registry | None = None) -> Middleware:
49
+ """Middleware that points the handlers at this backlog, per request.
50
+
51
+ `?computer=<name>` serves the request as that computer and `?project=<slug>` fixes its
52
+ project, so one server answers for every computer of its user. Without a computer name,
53
+ the request uses `unknown` instead of the server's computer name.
54
+ """
55
+
56
+ @web.middleware
57
+ async def middleware(request: web.Request, handler: Handler) -> web.StreamResponse:
58
+ connection = await backlog.open()
59
+ computer = request.query.get("computer") or "unknown"
60
+ project = request.query.get("project") or None
61
+ try:
62
+ identity = None
63
+ if PRINCIPAL in request:
64
+ principal = request[PRINCIPAL]
65
+ identity = principal.namespace
66
+ assert identity, "authenticated users must have a storage identity"
67
+ async with backlog.transaction:
68
+ await register(
69
+ connection,
70
+ backlog.actor,
71
+ identity,
72
+ principal.subject or principal.client_id or identity,
73
+ )
74
+ view = backlog.view(computer=computer, project=project, principal=identity)
75
+ if identity is not None:
76
+ jwt = any(
77
+ isinstance(policy, JWTAuthentication) and result is principal
78
+ for policy, result in request.get(VERIFIED, {}).items()
79
+ )
80
+ view.auth_type = "jwt" if jwt else "basic"
81
+ use(view)
82
+ if configured is not None:
83
+ ACTIVE_REGISTRY.set(configured)
84
+ except ValueError as error:
85
+ raise web.HTTPBadRequest(text=str(error)) from error
86
+ response = await handler(request)
87
+ if request.method == "GET" and response.status == 404:
88
+ missing_session = False
89
+ if isinstance(response, web.Response) and response.content_type == "application/json":
90
+ try:
91
+ payload = json.loads(response.text or "{}")
92
+ except ValueError:
93
+ payload = None
94
+ if isinstance(payload, dict):
95
+ rpc_error = payload.get("error")
96
+ missing_session = (
97
+ isinstance(rpc_error, dict) and rpc_error.get("code") == -32001
98
+ )
99
+ if missing_session:
100
+ log.warning(
101
+ "MCP GET rejected: session not found or owned by another principal; "
102
+ "the client must initialize a new session"
103
+ )
104
+ else:
105
+ log.warning("MCP GET returned 404 without a session-not-found error")
106
+ return response
107
+
108
+ return middleware
109
+
110
+
111
+ def authentication(endpoint: Endpoint) -> Middleware:
112
+ """Authenticate MCP requests before binding their application identity."""
113
+
114
+ @web.middleware
115
+ async def middleware(request: web.Request, handler: Handler) -> web.StreamResponse:
116
+ token = namespace.set(None)
117
+ try:
118
+ try:
119
+ principal = await endpoint.verified(request)
120
+ except Unauthorized as refusal:
121
+ log.warning("refused %s %s from %s", request.method, request.path, request.remote)
122
+ return endpoint.refuse(refusal)
123
+ if principal is not None:
124
+ request[PRINCIPAL] = principal
125
+ return await handler(request)
126
+ finally:
127
+ namespace.reset(token)
128
+
129
+ return middleware
130
+
131
+
132
+ def application(
133
+ backlog: Backlog,
134
+ *,
135
+ basic: Sequence[str] = (),
136
+ jwt_public_key: str = "",
137
+ jwt_pre_shared_key: str = "",
138
+ jwt_issuer: str = "",
139
+ jwt_audience: str = "",
140
+ console: bool = True,
141
+ allowed_origins: Collection[URL] = (),
142
+ trust_proxy: bool = False,
143
+ ) -> web.Application:
144
+ """The authenticated MCP subapp at `/mcp` and the public UI at `/ui`.
145
+
146
+ Without Basic credentials or a JWT key, requests do not require authentication.
147
+ Project memberships control data access. Sessions remain principal-scoped.
148
+
149
+ The endpoint refuses a browser `Origin` that is not its own, against DNS rebinding.
150
+ `allowed_origins` adds exact public origins for TLS termination without disabling this check.
151
+ `trust_proxy` turns the check off entirely, so the proxy must validate the origin instead.
152
+ """
153
+ policies: list[Authentication] = []
154
+ accounts: list[tuple[str, str]] = []
155
+ if basic:
156
+ for account in normalize_accounts(basic):
157
+ user, hashed = account.removeprefix("bcrypt|").rsplit("|", 1)
158
+ accounts.append((user, hashed))
159
+ policies.append(BasicAuthentication(hashed_accounts=accounts))
160
+ if jwt_pre_shared_key:
161
+ policies.append(
162
+ JWTAuthentication(
163
+ HMACJWTVerifier(jwt_pre_shared_key, issuer=jwt_issuer, audience=jwt_audience)
164
+ )
165
+ )
166
+ if jwt_public_key:
167
+ policies.append(
168
+ JWTAuthentication(
169
+ PublicKeyJWTVerifier(jwt_public_key, issuer=jwt_issuer, audience=jwt_audience)
170
+ )
171
+ )
172
+ if (jwt_issuer or jwt_audience) and not (jwt_public_key or jwt_pre_shared_key):
173
+ raise ValueError("JWT issuer and audience require a JWT public key or pre-shared key")
174
+ if not policies:
175
+ log.warning("no credentials given: every request is served without authentication")
176
+ configured, storage = persistent_registry(backlog, policies)
177
+ middlewares: list[Middleware] = [bind(backlog, configured)]
178
+ endpoint = Endpoint(
179
+ configured,
180
+ # aiohttp-tiny-mcp currently accepts strings, not URL objects.
181
+ allowed_origins={str(origin) for origin in allowed_origins},
182
+ trust_proxy_origin_validation=trust_proxy,
183
+ )
184
+ if policies:
185
+ middlewares.insert(0, authentication(endpoint))
186
+ mcp = web.Application(middlewares=middlewares)
187
+ mcp.add_routes(endpoint.routes("", metadata=False))
188
+ app = web.Application()
189
+ app[STORAGE] = storage
190
+ app.add_routes(endpoint.metadata_routes())
191
+ app.add_subapp(ENDPOINT_PATH, mcp)
192
+
193
+ async def index(request: web.Request) -> web.Response:
194
+ raise web.HTTPFound("/ui/")
195
+
196
+ app.router.add_get("/", index)
197
+ app.add_subapp("/ui", webui.application())
198
+ if console:
199
+ page = Console(
200
+ endpoint_path=ENDPOINT_PATH,
201
+ title=f"backlog {VERSION}",
202
+ description=CONSOLE_ABOUT,
203
+ )
204
+
205
+ async def console_index(request: web.Request) -> web.Response:
206
+ raise web.HTTPFound(request.rel_url.with_path(CONSOLE_PATH, keep_query=True))
207
+
208
+ app.router.add_get(f"{CONSOLE_PATH}/", console_index)
209
+ app.add_routes(
210
+ route for route in page.routes(CONSOLE_PATH) if route.path != f"{CONSOLE_PATH}/"
211
+ )
212
+
213
+ async def lifespan(app: web.Application) -> AsyncIterator[None]:
214
+ connection = await backlog.open()
215
+ try:
216
+ for user, _password in accounts:
217
+ async with backlog.transaction:
218
+ await register(connection, backlog.actor, user_identity(user), user)
219
+ log.info("database %s", backlog.database.path)
220
+ async for _ in storage.cleanup_ctx(app):
221
+ yield
222
+ finally:
223
+ await backlog.close()
224
+
225
+ app.cleanup_ctx.append(lifespan)
226
+ return app
227
+
228
+
229
+ async def serve(
230
+ backlog: Backlog,
231
+ *,
232
+ address: str,
233
+ port: int,
234
+ shutdown_timeout: float = 8.0,
235
+ **kw: Any,
236
+ ) -> None:
237
+ """Serve until interrupted, then clean up HTTP and database resources.
238
+
239
+ aiohttp can spend ``shutdown_timeout`` in each of two request-draining phases, so the
240
+ default remains well below half of the container's 30-second termination grace period.
241
+ """
242
+ runner = web.AppRunner(application(backlog, **kw), shutdown_timeout=shutdown_timeout)
243
+ loop = asyncio.get_running_loop()
244
+ stopped = asyncio.Event()
245
+ registered: list[signal.Signals] = []
246
+ try:
247
+ for signum in (signal.SIGINT, signal.SIGTERM):
248
+ try:
249
+ loop.add_signal_handler(signum, stopped.set)
250
+ registered.append(signum)
251
+ except NotImplementedError:
252
+ pass
253
+ await runner.setup()
254
+ await web.TCPSite(runner, address, port).start()
255
+ where = f"http://{address}:{port}"
256
+ log.info("serving %s%s, console at %s%s", where, ENDPOINT_PATH, where, CONSOLE_PATH)
257
+ await stopped.wait()
258
+ finally:
259
+ for signum in registered:
260
+ loop.remove_signal_handler(signum)
261
+ await runner.cleanup()
262
+
263
+
264
+ __all__ = [
265
+ "CONSOLE_PATH",
266
+ "ENDPOINT_PATH",
267
+ "application",
268
+ "authentication",
269
+ "serve",
270
+ ]