crudkit 0.3.0__tar.gz → 0.4.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 (125) hide show
  1. {crudkit-0.3.0 → crudkit-0.4.0}/CHANGELOG.md +24 -0
  2. {crudkit-0.3.0 → crudkit-0.4.0}/PKG-INFO +49 -2
  3. {crudkit-0.3.0 → crudkit-0.4.0}/README.md +44 -1
  4. {crudkit-0.3.0 → crudkit-0.4.0}/pyproject.toml +5 -2
  5. {crudkit-0.3.0 → crudkit-0.4.0}/src/crudkit/authorization.py +12 -0
  6. {crudkit-0.3.0 → crudkit-0.4.0}/src/crudkit/models.py +2 -0
  7. crudkit-0.4.0/src/crudkit/tests/test_authorization.py +20 -0
  8. crudkit-0.4.0/src/crudkit_api/services.py +235 -0
  9. {crudkit-0.3.0 → crudkit-0.4.0}/src/crudkit_api/views.py +4 -21
  10. {crudkit-0.3.0 → crudkit-0.4.0}/src/crudkit_assistant/consumers.py +1 -2
  11. crudkit-0.4.0/src/crudkit_assistant/execution.py +40 -0
  12. {crudkit-0.3.0 → crudkit-0.4.0}/src/crudkit_assistant/runner.py +2 -1
  13. {crudkit-0.3.0 → crudkit-0.4.0}/src/crudkit_assistant/tools.py +4 -35
  14. {crudkit-0.3.0 → crudkit-0.4.0}/src/crudkit_assistant/utils.py +0 -8
  15. crudkit-0.3.0/src/crudkit_frontend/static/crudkit_frontend/assets/index-BYJWd3yY.js → crudkit-0.4.0/src/crudkit_frontend/static/crudkit_frontend/assets/index-CU-EhJ5W.js +182 -182
  16. {crudkit-0.3.0 → crudkit-0.4.0}/src/crudkit_frontend/templates/crudkit_frontend/index.html +1 -1
  17. crudkit-0.4.0/src/crudkit_mcp/admin.py +35 -0
  18. crudkit-0.4.0/src/crudkit_mcp/apps.py +7 -0
  19. crudkit-0.4.0/src/crudkit_mcp/authentication.py +35 -0
  20. crudkit-0.4.0/src/crudkit_mcp/conf.py +21 -0
  21. crudkit-0.4.0/src/crudkit_mcp/migrations/0001_initial.py +189 -0
  22. crudkit-0.4.0/src/crudkit_mcp/models.py +125 -0
  23. crudkit-0.4.0/src/crudkit_mcp/oauth.py +337 -0
  24. crudkit-0.4.0/src/crudkit_mcp/server.py +99 -0
  25. crudkit-0.4.0/src/crudkit_mcp/templates/crudkit_mcp/authorize.html +46 -0
  26. crudkit-0.4.0/src/crudkit_mcp/tests/__init__.py +0 -0
  27. crudkit-0.4.0/src/crudkit_mcp/tests/test_mcp.py +432 -0
  28. crudkit-0.4.0/src/crudkit_mcp/tests/test_oauth.py +761 -0
  29. crudkit-0.4.0/src/crudkit_mcp/tools.py +457 -0
  30. crudkit-0.4.0/src/crudkit_mcp/urls.py +18 -0
  31. crudkit-0.4.0/src/crudkit_mcp/views.py +46 -0
  32. crudkit-0.4.0/src/crudkit_mcp/well_known_urls.py +21 -0
  33. {crudkit-0.3.0 → crudkit-0.4.0}/tests/settings.py +1 -0
  34. crudkit-0.4.0/tests/testapp/__init__.py +0 -0
  35. crudkit-0.4.0/tests/testapp/migrations/__init__.py +0 -0
  36. {crudkit-0.3.0 → crudkit-0.4.0}/tests/urls.py +2 -0
  37. crudkit-0.3.0/src/crudkit_assistant/execution.py +0 -199
  38. {crudkit-0.3.0 → crudkit-0.4.0}/.gitignore +0 -0
  39. {crudkit-0.3.0 → crudkit-0.4.0}/manage.py +0 -0
  40. {crudkit-0.3.0 → crudkit-0.4.0}/src/crudkit/__init__.py +0 -0
  41. {crudkit-0.3.0 → crudkit-0.4.0}/src/crudkit/admin.py +0 -0
  42. {crudkit-0.3.0 → crudkit-0.4.0}/src/crudkit/ai_backend.py +0 -0
  43. {crudkit-0.3.0 → crudkit-0.4.0}/src/crudkit/apps.py +0 -0
  44. {crudkit-0.3.0 → crudkit-0.4.0}/src/crudkit/checks.py +0 -0
  45. {crudkit-0.3.0 → crudkit-0.4.0}/src/crudkit/decorators.py +0 -0
  46. {crudkit-0.3.0 → crudkit-0.4.0}/src/crudkit/fields.py +0 -0
  47. {crudkit-0.3.0 → crudkit-0.4.0}/src/crudkit/llm.py +0 -0
  48. {crudkit-0.3.0 → crudkit-0.4.0}/src/crudkit/management/__init__.py +0 -0
  49. {crudkit-0.3.0 → crudkit-0.4.0}/src/crudkit/management/commands/__init__.py +0 -0
  50. {crudkit-0.3.0 → crudkit-0.4.0}/src/crudkit/management/commands/add_default_exchange_rates.py +0 -0
  51. {crudkit-0.3.0 → crudkit-0.4.0}/src/crudkit/management/commands/backfill_ai_fields.py +0 -0
  52. {crudkit-0.3.0 → crudkit-0.4.0}/src/crudkit/management/commands/set_exchange_rate.py +0 -0
  53. {crudkit-0.3.0 → crudkit-0.4.0}/src/crudkit/migrations/0001_squashed.py +0 -0
  54. {crudkit-0.3.0 → crudkit-0.4.0}/src/crudkit/migrations/0002_workspace.py +0 -0
  55. {crudkit-0.3.0 → crudkit-0.4.0}/src/crudkit/migrations/0003_enforce_data_invariants.py +0 -0
  56. {crudkit-0.3.0 → crudkit-0.4.0}/src/crudkit/migrations/__init__.py +0 -0
  57. {crudkit-0.3.0 → crudkit-0.4.0}/src/crudkit/profile.py +0 -0
  58. {crudkit-0.3.0 → crudkit-0.4.0}/src/crudkit/signals.py +0 -0
  59. {crudkit-0.3.0 → crudkit-0.4.0}/src/crudkit/tasks.py +0 -0
  60. {crudkit-0.3.0 → crudkit-0.4.0}/src/crudkit/templatetags/__init__.py +0 -0
  61. {crudkit-0.3.0 → crudkit-0.4.0}/src/crudkit/templatetags/crm_forms.py +0 -0
  62. {crudkit-0.3.0 → crudkit-0.4.0}/src/crudkit/templatetags/crm_time.py +0 -0
  63. {crudkit-0.3.0 → crudkit-0.4.0}/src/crudkit/templatetags/gravatar.py +0 -0
  64. {crudkit-0.3.0 → crudkit-0.4.0}/src/crudkit/templatetags/model_magic.py +0 -0
  65. {crudkit-0.3.0 → crudkit-0.4.0}/src/crudkit/tests/__init__.py +0 -0
  66. {crudkit-0.3.0 → crudkit-0.4.0}/src/crudkit/tests/test_ai_backend.py +0 -0
  67. {crudkit-0.3.0 → crudkit-0.4.0}/src/crudkit/tests/test_ai_fields.py +0 -0
  68. {crudkit-0.3.0 → crudkit-0.4.0}/src/crudkit/tests/test_ai_tasks.py +0 -0
  69. {crudkit-0.3.0 → crudkit-0.4.0}/src/crudkit/tests/test_backfill_command.py +0 -0
  70. {crudkit-0.3.0 → crudkit-0.4.0}/src/crudkit/tests/test_fields.py +0 -0
  71. {crudkit-0.3.0 → crudkit-0.4.0}/src/crudkit/tests/test_integrity.py +0 -0
  72. {crudkit-0.3.0 → crudkit-0.4.0}/src/crudkit/tests/test_llm.py +0 -0
  73. {crudkit-0.3.0 → crudkit-0.4.0}/src/crudkit/tests/test_money.py +0 -0
  74. {crudkit-0.3.0 → crudkit-0.4.0}/src/crudkit/tests/test_tasks.py +0 -0
  75. {crudkit-0.3.0 → crudkit-0.4.0}/src/crudkit/tests/test_workspace.py +0 -0
  76. {crudkit-0.3.0 → crudkit-0.4.0}/src/crudkit/utils.py +0 -0
  77. {crudkit-0.3.0 → crudkit-0.4.0}/src/crudkit/widgets.py +0 -0
  78. {crudkit-0.3.0 → crudkit-0.4.0}/src/crudkit_api/__init__.py +0 -0
  79. {crudkit-0.3.0 → crudkit-0.4.0}/src/crudkit_api/authentication.py +0 -0
  80. {crudkit-0.3.0 → crudkit-0.4.0}/src/crudkit_api/filters.py +0 -0
  81. {crudkit-0.3.0 → crudkit-0.4.0}/src/crudkit_api/metadata.py +0 -0
  82. {crudkit-0.3.0 → crudkit-0.4.0}/src/crudkit_api/pagination.py +0 -0
  83. {crudkit-0.3.0 → crudkit-0.4.0}/src/crudkit_api/permissions.py +0 -0
  84. {crudkit-0.3.0 → crudkit-0.4.0}/src/crudkit_api/serializers.py +0 -0
  85. {crudkit-0.3.0 → crudkit-0.4.0}/src/crudkit_api/tests/__init__.py +0 -0
  86. {crudkit-0.3.0 → crudkit-0.4.0}/src/crudkit_api/tests/test_authorization.py +0 -0
  87. {crudkit-0.3.0 → crudkit-0.4.0}/src/crudkit_api/tests/test_email_id_serialization.py +0 -0
  88. {crudkit-0.3.0 → crudkit-0.4.0}/src/crudkit_api/tests/test_filters.py +0 -0
  89. {crudkit-0.3.0 → crudkit-0.4.0}/src/crudkit_api/tests/test_list_serialization.py +0 -0
  90. {crudkit-0.3.0 → crudkit-0.4.0}/src/crudkit_api/tests/test_merge.py +0 -0
  91. {crudkit-0.3.0 → crudkit-0.4.0}/src/crudkit_api/tests/test_metadata.py +0 -0
  92. {crudkit-0.3.0 → crudkit-0.4.0}/src/crudkit_api/tests/test_user_profile.py +0 -0
  93. {crudkit-0.3.0 → crudkit-0.4.0}/src/crudkit_api/urls.py +0 -0
  94. {crudkit-0.3.0 → crudkit-0.4.0}/src/crudkit_assistant/__init__.py +0 -0
  95. {crudkit-0.3.0 → crudkit-0.4.0}/src/crudkit_assistant/admin.py +0 -0
  96. {crudkit-0.3.0 → crudkit-0.4.0}/src/crudkit_assistant/agent.py +0 -0
  97. {crudkit-0.3.0 → crudkit-0.4.0}/src/crudkit_assistant/apps.py +0 -0
  98. {crudkit-0.3.0 → crudkit-0.4.0}/src/crudkit_assistant/deps.py +0 -0
  99. {crudkit-0.3.0 → crudkit-0.4.0}/src/crudkit_assistant/migrations/0001_initial.py +0 -0
  100. {crudkit-0.3.0 → crudkit-0.4.0}/src/crudkit_assistant/migrations/__init__.py +0 -0
  101. {crudkit-0.3.0 → crudkit-0.4.0}/src/crudkit_assistant/models.py +0 -0
  102. {crudkit-0.3.0 → crudkit-0.4.0}/src/crudkit_assistant/routing.py +0 -0
  103. {crudkit-0.3.0 → crudkit-0.4.0}/src/crudkit_assistant/tests/__init__.py +0 -0
  104. {crudkit-0.3.0 → crudkit-0.4.0}/src/crudkit_assistant/tests/test_proposals.py +0 -0
  105. {crudkit-0.3.0 → crudkit-0.4.0}/src/crudkit_frontend/__init__.py +0 -0
  106. {crudkit-0.3.0 → crudkit-0.4.0}/src/crudkit_frontend/apps.py +0 -0
  107. {crudkit-0.3.0 → crudkit-0.4.0}/src/crudkit_frontend/context_processors.py +0 -0
  108. {crudkit-0.3.0 → crudkit-0.4.0}/src/crudkit_frontend/static/crudkit_frontend/assets/favicon-Cit_9t8D.svg +0 -0
  109. {crudkit-0.3.0 → crudkit-0.4.0}/src/crudkit_frontend/static/crudkit_frontend/assets/index-D_4ufdxB.css +0 -0
  110. {crudkit-0.3.0 → crudkit-0.4.0}/src/crudkit_frontend/tests/__init__.py +0 -0
  111. {crudkit-0.3.0 → crudkit-0.4.0}/src/crudkit_frontend/tests/templates/crudkit_frontend/index.html +0 -0
  112. {crudkit-0.3.0 → crudkit-0.4.0}/src/crudkit_frontend/tests/test_frontend.py +0 -0
  113. {crudkit-0.3.0 → crudkit-0.4.0}/src/crudkit_frontend/tests/urls.py +0 -0
  114. {crudkit-0.3.0 → crudkit-0.4.0}/src/crudkit_frontend/urls.py +0 -0
  115. {crudkit-0.3.0 → crudkit-0.4.0}/src/crudkit_frontend/views.py +0 -0
  116. {crudkit-0.3.0/tests/testapp → crudkit-0.4.0/src/crudkit_mcp}/__init__.py +0 -0
  117. {crudkit-0.3.0/tests/testapp → crudkit-0.4.0/src/crudkit_mcp}/migrations/__init__.py +0 -0
  118. {crudkit-0.3.0 → crudkit-0.4.0}/tests/__init__.py +0 -0
  119. {crudkit-0.3.0 → crudkit-0.4.0}/tests/celery.py +0 -0
  120. {crudkit-0.3.0 → crudkit-0.4.0}/tests/testapp/adapters.py +0 -0
  121. {crudkit-0.3.0 → crudkit-0.4.0}/tests/testapp/ai.py +0 -0
  122. {crudkit-0.3.0 → crudkit-0.4.0}/tests/testapp/apps.py +0 -0
  123. {crudkit-0.3.0 → crudkit-0.4.0}/tests/testapp/migrations/0001_initial.py +0 -0
  124. {crudkit-0.3.0 → crudkit-0.4.0}/tests/testapp/migrations/0002_customer_currency.py +0 -0
  125. {crudkit-0.3.0 → crudkit-0.4.0}/tests/testapp/models.py +0 -0
@@ -1,5 +1,29 @@
1
1
  # Changelog
2
2
 
3
+ ## 0.4.0 (2026-09-24)
4
+
5
+ - `crudkit_mcp` (new app, `crudkit[mcp]`): remote MCP server + OAuth 2.1 provider, moved from
6
+ fenerum-crm. A fixed, type-parameterised tool set addressing records by TYPE_ID/CK-ID —
7
+ `describe_types`, `search`, `list_records`, `get_record`, and — with
8
+ `CRUDKIT_MCP_WRITE_ENABLED` and the `write` scope — `create_record`, `update_record`,
9
+ `run_action`, `add_note`; all respecting model/row/action permissions. New settings `CRUDKIT_MCP_SERVER_NAME`, `CRUDKIT_MCP_WRITE_ENABLED`,
10
+ `CRUDKIT_MCP_EXTRA_TOOLS`, `CRUDKIT_MCP_MODELS`, `CRUDKIT_MCP_BASE_URL`; new
11
+ `CrudKitSettings.mcp_exclude`. The consent page always grants `read` and offers `write`
12
+ as a checkbox. (#39)
13
+ - `crudkit`: `get_authorized_instance` moved from `crudkit_assistant.utils` to
14
+ `crudkit.authorization`. (#39)
15
+ - `crudkit_api`: new `crudkit_api.services` with the search, feed, change log and mutation
16
+ helpers shared by the REST API, the assistant and the MCP server. (#39)
17
+
18
+ ## 0.3.1 (2026-09-22)
19
+
20
+ - `crudkit_frontend`: feed items whose related object isn't an email (chat messages, calls,
21
+ meetings, ...) show the feed item's `body` instead of an empty frame. (#36)
22
+ - `crudkit_frontend`: views only appear in menus (sidebar, workspace tabs, command palette)
23
+ when `show_in_menu` is set. The shared Workspace section and workspace tabs only list public
24
+ views; per-type view tabs, the default-view pick and the command palette only list public or
25
+ own views, so superusers no longer see other users' private views there. (#37)
26
+
3
27
  ## 0.3.0 (2026-09-21)
4
28
 
5
29
  - `crudkit_frontend`: related-record pickers offer `+ Create <model> "<typed text>"`, which
@@ -1,6 +1,6 @@
1
1
  Metadata-Version: 2.5
2
2
  Name: crudkit
3
- Version: 0.3.0
3
+ Version: 0.4.0
4
4
  Summary: A metadata-driven CRUD framework for Django: typed object IDs, soft delete, merge, change log, activity feed, saved views, AI fields and a generic REST API.
5
5
  Project-URL: Homepage, https://github.com/fenerum/crudkit
6
6
  Project-URL: Changelog, https://github.com/fenerum/crudkit/blob/main/backend/CHANGELOG.md
@@ -30,6 +30,10 @@ Requires-Dist: channels>=4.1; extra == 'assistant'
30
30
  Requires-Dist: djangorestframework-simplejwt>=5.4; extra == 'assistant'
31
31
  Requires-Dist: djangorestframework>=3.15; extra == 'assistant'
32
32
  Requires-Dist: drf-extra-fields>=3.7; extra == 'assistant'
33
+ Provides-Extra: mcp
34
+ Requires-Dist: djangorestframework-simplejwt>=5.4; extra == 'mcp'
35
+ Requires-Dist: djangorestframework>=3.15; extra == 'mcp'
36
+ Requires-Dist: drf-extra-fields>=3.7; extra == 'mcp'
33
37
  Description-Content-Type: text/markdown
34
38
 
35
39
  # crudkit
@@ -69,6 +73,7 @@ fields (`AISummaryField`, `AICategoryField`, `AIBooleanField`, `AITagsField`,
69
73
  ```
70
74
  pip install crudkit[api] # REST API included
71
75
  pip install crudkit[assistant] # + per-object AI assistant (Channels)
76
+ pip install crudkit[mcp] # + remote MCP server with OAuth (e.g. a Claude connector)
72
77
  ```
73
78
 
74
79
  ```python
@@ -113,6 +118,48 @@ permission and can be narrowed further with
113
118
  | `CRUDKIT_ASSISTANT_NAME`, `CRUDKIT_ASSISTANT_SYSTEM_PROMPT`, `CRUDKIT_ASSISTANT_AVATAR_URL` | assistant branding |
114
119
  | `CRUDKIT_FRONTEND_CONFIG` | dict injected into the bundled SPA at runtime (`app_name`, `logo_url`, ...) |
115
120
  | `CRUDKIT_FRONTEND_LOGIN_REQUIRED` | redirect anonymous users of the SPA view to `LOGIN_URL` |
121
+ | `CRUDKIT_MCP_SERVER_NAME` | `serverInfo.name` reported by the MCP server (default `"crudkit"`) |
122
+ | `CRUDKIT_MCP_WRITE_ENABLED` | offer the `write` OAuth scope and the create/update/action/note tools (default `False`) |
123
+ | `CRUDKIT_MCP_MODELS` | list of TYPE_IDs to expose over MCP (default: every project model) |
124
+ | `CRUDKIT_MCP_EXTRA_TOOLS` | dotted paths to `crudkit_mcp.tools.Tool` instances; added to, or replacing, the generated tools |
125
+ | `CRUDKIT_MCP_BASE_URL` | public origin for OAuth metadata URLs when the request's host/scheme is wrong (e.g. behind a proxy) |
126
+
127
+ ## MCP server
128
+
129
+ `crudkit_mcp` exposes the models as a remote [MCP](https://modelcontextprotocol.io)
130
+ server (streamable HTTP) with its own OAuth 2.1 authorization server
131
+ (dynamic client registration, PKCE, rotating refresh tokens), so it can be
132
+ added as e.g. a Claude connector by URL.
133
+
134
+ ```python
135
+ INSTALLED_APPS = [..., "crudkit_mcp"]
136
+ LOGIN_URL = "/login/" # the OAuth consent page needs a session login
137
+
138
+ urlpatterns = [
139
+ path("api/v1/", include("crudkit_mcp.urls")), # /api/v1/mcp, /api/v1/oauth/...
140
+ path("", include("crudkit_mcp.well_known_urls")), # /.well-known/oauth-* (site root)
141
+ ...,
142
+ ]
143
+ ```
144
+
145
+ The tool set is fixed — records are addressed by TYPE_ID and CK-ID, so the
146
+ same tools serve any project:
147
+
148
+ | Tool | |
149
+ |---|---|
150
+ | `describe_types` | the record types; for one `type`, its filters, writable fields, actions and permissions |
151
+ | `search` | free-text search across types, returning `{id, label}` |
152
+ | `list_records` | one `type`, a `filters` object (keys from `describe_types`), `query`, `order_by`, `limit`, `offset` |
153
+ | `get_record` | one record by ID, with its feed, change log and available actions |
154
+
155
+ With `CRUDKIT_MCP_WRITE_ENABLED` and a token granted the `write` scope, four
156
+ more: `create_record`, `update_record`, `run_action` and `add_note`.
157
+
158
+ Every call is filtered through the token user's model, row and action
159
+ permissions, so a type the user can't view isn't listed and can't be read.
160
+ CrudKit's own models and Django's (including `User`) are never exposed;
161
+ narrow the rest with `CRUDKIT_MCP_MODELS = ["CMP", "PER", ...]` or opt a
162
+ single model out with `CrudKitSettings.mcp_exclude = True`.
116
163
 
117
164
  ## Bundled frontend
118
165
 
@@ -149,7 +196,7 @@ backend; `npm run build` there regenerates the bundled assets.
149
196
  ```
150
197
  cd backend
151
198
  uv sync --all-extras
152
- uv run manage.py test crudkit crudkit_api crudkit_assistant crudkit_frontend tests
199
+ uv run manage.py test crudkit crudkit_api crudkit_assistant crudkit_frontend crudkit_mcp tests
153
200
  ```
154
201
 
155
202
  ## License
@@ -35,6 +35,7 @@ fields (`AISummaryField`, `AICategoryField`, `AIBooleanField`, `AITagsField`,
35
35
  ```
36
36
  pip install crudkit[api] # REST API included
37
37
  pip install crudkit[assistant] # + per-object AI assistant (Channels)
38
+ pip install crudkit[mcp] # + remote MCP server with OAuth (e.g. a Claude connector)
38
39
  ```
39
40
 
40
41
  ```python
@@ -79,6 +80,48 @@ permission and can be narrowed further with
79
80
  | `CRUDKIT_ASSISTANT_NAME`, `CRUDKIT_ASSISTANT_SYSTEM_PROMPT`, `CRUDKIT_ASSISTANT_AVATAR_URL` | assistant branding |
80
81
  | `CRUDKIT_FRONTEND_CONFIG` | dict injected into the bundled SPA at runtime (`app_name`, `logo_url`, ...) |
81
82
  | `CRUDKIT_FRONTEND_LOGIN_REQUIRED` | redirect anonymous users of the SPA view to `LOGIN_URL` |
83
+ | `CRUDKIT_MCP_SERVER_NAME` | `serverInfo.name` reported by the MCP server (default `"crudkit"`) |
84
+ | `CRUDKIT_MCP_WRITE_ENABLED` | offer the `write` OAuth scope and the create/update/action/note tools (default `False`) |
85
+ | `CRUDKIT_MCP_MODELS` | list of TYPE_IDs to expose over MCP (default: every project model) |
86
+ | `CRUDKIT_MCP_EXTRA_TOOLS` | dotted paths to `crudkit_mcp.tools.Tool` instances; added to, or replacing, the generated tools |
87
+ | `CRUDKIT_MCP_BASE_URL` | public origin for OAuth metadata URLs when the request's host/scheme is wrong (e.g. behind a proxy) |
88
+
89
+ ## MCP server
90
+
91
+ `crudkit_mcp` exposes the models as a remote [MCP](https://modelcontextprotocol.io)
92
+ server (streamable HTTP) with its own OAuth 2.1 authorization server
93
+ (dynamic client registration, PKCE, rotating refresh tokens), so it can be
94
+ added as e.g. a Claude connector by URL.
95
+
96
+ ```python
97
+ INSTALLED_APPS = [..., "crudkit_mcp"]
98
+ LOGIN_URL = "/login/" # the OAuth consent page needs a session login
99
+
100
+ urlpatterns = [
101
+ path("api/v1/", include("crudkit_mcp.urls")), # /api/v1/mcp, /api/v1/oauth/...
102
+ path("", include("crudkit_mcp.well_known_urls")), # /.well-known/oauth-* (site root)
103
+ ...,
104
+ ]
105
+ ```
106
+
107
+ The tool set is fixed — records are addressed by TYPE_ID and CK-ID, so the
108
+ same tools serve any project:
109
+
110
+ | Tool | |
111
+ |---|---|
112
+ | `describe_types` | the record types; for one `type`, its filters, writable fields, actions and permissions |
113
+ | `search` | free-text search across types, returning `{id, label}` |
114
+ | `list_records` | one `type`, a `filters` object (keys from `describe_types`), `query`, `order_by`, `limit`, `offset` |
115
+ | `get_record` | one record by ID, with its feed, change log and available actions |
116
+
117
+ With `CRUDKIT_MCP_WRITE_ENABLED` and a token granted the `write` scope, four
118
+ more: `create_record`, `update_record`, `run_action` and `add_note`.
119
+
120
+ Every call is filtered through the token user's model, row and action
121
+ permissions, so a type the user can't view isn't listed and can't be read.
122
+ CrudKit's own models and Django's (including `User`) are never exposed;
123
+ narrow the rest with `CRUDKIT_MCP_MODELS = ["CMP", "PER", ...]` or opt a
124
+ single model out with `CrudKitSettings.mcp_exclude = True`.
82
125
 
83
126
  ## Bundled frontend
84
127
 
@@ -115,7 +158,7 @@ backend; `npm run build` there regenerates the bundled assets.
115
158
  ```
116
159
  cd backend
117
160
  uv sync --all-extras
118
- uv run manage.py test crudkit crudkit_api crudkit_assistant crudkit_frontend tests
161
+ uv run manage.py test crudkit crudkit_api crudkit_assistant crudkit_frontend crudkit_mcp tests
119
162
  ```
120
163
 
121
164
  ## License
@@ -1,6 +1,6 @@
1
1
  [project]
2
2
  name = "crudkit"
3
- version = "0.3.0"
3
+ version = "0.4.0"
4
4
  description = "A metadata-driven CRUD framework for Django: typed object IDs, soft delete, merge, change log, activity feed, saved views, AI fields and a generic REST API."
5
5
  readme = "README.md"
6
6
  license = "MIT"
@@ -35,6 +35,9 @@ assistant = [
35
35
  "crudkit[api]",
36
36
  "channels>=4.1",
37
37
  ]
38
+ mcp = [
39
+ "crudkit[api]",
40
+ ]
38
41
 
39
42
  [project.urls]
40
43
  Homepage = "https://github.com/fenerum/crudkit"
@@ -45,7 +48,7 @@ requires = ["hatchling"]
45
48
  build-backend = "hatchling.build"
46
49
 
47
50
  [tool.hatch.build.targets.wheel]
48
- packages = ["src/crudkit", "src/crudkit_api", "src/crudkit_assistant", "src/crudkit_frontend"]
51
+ packages = ["src/crudkit", "src/crudkit_api", "src/crudkit_assistant", "src/crudkit_frontend", "src/crudkit_mcp"]
49
52
  exclude = ["**/tests"]
50
53
  # The built SPA (static assets + index.html template) is gitignored, so it
51
54
  # must be declared as build artifacts to end up in the wheel. Run
@@ -1,6 +1,8 @@
1
1
  from django.core.exceptions import PermissionDenied
2
2
  from django.db.models import Model, QuerySet
3
3
 
4
+ from crudkit.utils import get_model_types
5
+
4
6
 
5
7
  def get_permission_action(method: str, view_action: str | None = None) -> str:
6
8
  if view_action in {"create", "initial_data"}:
@@ -31,6 +33,16 @@ def get_authorized_queryset(user, queryset: QuerySet, action: str = "view") -> Q
31
33
  return authorize(user, queryset, action) if authorize else queryset
32
34
 
33
35
 
36
+ def get_authorized_instance(user, type_id: str, pk: int, action: str = "view"):
37
+ model = get_model_types().get(type_id)
38
+ if model is None:
39
+ return None
40
+ queryset = get_authorized_queryset(user, model.objects.all(), action)
41
+ if hasattr(model, "deleted"):
42
+ queryset = queryset.filter(deleted=False)
43
+ return queryset.filter(pk=pk).first()
44
+
45
+
34
46
  def has_object_permission(user, instance: Model, action: str = "view") -> bool:
35
47
  queryset = get_authorized_queryset(user, instance.__class__._default_manager.all(), action)
36
48
  return queryset.filter(pk=instance.pk).exists()
@@ -378,6 +378,8 @@ class BaseCrudKitModel(models.Model):
378
378
  # this model. Lets the CRM (or any consumer) plug in model-specific
379
379
  # capabilities without touching the framework app.
380
380
  assistant_tools = []
381
+ # Leave this model out of the MCP server's generated tools.
382
+ mcp_exclude = False
381
383
 
382
384
  @staticmethod
383
385
  def get_authorized_queryset(user, queryset, action):
@@ -0,0 +1,20 @@
1
+ from django.contrib.auth.models import User
2
+ from django.test import TestCase
3
+
4
+ from crudkit.authorization import get_authorized_instance
5
+ from crudkit.models import parse_ck_id
6
+ from tests.testapp.models import Customer
7
+
8
+
9
+ class GetAuthorizedInstanceTests(TestCase):
10
+ def setUp(self):
11
+ self.user = User.objects.create_superuser(username="admin", password="pw")
12
+ self.customer = Customer.objects.create(name="Acme", created_by=self.user, updated_by=self.user)
13
+ self.pk = parse_ck_id(self.customer.id)[1]
14
+
15
+ def test_returns_instance(self):
16
+ self.assertEqual(get_authorized_instance(self.user, "CUS", self.pk), self.customer)
17
+
18
+ def test_skips_soft_deleted(self):
19
+ Customer.objects.filter(pk=self.customer.pk).update(deleted=True)
20
+ self.assertIsNone(get_authorized_instance(self.user, "CUS", self.pk))
@@ -0,0 +1,235 @@
1
+ """
2
+ Object operations shared by the REST API, the assistant and the MCP server.
3
+ They route through the same serializers and permission checks as the REST
4
+ API so validation, FK coercion and ChangeLog behave identically everywhere.
5
+ """
6
+
7
+ import logging
8
+ from typing import Any
9
+
10
+ from django.contrib.contenttypes.models import ContentType
11
+ from django.db import models, transaction
12
+ from django.db.models import Q
13
+ from django.http import HttpResponseRedirect
14
+ from rest_framework.exceptions import ValidationError as DRFValidationError
15
+
16
+ from crudkit.authorization import (
17
+ get_authorized_queryset,
18
+ has_model_permission,
19
+ require_action_permission,
20
+ )
21
+ from crudkit.models import ChangeLog, FeedItem
22
+ from crudkit.utils import get_model_types
23
+ from crudkit_api.serializers import get_serializer
24
+
25
+ logger = logging.getLogger(__name__)
26
+
27
+
28
+ class RequestShim:
29
+ """Minimal request-like object for @crm_action methods and the DRF
30
+ serializer's request-aware `_fields` filtering."""
31
+
32
+ def __init__(self, user):
33
+ self.user = user
34
+ self.data: dict = {}
35
+
36
+ class _EmptyGet:
37
+ def get(self, *args, **kwargs):
38
+ return None
39
+
40
+ def __contains__(self, key):
41
+ return False
42
+
43
+ GET = _EmptyGet()
44
+
45
+
46
+ # ---------------------------------------------------------------------------
47
+ # Reads
48
+
49
+
50
+ def get_search_fields(model) -> list[str]:
51
+ return list(getattr(getattr(model, "CrudKitSettings", None), "search_fields", None) or [])
52
+
53
+
54
+ def search_filter(model, query: str) -> Q:
55
+ """Case-insensitive match of `query` against the model's `CrudKitSettings.search_fields`."""
56
+ q = Q()
57
+ for field in get_search_fields(model):
58
+ q |= Q(**{f"{field}__icontains": query.strip()})
59
+ return q
60
+
61
+
62
+ def search_objects(user, query: str, models_to_search=None, limit_per_model: int = 5) -> list[dict[str, Any]]:
63
+ """`search_filter` across models, restricted to what `user` may view."""
64
+ if models_to_search is None:
65
+ models_to_search = get_model_types().values()
66
+ results = []
67
+ for mdl in models_to_search:
68
+ if not get_search_fields(mdl) or not has_model_permission(user, mdl, "view"):
69
+ continue
70
+ serializer_cls = get_serializer(mdl, depth=0, fields=["id", "label", "object_images"])
71
+ qs = get_authorized_queryset(user, mdl.objects.all(), "view").filter(search_filter(mdl, query))
72
+ if "deleted" in [field.name for field in mdl._meta.fields]:
73
+ qs = qs.filter(deleted=False)
74
+ results += [serializer_cls(obj).data for obj in qs[0:limit_per_model]]
75
+ return results
76
+
77
+
78
+ def get_feed(instance, limit: int = 20) -> list[dict[str, Any]]:
79
+ """Recent FeedItems (notes, related-object events) on `instance`."""
80
+ ct = ContentType.objects.get_for_model(instance.__class__)
81
+ qs = FeedItem.objects.filter(parent_content_type=ct, parent_object_id=instance.pk, deleted=False).order_by(
82
+ "-created_at"
83
+ )[:limit]
84
+ return [
85
+ {
86
+ "at": fei.created_at.isoformat(),
87
+ "by": str(fei.created_by) if fei.created_by_id else None,
88
+ "body": fei.body or "",
89
+ "related_model": fei.related_content_type.model if fei.related_content_type_id else None,
90
+ "related_id": str(fei.related_object_id) if fei.related_object_id else None,
91
+ }
92
+ for fei in qs
93
+ ]
94
+
95
+
96
+ def get_changelog(instance, limit: int = 20) -> list[dict[str, Any]]:
97
+ """Recent ChangeLog entries for `instance`: {at, by, field_changes: {field: [old, new]}}."""
98
+ ct = ContentType.objects.get_for_model(instance.__class__)
99
+ qs = ChangeLog.objects.filter(related_content_type=ct, related_object_id=instance.pk).order_by("-updated_at")[
100
+ :limit
101
+ ]
102
+ return [
103
+ {
104
+ "at": cl.updated_at.isoformat(),
105
+ "by": str(cl.updated_by) if cl.updated_by_id else None,
106
+ "field_changes": cl.field_changes or {},
107
+ }
108
+ for cl in qs
109
+ ]
110
+
111
+
112
+ # ---------------------------------------------------------------------------
113
+ # Writes
114
+
115
+
116
+ def run_action(instance, action_name: str, user, request=None) -> dict[str, Any]:
117
+ """Mirror crudkit_api.views.GenericViewSet.call_action — invoke a
118
+ @crm_action method bound to the instance."""
119
+ if not action_name or action_name not in instance._actions:
120
+ available = list(instance._actions.keys())
121
+ logger.warning(
122
+ "Action %r not available on %s; available=%s",
123
+ action_name,
124
+ instance.__class__.__name__,
125
+ available,
126
+ )
127
+ raise ValueError(f"Action {action_name!r} not available on {instance}")
128
+ require_action_permission(user, instance, action_name)
129
+ if request is None:
130
+ request = RequestShim(user)
131
+ logger.info("Running action %s on %s.%s", action_name, instance.__class__.__name__, instance.pk)
132
+ response = instance._actions[action_name](request)
133
+ return _serialize_action_response(response)
134
+
135
+
136
+ def _serialize_action_response(response) -> dict[str, Any]:
137
+ """Normalise whatever a @crm_action returned into a JSON-safe outcome dict."""
138
+ if isinstance(response, HttpResponseRedirect):
139
+ return {"kind": "redirect", "url": response.url}
140
+ if isinstance(response, models.Model):
141
+ return {"kind": "object", "id": str(getattr(response, "id", response.pk))}
142
+ if hasattr(response, "data"):
143
+ try:
144
+ return {"kind": "response", "data": response.data}
145
+ except Exception:
146
+ return {"kind": "response", "status": getattr(response, "status_code", None)}
147
+ return {"kind": "value", "value": str(response) if response is not None else None}
148
+
149
+
150
+ def _unwrap_fk_dict_values(model, fields: dict[str, Any]) -> dict[str, Any]:
151
+ """Agents often echo the `describe_object` shape for FK fields,
152
+ e.g. `{"stage": {"id": "OST1", "display": "Discovery"}}`. The DRF
153
+ serializer's inline FK field expects a bare PK, not a dict — so we
154
+ unwrap any value of that shape on a ForeignKey to just its `id` before
155
+ handing it on. Other values are left untouched."""
156
+ model_fields = {f.name: f for f in model._meta.fields}
157
+ out: dict[str, Any] = {}
158
+ for name, value in fields.items():
159
+ field = model_fields.get(name)
160
+ if field is not None and getattr(field, "many_to_one", False) and isinstance(value, dict) and "id" in value:
161
+ unwrapped = value["id"]
162
+ logger.info("Unwrapped FK dict for %s.%s: %s -> %r", model.__name__, name, value, unwrapped)
163
+ out[name] = unwrapped
164
+ else:
165
+ out[name] = value
166
+ return out
167
+
168
+
169
+ def _validated_serializer(model, instance, fields: dict[str, Any], user, request, partial: bool):
170
+ """Build and validate the REST API serializer for `fields`. DRF silently
171
+ drops fields not declared on the serializer; an agent mustn't get away
172
+ with "I set X" when X never existed, so unknown fields are rejected."""
173
+ fields = _unwrap_fk_dict_values(model, fields)
174
+ serializer = get_serializer(model)(
175
+ instance,
176
+ data=fields,
177
+ partial=partial,
178
+ context={"request": request or RequestShim(user)},
179
+ )
180
+ unknown = [k for k in fields if k not in serializer.fields]
181
+ if unknown:
182
+ logger.warning("Rejected unknown field(s) %s on %s", unknown, model.__name__)
183
+ raise ValueError(f"Field(s) not on {model.__name__}: {unknown}")
184
+ try:
185
+ serializer.is_valid(raise_exception=True)
186
+ except DRFValidationError as exc:
187
+ logger.warning("Validation failed on %s fields=%s errors=%s", model.__name__, list(fields), exc.detail)
188
+ raise ValueError(f"Validation failed: {exc.detail}") from exc
189
+ return serializer
190
+
191
+
192
+ def patch_fields(instance, fields: dict[str, Any], user, request=None) -> dict[str, Any]:
193
+ """Apply a partial update through the same DRF serializer the REST API
194
+ uses. The serializer turns FK PKs (ints or numeric strings) into model
195
+ instances, runs `clean()`, and surfaces validation errors as ValueError."""
196
+ if not isinstance(fields, dict) or not fields:
197
+ raise ValueError("No fields to patch")
198
+ serializer = _validated_serializer(instance.__class__, instance, fields, user, request, partial=True)
199
+
200
+ # Mirror GenericViewSet.perform_update — snapshot the pre-save state for
201
+ # ChangeLog, save, log the diff.
202
+ old_instance = instance.__class__.objects.get(pk=instance.pk)
203
+ with transaction.atomic():
204
+ serializer.save()
205
+ ChangeLog.objects.create_from_objects(old_instance, serializer.instance)
206
+
207
+ logger.info("Patched %s.%s fields=%s", instance.__class__.__name__, instance.pk, list(fields))
208
+ return {"kind": "patch", "applied": list(fields.keys())}
209
+
210
+
211
+ def create_object(model, fields: dict[str, Any], user, request=None):
212
+ """Mirror GenericViewSet.create + perform_create."""
213
+ serializer = _validated_serializer(model, None, fields, user, request, partial=False)
214
+ serializer.initial_instance = model.from_query_params({}, {"created_by": user, "updated_by": user})
215
+ with transaction.atomic():
216
+ instance = serializer.save()
217
+ ChangeLog.objects.create_from_objects(None, instance)
218
+ logger.info("Created %s.%s", model.__name__, instance.pk)
219
+ return instance
220
+
221
+
222
+ def create_note(instance, body: str, user) -> dict[str, Any]:
223
+ """Create a FeedItem note on the target object."""
224
+ body = (body or "").strip()
225
+ if not body:
226
+ raise ValueError("Note body is empty")
227
+ fei = FeedItem.objects.create(
228
+ parent_content_type=ContentType.objects.get_for_model(instance.__class__),
229
+ parent_object_id=instance.pk,
230
+ body=body,
231
+ created_by=user,
232
+ updated_by=user,
233
+ )
234
+ logger.info("Created FeedItem %s on %s.%s", fei.pk, instance.__class__.__name__, instance.pk)
235
+ return {"kind": "note", "feeditem_id": fei.id}
@@ -4,7 +4,7 @@ from django.contrib.auth.models import User
4
4
  from django.contrib.contenttypes.fields import GenericForeignKey, GenericRelation
5
5
  from django.core.exceptions import ValidationError
6
6
  from django.db import connection, models, reset_queries, transaction
7
- from django.db.models import ProtectedError, Q
7
+ from django.db.models import ProtectedError
8
8
  from django.http import HttpResponseRedirect
9
9
  from django.utils.safestring import mark_safe
10
10
  from rest_framework import viewsets
@@ -18,13 +18,13 @@ from crudkit.authorization import (
18
18
  get_authorized_queryset,
19
19
  get_permission_action,
20
20
  has_action_permission,
21
- has_model_permission,
22
21
  )
23
22
  from crudkit.models import BaseCrudKitModel, ChangeLog
24
23
  from crudkit.utils import get_model_types
25
24
  from crudkit_api.metadata import build_model_metadata
26
25
  from crudkit_api.permissions import CrudKitModelPermissions
27
26
  from crudkit_api.serializers import GenericSerializer, get_serializer
27
+ from crudkit_api.services import search_filter, search_objects
28
28
 
29
29
 
30
30
  class GenericViewSet(viewsets.ModelViewSet):
@@ -41,10 +41,7 @@ class GenericViewSet(viewsets.ModelViewSet):
41
41
  queryset = queryset.filter(deleted=False)
42
42
  search = self.request.GET.get("_q", False)
43
43
  if search:
44
- search_filters = Q()
45
- for field in self.queryset.model.CrudKitSettings.search_fields:
46
- search_filters = search_filters | (Q(**{f"{field}__icontains": search.strip()}))
47
- queryset = queryset.filter(search_filters)
44
+ queryset = queryset.filter(search_filter(self.queryset.model, search))
48
45
  return queryset
49
46
 
50
47
  @transaction.atomic
@@ -229,9 +226,6 @@ class SearchViewSet(viewsets.ViewSet):
229
226
  if not query:
230
227
  return Response({"results": []})
231
228
 
232
- # Try getting
233
- results = []
234
-
235
229
  if len(query) > 3 and CRM_TYPE_REGEX.match(query) and ":" in query:
236
230
  search_type, query = query.split(":")
237
231
  possible_searches = [
@@ -246,18 +240,7 @@ class SearchViewSet(viewsets.ViewSet):
246
240
  if hasattr(mdl, "CrudKitSettings") and mdl.CrudKitSettings.search_fields
247
241
  ]
248
242
 
249
- for mdl in possible_searches:
250
- if not has_model_permission(request.user, mdl, "view"):
251
- continue
252
- serializer_cls = get_serializer(mdl, depth=0, fields=["id", "label", "object_images"])
253
- allowed = get_authorized_queryset(request.user, mdl.objects.all(), "view")
254
- qs = mdl.objects.none()
255
- for field in mdl.CrudKitSettings.search_fields:
256
- qs = qs | allowed.filter(**{f"{field}__icontains": query.strip()})
257
- if "deleted" in [field.name for field in mdl._meta.fields]:
258
- qs = qs.filter(deleted=False)
259
- results += [serializer_cls(obj).data for obj in qs[0 : (20 if len(possible_searches) == 1 else 5)]]
260
-
243
+ results = search_objects(request.user, query, possible_searches, 20 if len(possible_searches) == 1 else 5)
261
244
  return Response({"results": results})
262
245
 
263
246
 
@@ -28,11 +28,10 @@ from rest_framework_simplejwt.exceptions import TokenError
28
28
  from rest_framework_simplejwt.settings import api_settings
29
29
  from rest_framework_simplejwt.tokens import AccessToken
30
30
 
31
- from crudkit.authorization import has_object_permission
31
+ from crudkit.authorization import get_authorized_instance, has_object_permission
32
32
  from crudkit_assistant.deps import AssistantDeps
33
33
  from crudkit_assistant.models import AssistantProposal
34
34
  from crudkit_assistant.runner import run_turn
35
- from crudkit_assistant.utils import get_authorized_instance
36
35
 
37
36
  logger = logging.getLogger(__name__)
38
37
 
@@ -0,0 +1,40 @@
1
+ """
2
+ Carries out a confirmed AssistantProposal. Runs synchronously in the consumer
3
+ thread when the user clicks Confirm. Routes through crudkit_api.services so
4
+ permissions, validation, FK PK coercion, and ChangeLog behave identically to
5
+ the REST API.
6
+ """
7
+
8
+ import logging
9
+ from typing import Any
10
+
11
+ from crudkit.authorization import require_object_permission
12
+ from crudkit_api.services import create_note, patch_fields, run_action
13
+
14
+ logger = logging.getLogger(__name__)
15
+
16
+
17
+ def execute_proposal(proposal, user, request=None) -> dict[str, Any]:
18
+ """Dispatch a confirmed proposal to the right executor. Raises on failure;
19
+ `AssistantProposal.apply()` converts that to status=FAILED."""
20
+ instance = proposal.target
21
+ if instance is None:
22
+ raise ValueError("Target object no longer exists")
23
+ require_object_permission(user, instance, "change")
24
+
25
+ logger.info(
26
+ "execute_proposal id=%s kind=%s target=%s.%s",
27
+ proposal.pk,
28
+ proposal.kind,
29
+ instance.__class__.__name__,
30
+ instance.pk,
31
+ )
32
+
33
+ payload = proposal.payload
34
+ if proposal.kind == proposal.Kind.ACTION:
35
+ return run_action(instance, payload.get("action"), user, request)
36
+ if proposal.kind == proposal.Kind.PATCH:
37
+ return patch_fields(instance, payload.get("fields") or {}, user, request)
38
+ if proposal.kind == proposal.Kind.NOTE:
39
+ return create_note(instance, payload.get("body"), user)
40
+ raise ValueError(f"Unknown proposal kind {proposal.kind!r}")
@@ -19,9 +19,10 @@ from asgiref.sync import sync_to_async
19
19
  from django.contrib.auth import get_user_model
20
20
 
21
21
  from crudkit import llm
22
+ from crudkit.authorization import get_authorized_instance
22
23
  from crudkit_assistant.agent import assistant_agent
23
24
  from crudkit_assistant.deps import AssistantDeps
24
- from crudkit_assistant.utils import get_assistant_tools, get_authorized_instance
25
+ from crudkit_assistant.utils import get_assistant_tools
25
26
 
26
27
  logger = logging.getLogger(__name__)
27
28