shellui-django 0.5.0__tar.gz → 0.5.1__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 (41) hide show
  1. {shellui_django-0.5.0 → shellui_django-0.5.1}/CHANGELOG.md +12 -0
  2. {shellui_django-0.5.0 → shellui_django-0.5.1}/PKG-INFO +1 -1
  3. {shellui_django-0.5.0 → shellui_django-0.5.1}/pyproject.toml +1 -1
  4. {shellui_django-0.5.0 → shellui_django-0.5.1}/src/shellui_django/__init__.py +1 -1
  5. shellui_django-0.5.1/src/shellui_django/mcp/openapi_tools.py +326 -0
  6. {shellui_django-0.5.0 → shellui_django-0.5.1}/src/shellui_django/mcp/resources.py +18 -3
  7. shellui_django-0.5.1/src/shellui_django/mcp/tests/test_openapi_tools.py +207 -0
  8. {shellui_django-0.5.0 → shellui_django-0.5.1}/src/shellui_django/mcp/tests/test_resources.py +13 -0
  9. shellui_django-0.5.0/src/shellui_django/mcp/openapi_tools.py +0 -120
  10. shellui_django-0.5.0/src/shellui_django/mcp/tests/test_openapi_tools.py +0 -25
  11. {shellui_django-0.5.0 → shellui_django-0.5.1}/.gitignore +0 -0
  12. {shellui_django-0.5.0 → shellui_django-0.5.1}/LICENSE +0 -0
  13. {shellui_django-0.5.0 → shellui_django-0.5.1}/README.md +0 -0
  14. {shellui_django-0.5.0 → shellui_django-0.5.1}/SECURITY.md +0 -0
  15. {shellui_django-0.5.0 → shellui_django-0.5.1}/src/shellui_django/mcp/__init__.py +0 -0
  16. {shellui_django-0.5.0 → shellui_django-0.5.1}/src/shellui_django/mcp/decorators.py +0 -0
  17. {shellui_django-0.5.0 → shellui_django-0.5.1}/src/shellui_django/mcp/delegation.py +0 -0
  18. {shellui_django-0.5.0 → shellui_django-0.5.1}/src/shellui_django/mcp/gateway.py +0 -0
  19. {shellui_django-0.5.0 → shellui_django-0.5.1}/src/shellui_django/mcp/identity_jwks.py +0 -0
  20. {shellui_django-0.5.0 → shellui_django-0.5.1}/src/shellui_django/mcp/internal.py +0 -0
  21. {shellui_django-0.5.0 → shellui_django-0.5.1}/src/shellui_django/mcp/masking.py +0 -0
  22. {shellui_django-0.5.0 → shellui_django-0.5.1}/src/shellui_django/mcp/openapi_mcp.py +0 -0
  23. {shellui_django-0.5.0 → shellui_django-0.5.1}/src/shellui_django/mcp/rate_limit.py +0 -0
  24. {shellui_django-0.5.0 → shellui_django-0.5.1}/src/shellui_django/mcp/routing.py +0 -0
  25. {shellui_django-0.5.0 → shellui_django-0.5.1}/src/shellui_django/mcp/server.py +0 -0
  26. {shellui_django-0.5.0 → shellui_django-0.5.1}/src/shellui_django/mcp/tests/__init__.py +0 -0
  27. {shellui_django-0.5.0 → shellui_django-0.5.1}/src/shellui_django/mcp/tests/mcp_routing_urlconf.py +0 -0
  28. {shellui_django-0.5.0 → shellui_django-0.5.1}/src/shellui_django/mcp/tests/rs256_helpers.py +0 -0
  29. {shellui_django-0.5.0 → shellui_django-0.5.1}/src/shellui_django/mcp/tests/test_approval_authority.py +0 -0
  30. {shellui_django-0.5.0 → shellui_django-0.5.1}/src/shellui_django/mcp/tests/test_delegation.py +0 -0
  31. {shellui_django-0.5.0 → shellui_django-0.5.1}/src/shellui_django/mcp/tests/test_gateway.py +0 -0
  32. {shellui_django-0.5.0 → shellui_django-0.5.1}/src/shellui_django/mcp/tests/test_identity_jwks_decode.py +0 -0
  33. {shellui_django-0.5.0 → shellui_django-0.5.1}/src/shellui_django/mcp/tests/test_internal_assertions.py +0 -0
  34. {shellui_django-0.5.0 → shellui_django-0.5.1}/src/shellui_django/mcp/tests/test_internal_revocation.py +0 -0
  35. {shellui_django-0.5.0 → shellui_django-0.5.1}/src/shellui_django/mcp/tests/test_masking.py +0 -0
  36. {shellui_django-0.5.0 → shellui_django-0.5.1}/src/shellui_django/mcp/tests/test_package.py +0 -0
  37. {shellui_django-0.5.0 → shellui_django-0.5.1}/src/shellui_django/mcp/tests/test_routing.py +0 -0
  38. {shellui_django-0.5.0 → shellui_django-0.5.1}/src/shellui_django/mcp/tests/test_server_routing.py +0 -0
  39. {shellui_django-0.5.0 → shellui_django-0.5.1}/src/shellui_django/mcp/tests/test_write_gate_mcp.py +0 -0
  40. {shellui_django-0.5.0 → shellui_django-0.5.1}/src/shellui_django/mcp/write_gate.py +0 -0
  41. {shellui_django-0.5.0 → shellui_django-0.5.1}/src/shellui_django/testing/__init__.py +0 -0
@@ -23,6 +23,18 @@ Breaking changes bump the major version (minor while below 1.0.0), so services c
23
23
  See for sample https://raw.githubusercontent.com/favoloso/conventional-changelog-emoji/master/CHANGELOG.md
24
24
  -->
25
25
 
26
+ ## [0.5.1] - 2026-11-09
27
+
28
+ ### 🐛 Bug Fixes
29
+
30
+ - MCP resource indicators: allow plain `http` for private and CGNAT (RFC 6598 `100.64.0.0/10`, e.g. Tailscale) IP literals in addition to loopback. Public hostnames over `http` remain rejected.
31
+ - `tools_from_schema`: resolve OpenAPI `$ref` request bodies and emit typed `body` / `query` properties. Previously `$ref`-only bodies (common with drf-spectacular) produced an empty `body` object, so MCP clients could not submit fields such as template draft `subject` / `document`. Untyped JSONField fragments become free-form objects (`additionalProperties: true`).
32
+ - `tools_from_schema`: field schemas also resolve nested `$ref`, `allOf`, and `oneOf`/`anyOf` wrappers, so drf-spectacular choice fields stay typed strings with their `enum` values, nested serializers stay typed objects, and nullable fields accept `null`.
33
+
34
+ ### 📚 Documentation
35
+
36
+ - Document private/CGNAT `http` resource URLs and `$ref` body expansion for MCP tools.
37
+
26
38
  ## [0.5.0] - 2026-11-06
27
39
 
28
40
  ### 🛠 Improvements
@@ -1,6 +1,6 @@
1
1
  Metadata-Version: 2.5
2
2
  Name: shellui-django
3
- Version: 0.5.0
3
+ Version: 0.5.1
4
4
  Summary: Shared Django libraries for Shellui services
5
5
  Project-URL: Homepage, https://shellui.com
6
6
  Project-URL: Source, https://github.com/shellui/django-commons
@@ -1,6 +1,6 @@
1
1
  [project]
2
2
  name = "shellui-django"
3
- version = "0.5.0"
3
+ version = "0.5.1"
4
4
  description = "Shared Django libraries for Shellui services"
5
5
  readme = "README.md"
6
6
  license = "MIT"
@@ -1,3 +1,3 @@
1
1
  """Shared Django libraries for Shellui services."""
2
2
 
3
- __version__ = '0.5.0'
3
+ __version__ = '0.5.1'
@@ -0,0 +1,326 @@
1
+ """Build MCP tool definitions from a drf-spectacular OpenAPI schema."""
2
+
3
+ from __future__ import annotations
4
+
5
+ import re
6
+ from copy import deepcopy
7
+ from typing import Any
8
+
9
+ from shellui_django.mcp.openapi_mcp import tool_access_flags
10
+ from shellui_django.mcp.routing import path_parameter_names
11
+
12
+ MCP_TOOL_TAG = 'mcp-tools'
13
+
14
+
15
+ def _components(root: dict[str, Any]) -> dict[str, Any]:
16
+ return (root.get('components') or {}).get('schemas') or {}
17
+
18
+
19
+ def _resolve_schema(
20
+ schema: dict[str, Any] | None,
21
+ root: dict[str, Any],
22
+ *,
23
+ _seen: frozenset[str] | None = None,
24
+ ) -> dict[str, Any]:
25
+ if not schema or not isinstance(schema, dict):
26
+ return {}
27
+ ref = schema.get('$ref')
28
+ if isinstance(ref, str) and ref.startswith('#/components/schemas/'):
29
+ name = ref.rsplit('/', 1)[-1]
30
+ seen = _seen or frozenset()
31
+ if name in seen:
32
+ return {
33
+ 'type': 'object',
34
+ 'additionalProperties': True,
35
+ 'description': f'Circular $ref: {ref}',
36
+ }
37
+ target = _components(root).get(name)
38
+ if isinstance(target, dict):
39
+ return _resolve_schema(deepcopy(target), root, _seen=seen | {name})
40
+ return {}
41
+ if '$ref' in schema and len(schema) > 1:
42
+ resolved = _resolve_schema({'$ref': schema['$ref']}, root, _seen=_seen)
43
+ return {**resolved, **{k: v for k, v in schema.items() if k != '$ref'}}
44
+ return schema
45
+
46
+
47
+ _SCALAR_TYPES = frozenset({'string', 'integer', 'number', 'boolean'})
48
+
49
+
50
+ def _free_form(description: str | None = None) -> dict[str, Any]:
51
+ return {'type': 'object', 'additionalProperties': True, 'description': description or 'JSON value'}
52
+
53
+
54
+ def _is_null_variant(node: Any) -> bool:
55
+ if not isinstance(node, dict):
56
+ return False
57
+ if node.get('type') == 'null':
58
+ return True
59
+ enum = node.get('enum')
60
+ return isinstance(enum, list) and len(enum) > 0 and all(v is None for v in enum)
61
+
62
+
63
+ def _enum_type(values: list[Any]) -> str | None:
64
+ non_null = [v for v in values if v is not None]
65
+ if not non_null:
66
+ return None
67
+ if all(isinstance(v, bool) for v in non_null):
68
+ return 'boolean'
69
+ if all(isinstance(v, int) and not isinstance(v, bool) for v in non_null):
70
+ return 'integer'
71
+ if all(isinstance(v, (int, float)) and not isinstance(v, bool) for v in non_null):
72
+ return 'number'
73
+ if all(isinstance(v, str) for v in non_null):
74
+ return 'string'
75
+ return None
76
+
77
+
78
+ def _flatten(node: dict[str, Any], root: dict[str, Any], seen: frozenset[str]) -> tuple[dict[str, Any], frozenset[str], bool]:
79
+ """Resolve ``$ref`` and single-schema ``allOf`` / ``oneOf`` / ``anyOf`` wrappers.
80
+
81
+ Returns the flattened node, the refs visited, and whether null is allowed.
82
+ """
83
+ nullable = bool(node.get('nullable'))
84
+ for _ in range(32):
85
+ ref = node.get('$ref')
86
+ if isinstance(ref, str):
87
+ name = ref.rsplit('/', 1)[-1]
88
+ target = _components(root).get(name) if ref.startswith('#/components/schemas/') else None
89
+ if name in seen or not isinstance(target, dict):
90
+ return _free_form(f'Unresolved $ref: {ref}'), seen, nullable
91
+ seen = seen | {name}
92
+ siblings = {k: v for k, v in node.items() if k != '$ref'}
93
+ node = {**deepcopy(target), **siblings}
94
+ nullable = nullable or bool(node.get('nullable'))
95
+ continue
96
+ all_of = node.get('allOf')
97
+ if isinstance(all_of, list) and all_of:
98
+ siblings = {k: v for k, v in node.items() if k != 'allOf'}
99
+ merged: dict[str, Any] = {}
100
+ props: dict[str, Any] = {}
101
+ required: list[Any] = []
102
+ for part in all_of:
103
+ if not isinstance(part, dict):
104
+ continue
105
+ flat, seen, part_null = _flatten(part, root, seen)
106
+ nullable = nullable or part_null
107
+ props.update(flat.get('properties') or {})
108
+ required.extend(flat.get('required') or [])
109
+ merged.update({k: v for k, v in flat.items() if k not in {'properties', 'required'}})
110
+ if props:
111
+ merged['properties'] = props
112
+ if required:
113
+ merged['required'] = required
114
+ node = {**merged, **siblings}
115
+ continue
116
+ for key in ('oneOf', 'anyOf'):
117
+ variants = node.get(key)
118
+ if not isinstance(variants, list) or not variants:
119
+ continue
120
+ siblings = {k: v for k, v in node.items() if k != key}
121
+ kept: list[dict[str, Any]] = []
122
+ for variant in variants:
123
+ if not isinstance(variant, dict):
124
+ continue
125
+ flat, seen, var_null = _flatten(variant, root, seen)
126
+ if _is_null_variant(flat):
127
+ nullable = True
128
+ continue
129
+ nullable = nullable or var_null
130
+ kept.append(flat)
131
+ if len(kept) == 1:
132
+ node = {**kept[0], **siblings}
133
+ elif kept and all(isinstance(v.get('enum'), list) for v in kept):
134
+ # drf-spectacular: oneOf [StatusEnum, BlankEnum, NullEnum].
135
+ values: list[Any] = []
136
+ for v in kept:
137
+ values.extend(x for x in v['enum'] if x not in values)
138
+ node = {'enum': values, **siblings}
139
+ else:
140
+ return _free_form(siblings.get('description')), seen, nullable
141
+ break
142
+ else:
143
+ return node, seen, nullable
144
+ return _free_form(node.get('description')), seen, nullable
145
+
146
+
147
+ def _client_prop_schema(
148
+ node: Any,
149
+ root: dict[str, Any] | None = None,
150
+ _seen: frozenset[str] | None = None,
151
+ ) -> dict[str, Any]:
152
+ """JSON Schema fragment safe for strict MCP clients."""
153
+ if not isinstance(node, dict):
154
+ return {'type': 'string'}
155
+ root = root or {}
156
+ node, seen, nullable = _flatten(node, root, _seen or frozenset())
157
+ out: dict[str, Any] = {}
158
+ if node.get('description'):
159
+ out['description'] = str(node['description'])
160
+ typ = node.get('type')
161
+ if isinstance(typ, list):
162
+ if 'null' in typ:
163
+ nullable = True
164
+ non_null = [t for t in typ if t != 'null']
165
+ typ = non_null[0] if non_null else None
166
+ enum = node.get('enum') if isinstance(node.get('enum'), list) else None
167
+ if enum is not None:
168
+ if None in enum:
169
+ nullable = True
170
+ enum = [v for v in enum if v is not None]
171
+ typ = typ or _enum_type(enum)
172
+ if typ in _SCALAR_TYPES:
173
+ out['type'] = [typ, 'null'] if nullable else typ
174
+ if typ == 'string' and node.get('format'):
175
+ out['format'] = str(node['format'])
176
+ if enum:
177
+ out['enum'] = enum + [None] if nullable else enum
178
+ return out
179
+ if typ == 'array':
180
+ out['type'] = ['array', 'null'] if nullable else 'array'
181
+ items = node.get('items')
182
+ out['items'] = _client_prop_schema(items if isinstance(items, dict) else {'type': 'string'}, root, seen)
183
+ return out
184
+ if typ == 'object' or isinstance(node.get('properties'), dict):
185
+ out['type'] = ['object', 'null'] if nullable else 'object'
186
+ props = node.get('properties') if isinstance(node.get('properties'), dict) else {}
187
+ out['properties'] = {str(k): _client_prop_schema(v, root, seen) for k, v in props.items()}
188
+ # Named props stay closed; empty object schemas (JSONField) stay open.
189
+ out['additionalProperties'] = bool(node.get('additionalProperties', False)) if props else True
190
+ req = node.get('required')
191
+ if isinstance(req, list):
192
+ required = [str(k) for k in req if str(k) in out['properties']]
193
+ if required:
194
+ out['required'] = required
195
+ return out
196
+ # drf-spectacular JSONField often emits ``{}`` or description-only nodes.
197
+ out['type'] = 'object'
198
+ out['additionalProperties'] = True
199
+ if not out.get('description'):
200
+ out['description'] = 'JSON value'
201
+ return out
202
+
203
+
204
+ def _parameter_schemas(
205
+ operation: dict[str, Any],
206
+ root: dict[str, Any],
207
+ *,
208
+ location: str,
209
+ ) -> tuple[dict[str, Any], list[str]]:
210
+ properties: dict[str, Any] = {}
211
+ required: list[str] = []
212
+ for param in operation.get('parameters') or []:
213
+ if not isinstance(param, dict) or param.get('in') != location:
214
+ continue
215
+ name = param.get('name')
216
+ if not name:
217
+ continue
218
+ key = str(name)
219
+ raw = param.get('schema') if isinstance(param.get('schema'), dict) else {'type': 'string'}
220
+ properties[key] = _client_prop_schema(raw if isinstance(raw, dict) else {}, root)
221
+ if param.get('required'):
222
+ required.append(key)
223
+ return properties, required
224
+
225
+
226
+ def _body_schemas(operation: dict[str, Any], root: dict[str, Any]) -> tuple[dict[str, Any], list[str]]:
227
+ request_body = operation.get('requestBody') or {}
228
+ if not isinstance(request_body, dict):
229
+ return {}, []
230
+ content = request_body.get('content') or {}
231
+ schema = content.get('application/json', {}).get('schema') or {}
232
+ if not isinstance(schema, dict):
233
+ return {}, []
234
+ resolved = _resolve_schema(schema, root)
235
+ props = resolved.get('properties') or {}
236
+ if not isinstance(props, dict):
237
+ return {}, []
238
+ properties = {str(key): _client_prop_schema(val, root) for key, val in props.items()}
239
+ required_raw = resolved.get('required') or []
240
+ required = [str(key) for key in required_raw if str(key) in properties]
241
+ return properties, required
242
+
243
+
244
+ def _slug_tool_name(method: str, path: str, operation_id: str | None) -> str:
245
+ if operation_id:
246
+ base = re.sub(r'[^a-zA-Z0-9_]+', '_', operation_id).strip('_').lower()
247
+ if base:
248
+ return base[:120]
249
+ cleaned = re.sub(r'[^a-zA-Z0-9_]+', '_', f'{method}_{path}').strip('_').lower()
250
+ return cleaned[:120]
251
+
252
+
253
+ def tools_from_schema(schema: dict[str, Any]) -> list[dict[str, Any]]:
254
+ paths = schema.get('paths') or {}
255
+ tools: list[dict[str, Any]] = []
256
+ for path, path_item in paths.items():
257
+ if not isinstance(path_item, dict):
258
+ continue
259
+ for method, operation in path_item.items():
260
+ if method.lower() not in {'get', 'post', 'put', 'patch', 'delete'}:
261
+ continue
262
+ if not isinstance(operation, dict):
263
+ continue
264
+ tags = operation.get('tags') or []
265
+ if MCP_TOOL_TAG not in tags:
266
+ continue
267
+ name = _slug_tool_name(method, path, operation.get('operationId'))
268
+ description = (operation.get('summary') or operation.get('description') or name).strip()
269
+ path_params = path_parameter_names(path)
270
+ query_props, query_required = _parameter_schemas(operation, schema, location='query')
271
+ body_props, body_required = _body_schemas(operation, schema)
272
+ properties: dict[str, Any] = {
273
+ 'path': {'type': 'string', 'const': path},
274
+ 'method': {'type': 'string', 'enum': [method.upper()]},
275
+ 'query': {
276
+ 'type': 'object',
277
+ 'additionalProperties': False,
278
+ 'properties': query_props,
279
+ },
280
+ 'body': {
281
+ 'type': 'object',
282
+ 'additionalProperties': False,
283
+ 'properties': body_props,
284
+ },
285
+ }
286
+ if query_required:
287
+ properties['query']['required'] = query_required
288
+ if body_required:
289
+ properties['body']['required'] = body_required
290
+ required = ['path', 'method']
291
+ if path_params:
292
+ properties['path_params'] = {
293
+ 'type': 'object',
294
+ 'additionalProperties': False,
295
+ 'properties': {param: {'type': 'string'} for param in path_params},
296
+ 'required': path_params,
297
+ }
298
+ required.append('path_params')
299
+ access = tool_access_flags(operation)
300
+ tools.append(
301
+ {
302
+ 'name': name,
303
+ 'description': description,
304
+ 'inputSchema': {
305
+ 'type': 'object',
306
+ 'properties': properties,
307
+ 'required': required,
308
+ 'additionalProperties': False,
309
+ },
310
+ '_meta': {
311
+ 'path': path,
312
+ 'method': method.upper(),
313
+ 'operationId': operation.get('operationId'),
314
+ 'path_params': path_params,
315
+ 'query_fields': sorted(query_props.keys()) or None,
316
+ 'query_required': query_required or None,
317
+ 'body_fields': sorted(body_props.keys()) or None,
318
+ 'body_required': body_required or None,
319
+ 'read_only': access['read_only'],
320
+ 'destructive': access['destructive'],
321
+ 'mcp_tagged': access['tagged'],
322
+ },
323
+ }
324
+ )
325
+ tools.sort(key=lambda t: t['name'])
326
+ return tools
@@ -3,9 +3,13 @@
3
3
  from __future__ import annotations
4
4
 
5
5
  import hmac
6
+ import ipaddress
6
7
  from urllib.parse import urlsplit
7
8
 
8
9
  MCP_RESOURCE_SUFFIX = '/mcp'
10
+ _LOOPBACK_HOSTS = frozenset({'127.0.0.1', 'localhost', '::1'})
11
+ # RFC 6598 shared space (Tailscale etc.). Not ``is_private`` on modern Python.
12
+ _CGNAT_SHARED = ipaddress.ip_network('100.64.0.0/10')
9
13
 
10
14
 
11
15
  def mcp_resource_from_origin(origin: str) -> str:
@@ -16,10 +20,22 @@ def mcp_resource_from_origin(origin: str) -> str:
16
20
  return f'{base}{MCP_RESOURCE_SUFFIX}'
17
21
 
18
22
 
23
+ def _http_dev_host_allowed(host: str | None) -> bool:
24
+ """Loopback names/IPs and private/CGNAT IP literals (LAN / Tailscale)."""
25
+ h = (host or '').lower()
26
+ if h in _LOOPBACK_HOSTS:
27
+ return True
28
+ try:
29
+ ip = ipaddress.ip_address(h)
30
+ except ValueError:
31
+ return False
32
+ return bool(ip.is_loopback or ip.is_private or ip.is_link_local or ip in _CGNAT_SHARED)
33
+
34
+
19
35
  def normalize_resource_indicator(raw: str | None) -> str | None:
20
36
  """
21
37
  Canonical resource URL for authorize/token/refresh ``resource`` parameter.
22
- Must be absolute https (or http loopback) ending in ``/mcp`` with no fragment.
38
+ Must be absolute https (or http on loopback/private IP) ending in ``/mcp`` with no fragment.
23
39
  """
24
40
  s = str(raw or '').strip()
25
41
  if not s or '#' in s:
@@ -38,8 +54,7 @@ def normalize_resource_indicator(raw: str | None) -> str | None:
38
54
  return None
39
55
  if parsed.query or parsed.fragment:
40
56
  return None
41
- host = (parsed.hostname or '').lower()
42
- if parsed.scheme == 'http' and host not in ('127.0.0.1', 'localhost', '::1'):
57
+ if parsed.scheme == 'http' and not _http_dev_host_allowed(parsed.hostname):
43
58
  return None
44
59
  return s
45
60
 
@@ -0,0 +1,207 @@
1
+ from django.test import SimpleTestCase
2
+
3
+ from shellui_django.mcp.openapi_tools import tools_from_schema
4
+
5
+
6
+ class OpenApiToolsPathParamTests(SimpleTestCase):
7
+ def test_path_params_required_in_input_schema(self):
8
+ schema = {
9
+ 'paths': {
10
+ '/api/v1/companies/{company_id}/widgets/': {
11
+ 'get': {
12
+ 'tags': ['mcp-tools'],
13
+ 'operationId': 'list_widgets',
14
+ 'parameters': [
15
+ {
16
+ 'in': 'query',
17
+ 'name': 'limit',
18
+ 'required': True,
19
+ 'schema': {'type': 'integer'},
20
+ }
21
+ ],
22
+ },
23
+ },
24
+ },
25
+ }
26
+ tools = tools_from_schema(schema)
27
+ self.assertEqual(len(tools), 1)
28
+ tool = tools[0]
29
+ self.assertIn('path_params', tool['inputSchema']['properties'])
30
+ self.assertIn('path_params', tool['inputSchema']['required'])
31
+ self.assertEqual(tool['_meta']['path_params'], ['company_id'])
32
+ self.assertEqual(tool['_meta']['query_fields'], ['limit'])
33
+ self.assertEqual(
34
+ tool['inputSchema']['properties']['query']['properties']['limit']['type'],
35
+ 'integer',
36
+ )
37
+
38
+
39
+ class OpenApiToolsBodyRefTests(SimpleTestCase):
40
+ def test_request_body_ref_exposes_typed_fields(self):
41
+ schema = {
42
+ 'components': {
43
+ 'schemas': {
44
+ 'TemplateVersionCreateRequest': {
45
+ 'type': 'object',
46
+ 'properties': {
47
+ 'subject': {'type': 'string'},
48
+ 'preheader': {'type': 'string'},
49
+ 'document': {},
50
+ 'translations': {'description': 'Other languages'},
51
+ 'theme': {'description': 'Theme map'},
52
+ 'library_id': {'type': 'integer'},
53
+ },
54
+ },
55
+ },
56
+ },
57
+ 'paths': {
58
+ '/api/v1/templates/{template_id}/versions': {
59
+ 'post': {
60
+ 'tags': ['mcp-tools'],
61
+ 'operationId': 'api_v1_template_versions_create',
62
+ 'summary': 'Create a draft template version',
63
+ 'requestBody': {
64
+ 'content': {
65
+ 'application/json': {
66
+ 'schema': {
67
+ '$ref': '#/components/schemas/TemplateVersionCreateRequest',
68
+ }
69
+ }
70
+ }
71
+ },
72
+ },
73
+ },
74
+ },
75
+ }
76
+ tools = tools_from_schema(schema)
77
+ self.assertEqual(len(tools), 1)
78
+ tool = tools[0]
79
+ body = tool['inputSchema']['properties']['body']
80
+ self.assertEqual(
81
+ set(body['properties']),
82
+ {'subject', 'preheader', 'document', 'translations', 'theme', 'library_id'},
83
+ )
84
+ self.assertEqual(body['properties']['subject']['type'], 'string')
85
+ self.assertEqual(body['properties']['library_id']['type'], 'integer')
86
+ self.assertEqual(body['properties']['document']['type'], 'object')
87
+ self.assertTrue(body['properties']['document']['additionalProperties'])
88
+ self.assertEqual(body['properties']['theme']['type'], 'object')
89
+ self.assertTrue(body['properties']['theme']['additionalProperties'])
90
+ self.assertEqual(
91
+ tool['_meta']['body_fields'],
92
+ ['document', 'library_id', 'preheader', 'subject', 'theme', 'translations'],
93
+ )
94
+
95
+ def test_inline_body_properties_still_work(self):
96
+ schema = {
97
+ 'paths': {
98
+ '/api/v1/notes': {
99
+ 'post': {
100
+ 'tags': ['mcp-tools'],
101
+ 'operationId': 'create_note',
102
+ 'requestBody': {
103
+ 'content': {
104
+ 'application/json': {
105
+ 'schema': {
106
+ 'type': 'object',
107
+ 'properties': {'title': {'type': 'string'}},
108
+ 'required': ['title'],
109
+ }
110
+ }
111
+ }
112
+ },
113
+ },
114
+ },
115
+ },
116
+ }
117
+ tool = tools_from_schema(schema)[0]
118
+ body = tool['inputSchema']['properties']['body']
119
+ self.assertEqual(body['properties']['title']['type'], 'string')
120
+ self.assertEqual(body['required'], ['title'])
121
+ self.assertEqual(tool['_meta']['body_fields'], ['title'])
122
+
123
+
124
+ class OpenApiToolsNestedRefTests(SimpleTestCase):
125
+ def _body(self, props: dict, components: dict) -> dict:
126
+ schema = {
127
+ 'components': {
128
+ 'schemas': {
129
+ **components,
130
+ 'Req': {'type': 'object', 'properties': props},
131
+ },
132
+ },
133
+ 'paths': {
134
+ '/api/v1/things': {
135
+ 'post': {
136
+ 'tags': ['mcp-tools'],
137
+ 'operationId': 'create_thing',
138
+ 'requestBody': {
139
+ 'content': {
140
+ 'application/json': {
141
+ 'schema': {'$ref': '#/components/schemas/Req'},
142
+ }
143
+ }
144
+ },
145
+ },
146
+ },
147
+ },
148
+ }
149
+ return tools_from_schema(schema)[0]['inputSchema']['properties']['body']['properties']
150
+
151
+ def test_enum_ref_and_all_of_stay_strings(self):
152
+ components = {'StatusEnum': {'type': 'string', 'enum': ['draft', 'live']}}
153
+ body = self._body(
154
+ {
155
+ 'status': {'$ref': '#/components/schemas/StatusEnum'},
156
+ 'status_wrapped': {'allOf': [{'$ref': '#/components/schemas/StatusEnum'}]},
157
+ },
158
+ components,
159
+ )
160
+ for key in ('status', 'status_wrapped'):
161
+ self.assertEqual(body[key]['type'], 'string')
162
+ self.assertEqual(body[key]['enum'], ['draft', 'live'])
163
+
164
+ def test_nullable_blank_enum_one_of(self):
165
+ components = {
166
+ 'StatusEnum': {'type': 'string', 'enum': ['draft', 'live']},
167
+ 'BlankEnum': {'enum': ['']},
168
+ 'NullEnum': {'enum': [None]},
169
+ }
170
+ body = self._body(
171
+ {
172
+ 'status': {
173
+ 'oneOf': [
174
+ {'$ref': '#/components/schemas/StatusEnum'},
175
+ {'$ref': '#/components/schemas/BlankEnum'},
176
+ {'$ref': '#/components/schemas/NullEnum'},
177
+ ]
178
+ },
179
+ 'name': {'type': 'string', 'nullable': True},
180
+ },
181
+ components,
182
+ )
183
+ self.assertEqual(body['status']['type'], ['string', 'null'])
184
+ self.assertEqual(body['status']['enum'], ['draft', 'live', '', None])
185
+ self.assertEqual(body['name']['type'], ['string', 'null'])
186
+
187
+ def test_nested_serializer_ref_is_typed_object(self):
188
+ components = {
189
+ 'Child': {
190
+ 'type': 'object',
191
+ 'properties': {'x': {'type': 'integer'}, 'parent': {'$ref': '#/components/schemas/Child'}},
192
+ 'required': ['x'],
193
+ },
194
+ }
195
+ body = self._body(
196
+ {
197
+ 'child': {'$ref': '#/components/schemas/Child'},
198
+ 'children': {'type': 'array', 'items': {'$ref': '#/components/schemas/Child'}},
199
+ },
200
+ components,
201
+ )
202
+ self.assertEqual(body['child']['type'], 'object')
203
+ self.assertEqual(body['child']['properties']['x']['type'], 'integer')
204
+ self.assertEqual(body['child']['required'], ['x'])
205
+ # Self-reference stops instead of recursing forever.
206
+ self.assertTrue(body['child']['properties']['parent']['additionalProperties'])
207
+ self.assertEqual(body['children']['items']['properties']['x']['type'], 'integer')
@@ -17,6 +17,19 @@ class McpResourceTests(SimpleTestCase):
17
17
  'https://auth.example.com/mcp',
18
18
  )
19
19
  self.assertIsNone(normalize_resource_indicator('https://auth.example.com/other'))
20
+ self.assertEqual(
21
+ normalize_resource_indicator('http://127.0.0.1:8000/mcp'),
22
+ 'http://127.0.0.1:8000/mcp',
23
+ )
24
+ self.assertEqual(
25
+ normalize_resource_indicator('http://100.127.19.94:8001/mcp'),
26
+ 'http://100.127.19.94:8001/mcp',
27
+ )
28
+ self.assertEqual(
29
+ normalize_resource_indicator('http://192.168.1.10:8001/mcp'),
30
+ 'http://192.168.1.10:8001/mcp',
31
+ )
32
+ self.assertIsNone(normalize_resource_indicator('http://evil.example.com/mcp'))
20
33
 
21
34
  def test_audience_match(self):
22
35
  payload = {'aud': 'https://auth.example.com/mcp'}
@@ -1,120 +0,0 @@
1
- """Build MCP tool definitions from a drf-spectacular OpenAPI schema."""
2
-
3
- from __future__ import annotations
4
-
5
- import re
6
- from typing import Any
7
-
8
- from shellui_django.mcp.openapi_mcp import tool_access_flags
9
- from shellui_django.mcp.routing import path_parameter_names
10
-
11
- MCP_TOOL_TAG = 'mcp-tools'
12
-
13
-
14
- def _parameter_field_names(operation: dict[str, Any], *, location: str) -> tuple[list[str], list[str]]:
15
- names: list[str] = []
16
- required: list[str] = []
17
- for param in operation.get('parameters') or []:
18
- if not isinstance(param, dict) or param.get('in') != location:
19
- continue
20
- name = param.get('name')
21
- if not name:
22
- continue
23
- names.append(str(name))
24
- if param.get('required'):
25
- required.append(str(name))
26
- return names, required
27
-
28
-
29
- def _body_field_names(operation: dict[str, Any]) -> tuple[list[str], list[str]]:
30
- request_body = operation.get('requestBody') or {}
31
- if not isinstance(request_body, dict):
32
- return [], []
33
- content = request_body.get('content') or {}
34
- schema = content.get('application/json', {}).get('schema') or {}
35
- if not isinstance(schema, dict):
36
- return [], []
37
- props = schema.get('properties') or {}
38
- if not isinstance(props, dict):
39
- return [], []
40
- names = [str(key) for key in props.keys()]
41
- required_raw = schema.get('required') or []
42
- required = [str(key) for key in required_raw if str(key) in names]
43
- return names, required
44
-
45
-
46
- def _slug_tool_name(method: str, path: str, operation_id: str | None) -> str:
47
- if operation_id:
48
- base = re.sub(r'[^a-zA-Z0-9_]+', '_', operation_id).strip('_').lower()
49
- if base:
50
- return base[:120]
51
- cleaned = re.sub(r'[^a-zA-Z0-9_]+', '_', f'{method}_{path}').strip('_').lower()
52
- return cleaned[:120]
53
-
54
-
55
- def tools_from_schema(schema: dict[str, Any]) -> list[dict[str, Any]]:
56
- paths = schema.get('paths') or {}
57
- tools: list[dict[str, Any]] = []
58
- for path, path_item in paths.items():
59
- if not isinstance(path_item, dict):
60
- continue
61
- for method, operation in path_item.items():
62
- if method.lower() not in {'get', 'post', 'put', 'patch', 'delete'}:
63
- continue
64
- if not isinstance(operation, dict):
65
- continue
66
- tags = operation.get('tags') or []
67
- if MCP_TOOL_TAG not in tags:
68
- continue
69
- name = _slug_tool_name(method, path, operation.get('operationId'))
70
- description = (operation.get('summary') or operation.get('description') or name).strip()
71
- path_params = path_parameter_names(path)
72
- query_fields, query_required = _parameter_field_names(operation, location='query')
73
- body_fields, body_required = _body_field_names(operation)
74
- properties: dict[str, Any] = {
75
- 'path': {'type': 'string', 'const': path},
76
- 'method': {'type': 'string', 'enum': [method.upper()]},
77
- 'query': {'type': 'object', 'additionalProperties': False, 'properties': {}},
78
- 'body': {'type': 'object', 'additionalProperties': False, 'properties': {}},
79
- }
80
- required = ['path', 'method']
81
- if path_params:
82
- properties['path_params'] = {
83
- 'type': 'object',
84
- 'additionalProperties': False,
85
- 'properties': {param: {'type': 'string'} for param in path_params},
86
- 'required': path_params,
87
- }
88
- required.append('path_params')
89
- if query_fields:
90
- properties['query']['properties'] = {field: {} for field in query_fields}
91
- if body_fields:
92
- properties['body']['properties'] = {field: {} for field in body_fields}
93
- access = tool_access_flags(operation)
94
- tools.append(
95
- {
96
- 'name': name,
97
- 'description': description,
98
- 'inputSchema': {
99
- 'type': 'object',
100
- 'properties': properties,
101
- 'required': required,
102
- 'additionalProperties': False,
103
- },
104
- '_meta': {
105
- 'path': path,
106
- 'method': method.upper(),
107
- 'operationId': operation.get('operationId'),
108
- 'path_params': path_params,
109
- 'query_fields': query_fields or None,
110
- 'query_required': query_required or None,
111
- 'body_fields': body_fields or None,
112
- 'body_required': body_required or None,
113
- 'read_only': access['read_only'],
114
- 'destructive': access['destructive'],
115
- 'mcp_tagged': access['tagged'],
116
- },
117
- }
118
- )
119
- tools.sort(key=lambda t: t['name'])
120
- return tools
@@ -1,25 +0,0 @@
1
- from django.test import SimpleTestCase
2
-
3
- from shellui_django.mcp.openapi_tools import tools_from_schema
4
-
5
-
6
- class OpenApiToolsPathParamTests(SimpleTestCase):
7
- def test_path_params_required_in_input_schema(self):
8
- schema = {
9
- 'paths': {
10
- '/api/v1/companies/{company_id}/widgets/': {
11
- 'get': {
12
- 'tags': ['mcp-tools'],
13
- 'operationId': 'list_widgets',
14
- 'parameters': [{'in': 'query', 'name': 'limit', 'required': True, 'schema': {'type': 'integer'}}],
15
- },
16
- },
17
- },
18
- }
19
- tools = tools_from_schema(schema)
20
- self.assertEqual(len(tools), 1)
21
- tool = tools[0]
22
- self.assertIn('path_params', tool['inputSchema']['properties'])
23
- self.assertIn('path_params', tool['inputSchema']['required'])
24
- self.assertEqual(tool['_meta']['path_params'], ['company_id'])
25
- self.assertEqual(tool['_meta']['query_fields'], ['limit'])
File without changes
File without changes