mcp-dispatch-pg 0.1.0a1__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 (36) hide show
  1. mcp_dispatch_pg/__init__.py +9 -0
  2. mcp_dispatch_pg/__main__.py +3 -0
  3. mcp_dispatch_pg/alias.py +37 -0
  4. mcp_dispatch_pg/anchor.py +85 -0
  5. mcp_dispatch_pg/attention.py +17 -0
  6. mcp_dispatch_pg/blob.py +48 -0
  7. mcp_dispatch_pg/cli.py +90 -0
  8. mcp_dispatch_pg/derived.py +65 -0
  9. mcp_dispatch_pg/file.py +57 -0
  10. mcp_dispatch_pg/link.py +61 -0
  11. mcp_dispatch_pg/migrate.py +304 -0
  12. mcp_dispatch_pg/migrations/core/0001_tables.sql +289 -0
  13. mcp_dispatch_pg/migrations/core/0002_embedding_partition.sql +35 -0
  14. mcp_dispatch_pg/migrations/core/0003_work.sql +129 -0
  15. mcp_dispatch_pg/migrations/core/0004_record.sql +551 -0
  16. mcp_dispatch_pg/migrations/core/0005_blob.sql +56 -0
  17. mcp_dispatch_pg/migrations/core/0006_link_alias.sql +255 -0
  18. mcp_dispatch_pg/migrations/core/0007_tag.sql +177 -0
  19. mcp_dispatch_pg/migrations/core/0008_purge.sql +72 -0
  20. mcp_dispatch_pg/migrations/core/0009_derived.sql +129 -0
  21. mcp_dispatch_pg/migrations/core/0010_state_attention.sql +47 -0
  22. mcp_dispatch_pg/migrations/core/0011_position.sql +133 -0
  23. mcp_dispatch_pg/migrations/core/0012_anchor.sql +93 -0
  24. mcp_dispatch_pg/migrations/core/0013_file.sql +91 -0
  25. mcp_dispatch_pg/pool.py +159 -0
  26. mcp_dispatch_pg/position.py +27 -0
  27. mcp_dispatch_pg/py.typed +0 -0
  28. mcp_dispatch_pg/record.py +366 -0
  29. mcp_dispatch_pg/state.py +27 -0
  30. mcp_dispatch_pg/tag.py +69 -0
  31. mcp_dispatch_pg/work.py +116 -0
  32. mcp_dispatch_pg-0.1.0a1.dist-info/METADATA +706 -0
  33. mcp_dispatch_pg-0.1.0a1.dist-info/RECORD +36 -0
  34. mcp_dispatch_pg-0.1.0a1.dist-info/WHEEL +4 -0
  35. mcp_dispatch_pg-0.1.0a1.dist-info/entry_points.txt +2 -0
  36. mcp_dispatch_pg-0.1.0a1.dist-info/licenses/LICENSE +21 -0
@@ -0,0 +1,9 @@
1
+ """Postgres connections and independently numbered module migrations."""
2
+
3
+ from importlib.metadata import version
4
+
5
+ from .migrate import MigrationError, Module, Runner
6
+ from .pool import Call, Holder, Pool
7
+
8
+ __version__ = version("mcp-dispatch-pg")
9
+ __all__ = ["Call", "Holder", "MigrationError", "Module", "Pool", "Runner"]
@@ -0,0 +1,3 @@
1
+ from .cli import main
2
+
3
+ raise SystemExit(main())
@@ -0,0 +1,37 @@
1
+ """Alias writers and waiting-link resolution in the caller's transaction."""
2
+
3
+ from typing import Any
4
+
5
+ from psycopg import Connection
6
+
7
+ from .record import _call
8
+
9
+
10
+ def alias_put(
11
+ connection: Connection[Any],
12
+ *,
13
+ scheme: str,
14
+ value: str,
15
+ record: int,
16
+ actor: str,
17
+ move: bool = False,
18
+ ) -> bool:
19
+ """Register or explicitly move a name and resolve eligible waiting links."""
20
+ return bool(
21
+ _call(
22
+ connection,
23
+ "SELECT core.alias_put(%s, %s, %s, %s, %s)",
24
+ (scheme, value, record, actor, move),
25
+ )
26
+ )
27
+
28
+
29
+ def alias_remove(
30
+ connection: Connection[Any], *, scheme: str, value: str, actor: str
31
+ ) -> bool:
32
+ """Remove an alias with an event; resolved links keep their target."""
33
+ return bool(
34
+ _call(
35
+ connection, "SELECT core.alias_remove(%s, %s, %s)", (scheme, value, actor)
36
+ )
37
+ )
@@ -0,0 +1,85 @@
1
+ """Immutable anchor observations and mutable resolutions, without triggers."""
2
+
3
+ from collections.abc import Sequence
4
+ from typing import Any, cast
5
+
6
+ from psycopg import Connection
7
+
8
+ from .record import Data, _call, _json
9
+
10
+
11
+ def anchor_text(
12
+ connection: Connection[Any],
13
+ *,
14
+ record: int,
15
+ piece: int,
16
+ char_start: int,
17
+ char_end: int,
18
+ quote: str,
19
+ fingerprint: str,
20
+ note: str | None = None,
21
+ ) -> int:
22
+ """Insert a supplied text observation and its initial resolution."""
23
+ return int(
24
+ _call(
25
+ connection,
26
+ "SELECT core.anchor_text(%s, %s, %s, %s, %s, %s, %s)",
27
+ (record, piece, char_start, char_end, quote, fingerprint, note),
28
+ )
29
+ )
30
+
31
+
32
+ def anchor_code(
33
+ connection: Connection[Any],
34
+ *,
35
+ repo: str,
36
+ symbol_path: str,
37
+ line_start: int,
38
+ line_end: int,
39
+ quote: str,
40
+ fingerprint: str,
41
+ note: str | None = None,
42
+ ) -> int:
43
+ """Insert a supplied code observation and its initial resolution."""
44
+ return int(
45
+ _call(
46
+ connection,
47
+ "SELECT core.anchor_code(%s, %s, %s, %s, %s, %s, %s)",
48
+ (repo, symbol_path, line_start, line_end, quote, fingerprint, note),
49
+ )
50
+ )
51
+
52
+
53
+ def anchor_part(
54
+ connection: Connection[Any],
55
+ *,
56
+ record: int,
57
+ part_kind: str,
58
+ selector: str,
59
+ quote: str,
60
+ fingerprint: str,
61
+ note: str | None = None,
62
+ ) -> int:
63
+ """Insert a supplied structured observation and its initial resolution."""
64
+ return int(
65
+ _call(
66
+ connection,
67
+ "SELECT core.anchor_part(%s, %s, %s, %s, %s, %s)",
68
+ (record, part_kind, selector, quote, fingerprint, note),
69
+ )
70
+ )
71
+
72
+
73
+ def anchor_resolve(connection: Connection[Any], *, id: int, resolved: Data) -> bool:
74
+ """Stamp a resolution object with a state member, preserving the observation."""
75
+ return bool(
76
+ _call(connection, "SELECT core.anchor_resolve(%s, %s)", (id, _json(resolved)))
77
+ )
78
+
79
+
80
+ def anchor_remove(connection: Connection[Any], *, ids: Sequence[int]) -> list[int]:
81
+ """Remove existing anchors in first input order, deduplicating ids."""
82
+ return cast(
83
+ list[int],
84
+ _call(connection, "SELECT core.anchor_remove(%s::bigint[])", (list(ids),)),
85
+ )
@@ -0,0 +1,17 @@
1
+ """Batch attention stamps in the caller's transaction."""
2
+
3
+ from collections.abc import Sequence
4
+ from typing import Any, Literal
5
+
6
+ from psycopg import Connection
7
+
8
+ from .record import _call
9
+
10
+ type Attention = Literal["read", "seen", "dreamt", "watched", "recalled"]
11
+
12
+
13
+ def attend(
14
+ connection: Connection[Any], *, records: Sequence[int], what: Attention
15
+ ) -> None:
16
+ """Stamp each distinct record once; read also increments its read count."""
17
+ _call(connection, "SELECT core.attend(%s::bigint[], %s)", (list(records), what))
@@ -0,0 +1,48 @@
1
+ """Immutable blobs and collection in the caller's transaction."""
2
+
3
+ import builtins
4
+ from datetime import timedelta
5
+ from typing import Any, cast
6
+
7
+ from psycopg import Connection
8
+
9
+ from .record import _call
10
+
11
+
12
+ def blob_put(connection: Connection[Any], *, bytes: bytes, media: str | None) -> bytes:
13
+ """Store bytes once; an existing key keeps its media and storage source."""
14
+ return cast(
15
+ builtins.bytes,
16
+ _call(connection, "SELECT core.blob_put(%s, %s)", (bytes, media)),
17
+ )
18
+
19
+
20
+ def blob_put_path(
21
+ connection: Connection[Any],
22
+ *,
23
+ hash: bytes,
24
+ path: str,
25
+ size: int,
26
+ media: str,
27
+ ) -> bytes:
28
+ """Register a caller-hashed external file without reading it."""
29
+ return cast(
30
+ builtins.bytes,
31
+ _call(
32
+ connection,
33
+ "SELECT core.blob_put_path(%s, %s, %s, %s)",
34
+ (hash, path, size, media),
35
+ ),
36
+ )
37
+
38
+
39
+ def blob_sweep(
40
+ connection: Connection[Any], *, older_than: timedelta, n: int = 1000
41
+ ) -> list[tuple[bytes, str | None]]:
42
+ """Remove old unreferenced blobs; delete returned files only after commit."""
43
+ return cast(
44
+ list[tuple[bytes, str | None]],
45
+ connection.execute(
46
+ "SELECT hash, path FROM core.blob_sweep(%s, %s)", (older_than, n)
47
+ ).fetchall(),
48
+ )
mcp_dispatch_pg/cli.py ADDED
@@ -0,0 +1,90 @@
1
+ """The address is read only from the selected environment variable."""
2
+
3
+ import argparse
4
+ import os
5
+ import re
6
+ import sys
7
+ from collections.abc import Sequence
8
+ from pathlib import Path
9
+
10
+ import psycopg
11
+
12
+ from .migrate import MigrationError, Module, Runner
13
+
14
+
15
+ def main(argv: Sequence[str] | None = None) -> int:
16
+ parser = argparse.ArgumentParser(prog="mcp-dispatch-pg")
17
+ parser.add_argument("command", choices=("migrate", "status"))
18
+ parser.add_argument("--url-env", default="MCP_DISPATCH_PG_URL", metavar="NAME")
19
+ parser.add_argument(
20
+ "--module",
21
+ action="append",
22
+ default=[],
23
+ metavar="NAME=DIRECTORY",
24
+ help="register external SQL; repeat for each module",
25
+ )
26
+ parser.add_argument(
27
+ "--requires",
28
+ action="append",
29
+ default=[],
30
+ metavar="NAME=DEPENDENCY,DEPENDENCY",
31
+ help="set prerequisites for an external module (default: core)",
32
+ )
33
+ args = parser.parse_args(argv)
34
+ if not re.fullmatch(r"[A-Za-z_][A-Za-z0-9_]*", args.url_env):
35
+ parser.error(
36
+ "--url-env takes an environment variable name; set its value outside the command"
37
+ )
38
+ address = os.environ.get(args.url_env)
39
+ if not address:
40
+ print(
41
+ f"Set {args.url_env} to the database address, then retry.", file=sys.stderr
42
+ )
43
+ return 1
44
+ try:
45
+ dependencies: dict[str, tuple[str, ...]] = {}
46
+ for value in args.requires:
47
+ name, separator, required = value.partition("=")
48
+ if not separator or not required:
49
+ raise MigrationError("Use --requires NAME=DEPENDENCY,DEPENDENCY.")
50
+ if name in dependencies:
51
+ raise MigrationError("Set --requires once per module.")
52
+ dependencies[name] = tuple(required.split(","))
53
+ modules = []
54
+ for value in args.module:
55
+ name, separator, directory = value.partition("=")
56
+ if not separator or not directory:
57
+ raise MigrationError(
58
+ "Use --module NAME=DIRECTORY with numbered SQL files."
59
+ )
60
+ modules.append(
61
+ Module(name, Path(directory), dependencies.pop(name, ("core",)))
62
+ )
63
+ if dependencies:
64
+ raise MigrationError(
65
+ "Register each --requires module with --module NAME=DIRECTORY."
66
+ )
67
+ runner = Runner(modules)
68
+ if args.command == "migrate":
69
+ for migration in runner.migrate(address):
70
+ print(
71
+ f"applied {migration.module}/{migration.version:04d}_{migration.name}"
72
+ )
73
+ print("Migrations are current.")
74
+ else:
75
+ for status in runner.status(address):
76
+ m = status.migration
77
+ print(
78
+ f"{'applied' if status.applied else 'pending'} {m.module}/{m.version:04d}_{m.name}"
79
+ )
80
+ except MigrationError as error:
81
+ print(str(error), file=sys.stderr)
82
+ return 1
83
+ except (psycopg.Error, OSError, UnicodeError):
84
+ # Driver and filesystem errors can contain credentials or private addresses.
85
+ print(
86
+ "Cannot inspect or migrate the database; check the selected environment variable, server access, SQL directory, and database privileges, then retry.",
87
+ file=sys.stderr,
88
+ )
89
+ return 1
90
+ return 0
@@ -0,0 +1,65 @@
1
+ """Hash-guarded derived rows in the caller's transaction."""
2
+
3
+ from collections.abc import Sequence
4
+ from decimal import Decimal
5
+ from typing import Any
6
+
7
+ from psycopg import Connection
8
+
9
+ from .record import _call
10
+
11
+
12
+ def summary_put(
13
+ connection: Connection[Any],
14
+ *,
15
+ record: int,
16
+ kind: str,
17
+ text: str,
18
+ of_hash: bytes,
19
+ actor: str,
20
+ ) -> bool:
21
+ """Upsert a summary only while its source is live and still has of_hash."""
22
+ return bool(
23
+ _call(
24
+ connection,
25
+ "SELECT core.summary_put(%s, %s, %s, %s, %s)",
26
+ (record, kind, text, of_hash, actor),
27
+ )
28
+ )
29
+
30
+
31
+ def keyword_put(
32
+ connection: Connection[Any],
33
+ *,
34
+ record: int,
35
+ terms: Sequence[str],
36
+ numbers: Sequence[Decimal | int | float],
37
+ of_hash: bytes,
38
+ ) -> bool:
39
+ """Upsert keyword terms and numbers only for the current source hash."""
40
+ return bool(
41
+ _call(
42
+ connection,
43
+ "SELECT core.keyword_put(%s, %s::text[], %s::numeric[], %s)",
44
+ (record, list(terms), list(numbers), of_hash),
45
+ )
46
+ )
47
+
48
+
49
+ def embedding_put(
50
+ connection: Connection[Any],
51
+ *,
52
+ record: int,
53
+ embedder: str,
54
+ part: str,
55
+ vector: Sequence[float],
56
+ of_hash: bytes,
57
+ ) -> bool:
58
+ """Write a vector with the containing thing's canonical type and root."""
59
+ return bool(
60
+ _call(
61
+ connection,
62
+ "SELECT core.embedding_put(%s, %s, %s, %s::public.vector, %s)",
63
+ (record, embedder, part, "[" + ",".join(map(str, vector)) + "]", of_hash),
64
+ )
65
+ )
@@ -0,0 +1,57 @@
1
+ """Named blob states in the caller's transaction; no transaction or retry policy."""
2
+
3
+ from datetime import datetime
4
+ from typing import Any, cast
5
+
6
+ from psycopg import Connection
7
+
8
+ from .record import _call
9
+
10
+
11
+ def file_set(
12
+ connection: Connection[Any],
13
+ *,
14
+ name: str,
15
+ actor: str,
16
+ blob: bytes | None,
17
+ expect: bytes | None = None,
18
+ unchecked: bool = False,
19
+ root: int | None = None,
20
+ type: str = "file",
21
+ ) -> int:
22
+ """Set or remove a name; compare its present blob unless unchecked is true."""
23
+ return int(
24
+ _call(
25
+ connection,
26
+ "SELECT core.file_set(%s, %s, %s, %s, %s, %s, %s)",
27
+ (name, actor, blob, expect, unchecked, root, type),
28
+ conflict_name=name,
29
+ )
30
+ )
31
+
32
+
33
+ def file_id(connection: Connection[Any], *, name: str) -> int | None:
34
+ """Return the record for a name, including removed and retired files."""
35
+ return cast(int | None, _call(connection, "SELECT core.file_id(%s)", (name,)))
36
+
37
+
38
+ def file_versions(
39
+ connection: Connection[Any], *, name: str
40
+ ) -> list[tuple[bytes | None, datetime, str]]:
41
+ """Return every state, including removals, newest first with time and actor."""
42
+ return cast(
43
+ list[tuple[bytes | None, datetime, str]],
44
+ connection.execute(
45
+ "SELECT blob, at, by FROM core.file_versions(%s)", (name,)
46
+ ).fetchall(),
47
+ )
48
+
49
+
50
+ def file_names(connection: Connection[Any], *, prefix: str = "") -> list[str]:
51
+ """List names with content under a literal prefix, ordered by bytes."""
52
+ return [
53
+ name
54
+ for (name,) in connection.execute(
55
+ "SELECT core.file_names(%s)", (prefix,)
56
+ ).fetchall()
57
+ ]
@@ -0,0 +1,61 @@
1
+ """Link writers in the caller's transaction."""
2
+
3
+ from collections.abc import Sequence
4
+ from typing import Any, cast
5
+
6
+ from psycopg import Connection
7
+
8
+ from .record import Data, _call, _json
9
+
10
+
11
+ def link_put(
12
+ connection: Connection[Any],
13
+ *,
14
+ src: int,
15
+ type: str,
16
+ actor: str,
17
+ dst: int | None = None,
18
+ dst_name: str | None = None,
19
+ note: Data = None,
20
+ pin: bool = False,
21
+ ) -> int:
22
+ """Normalize and insert a link, or return its existing id."""
23
+ return int(
24
+ _call(
25
+ connection,
26
+ "SELECT core.link_put(%s, %s, %s, %s, %s, %s, %s)",
27
+ (src, type, actor, dst, dst_name, _json(note), pin),
28
+ )
29
+ )
30
+
31
+
32
+ def link_note(
33
+ connection: Connection[Any],
34
+ *,
35
+ id: int,
36
+ actor: str,
37
+ note: Data = None,
38
+ merge: Data = None,
39
+ ) -> bool:
40
+ """Replace or shallow-merge a link note; report whether it changed."""
41
+ return bool(
42
+ _call(
43
+ connection,
44
+ "SELECT core.link_note(%s, %s, %s, %s)",
45
+ (id, actor, _json(note), _json(merge)),
46
+ )
47
+ )
48
+
49
+
50
+ def link_remove(
51
+ connection: Connection[Any], *, ids: Sequence[int], actor: str, note: Data = None
52
+ ) -> list[int]:
53
+ """Remove existing links and always record their endpoints and authorship."""
54
+ return cast(
55
+ list[int],
56
+ _call(
57
+ connection,
58
+ "SELECT core.link_remove(%s::bigint[], %s, %s)",
59
+ (list(ids), actor, _json(note)),
60
+ ),
61
+ )