django-admin-api-mcp 0.1.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.
Files changed (73) hide show
  1. admin_api_mcp/__init__.py +9 -0
  2. admin_api_mcp/actions.py +197 -0
  3. admin_api_mcp/admin.py +131 -0
  4. admin_api_mcp/apps.py +10 -0
  5. admin_api_mcp/auth.py +62 -0
  6. admin_api_mcp/changelist.py +261 -0
  7. admin_api_mcp/checks.py +35 -0
  8. admin_api_mcp/confirm.py +97 -0
  9. admin_api_mcp/contrib/__init__.py +1 -0
  10. admin_api_mcp/contrib/search/__init__.py +0 -0
  11. admin_api_mcp/contrib/search/apps.py +21 -0
  12. admin_api_mcp/contrib/search/backend.py +121 -0
  13. admin_api_mcp/contrib/search/checks.py +12 -0
  14. admin_api_mcp/contrib/search/conf.py +42 -0
  15. admin_api_mcp/contrib/search/engines/__init__.py +0 -0
  16. admin_api_mcp/contrib/search/engines/base.py +99 -0
  17. admin_api_mcp/contrib/search/engines/db.py +265 -0
  18. admin_api_mcp/contrib/search/fold.py +41 -0
  19. admin_api_mcp/contrib/search/indexer.py +364 -0
  20. admin_api_mcp/contrib/search/management/__init__.py +0 -0
  21. admin_api_mcp/contrib/search/management/commands/__init__.py +0 -0
  22. admin_api_mcp/contrib/search/management/commands/rebuild_search_index.py +29 -0
  23. admin_api_mcp/contrib/search/management/commands/search_index.py +25 -0
  24. admin_api_mcp/contrib/search/migrations/0001_initial.py +83 -0
  25. admin_api_mcp/contrib/search/migrations/__init__.py +0 -0
  26. admin_api_mcp/contrib/search/models.py +43 -0
  27. admin_api_mcp/contrib/subadmin.py +37 -0
  28. admin_api_mcp/custom_views.py +471 -0
  29. admin_api_mcp/decorators.py +26 -0
  30. admin_api_mcp/deletion.py +58 -0
  31. admin_api_mcp/detail.py +115 -0
  32. admin_api_mcp/encoders.py +72 -0
  33. admin_api_mcp/errors.py +82 -0
  34. admin_api_mcp/jsonschema.py +225 -0
  35. admin_api_mcp/management/__init__.py +0 -0
  36. admin_api_mcp/management/commands/__init__.py +0 -0
  37. admin_api_mcp/management/commands/create_api_token.py +40 -0
  38. admin_api_mcp/management/commands/mcp_serve.py +86 -0
  39. admin_api_mcp/management/commands/migrate_from_admin_api.py +153 -0
  40. admin_api_mcp/mcp/__init__.py +7 -0
  41. admin_api_mcp/mcp/bridge.py +71 -0
  42. admin_api_mcp/mcp/handlers.py +771 -0
  43. admin_api_mcp/mcp/resolve.py +410 -0
  44. admin_api_mcp/mcp/server.py +76 -0
  45. admin_api_mcp/mcp/sites.py +284 -0
  46. admin_api_mcp/mcp/stdio.py +53 -0
  47. admin_api_mcp/mcp/tools.py +84 -0
  48. admin_api_mcp/mcp/views.py +74 -0
  49. admin_api_mcp/middleware.py +18 -0
  50. admin_api_mcp/migrations/0001_initial.py +40 -0
  51. admin_api_mcp/migrations/0002_mcp_confirmation.py +27 -0
  52. admin_api_mcp/migrations/0003_mcp_user_instructions.py +28 -0
  53. admin_api_mcp/migrations/__init__.py +0 -0
  54. admin_api_mcp/mixins.py +173 -0
  55. admin_api_mcp/models.py +145 -0
  56. admin_api_mcp/nested.py +122 -0
  57. admin_api_mcp/resolver.py +95 -0
  58. admin_api_mcp/scopes.py +142 -0
  59. admin_api_mcp/sensitive.py +67 -0
  60. admin_api_mcp/services.py +652 -0
  61. admin_api_mcp/sites.py +242 -0
  62. admin_api_mcp/templates/admin_api_mcp/token_created.html +17 -0
  63. admin_api_mcp/views/__init__.py +0 -0
  64. admin_api_mcp/views/changelist.py +70 -0
  65. admin_api_mcp/views/custom.py +33 -0
  66. admin_api_mcp/views/detail.py +50 -0
  67. admin_api_mcp/views/nested.py +73 -0
  68. admin_api_mcp/views/registry.py +15 -0
  69. admin_api_mcp/writes.py +530 -0
  70. django_admin_api_mcp-0.1.0.dist-info/METADATA +280 -0
  71. django_admin_api_mcp-0.1.0.dist-info/RECORD +73 -0
  72. django_admin_api_mcp-0.1.0.dist-info/WHEEL +4 -0
  73. django_admin_api_mcp-0.1.0.dist-info/licenses/LICENSE +21 -0
@@ -0,0 +1,29 @@
1
+ from django.core.management.base import BaseCommand, CommandError
2
+
3
+ from ...indexer import get_indexer
4
+
5
+
6
+ class Command(BaseCommand):
7
+ help = "Rebuild the search index rows: object rows in batches (then prune), and the model label rows."
8
+
9
+ def add_arguments(self, parser):
10
+ parser.add_argument("--model", action="append", dest="models", metavar="APP.MODEL", help="Only this model.")
11
+ parser.add_argument("--models-only", action="store_true", help="Only the model label rows.")
12
+ parser.add_argument("--batch-size", type=int, default=1000, help="Objects per transaction (default 1000).")
13
+
14
+ def handle(self, *args, models=None, models_only=False, batch_size=1000, **options):
15
+ if batch_size < 1:
16
+ raise CommandError("--batch-size must be at least 1.")
17
+ indexer = get_indexer()
18
+ labels = None
19
+ if models:
20
+ labels = {label.lower() for label in models}
21
+ known = {m._meta.label_lower for m in indexer.admins}
22
+ unknown = sorted(labels - known)
23
+ if unknown:
24
+ raise CommandError(f"Not indexed: {', '.join(unknown)}. Indexed: {', '.join(sorted(known)) or 'none'}.")
25
+ rows = indexer.refresh_model_rows()
26
+ self.stdout.write(f"model rows: {rows}")
27
+ if not models_only:
28
+ rebuilt = indexer.rebuild(labels, batch_size=batch_size, stdout=self.stdout)
29
+ self.stdout.write(f"rebuilt: {', '.join(rebuilt) or 'nothing'}")
@@ -0,0 +1,25 @@
1
+ from django.core.management.base import BaseCommand, CommandError
2
+
3
+ from ...conf import get_engine
4
+ from ...indexer import get_indexer
5
+
6
+
7
+ class Command(BaseCommand):
8
+ help = (
9
+ "search_index ensure: refresh the model label rows and rebuild the models whose indexed fields, "
10
+ "languages or engine changed since the last run. Idempotent; run it after migrate on every deploy."
11
+ )
12
+
13
+ def add_arguments(self, parser):
14
+ sub = parser.add_subparsers(dest="action", required=True)
15
+ ensure = sub.add_parser("ensure", help="Refresh label rows; rebuild changed models.")
16
+ ensure.add_argument("--batch-size", type=int, default=1000, help="Objects per transaction (default 1000).")
17
+
18
+ def handle(self, *args, action=None, batch_size=1000, **options):
19
+ problems = get_engine().check()
20
+ if problems:
21
+ raise CommandError(" ".join(f"{p.msg} {p.hint}" for p in problems))
22
+ indexer = get_indexer()
23
+ self.stdout.write(f"model rows: {indexer.refresh_model_rows()}")
24
+ rebuilt = indexer.rebuild(batch_size=batch_size, force=False, stdout=self.stdout)
25
+ self.stdout.write(f"rebuilt: {', '.join(rebuilt) or 'nothing'}")
@@ -0,0 +1,83 @@
1
+ import logging
2
+
3
+ import django.db.models.deletion
4
+ from django.db import DatabaseError, migrations, models, transaction
5
+
6
+ logger = logging.getLogger("admin_api_mcp.search")
7
+ GIN_INDEX = "admin_api_mcp_search_entry_norm_trgm"
8
+
9
+
10
+ def create_trigram_index(apps, schema_editor):
11
+ """Postgres only: pg_trgm and a GIN index on norm. Skipped with a warning when the role may not
12
+ create the extension; search then runs without the index and without the trigram pass."""
13
+ if schema_editor.connection.vendor != "postgresql":
14
+ return
15
+ try:
16
+ with transaction.atomic(using=schema_editor.connection.alias):
17
+ schema_editor.execute("CREATE EXTENSION IF NOT EXISTS pg_trgm")
18
+ except DatabaseError as exc:
19
+ logger.warning("admin_api_mcp_search: could not create pg_trgm (%s); no trigram index", exc)
20
+ return
21
+ schema_editor.execute(
22
+ f"CREATE INDEX IF NOT EXISTS {GIN_INDEX} ON admin_api_mcp_search_entry USING gin (norm gin_trgm_ops)"
23
+ )
24
+
25
+
26
+ def drop_trigram_index(apps, schema_editor):
27
+ if schema_editor.connection.vendor == "postgresql":
28
+ schema_editor.execute(f"DROP INDEX IF EXISTS {GIN_INDEX}")
29
+
30
+
31
+ class Migration(migrations.Migration):
32
+
33
+ initial = True
34
+
35
+ dependencies = [
36
+ ("contenttypes", "0002_remove_content_type_name"),
37
+ ]
38
+
39
+ operations = [
40
+ migrations.CreateModel(
41
+ name="SearchEntry",
42
+ fields=[
43
+ ("id", models.BigAutoField(primary_key=True, serialize=False)),
44
+ ("kind", models.CharField(max_length=8)),
45
+ ("object_pk", models.CharField(blank=True, max_length=255, null=True)),
46
+ ("field", models.CharField(max_length=100)),
47
+ ("language", models.CharField(blank=True, default="", max_length=15)),
48
+ ("text", models.TextField()),
49
+ ("norm", models.TextField()),
50
+ ("updated_at", models.DateTimeField()),
51
+ ("indexed_at", models.DateTimeField()),
52
+ (
53
+ "content_type",
54
+ models.ForeignKey(
55
+ on_delete=django.db.models.deletion.CASCADE,
56
+ related_name="+",
57
+ to="contenttypes.contenttype",
58
+ ),
59
+ ),
60
+ ],
61
+ options={
62
+ "verbose_name_plural": "search entries",
63
+ "db_table": "admin_api_mcp_search_entry",
64
+ "constraints": [
65
+ models.UniqueConstraint(
66
+ fields=("content_type", "object_pk", "field", "language"),
67
+ name="admin_api_mcp_search_entry_unique",
68
+ )
69
+ ],
70
+ },
71
+ ),
72
+ migrations.CreateModel(
73
+ name="SearchIndexState",
74
+ fields=[
75
+ ("label", models.CharField(max_length=100, primary_key=True, serialize=False)),
76
+ ("fingerprint", models.CharField(max_length=64)),
77
+ ],
78
+ options={
79
+ "db_table": "admin_api_mcp_search_state",
80
+ },
81
+ ),
82
+ migrations.RunPython(create_trigram_index, drop_trigram_index),
83
+ ]
File without changes
@@ -0,0 +1,43 @@
1
+ from django.contrib.contenttypes.models import ContentType
2
+ from django.db import models
3
+
4
+
5
+ class SearchEntry(models.Model):
6
+ """A row of the ``db`` engine: one object search field, or one model label in one language.
7
+ ``updated_at`` moves when ``norm`` changes, ``indexed_at`` on every write (prune uses it)."""
8
+
9
+ id = models.BigAutoField(primary_key=True)
10
+ kind = models.CharField(max_length=8)
11
+ content_type = models.ForeignKey(ContentType, on_delete=models.CASCADE, related_name="+")
12
+ object_pk = models.CharField(max_length=255, null=True, blank=True)
13
+ field = models.CharField(max_length=100)
14
+ language = models.CharField(max_length=15, blank=True, default="")
15
+ text = models.TextField()
16
+ norm = models.TextField()
17
+ updated_at = models.DateTimeField()
18
+ indexed_at = models.DateTimeField()
19
+
20
+ class Meta:
21
+ db_table = "admin_api_mcp_search_entry"
22
+ verbose_name_plural = "search entries"
23
+ constraints = [
24
+ models.UniqueConstraint(
25
+ fields=["content_type", "object_pk", "field", "language"], name="admin_api_mcp_search_entry_unique"
26
+ )
27
+ ]
28
+
29
+ def __str__(self):
30
+ return self.text
31
+
32
+
33
+ class SearchIndexState(models.Model):
34
+ """The fingerprint ``search_index ensure`` compares per indexed model."""
35
+
36
+ label = models.CharField(max_length=100, primary_key=True)
37
+ fingerprint = models.CharField(max_length=64)
38
+
39
+ class Meta:
40
+ db_table = "admin_api_mcp_search_state"
41
+
42
+ def __str__(self):
43
+ return self.label
@@ -0,0 +1,37 @@
1
+ """django-subadmin support (https://github.com/inueni/django-subadmin).
2
+
3
+ A ``SubAdmin`` is not registered on the admin site: it hangs off a registered
4
+ ``RootSubAdmin`` (``subadmins = [...]``), at any depth, and every one of its views needs
5
+ ``request.subadmin`` (a ``SubAdminHelper`` that loads and checks the ancestors). This adapter
6
+ discovers the subadmins and builds that helper before admin_api_mcp calls a nested admin.
7
+
8
+ Duck-typed: nothing here imports ``subadmin``, so admin_api_mcp does not depend on it.
9
+ """
10
+
11
+ from __future__ import annotations
12
+
13
+ from django.core.exceptions import PermissionDenied
14
+ from django.http import Http404
15
+
16
+ from ..errors import NotFound, PermissionDeniedError
17
+ from ..nested import NestedAdapter
18
+
19
+
20
+ class SubAdminAdapter(NestedAdapter):
21
+ def get_children(self, model_admin) -> list:
22
+ children = getattr(model_admin, "subadmin_instances", None) or []
23
+ return [child for child in children if self.is_child(child)]
24
+
25
+ def is_child(self, model_admin) -> bool:
26
+ return hasattr(model_admin, "get_subadmin_helper") and hasattr(model_admin, "parent_admin")
27
+
28
+ def init_args(self, child) -> tuple:
29
+ return (child.parent_model, child.parent_admin)
30
+
31
+ def prepare_request(self, model_admin, request, parents: list) -> None:
32
+ try:
33
+ request.subadmin = model_admin.get_subadmin_helper(request, [str(pk) for pk in parents])
34
+ except Http404 as exc:
35
+ raise NotFound(f"Parent objects {list(parents)!r} not found (or not related to each other).") from exc
36
+ except PermissionDenied as exc:
37
+ raise PermissionDeniedError("No permission on a parent object.") from exc