shellui-django 0.5.0__tar.gz → 0.6.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 (43) hide show
  1. {shellui_django-0.5.0 → shellui_django-0.6.0}/CHANGELOG.md +48 -0
  2. {shellui_django-0.5.0 → shellui_django-0.6.0}/PKG-INFO +1 -1
  3. {shellui_django-0.5.0 → shellui_django-0.6.0}/pyproject.toml +1 -1
  4. {shellui_django-0.5.0 → shellui_django-0.6.0}/src/shellui_django/__init__.py +1 -1
  5. {shellui_django-0.5.0 → shellui_django-0.6.0}/src/shellui_django/mcp/gateway.py +22 -22
  6. {shellui_django-0.5.0 → shellui_django-0.6.0}/src/shellui_django/mcp/identity_jwks.py +74 -5
  7. {shellui_django-0.5.0 → shellui_django-0.6.0}/src/shellui_django/mcp/internal.py +2 -1
  8. shellui_django-0.6.0/src/shellui_django/mcp/openapi_tools.py +326 -0
  9. {shellui_django-0.5.0 → shellui_django-0.6.0}/src/shellui_django/mcp/resources.py +18 -3
  10. {shellui_django-0.5.0 → shellui_django-0.6.0}/src/shellui_django/mcp/routing.py +57 -1
  11. {shellui_django-0.5.0 → shellui_django-0.6.0}/src/shellui_django/mcp/server.py +176 -24
  12. {shellui_django-0.5.0 → shellui_django-0.6.0}/src/shellui_django/mcp/tests/mcp_routing_urlconf.py +11 -2
  13. {shellui_django-0.5.0 → shellui_django-0.6.0}/src/shellui_django/mcp/tests/rs256_helpers.py +27 -0
  14. {shellui_django-0.5.0 → shellui_django-0.6.0}/src/shellui_django/mcp/tests/test_gateway.py +74 -43
  15. shellui_django-0.6.0/src/shellui_django/mcp/tests/test_identity_jwks_fetch.py +110 -0
  16. {shellui_django-0.5.0 → shellui_django-0.6.0}/src/shellui_django/mcp/tests/test_internal_assertions.py +20 -0
  17. shellui_django-0.6.0/src/shellui_django/mcp/tests/test_openapi_tools.py +207 -0
  18. {shellui_django-0.5.0 → shellui_django-0.6.0}/src/shellui_django/mcp/tests/test_resources.py +13 -0
  19. {shellui_django-0.5.0 → shellui_django-0.6.0}/src/shellui_django/mcp/tests/test_routing.py +28 -1
  20. shellui_django-0.6.0/src/shellui_django/mcp/tests/test_server_hardening.py +257 -0
  21. {shellui_django-0.5.0 → shellui_django-0.6.0}/src/shellui_django/mcp/tests/test_server_routing.py +31 -7
  22. shellui_django-0.5.0/src/shellui_django/mcp/openapi_tools.py +0 -120
  23. shellui_django-0.5.0/src/shellui_django/mcp/tests/test_openapi_tools.py +0 -25
  24. {shellui_django-0.5.0 → shellui_django-0.6.0}/.gitignore +0 -0
  25. {shellui_django-0.5.0 → shellui_django-0.6.0}/LICENSE +0 -0
  26. {shellui_django-0.5.0 → shellui_django-0.6.0}/README.md +0 -0
  27. {shellui_django-0.5.0 → shellui_django-0.6.0}/SECURITY.md +0 -0
  28. {shellui_django-0.5.0 → shellui_django-0.6.0}/src/shellui_django/mcp/__init__.py +0 -0
  29. {shellui_django-0.5.0 → shellui_django-0.6.0}/src/shellui_django/mcp/decorators.py +0 -0
  30. {shellui_django-0.5.0 → shellui_django-0.6.0}/src/shellui_django/mcp/delegation.py +0 -0
  31. {shellui_django-0.5.0 → shellui_django-0.6.0}/src/shellui_django/mcp/masking.py +0 -0
  32. {shellui_django-0.5.0 → shellui_django-0.6.0}/src/shellui_django/mcp/openapi_mcp.py +0 -0
  33. {shellui_django-0.5.0 → shellui_django-0.6.0}/src/shellui_django/mcp/rate_limit.py +0 -0
  34. {shellui_django-0.5.0 → shellui_django-0.6.0}/src/shellui_django/mcp/tests/__init__.py +0 -0
  35. {shellui_django-0.5.0 → shellui_django-0.6.0}/src/shellui_django/mcp/tests/test_approval_authority.py +0 -0
  36. {shellui_django-0.5.0 → shellui_django-0.6.0}/src/shellui_django/mcp/tests/test_delegation.py +0 -0
  37. {shellui_django-0.5.0 → shellui_django-0.6.0}/src/shellui_django/mcp/tests/test_identity_jwks_decode.py +0 -0
  38. {shellui_django-0.5.0 → shellui_django-0.6.0}/src/shellui_django/mcp/tests/test_internal_revocation.py +0 -0
  39. {shellui_django-0.5.0 → shellui_django-0.6.0}/src/shellui_django/mcp/tests/test_masking.py +0 -0
  40. {shellui_django-0.5.0 → shellui_django-0.6.0}/src/shellui_django/mcp/tests/test_package.py +0 -0
  41. {shellui_django-0.5.0 → shellui_django-0.6.0}/src/shellui_django/mcp/tests/test_write_gate_mcp.py +0 -0
  42. {shellui_django-0.5.0 → shellui_django-0.6.0}/src/shellui_django/mcp/write_gate.py +0 -0
  43. {shellui_django-0.5.0 → shellui_django-0.6.0}/src/shellui_django/testing/__init__.py +0 -0
@@ -23,6 +23,54 @@ 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.6.0] - 2026-11-21
27
+
28
+ Breaking: services must pass the new `McpServer` settings listed under Changed before upgrading.
29
+
30
+ ### 🛠 Improvements
31
+
32
+ - MCP `tools/call` checks tenant fields (`company_id`, `companyId`, `company-id`) in tool arguments, including nested objects, against the verified token `company_id`. The aggregating gateway applies the same check before it forwards a call. `0` is a real company id.
33
+ - `McpServer.handle` verifies the bearer token (RS256, `identity_issuer`, `mcp_audience`, JWKS) and authenticates the inner view with those claims.
34
+ - `identity_revocation_check` runs on every request. A missing hook, or a hook that raises, is rejected with HTTP 403 `revocation_unavailable`.
35
+ - Identity JWKS fetch uses the configured URL only: redirects are not followed, `https` is required unless Django `DEBUG` is true, other schemes are rejected, the body is capped at 256 KiB, and the timeout must be positive (default 10 seconds).
36
+ - Internal assertion verification requires `target` to equal `expected_target`. An empty or missing `target` does not match.
37
+ - `mcp_gateway_delegated` skips a second approval only for the tool named in `action` while `exp` is still in the future.
38
+
39
+ ### 🚨 Changed
40
+
41
+ - `McpServer` needs `identity_issuer`, `mcp_audience`, and `identity_jwks` or `identity_jwks_url`, plus `identity_revocation_check`. `handle` does not authorize from the `agent_claims` argument. Inner `request.user` is the verified agent principal, and `request.auth` is the verified claims.
42
+ - `mcp_gateway_delegated` must be an object `{"action": "<tool name>", "exp": <unix seconds>}`. A boolean value does not skip approval.
43
+ - JWKS clients that used plain `http` while `DEBUG` is false, or that followed a redirect, now get an error from `get_jwks_document`.
44
+
45
+ ### 🏗 Chore
46
+
47
+ - PyPI publishing checks that the release tag matches the package version before upload.
48
+
49
+ ## [0.5.3] - 2026-11-11
50
+
51
+ ### 🐛 Bug Fixes
52
+
53
+ - MCP `tools/call`: honor `mcp_gateway_delegated` on agent tokens so downstream services do not open a second human approval after the AI company gateway already approved and consumed the grant.
54
+
55
+ ## [0.5.2] - 2026-11-11
56
+
57
+ ### 🐛 Bug Fixes
58
+
59
+ - MCP `tools/list`: keep registry `_meta` (path, method, read_only, destructive) on the wire. Services publish flat agent schemas without transport arguments; the AI gateway needs `_meta` to route `tools/call`. Other private `_` keys are still stripped.
60
+ - MCP argument validation: ignore DRF `format` query noise so legacy nested `tools/call` envelopes from older MCP clients do not fail with `Unexpected query fields: format`.
61
+
62
+ ## [0.5.1] - 2026-11-09
63
+
64
+ ### 🐛 Bug Fixes
65
+
66
+ - 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.
67
+ - `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`).
68
+ - `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`.
69
+
70
+ ### 📚 Documentation
71
+
72
+ - Document private/CGNAT `http` resource URLs and `$ref` body expansion for MCP tools.
73
+
26
74
  ## [0.5.0] - 2026-11-06
27
75
 
28
76
  ### 🛠 Improvements
@@ -1,6 +1,6 @@
1
1
  Metadata-Version: 2.5
2
2
  Name: shellui-django
3
- Version: 0.5.0
3
+ Version: 0.6.0
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.6.0"
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.6.0'
@@ -13,7 +13,7 @@ from django.core.cache import cache as django_cache
13
13
  from django.http import HttpRequest, JsonResponse
14
14
 
15
15
  from shellui_django.mcp.openapi_tools import tools_from_schema
16
- from shellui_django.mcp.rate_limit import check_agent_rate_limit
16
+ from shellui_django.mcp.routing import tool_arguments_match_company
17
17
  from shellui_django.mcp.server import McpServer
18
18
 
19
19
  logger = logging.getLogger(__name__)
@@ -42,11 +42,20 @@ def service_allowed(agent_services: list[str] | None, service_id: str) -> bool:
42
42
 
43
43
 
44
44
  def public_mcp_tools(raw: list[dict[str, Any]]) -> list[dict[str, Any]]:
45
+ """Strip private ``_`` keys from tools/list rows, but keep registry ``_meta``.
46
+
47
+ Downstream services publish flat agent schemas without ``method``/``path``
48
+ arguments. Gateways need ``_meta.path`` / ``_meta.method`` to route calls.
49
+ """
45
50
  out: list[dict[str, Any]] = []
46
51
  for tool in raw:
47
52
  if not isinstance(tool, dict):
48
53
  continue
49
- out.append({k: v for k, v in tool.items() if not str(k).startswith('_')})
54
+ row = {k: v for k, v in tool.items() if not str(k).startswith('_')}
55
+ meta = tool.get('_meta')
56
+ if isinstance(meta, dict):
57
+ row['_meta'] = meta
58
+ out.append(row)
50
59
  return out
51
60
 
52
61
 
@@ -178,25 +187,12 @@ class AggregatingMcpServer(McpServer):
178
187
  self._cache().set(cache_key, public, self._gateway.tools_cache_ttl_seconds)
179
188
  return public
180
189
 
181
- def handle(self, request: HttpRequest, *, agent_claims: dict[str, Any] | None) -> JsonResponse:
182
- if request.method != 'POST':
183
- return JsonResponse({'error': 'method_not_allowed'}, status=405)
184
- if agent_claims is None:
185
- return JsonResponse({'error': 'unauthorized'}, status=401)
186
- agent_id = str(agent_claims.get('agent_id') or '')
187
- if not agent_id:
188
- return JsonResponse({'error': 'unauthorized'}, status=401)
189
- if check_agent_rate_limit(agent_id):
190
- return JsonResponse({'error': 'rate_limited'}, status=429)
191
- company_id = agent_claims.get('company_id')
192
- try:
193
- company_id_int = int(company_id) if company_id is not None else None
194
- except (TypeError, ValueError):
195
- company_id_int = None
196
- if self.identity_revocation_check and self.identity_revocation_check(agent_id, company_id_int):
197
- return JsonResponse({'error': 'agent_revoked'}, status=403)
198
- if not self._service_allowed(agent_claims, self.service_name):
199
- return JsonResponse({'error': 'forbidden'}, status=403)
190
+ def handle(self, request: HttpRequest, *, agent_claims: dict[str, Any] | None = None) -> JsonResponse:
191
+ del agent_claims
192
+ prepared = self._prepare(request)
193
+ if isinstance(prepared, JsonResponse):
194
+ return prepared
195
+ agent_claims = prepared
200
196
  try:
201
197
  payload = json.loads(request.body.decode('utf-8') or '{}')
202
198
  except json.JSONDecodeError:
@@ -228,7 +224,7 @@ class AggregatingMcpServer(McpServer):
228
224
  forwarded = self._maybe_forward_tool_call(request, req_id, params, agent_claims)
229
225
  if forwarded is not None:
230
226
  return forwarded
231
- return super().handle(request, agent_claims=agent_claims)
227
+ return self._handle_prepared(request, agent_claims)
232
228
 
233
229
  def _aggregated_tools_list(self, req_id: Any, agent_claims: dict[str, Any]) -> JsonResponse:
234
230
  agent = self._gateway.resolve_agent(agent_claims)
@@ -272,6 +268,10 @@ class AggregatingMcpServer(McpServer):
272
268
  tool_name = str(params.get('name') or '')
273
269
  if not tool_name:
274
270
  return None
271
+ company_raw = agent_claims.get('company_id')
272
+ company_id = company_raw if isinstance(company_raw, int) and not isinstance(company_raw, bool) else None
273
+ if not tool_arguments_match_company(params.get('arguments'), company_id):
274
+ return JsonResponse(self._error(req_id, -32602, 'company_id does not match the authenticated company'))
275
275
  route = self._lookup_route(tool_name)
276
276
  local_id = self._gateway.local_service_id
277
277
  if route is None:
@@ -8,6 +8,7 @@ import time
8
8
  import urllib.error
9
9
  import urllib.request
10
10
  from typing import Any
11
+ from urllib.parse import urlsplit
11
12
 
12
13
  import jwt
13
14
  from jwt.algorithms import RSAAlgorithm
@@ -15,6 +16,8 @@ from jwt.algorithms import RSAAlgorithm
15
16
  _CACHE_TTL_SECONDS = 300
16
17
  # Match ``INTERNAL_ASSERTION_LEEWAY_SECONDS`` in ``internal`` for Identity JWT verification.
17
18
  IDENTITY_RS256_LEEWAY_SECONDS = 5
19
+ JWKS_MAX_RESPONSE_BYTES = 256 * 1024
20
+ _DEFAULT_JWKS_TIMEOUT_SECONDS = 10.0
18
21
  _cache_lock = threading.Lock()
19
22
  _jwks_cache: dict[str, tuple[float, dict[str, Any]]] = {}
20
23
 
@@ -51,13 +54,79 @@ def identity_jwks_url_for_issuer(issuer: str) -> str:
51
54
  return f'{base}/.well-known/jwks.json'
52
55
 
53
56
 
57
+ def _allow_insecure_jwks_url() -> bool:
58
+ """``http`` JWKS URLs are accepted only when Django ``DEBUG`` is on."""
59
+ try:
60
+ from django.conf import settings
61
+
62
+ return bool(settings.DEBUG)
63
+ except Exception:
64
+ return False
65
+
66
+
67
+ def _validated_jwks_url(url: str) -> str:
68
+ """Return ``url`` when it is the exact document to fetch."""
69
+ raw = (url or '').strip()
70
+ if not raw or any(char in raw for char in ('\r', '\n', '\t', ' ')):
71
+ raise IdentityJwksError('Identity JWKS URL is invalid.')
72
+ parsed = urlsplit(raw)
73
+ if parsed.username or parsed.password or parsed.fragment:
74
+ raise IdentityJwksError('Identity JWKS URL is invalid.')
75
+ if not parsed.hostname or not parsed.netloc:
76
+ raise IdentityJwksError('Identity JWKS URL is invalid.')
77
+ if parsed.scheme == 'https':
78
+ return raw
79
+ if parsed.scheme == 'http' and _allow_insecure_jwks_url():
80
+ return raw
81
+ if parsed.scheme == 'http':
82
+ raise IdentityJwksError('Identity JWKS URL must use https.')
83
+ raise IdentityJwksError('Identity JWKS URL is invalid.')
84
+
85
+
86
+ def _positive_timeout(timeout: float) -> float:
87
+ if isinstance(timeout, bool) or not isinstance(timeout, (int, float)):
88
+ raise IdentityJwksError('Identity JWKS timeout is required.')
89
+ if timeout <= 0:
90
+ raise IdentityJwksError('Identity JWKS timeout is required.')
91
+ return float(timeout)
92
+
93
+
94
+ def _jwks_opener() -> urllib.request.OpenerDirector:
95
+ """HTTP(S) opener that does not follow redirects or local URL schemes."""
96
+ opener = urllib.request.OpenerDirector()
97
+ opener.add_handler(urllib.request.HTTPHandler())
98
+ opener.add_handler(urllib.request.HTTPSHandler())
99
+ opener.add_handler(urllib.request.HTTPErrorProcessor())
100
+ opener.add_handler(urllib.request.HTTPDefaultErrorHandler())
101
+ return opener
102
+
103
+
54
104
  def _fetch_jwks_document(url: str, *, timeout: float) -> dict[str, Any]:
55
- request = urllib.request.Request(url, headers={'Accept': 'application/json'})
105
+ fetch_url = _validated_jwks_url(url)
106
+ timeout_s = _positive_timeout(timeout)
107
+ request = urllib.request.Request(fetch_url, headers={'Accept': 'application/json'})
56
108
  try:
57
- with urllib.request.urlopen(request, timeout=timeout) as response:
58
- raw = response.read()
59
- except (urllib.error.URLError, TimeoutError) as exc:
109
+ response = _jwks_opener().open(request, timeout=timeout_s)
110
+ except urllib.error.HTTPError as exc:
111
+ if 300 <= int(getattr(exc, 'code', 0) or 0) < 400:
112
+ raise IdentityJwksError('Identity JWKS redirects are not allowed.') from exc
113
+ raise IdentityJwksError('Failed to fetch Identity JWKS.') from exc
114
+ except (urllib.error.URLError, TimeoutError, OSError) as exc:
60
115
  raise IdentityJwksError('Failed to fetch Identity JWKS.') from exc
116
+ with response:
117
+ final_url = response.geturl()
118
+ if urlsplit(final_url) != urlsplit(fetch_url):
119
+ raise IdentityJwksError('Identity JWKS redirects are not allowed.')
120
+ declared = response.headers.get('Content-Length')
121
+ if declared is not None:
122
+ try:
123
+ if int(declared) > JWKS_MAX_RESPONSE_BYTES:
124
+ raise IdentityJwksError('Identity JWKS response is too large.')
125
+ except ValueError as exc:
126
+ raise IdentityJwksError('Identity JWKS response is too large.') from exc
127
+ raw = response.read(JWKS_MAX_RESPONSE_BYTES + 1)
128
+ if len(raw) > JWKS_MAX_RESPONSE_BYTES:
129
+ raise IdentityJwksError('Identity JWKS response is too large.')
61
130
  try:
62
131
  document = json.loads(raw.decode('utf-8'))
63
132
  except (UnicodeDecodeError, json.JSONDecodeError) as exc:
@@ -67,7 +136,7 @@ def _fetch_jwks_document(url: str, *, timeout: float) -> dict[str, Any]:
67
136
  return document
68
137
 
69
138
 
70
- def get_jwks_document(*, jwks_url: str | None = None, jwks: dict[str, Any] | None = None, timeout: float = 10.0) -> dict[str, Any]:
139
+ def get_jwks_document(*, jwks_url: str | None = None, jwks: dict[str, Any] | None = None, timeout: float = _DEFAULT_JWKS_TIMEOUT_SECONDS) -> dict[str, Any]:
71
140
  if jwks is not None:
72
141
  if not isinstance(jwks.get('keys'), list):
73
142
  raise IdentityJwksError('Inline JWKS document is invalid.')
@@ -515,8 +515,9 @@ def verify_rs256_mcp_assertion(
515
515
  elif str(aud or '') != expected_audience:
516
516
  raise InternalAssertionError('Assertion audience mismatch.')
517
517
  if expected_target:
518
+ expected = str(expected_target).rstrip('/')
518
519
  target = str(payload.get('target') or '').rstrip('/')
519
- if target and target != expected_target.rstrip('/'):
520
+ if not target or target != expected:
520
521
  raise InternalAssertionError('Assertion target mismatch.')
521
522
  _assert_lifetime_within_limit(payload, max_lifetime_seconds=max_lifetime_seconds)
522
523
  jti = str(payload.get('jti') or '').strip()
@@ -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