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.
- 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.34.2.dist-info/METADATA +84 -0
- backlog_tiny_mcp-0.34.2.dist-info/RECORD +97 -0
- backlog_tiny_mcp-0.34.2.dist-info/WHEEL +4 -0
- backlog_tiny_mcp-0.34.2.dist-info/entry_points.txt +4 -0
backlog_mcp/client.py
ADDED
|
@@ -0,0 +1,320 @@
|
|
|
1
|
+
"""MCP connections used by the command line, including a local stdio subprocess."""
|
|
2
|
+
|
|
3
|
+
from __future__ import annotations
|
|
4
|
+
|
|
5
|
+
import asyncio
|
|
6
|
+
import contextlib
|
|
7
|
+
import json
|
|
8
|
+
import logging
|
|
9
|
+
import sys
|
|
10
|
+
from base64 import b64encode
|
|
11
|
+
from collections.abc import AsyncIterator, Awaitable, Callable
|
|
12
|
+
from contextlib import AsyncExitStack, asynccontextmanager
|
|
13
|
+
from dataclasses import dataclass
|
|
14
|
+
from pathlib import Path
|
|
15
|
+
from typing import TYPE_CHECKING, Any
|
|
16
|
+
|
|
17
|
+
from aiohttp import ClientResponse, ClientSession, ClientTimeout
|
|
18
|
+
from aiohttp_tiny_mcp import AdapterSet, Client, StdioClient
|
|
19
|
+
from aiohttp_tiny_mcp.client.base import BaseClient, Elicitor
|
|
20
|
+
from aiohttp_tiny_mcp.protocol.models import CallToolResult, TextContent, TextResourceContents
|
|
21
|
+
from pydantic import BaseModel
|
|
22
|
+
from yarl import URL
|
|
23
|
+
|
|
24
|
+
from . import paths, skills
|
|
25
|
+
from .backlog import checkout_root
|
|
26
|
+
from .computer import check, hostname
|
|
27
|
+
from .models import ProjectBoard, ProjectOut, Projects
|
|
28
|
+
from .names import default_user
|
|
29
|
+
|
|
30
|
+
if TYPE_CHECKING:
|
|
31
|
+
from .cli import CLI
|
|
32
|
+
|
|
33
|
+
|
|
34
|
+
class ToolError(Exception):
|
|
35
|
+
"""An operation rejected by the MCP server."""
|
|
36
|
+
|
|
37
|
+
@property
|
|
38
|
+
def exit_code(self) -> int:
|
|
39
|
+
return 2 if str(self).startswith(("no project", "no computer")) else 1
|
|
40
|
+
|
|
41
|
+
|
|
42
|
+
@dataclass(frozen=True)
|
|
43
|
+
class Registration:
|
|
44
|
+
name: str | None = None
|
|
45
|
+
description: str | None = None
|
|
46
|
+
project: str | None = None
|
|
47
|
+
computer: str | None = None
|
|
48
|
+
root: Path | None = None
|
|
49
|
+
|
|
50
|
+
|
|
51
|
+
Registrar = Callable[[str, Path, list[ProjectOut]], Registration]
|
|
52
|
+
|
|
53
|
+
|
|
54
|
+
@dataclass
|
|
55
|
+
class RemoteFile:
|
|
56
|
+
uri: str
|
|
57
|
+
size: int
|
|
58
|
+
|
|
59
|
+
|
|
60
|
+
@dataclass
|
|
61
|
+
class RemoteSkill:
|
|
62
|
+
name: str
|
|
63
|
+
uri: str
|
|
64
|
+
description: str
|
|
65
|
+
files: list[dict[str, Any]]
|
|
66
|
+
instructions: str = ""
|
|
67
|
+
|
|
68
|
+
@property
|
|
69
|
+
def references(self) -> list[RemoteFile]:
|
|
70
|
+
return [
|
|
71
|
+
RemoteFile(item["uri"], item["size"]) for item in self.files if item["uri"] != self.uri
|
|
72
|
+
]
|
|
73
|
+
|
|
74
|
+
|
|
75
|
+
class Connection:
|
|
76
|
+
"""Typed tool calls over one initialized connection."""
|
|
77
|
+
|
|
78
|
+
def __init__(self, client: BaseClient, *, computer: str, timeout: float, root: Path) -> None:
|
|
79
|
+
self.client = client
|
|
80
|
+
self.computer = computer
|
|
81
|
+
self.timeout = timeout
|
|
82
|
+
self.root = root
|
|
83
|
+
self.relocate: Callable[[str, Path], Awaitable[None]] | None = None
|
|
84
|
+
self.project: str | None = None
|
|
85
|
+
|
|
86
|
+
async def call[M: BaseModel](
|
|
87
|
+
self, model: type[M], tool: str, *, exclude_none: bool = True, **arguments: Any
|
|
88
|
+
) -> M:
|
|
89
|
+
if isinstance(self.client, Client) and arguments.get("project"):
|
|
90
|
+
arguments["project"] = project_reference(arguments["project"], self.root)
|
|
91
|
+
async with asyncio.timeout(self.timeout):
|
|
92
|
+
result = await self.client.call_tool(
|
|
93
|
+
tool,
|
|
94
|
+
{
|
|
95
|
+
key: value
|
|
96
|
+
for key, value in arguments.items()
|
|
97
|
+
if value is not None or not exclude_none
|
|
98
|
+
},
|
|
99
|
+
)
|
|
100
|
+
if not isinstance(result, CallToolResult):
|
|
101
|
+
raise ToolError("the server requested unsupported input")
|
|
102
|
+
text = "\n".join(item.text for item in result.content if isinstance(item, TextContent))
|
|
103
|
+
if result.is_error:
|
|
104
|
+
kind, separator, message = text.partition(": ")
|
|
105
|
+
if separator and kind in {
|
|
106
|
+
"LookupError",
|
|
107
|
+
"UnknownProject",
|
|
108
|
+
"ValueError",
|
|
109
|
+
"PermissionError",
|
|
110
|
+
}:
|
|
111
|
+
text = message
|
|
112
|
+
raise ToolError(text)
|
|
113
|
+
value = result.structured_content
|
|
114
|
+
if value is None:
|
|
115
|
+
value = json.loads(text)
|
|
116
|
+
return model.model_validate(value)
|
|
117
|
+
|
|
118
|
+
async def board(self, project: str | None = None) -> ProjectBoard:
|
|
119
|
+
reference = project or self.project
|
|
120
|
+
if reference is None:
|
|
121
|
+
raise ToolError("no project chosen: pass --project or register this checkout")
|
|
122
|
+
return await self.call(ProjectBoard, "project_board", project=reference)
|
|
123
|
+
|
|
124
|
+
async def skills(self) -> list[RemoteSkill]:
|
|
125
|
+
"""Read the skill list, then the root resource of each skill for its file manifest."""
|
|
126
|
+
content = await self.read(skills.LIST_URI)
|
|
127
|
+
found = []
|
|
128
|
+
for item in json.loads(content.text)["skills"]:
|
|
129
|
+
entry = json.loads((await self.read(item["root"])).text)
|
|
130
|
+
found.append(
|
|
131
|
+
RemoteSkill(
|
|
132
|
+
name=item["frontmatter"]["name"],
|
|
133
|
+
uri=item["uri"],
|
|
134
|
+
description=item["frontmatter"].get("description", ""),
|
|
135
|
+
files=entry["resources"],
|
|
136
|
+
)
|
|
137
|
+
)
|
|
138
|
+
return found
|
|
139
|
+
|
|
140
|
+
async def read(self, uri: str) -> TextResourceContents:
|
|
141
|
+
async with asyncio.timeout(self.timeout):
|
|
142
|
+
result = await self.client.read_resource(uri)
|
|
143
|
+
if not result.contents or not isinstance(result.contents[0], TextResourceContents):
|
|
144
|
+
raise ToolError(f"expected a text resource: {uri}")
|
|
145
|
+
return result.contents[0]
|
|
146
|
+
|
|
147
|
+
|
|
148
|
+
async def stop(process: asyncio.subprocess.Process) -> None:
|
|
149
|
+
"""Close stdin, then terminate or kill a child that does not stop."""
|
|
150
|
+
if process.stdin is not None:
|
|
151
|
+
process.stdin.close()
|
|
152
|
+
try:
|
|
153
|
+
await asyncio.wait_for(process.wait(), 2)
|
|
154
|
+
except TimeoutError:
|
|
155
|
+
with contextlib.suppress(ProcessLookupError):
|
|
156
|
+
process.terminate()
|
|
157
|
+
try:
|
|
158
|
+
await asyncio.wait_for(process.wait(), 2)
|
|
159
|
+
except TimeoutError:
|
|
160
|
+
with contextlib.suppress(ProcessLookupError):
|
|
161
|
+
process.kill()
|
|
162
|
+
await process.wait()
|
|
163
|
+
|
|
164
|
+
|
|
165
|
+
def project_reference(reference: str, root: Path) -> str:
|
|
166
|
+
if reference.startswith((".", "/", "~")):
|
|
167
|
+
return str((root / Path(reference).expanduser()).resolve())
|
|
168
|
+
return reference
|
|
169
|
+
|
|
170
|
+
|
|
171
|
+
def local_command(options: CLI, computer: str) -> list[str]:
|
|
172
|
+
level = "debug" if options.log_level < logging.INFO else "warning"
|
|
173
|
+
command = [sys.executable, "-m", "backlog_mcp", "--log-level", level]
|
|
174
|
+
for flag, value in (
|
|
175
|
+
("--database", (options.database or paths.database_path()).expanduser().resolve()),
|
|
176
|
+
("--root", (options.root or Path.cwd()).expanduser().resolve()),
|
|
177
|
+
("--computer", computer),
|
|
178
|
+
("--project", options.project),
|
|
179
|
+
):
|
|
180
|
+
if value is not None:
|
|
181
|
+
command.extend((flag, str(value)))
|
|
182
|
+
command.extend(("mcp", "--protocol", "stdio"))
|
|
183
|
+
command.extend(("--default-user", default_user(options.default_user)))
|
|
184
|
+
return command
|
|
185
|
+
|
|
186
|
+
|
|
187
|
+
def directory_project(computer: str, root: Path, projects: list[ProjectOut]) -> ProjectOut | None:
|
|
188
|
+
candidates = [
|
|
189
|
+
(Path(binding.root), project)
|
|
190
|
+
for project in projects
|
|
191
|
+
for binding in project.roots
|
|
192
|
+
if binding.computer == computer and binding.root and root.is_relative_to(Path(binding.root))
|
|
193
|
+
]
|
|
194
|
+
return max(candidates, key=lambda item: len(item[0].parts))[1] if candidates else None
|
|
195
|
+
|
|
196
|
+
|
|
197
|
+
async def bind_directory(connection: Connection, register: Registrar) -> ProjectOut:
|
|
198
|
+
"""Resolve a computer and directory before creating a binding through MCP."""
|
|
199
|
+
root = connection.root
|
|
200
|
+
if not root.is_dir():
|
|
201
|
+
raise ToolError(f"no such directory: {root}")
|
|
202
|
+
projects = await connection.call(Projects, "project_list", archived=True)
|
|
203
|
+
project = directory_project(connection.computer, root, projects.items)
|
|
204
|
+
if project is None:
|
|
205
|
+
directory = checkout_root(root)
|
|
206
|
+
known = await connection.call(Projects, "project_list", archived=True, all_computers=True)
|
|
207
|
+
chosen = register(connection.computer, directory, known.items)
|
|
208
|
+
directory = chosen.root or directory
|
|
209
|
+
computer = chosen.computer or connection.computer
|
|
210
|
+
if computer != connection.computer or directory != root:
|
|
211
|
+
assert connection.relocate is not None
|
|
212
|
+
await connection.relocate(computer, directory)
|
|
213
|
+
# The edited location can already belong to a project. Check the server again.
|
|
214
|
+
projects = await connection.call(Projects, "project_list", archived=True)
|
|
215
|
+
project = directory_project(computer, directory, projects.items)
|
|
216
|
+
if project is None:
|
|
217
|
+
project = await connection.call(
|
|
218
|
+
ProjectOut,
|
|
219
|
+
"project_save",
|
|
220
|
+
root=str(directory),
|
|
221
|
+
project=chosen.project,
|
|
222
|
+
name=chosen.name,
|
|
223
|
+
description=chosen.description,
|
|
224
|
+
)
|
|
225
|
+
connection.project = project.full_name
|
|
226
|
+
if isinstance(connection.client, Client):
|
|
227
|
+
connection.client.base_url = str(
|
|
228
|
+
URL(connection.client.base_url).update_query(project=project.full_name)
|
|
229
|
+
)
|
|
230
|
+
return project
|
|
231
|
+
|
|
232
|
+
|
|
233
|
+
@asynccontextmanager
|
|
234
|
+
async def connect(
|
|
235
|
+
options: CLI, *, on_ask: Elicitor, on_register: Registrar, scope_directory: bool = True
|
|
236
|
+
) -> AsyncIterator[Connection]:
|
|
237
|
+
async with AsyncExitStack() as stack:
|
|
238
|
+
connection = await stack.enter_async_context(transport(options, on_ask=on_ask))
|
|
239
|
+
|
|
240
|
+
async def relocate(computer: str, root: Path) -> None:
|
|
241
|
+
await stack.aclose()
|
|
242
|
+
options.computer = computer
|
|
243
|
+
options.root = root
|
|
244
|
+
replacement = await stack.enter_async_context(transport(options, on_ask=on_ask))
|
|
245
|
+
connection.client = replacement.client
|
|
246
|
+
connection.computer = replacement.computer
|
|
247
|
+
connection.root = replacement.root
|
|
248
|
+
|
|
249
|
+
connection.relocate = relocate
|
|
250
|
+
endpoint = URL(options.url) if options.url else None
|
|
251
|
+
explicit = options.project or (endpoint.query.get("project") if endpoint else None)
|
|
252
|
+
connection.project = explicit
|
|
253
|
+
if scope_directory and not explicit:
|
|
254
|
+
await bind_directory(connection, on_register)
|
|
255
|
+
yield connection
|
|
256
|
+
|
|
257
|
+
|
|
258
|
+
async def check_authentication(response: ClientResponse) -> None:
|
|
259
|
+
"""Reject HTTP auth errors before parsing JSON-RPC; allow MCP session recovery on 404."""
|
|
260
|
+
if response.status in {401, 403}:
|
|
261
|
+
response.raise_for_status()
|
|
262
|
+
|
|
263
|
+
|
|
264
|
+
@asynccontextmanager
|
|
265
|
+
async def transport(options: CLI, *, on_ask: Elicitor) -> AsyncIterator[Connection]:
|
|
266
|
+
"""Open one transport without resolving or registering a project."""
|
|
267
|
+
adapter = AdapterSet.default().by_version["2026-07-28"]
|
|
268
|
+
if options.timeout <= 0:
|
|
269
|
+
raise ValueError("--timeout must be greater than zero")
|
|
270
|
+
root = (options.root or Path.cwd()).expanduser().resolve()
|
|
271
|
+
endpoint = URL(options.url) if options.url else None
|
|
272
|
+
configured_computer = options.computer or (endpoint.query.get("computer") if endpoint else None)
|
|
273
|
+
computer = check(configured_computer) if configured_computer else hostname()
|
|
274
|
+
if endpoint is not None:
|
|
275
|
+
if endpoint.scheme not in {"http", "https"} or not endpoint.host:
|
|
276
|
+
raise ValueError("--url must be an absolute HTTP or HTTPS MCP endpoint")
|
|
277
|
+
endpoint = endpoint.update_query(computer=computer)
|
|
278
|
+
if options.project:
|
|
279
|
+
reference = project_reference(options.project, root)
|
|
280
|
+
endpoint = endpoint.update_query(project=reference)
|
|
281
|
+
options.project = reference
|
|
282
|
+
headers = {}
|
|
283
|
+
if options.token or endpoint.query.get("token"):
|
|
284
|
+
if options.user or options.password or endpoint.user or endpoint.query.get("auth"):
|
|
285
|
+
raise ValueError("configure --token or Basic authentication, not both")
|
|
286
|
+
if options.token:
|
|
287
|
+
headers["Authorization"] = f"Bearer {options.token}"
|
|
288
|
+
elif options.user:
|
|
289
|
+
if ":" in options.user:
|
|
290
|
+
raise ValueError("the Basic auth user must not contain a colon")
|
|
291
|
+
credentials = b64encode(f"{options.user}:{options.password}".encode()).decode("ascii")
|
|
292
|
+
headers["Authorization"] = f"Basic {credentials}"
|
|
293
|
+
async with (
|
|
294
|
+
ClientSession(
|
|
295
|
+
headers=headers,
|
|
296
|
+
timeout=ClientTimeout(total=None, sock_connect=options.timeout),
|
|
297
|
+
raise_for_status=check_authentication,
|
|
298
|
+
) as session,
|
|
299
|
+
Client(str(endpoint), adapter, session=session, on_ask=on_ask) as client,
|
|
300
|
+
):
|
|
301
|
+
async with asyncio.timeout(options.timeout):
|
|
302
|
+
await client.initialize()
|
|
303
|
+
connection = Connection(client, computer=computer, timeout=options.timeout, root=root)
|
|
304
|
+
yield connection
|
|
305
|
+
return
|
|
306
|
+
process = await asyncio.create_subprocess_exec(
|
|
307
|
+
*local_command(options, computer),
|
|
308
|
+
stdin=asyncio.subprocess.PIPE,
|
|
309
|
+
stdout=asyncio.subprocess.PIPE,
|
|
310
|
+
limit=8 * 1024 * 1024,
|
|
311
|
+
)
|
|
312
|
+
assert process.stdout is not None and process.stdin is not None
|
|
313
|
+
try:
|
|
314
|
+
local = StdioClient(process.stdout, process.stdin, adapter, on_ask=on_ask)
|
|
315
|
+
async with asyncio.timeout(options.timeout):
|
|
316
|
+
await local.initialize()
|
|
317
|
+
connection = Connection(local, computer=computer, timeout=options.timeout, root=root)
|
|
318
|
+
yield connection
|
|
319
|
+
finally:
|
|
320
|
+
await stop(process)
|
backlog_mcp/computer.py
ADDED
|
@@ -0,0 +1,33 @@
|
|
|
1
|
+
"""The name of the computer a project lives on.
|
|
2
|
+
|
|
3
|
+
A project is a directory tree on one computer. The name tells the computers apart when one
|
|
4
|
+
database, synced or served over HTTP, holds the projects of several of them.
|
|
5
|
+
"""
|
|
6
|
+
|
|
7
|
+
from __future__ import annotations
|
|
8
|
+
|
|
9
|
+
import re
|
|
10
|
+
import socket
|
|
11
|
+
|
|
12
|
+
#: One word of letters, digits, dots, dashes and underscores: it travels in URLs and config files.
|
|
13
|
+
PATTERN = re.compile(r"[A-Za-z0-9][A-Za-z0-9._-]{0,62}\Z")
|
|
14
|
+
|
|
15
|
+
|
|
16
|
+
def check(name: str) -> str:
|
|
17
|
+
"""The name stripped, or `ValueError` when it is not one plain word."""
|
|
18
|
+
cleaned = name.strip()
|
|
19
|
+
if not PATTERN.match(cleaned):
|
|
20
|
+
raise ValueError(
|
|
21
|
+
f"invalid computer name {name!r}: use letters, digits, dots, dashes and underscores"
|
|
22
|
+
)
|
|
23
|
+
return cleaned
|
|
24
|
+
|
|
25
|
+
|
|
26
|
+
def hostname() -> str:
|
|
27
|
+
"""The short host name, made a valid computer name. Falls back to `localhost`."""
|
|
28
|
+
short = socket.gethostname().split(".")[0]
|
|
29
|
+
cleaned = re.sub(r"[^A-Za-z0-9._-]+", "-", short).strip("-._")
|
|
30
|
+
return cleaned if PATTERN.match(cleaned) else "localhost"
|
|
31
|
+
|
|
32
|
+
|
|
33
|
+
__all__ = ["PATTERN", "check", "hostname"]
|
backlog_mcp/database.py
ADDED
|
@@ -0,0 +1,80 @@
|
|
|
1
|
+
"""Connection lifetime and schema initialization."""
|
|
2
|
+
|
|
3
|
+
import asyncio
|
|
4
|
+
import sqlite3
|
|
5
|
+
from dataclasses import dataclass, field
|
|
6
|
+
from pathlib import Path
|
|
7
|
+
|
|
8
|
+
import aiosqlite
|
|
9
|
+
|
|
10
|
+
from .migrate import migrate
|
|
11
|
+
from .names import owner_name
|
|
12
|
+
from .queries import QUERIES
|
|
13
|
+
from .transaction import Transaction
|
|
14
|
+
|
|
15
|
+
# Connection settings are an inline SQL exception; other queries belong in queries.sql.
|
|
16
|
+
PRAGMAS = {
|
|
17
|
+
"busy_timeout": 5000,
|
|
18
|
+
"foreign_keys": "ON",
|
|
19
|
+
"journal_mode": "WAL",
|
|
20
|
+
}
|
|
21
|
+
|
|
22
|
+
|
|
23
|
+
@dataclass(eq=False)
|
|
24
|
+
class Database:
|
|
25
|
+
path: Path
|
|
26
|
+
connection: aiosqlite.Connection | None = field(default=None, init=False)
|
|
27
|
+
transaction: Transaction | None = field(default=None, init=False)
|
|
28
|
+
opening: asyncio.Lock = field(default_factory=asyncio.Lock, init=False)
|
|
29
|
+
|
|
30
|
+
@property
|
|
31
|
+
def in_memory(self) -> bool:
|
|
32
|
+
return str(self.path) == ":memory:"
|
|
33
|
+
|
|
34
|
+
async def open(self, principal: str) -> aiosqlite.Connection:
|
|
35
|
+
async with self.opening:
|
|
36
|
+
if self.connection is not None:
|
|
37
|
+
return self.connection
|
|
38
|
+
if not self.in_memory:
|
|
39
|
+
self.path.parent.mkdir(parents=True, exist_ok=True)
|
|
40
|
+
connection = await aiosqlite.connect(str(self.path))
|
|
41
|
+
connection.row_factory = aiosqlite.Row
|
|
42
|
+
transaction = Transaction(connection, asyncio.Lock())
|
|
43
|
+
try:
|
|
44
|
+
for name, value in PRAGMAS.items():
|
|
45
|
+
# WAL can return BUSY immediately during concurrent startup.
|
|
46
|
+
for attempt in range(5):
|
|
47
|
+
try:
|
|
48
|
+
await connection.execute_fetchall(f"PRAGMA {name} = {value}")
|
|
49
|
+
break
|
|
50
|
+
except sqlite3.OperationalError as error:
|
|
51
|
+
if (
|
|
52
|
+
name != "journal_mode"
|
|
53
|
+
or error.sqlite_errorcode != sqlite3.SQLITE_BUSY
|
|
54
|
+
or attempt == 4
|
|
55
|
+
):
|
|
56
|
+
raise
|
|
57
|
+
await asyncio.sleep(0.05)
|
|
58
|
+
await migrate(connection, transaction=transaction)
|
|
59
|
+
async with transaction:
|
|
60
|
+
await QUERIES.register_principal(
|
|
61
|
+
connection,
|
|
62
|
+
identity=principal,
|
|
63
|
+
handle=owner_name(principal),
|
|
64
|
+
name=owner_name(principal),
|
|
65
|
+
)
|
|
66
|
+
except BaseException:
|
|
67
|
+
await connection.close()
|
|
68
|
+
raise
|
|
69
|
+
self.connection = connection
|
|
70
|
+
self.transaction = transaction
|
|
71
|
+
return connection
|
|
72
|
+
|
|
73
|
+
async def close(self) -> None:
|
|
74
|
+
from .embeddings import stop
|
|
75
|
+
|
|
76
|
+
await stop(self)
|
|
77
|
+
if self.connection is not None:
|
|
78
|
+
await self.connection.close()
|
|
79
|
+
self.connection = None
|
|
80
|
+
self.transaction = None
|