django-mcpz 1.0.0__tar.gz

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 (45) hide show
  1. django_mcpz-1.0.0/LICENSE +21 -0
  2. django_mcpz-1.0.0/PKG-INFO +110 -0
  3. django_mcpz-1.0.0/README.rst +74 -0
  4. django_mcpz-1.0.0/pyproject.toml +152 -0
  5. django_mcpz-1.0.0/pyproject.toml.orig +161 -0
  6. django_mcpz-1.0.0/src/django_mcpz/__init__.py +0 -0
  7. django_mcpz-1.0.0/src/django_mcpz/bearer_tokens/__init__.py +0 -0
  8. django_mcpz-1.0.0/src/django_mcpz/bearer_tokens/admin.py +61 -0
  9. django_mcpz-1.0.0/src/django_mcpz/bearer_tokens/apps.py +10 -0
  10. django_mcpz-1.0.0/src/django_mcpz/bearer_tokens/auth.py +48 -0
  11. django_mcpz-1.0.0/src/django_mcpz/bearer_tokens/cleanup.py +17 -0
  12. django_mcpz-1.0.0/src/django_mcpz/bearer_tokens/migrations/0001_initial.py +62 -0
  13. django_mcpz-1.0.0/src/django_mcpz/bearer_tokens/migrations/__init__.py +0 -0
  14. django_mcpz-1.0.0/src/django_mcpz/bearer_tokens/models.py +88 -0
  15. django_mcpz-1.0.0/src/django_mcpz/bearer_tokens/tasks.py +22 -0
  16. django_mcpz-1.0.0/src/django_mcpz/headers.py +49 -0
  17. django_mcpz-1.0.0/src/django_mcpz/jsonrpc.py +98 -0
  18. django_mcpz-1.0.0/src/django_mcpz/legacy.py +68 -0
  19. django_mcpz-1.0.0/src/django_mcpz/management/__init__.py +0 -0
  20. django_mcpz-1.0.0/src/django_mcpz/management/commands/__init__.py +0 -0
  21. django_mcpz-1.0.0/src/django_mcpz/management/commands/mcpz.py +110 -0
  22. django_mcpz-1.0.0/src/django_mcpz/oauth/__init__.py +0 -0
  23. django_mcpz-1.0.0/src/django_mcpz/oauth/admin.py +78 -0
  24. django_mcpz-1.0.0/src/django_mcpz/oauth/apps.py +10 -0
  25. django_mcpz-1.0.0/src/django_mcpz/oauth/auth.py +52 -0
  26. django_mcpz-1.0.0/src/django_mcpz/oauth/cimd.py +241 -0
  27. django_mcpz-1.0.0/src/django_mcpz/oauth/cleanup.py +58 -0
  28. django_mcpz-1.0.0/src/django_mcpz/oauth/conf.py +60 -0
  29. django_mcpz-1.0.0/src/django_mcpz/oauth/csp.py +41 -0
  30. django_mcpz-1.0.0/src/django_mcpz/oauth/discovery.py +80 -0
  31. django_mcpz-1.0.0/src/django_mcpz/oauth/migrations/0001_initial.py +236 -0
  32. django_mcpz-1.0.0/src/django_mcpz/oauth/migrations/__init__.py +0 -0
  33. django_mcpz-1.0.0/src/django_mcpz/oauth/models.py +190 -0
  34. django_mcpz-1.0.0/src/django_mcpz/oauth/static/django_mcpz/oauth/base.css +13 -0
  35. django_mcpz-1.0.0/src/django_mcpz/oauth/tasks.py +22 -0
  36. django_mcpz-1.0.0/src/django_mcpz/oauth/templates/django_mcpz/oauth/authorize.html +36 -0
  37. django_mcpz-1.0.0/src/django_mcpz/oauth/templates/django_mcpz/oauth/base.html +16 -0
  38. django_mcpz-1.0.0/src/django_mcpz/oauth/templates/django_mcpz/oauth/error.html +7 -0
  39. django_mcpz-1.0.0/src/django_mcpz/oauth/urls.py +23 -0
  40. django_mcpz-1.0.0/src/django_mcpz/oauth/views.py +570 -0
  41. django_mcpz-1.0.0/src/django_mcpz/oauth/wellknown.py +45 -0
  42. django_mcpz-1.0.0/src/django_mcpz/py.typed +0 -0
  43. django_mcpz-1.0.0/src/django_mcpz/schemas.py +106 -0
  44. django_mcpz-1.0.0/src/django_mcpz/server.py +840 -0
  45. django_mcpz-1.0.0/src/django_mcpz/tokens.py +21 -0
@@ -0,0 +1,21 @@
1
+ MIT License
2
+
3
+ Copyright (c) 2026 Adam Johnson
4
+
5
+ Permission is hereby granted, free of charge, to any person obtaining a copy
6
+ of this software and associated documentation files (the "Software"), to deal
7
+ in the Software without restriction, including without limitation the rights
8
+ to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
9
+ copies of the Software, and to permit persons to whom the Software is
10
+ furnished to do so, subject to the following conditions:
11
+
12
+ The above copyright notice and this permission notice shall be included in all
13
+ copies or substantial portions of the Software.
14
+
15
+ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
16
+ IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
17
+ FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
18
+ AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
19
+ LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
20
+ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
21
+ SOFTWARE.
@@ -0,0 +1,110 @@
1
+ Metadata-Version: 2.4
2
+ Name: django-mcpz
3
+ Version: 1.0.0
4
+ Summary: Easy peasy MCP servers in Django.
5
+ Keywords: Django,MCP,Model Context Protocol
6
+ Author: Adam Johnson
7
+ Author-email: Adam Johnson <me@adamj.eu>
8
+ License-Expression: MIT
9
+ License-File: LICENSE
10
+ Classifier: Development Status :: 4 - Beta
11
+ Classifier: Framework :: Django :: 5.2
12
+ Classifier: Framework :: Django :: 6.0
13
+ Classifier: Framework :: Django :: 6.1
14
+ Classifier: Intended Audience :: Developers
15
+ Classifier: Natural Language :: English
16
+ Classifier: Operating System :: OS Independent
17
+ Classifier: Programming Language :: Python :: 3 :: Only
18
+ Classifier: Programming Language :: Python :: 3.10
19
+ Classifier: Programming Language :: Python :: 3.11
20
+ Classifier: Programming Language :: Python :: 3.12
21
+ Classifier: Programming Language :: Python :: 3.13
22
+ Classifier: Programming Language :: Python :: 3.14
23
+ Classifier: Programming Language :: Python :: 3.15
24
+ Classifier: Programming Language :: Python :: Implementation :: CPython
25
+ Classifier: Typing :: Typed
26
+ Requires-Dist: asgiref>=3.6
27
+ Requires-Dist: django>=5.2
28
+ Requires-Dist: django-msgspec>=1
29
+ Requires-Dist: msgspec>=0.20
30
+ Requires-Python: >=3.10
31
+ Project-URL: Changelog, https://django-mcpz.readthedocs.io/en/latest/changelog.html
32
+ Project-URL: Documentation, https://django-mcpz.readthedocs.io/
33
+ Project-URL: Funding, https://adamj.eu/books/
34
+ Project-URL: Repository, https://github.com/adamchainz/django-mcpz
35
+ Description-Content-Type: text/x-rst
36
+
37
+ ===========
38
+ django-mcpz
39
+ ===========
40
+
41
+ .. image:: https://img.shields.io/readthedocs/django-mcpz?style=for-the-badge
42
+ :target: https://django-mcpz.readthedocs.io/en/latest/
43
+
44
+ .. image:: https://img.shields.io/github/actions/workflow/status/adamchainz/django-mcpz/main.yml.svg?branch=main&style=for-the-badge
45
+ :target: https://github.com/adamchainz/django-mcpz/actions?workflow=CI
46
+
47
+ .. image:: https://img.shields.io/badge/Coverage-100%25-success?style=for-the-badge
48
+ :target: https://github.com/adamchainz/django-mcpz/actions?workflow=CI
49
+
50
+ .. image:: https://img.shields.io/pypi/v/django-mcpz.svg?style=for-the-badge
51
+ :target: https://pypi.org/project/django-mcpz/
52
+
53
+ .. image:: https://img.shields.io/badge/code%20style-black-000000.svg?style=for-the-badge
54
+ :target: https://github.com/psf/black
55
+
56
+ .. image:: https://img.shields.io/badge/pre--commit-enabled-brightgreen?logo=pre-commit&logoColor=white&style=for-the-badge
57
+ :target: https://github.com/pre-commit/pre-commit
58
+ :alt: pre-commit
59
+
60
+ ----
61
+
62
+ *Easy peasy MCP servers in Django.*
63
+
64
+ django-mcpz lets you build a Model Context Protocol (MCP) server in your Django project.
65
+ Create an MCP server object with metadata, give it a URL, and attach Python functions to it as tools.
66
+ The MCP server acts like a regular synchronous Django view, handling the intricacies of the MCP protocol.
67
+ django-mcpz leans on `msgspec <https://msgspec.dev/>`__ for defining schemas and fast JSON serialization and deserialization.
68
+
69
+ A quick example:
70
+
71
+ .. code-block:: python
72
+
73
+ from typing import Literal
74
+
75
+ import msgspec
76
+
77
+ from django_mcpz.server import MCPServer
78
+ from django_mcpz.bearer_tokens.auth import token_auth
79
+ from example.models import Order
80
+
81
+ server = MCPServer(
82
+ name="shop",
83
+ version="1.0.0",
84
+ instructions="Query the shop’s order database.",
85
+ auth=token_auth,
86
+ )
87
+
88
+
89
+ class CountOrdersParams(msgspec.Struct):
90
+ status: Literal["pending", "shipped", "cancelled"] | None = None
91
+
92
+
93
+ class CountOrdersResult(msgspec.Struct):
94
+ count: int
95
+
96
+
97
+ @server.tool(
98
+ description="Count Order rows, optionally filtered by status.",
99
+ read_only=True,
100
+ )
101
+ def count_orders(request, params: CountOrdersParams) -> CountOrdersResult:
102
+ qs = Order.objects.all()
103
+ if params.status is not None:
104
+ qs = qs.filter(status=params.status)
105
+ return CountOrdersResult(count=qs.count())
106
+
107
+ Documentation
108
+ -------------
109
+
110
+ Please see https://django-mcpz.readthedocs.io/.
@@ -0,0 +1,74 @@
1
+ ===========
2
+ django-mcpz
3
+ ===========
4
+
5
+ .. image:: https://img.shields.io/readthedocs/django-mcpz?style=for-the-badge
6
+ :target: https://django-mcpz.readthedocs.io/en/latest/
7
+
8
+ .. image:: https://img.shields.io/github/actions/workflow/status/adamchainz/django-mcpz/main.yml.svg?branch=main&style=for-the-badge
9
+ :target: https://github.com/adamchainz/django-mcpz/actions?workflow=CI
10
+
11
+ .. image:: https://img.shields.io/badge/Coverage-100%25-success?style=for-the-badge
12
+ :target: https://github.com/adamchainz/django-mcpz/actions?workflow=CI
13
+
14
+ .. image:: https://img.shields.io/pypi/v/django-mcpz.svg?style=for-the-badge
15
+ :target: https://pypi.org/project/django-mcpz/
16
+
17
+ .. image:: https://img.shields.io/badge/code%20style-black-000000.svg?style=for-the-badge
18
+ :target: https://github.com/psf/black
19
+
20
+ .. image:: https://img.shields.io/badge/pre--commit-enabled-brightgreen?logo=pre-commit&logoColor=white&style=for-the-badge
21
+ :target: https://github.com/pre-commit/pre-commit
22
+ :alt: pre-commit
23
+
24
+ ----
25
+
26
+ *Easy peasy MCP servers in Django.*
27
+
28
+ django-mcpz lets you build a Model Context Protocol (MCP) server in your Django project.
29
+ Create an MCP server object with metadata, give it a URL, and attach Python functions to it as tools.
30
+ The MCP server acts like a regular synchronous Django view, handling the intricacies of the MCP protocol.
31
+ django-mcpz leans on `msgspec <https://msgspec.dev/>`__ for defining schemas and fast JSON serialization and deserialization.
32
+
33
+ A quick example:
34
+
35
+ .. code-block:: python
36
+
37
+ from typing import Literal
38
+
39
+ import msgspec
40
+
41
+ from django_mcpz.server import MCPServer
42
+ from django_mcpz.bearer_tokens.auth import token_auth
43
+ from example.models import Order
44
+
45
+ server = MCPServer(
46
+ name="shop",
47
+ version="1.0.0",
48
+ instructions="Query the shop’s order database.",
49
+ auth=token_auth,
50
+ )
51
+
52
+
53
+ class CountOrdersParams(msgspec.Struct):
54
+ status: Literal["pending", "shipped", "cancelled"] | None = None
55
+
56
+
57
+ class CountOrdersResult(msgspec.Struct):
58
+ count: int
59
+
60
+
61
+ @server.tool(
62
+ description="Count Order rows, optionally filtered by status.",
63
+ read_only=True,
64
+ )
65
+ def count_orders(request, params: CountOrdersParams) -> CountOrdersResult:
66
+ qs = Order.objects.all()
67
+ if params.status is not None:
68
+ qs = qs.filter(status=params.status)
69
+ return CountOrdersResult(count=qs.count())
70
+
71
+ Documentation
72
+ -------------
73
+
74
+ Please see https://django-mcpz.readthedocs.io/.
@@ -0,0 +1,152 @@
1
+ [build-system]
2
+ build-backend = "uv_build"
3
+ requires = ["uv-build>=0.12.1,<0.13"]
4
+
5
+ [project]
6
+ name = "django-mcpz"
7
+ version = "1.0.0"
8
+ description = "Easy peasy MCP servers in Django."
9
+ readme = "README.rst"
10
+ keywords = [
11
+ "Django",
12
+ "MCP",
13
+ "Model Context Protocol",
14
+ ]
15
+ license = "MIT"
16
+ license-files = ["LICENSE"]
17
+ requires-python = ">=3.10"
18
+ classifiers = [
19
+ "Development Status :: 4 - Beta",
20
+ "Framework :: Django :: 5.2",
21
+ "Framework :: Django :: 6.0",
22
+ "Framework :: Django :: 6.1",
23
+ "Intended Audience :: Developers",
24
+ "Natural Language :: English",
25
+ "Operating System :: OS Independent",
26
+ "Programming Language :: Python :: 3 :: Only",
27
+ "Programming Language :: Python :: 3.10",
28
+ "Programming Language :: Python :: 3.11",
29
+ "Programming Language :: Python :: 3.12",
30
+ "Programming Language :: Python :: 3.13",
31
+ "Programming Language :: Python :: 3.14",
32
+ "Programming Language :: Python :: 3.15",
33
+ "Programming Language :: Python :: Implementation :: CPython",
34
+ "Typing :: Typed",
35
+ ]
36
+ dependencies = [
37
+ "asgiref>=3.6",
38
+ "django>=5.2",
39
+ "django-msgspec>=1",
40
+ "msgspec>=0.20",
41
+ ]
42
+
43
+ [[project.authors]]
44
+ name = "Adam Johnson"
45
+ email = "me@adamj.eu"
46
+
47
+ [project.urls]
48
+ Changelog = "https://django-mcpz.readthedocs.io/en/latest/changelog.html"
49
+ Documentation = "https://django-mcpz.readthedocs.io/"
50
+ Funding = "https://adamj.eu/books/"
51
+ Repository = "https://github.com/adamchainz/django-mcpz"
52
+
53
+ [dependency-groups]
54
+ test = [
55
+ "coverage[toml]",
56
+ "mcp>=2,<3",
57
+ "pytest>=9",
58
+ "pytest-django",
59
+ "pytest-randomly",
60
+ ]
61
+ docs = [
62
+ "furo>=2024.8.6",
63
+ "sphinx>=7.4.7",
64
+ "sphinx-copybutton>=0.5.2",
65
+ ]
66
+ django52 = ["django>=5.2a1,<6; python_version>='3.10'"]
67
+ django60 = ["django>=6a1,<6.1; python_version>='3.12'"]
68
+ django61 = ["django>=6.1a1,<6.2; python_version>='3.12'"]
69
+ example = ["pillow>=10.1"]
70
+
71
+ [tool.uv]
72
+ conflicts = [[
73
+ { group = "django52" },
74
+ { group = "django60" },
75
+ { group = "django61" },
76
+ ]]
77
+
78
+ [tool.ruff.lint]
79
+ select = [
80
+ "B",
81
+ "C4",
82
+ "E",
83
+ "F",
84
+ "I",
85
+ "SIM",
86
+ "TID",
87
+ "UP",
88
+ "W",
89
+ ]
90
+ ignore = [
91
+ "B9",
92
+ "E501",
93
+ "SIM105",
94
+ "SIM108",
95
+ ]
96
+ extend-safe-fixes = ["UP006"]
97
+
98
+ [tool.ruff.lint.isort]
99
+ required-imports = ["from __future__ import annotations"]
100
+
101
+ [tool.pyproject-fmt]
102
+ max_supported_python = "3.15"
103
+
104
+ [tool.mypy]
105
+ mypy_path = "src/"
106
+ namespace_packages = false
107
+ warn_unreachable = true
108
+ enable_error_code = [
109
+ "ignore-without-code",
110
+ "redundant-expr",
111
+ "truthy-bool",
112
+ ]
113
+ strict = true
114
+ plugins = ["mypy_django_plugin.main"]
115
+
116
+ [[tool.mypy.overrides]]
117
+ module = "tests.*"
118
+ allow_untyped_defs = true
119
+ disallow_untyped_calls = false
120
+
121
+ [tool.django-stubs]
122
+ django_settings_module = "tests.settings"
123
+
124
+ [tool.pytest]
125
+ django_find_project = false
126
+ DJANGO_SETTINGS_MODULE = "tests.settings"
127
+ strict = true
128
+
129
+ [tool.coverage.run]
130
+ branch = true
131
+ data_file = ".coverage/cov"
132
+ parallel = true
133
+ source = [
134
+ "django_mcpz",
135
+ "tests",
136
+ ]
137
+
138
+ [tool.coverage.paths]
139
+ source = [
140
+ "src",
141
+ ".tox/**/site-packages",
142
+ ]
143
+
144
+ [tool.coverage.report]
145
+ show_missing = true
146
+ skip_covered = true
147
+ skip_empty = true
148
+
149
+ [tool.rstcheck]
150
+ ignore_directives = ["setting"]
151
+ ignore_roles = ["setting"]
152
+ report_level = "ERROR"
@@ -0,0 +1,161 @@
1
+ [build-system]
2
+ build-backend = "uv_build"
3
+ requires = [
4
+ "uv-build>=0.12.1,<0.13",
5
+ ]
6
+
7
+ [project]
8
+ name = "django-mcpz"
9
+ version = "1.0.0"
10
+ description = "Easy peasy MCP servers in Django."
11
+ readme = "README.rst"
12
+ keywords = [
13
+ "Django",
14
+ "MCP",
15
+ "Model Context Protocol",
16
+ ]
17
+ license = "MIT"
18
+ license-files = [ "LICENSE" ]
19
+ authors = [
20
+ { name = "Adam Johnson", email = "me@adamj.eu" },
21
+ ]
22
+ requires-python = ">=3.10"
23
+ classifiers = [
24
+ "Development Status :: 4 - Beta",
25
+ "Framework :: Django :: 5.2",
26
+ "Framework :: Django :: 6.0",
27
+ "Framework :: Django :: 6.1",
28
+ "Intended Audience :: Developers",
29
+ "Natural Language :: English",
30
+ "Operating System :: OS Independent",
31
+ "Programming Language :: Python :: 3 :: Only",
32
+ "Programming Language :: Python :: 3.10",
33
+ "Programming Language :: Python :: 3.11",
34
+ "Programming Language :: Python :: 3.12",
35
+ "Programming Language :: Python :: 3.13",
36
+ "Programming Language :: Python :: 3.14",
37
+ "Programming Language :: Python :: 3.15",
38
+ "Programming Language :: Python :: Implementation :: CPython",
39
+ "Typing :: Typed",
40
+ ]
41
+ dependencies = [
42
+ "asgiref>=3.6",
43
+ "django>=5.2",
44
+ "django-msgspec>=1",
45
+ "msgspec>=0.20",
46
+ ]
47
+ urls.Changelog = "https://django-mcpz.readthedocs.io/en/latest/changelog.html"
48
+ urls.Documentation = "https://django-mcpz.readthedocs.io/"
49
+ urls.Funding = "https://adamj.eu/books/"
50
+ urls.Repository = "https://github.com/adamchainz/django-mcpz"
51
+
52
+ [dependency-groups]
53
+ test = [
54
+ "coverage[toml]",
55
+ "mcp>=2,<3",
56
+ "pytest>=9",
57
+ "pytest-django",
58
+ "pytest-randomly",
59
+ ]
60
+ docs = [
61
+ "furo>=2024.8.6",
62
+ "sphinx>=7.4.7",
63
+ "sphinx-copybutton>=0.5.2",
64
+ ]
65
+ django52 = [ "django>=5.2a1,<6; python_version>='3.10'" ]
66
+ django60 = [ "django>=6a1,<6.1; python_version>='3.12'" ]
67
+ django61 = [ "django>=6.1a1,<6.2; python_version>='3.12'" ]
68
+ example = [ "pillow>=10.1" ]
69
+
70
+ [tool.uv]
71
+ conflicts = [
72
+ [
73
+ { group = "django52" },
74
+ { group = "django60" },
75
+ { group = "django61" },
76
+ ],
77
+ ]
78
+
79
+ [tool.ruff]
80
+ lint.select = [
81
+ # flake8-bugbear
82
+ "B",
83
+ # flake8-comprehensions
84
+ "C4",
85
+ # pycodestyle
86
+ "E",
87
+ # Pyflakes errors
88
+ "F",
89
+ # isort
90
+ "I",
91
+ # flake8-simplify
92
+ "SIM",
93
+ # flake8-tidy-imports
94
+ "TID",
95
+ # pyupgrade
96
+ "UP",
97
+ # Pyflakes warnings
98
+ "W",
99
+ ]
100
+ lint.ignore = [
101
+ # flake8-bugbear opinionated rules
102
+ "B9",
103
+ # line-too-long
104
+ "E501",
105
+ # suppressible-exception
106
+ "SIM105",
107
+ # if-else-block-instead-of-if-exp
108
+ "SIM108",
109
+ ]
110
+ lint.extend-safe-fixes = [
111
+ # non-pep585-annotation
112
+ "UP006",
113
+ ]
114
+ lint.isort.required-imports = [ "from __future__ import annotations" ]
115
+
116
+ [tool.pyproject-fmt]
117
+ max_supported_python = "3.15"
118
+
119
+ [tool.mypy]
120
+ mypy_path = "src/"
121
+ namespace_packages = false
122
+ warn_unreachable = true
123
+ enable_error_code = [
124
+ "ignore-without-code",
125
+ "redundant-expr",
126
+ "truthy-bool",
127
+ ]
128
+ strict = true
129
+ plugins = [ "mypy_django_plugin.main" ]
130
+ overrides = [
131
+ { module = "tests.*", allow_untyped_defs = true, disallow_untyped_calls = false },
132
+ ]
133
+
134
+ [tool.django-stubs]
135
+ django_settings_module = "tests.settings"
136
+
137
+ [tool.pytest]
138
+ django_find_project = false
139
+ DJANGO_SETTINGS_MODULE = "tests.settings"
140
+ strict = true
141
+
142
+ [tool.coverage]
143
+ run.branch = true
144
+ run.data_file = ".coverage/cov"
145
+ run.parallel = true
146
+ run.source = [
147
+ "django_mcpz",
148
+ "tests",
149
+ ]
150
+ paths.source = [
151
+ "src",
152
+ ".tox/**/site-packages",
153
+ ]
154
+ report.show_missing = true
155
+ report.skip_covered = true
156
+ report.skip_empty = true
157
+
158
+ [tool.rstcheck]
159
+ ignore_directives = [ "setting" ]
160
+ ignore_roles = [ "setting" ]
161
+ report_level = "ERROR"
File without changes
@@ -0,0 +1,61 @@
1
+ from __future__ import annotations
2
+
3
+ from typing import TYPE_CHECKING, Any
4
+
5
+ from django.contrib import admin, messages
6
+ from django.db.models import QuerySet
7
+ from django.http import HttpRequest
8
+ from django.utils import timezone
9
+
10
+ from django_mcpz import tokens
11
+ from django_mcpz.bearer_tokens.models import Token
12
+
13
+ if TYPE_CHECKING:
14
+ ModelAdmin = admin.ModelAdmin[Token]
15
+ else:
16
+ ModelAdmin = admin.ModelAdmin
17
+
18
+
19
+ @admin.register(Token)
20
+ class TokenAdmin(ModelAdmin):
21
+ list_display = [
22
+ "name",
23
+ "user",
24
+ "created_at",
25
+ "last_used_at",
26
+ "expires_at",
27
+ "revoked_at",
28
+ ]
29
+ list_filter = [("revoked_at", admin.EmptyFieldListFilter)]
30
+ search_fields = ["name"]
31
+ raw_id_fields = ["user"]
32
+ fields = [
33
+ "name",
34
+ "user",
35
+ "created_at",
36
+ "last_used_at",
37
+ "expires_at",
38
+ "revoked_at",
39
+ ]
40
+ # Revocation is one-way: it happens through the action, not the form.
41
+ readonly_fields = ["created_at", "last_used_at", "revoked_at"]
42
+ actions = ["revoke"]
43
+
44
+ def save_model(
45
+ self, request: HttpRequest, obj: Token, form: Any, change: bool
46
+ ) -> None:
47
+ if not change:
48
+ value = tokens.generate()
49
+ obj.digest = tokens.sha256_hex(value)
50
+ messages.success(
51
+ request,
52
+ f"Token created. Its value, shown only this once, is: {value}",
53
+ )
54
+ super().save_model(request, obj, form, change)
55
+
56
+ @admin.action(description="Revoke selected tokens")
57
+ def revoke(self, request: HttpRequest, queryset: QuerySet[Token]) -> None:
58
+ count = queryset.filter(revoked_at__isnull=True).update(
59
+ revoked_at=timezone.now()
60
+ )
61
+ messages.success(request, f"Revoked {count} token(s).")
@@ -0,0 +1,10 @@
1
+ from __future__ import annotations
2
+
3
+ from django.apps import AppConfig
4
+
5
+
6
+ class BearerTokensConfig(AppConfig):
7
+ name = "django_mcpz.bearer_tokens"
8
+ label = "django_mcpz_bearer_tokens"
9
+ verbose_name = "MCP bearer tokens"
10
+ default_auto_field = "django.db.models.BigAutoField"
@@ -0,0 +1,48 @@
1
+ from __future__ import annotations
2
+
3
+ from http import HTTPStatus
4
+
5
+ from django.db.models import Q
6
+ from django.http import HttpRequest, HttpResponse
7
+ from django.utils import timezone
8
+
9
+ from django_mcpz import tokens
10
+ from django_mcpz.bearer_tokens.models import Token
11
+
12
+
13
+ def token_auth(request: HttpRequest) -> HttpResponse | None:
14
+ """
15
+ Authenticate with a bearer token from the django_mcpz.bearer_tokens app.
16
+
17
+ Requires the Authorization header to carry an unrevoked, unexpired token,
18
+ for an active user, as a bearer credential. On success, attaches the Token as
19
+ request.mcp_token and sets request.user to the token's user.
20
+ """
21
+ header = request.headers.get("Authorization", "")
22
+ # The auth scheme is case-insensitive (RFC 9110 §11.1).
23
+ scheme, _, credential = header.partition(" ")
24
+ credential = credential.strip()
25
+ if scheme.lower() != "bearer" or not credential:
26
+ return _rejection()
27
+ try:
28
+ token = Token.objects.select_related("user").get(
29
+ Q(expires_at__isnull=True) | Q(expires_at__gt=timezone.now()),
30
+ digest=tokens.sha256_hex(credential),
31
+ revoked_at__isnull=True,
32
+ )
33
+ except Token.DoesNotExist:
34
+ return _rejection()
35
+ # Like Django's ModelBackend, treat a user model without is_active as
36
+ # always active.
37
+ if not getattr(token.user, "is_active", True):
38
+ return _rejection()
39
+ token.record_use()
40
+ request.mcp_token = token # type: ignore[attr-defined]
41
+ request.user = token.user
42
+ return None
43
+
44
+
45
+ def _rejection() -> HttpResponse:
46
+ return HttpResponse(
47
+ status=HTTPStatus.UNAUTHORIZED, headers={"WWW-Authenticate": "Bearer"}
48
+ )
@@ -0,0 +1,17 @@
1
+ from __future__ import annotations
2
+
3
+ from django.db.models import Q
4
+ from django.utils import timezone
5
+
6
+ from django_mcpz.bearer_tokens.models import Token
7
+
8
+
9
+ def clear_expired() -> int:
10
+ """
11
+ Delete expired and revoked bearer tokens.
12
+
13
+ Returns the number deleted.
14
+ """
15
+ return Token.objects.filter(
16
+ Q(expires_at__lt=timezone.now()) | Q(revoked_at__isnull=False)
17
+ ).delete()[0]