agenticdome-python-sdk 1.2.49__py3-none-any.whl → 1.2.50__py3-none-any.whl

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -1,6 +1,6 @@
1
1
  Metadata-Version: 2.4
2
2
  Name: agenticdome-python-sdk
3
- Version: 1.2.49
3
+ Version: 1.2.50
4
4
  Summary: Official Python SDK for AgenticDome security guardrails, DLP, tool authorization, and multi-agent delegation enforcement.
5
5
  Author: AgenticDome
6
6
  License-Expression: Apache-2.0
@@ -33,20 +33,20 @@ Requires-Dist: requests>=2.31.0
33
33
  Requires-Dist: urllib3>=2.0.0
34
34
  Requires-Dist: cryptography>=42.0.0
35
35
  Provides-Extra: crewai
36
- Requires-Dist: crewai<=1.15.23,>=1.15.5; extra == "crewai"
36
+ Requires-Dist: crewai<=1.15.34,>=1.15.5; extra == "crewai"
37
37
  Provides-Extra: redis
38
38
  Requires-Dist: redis>=4.5.0; extra == "redis"
39
39
  Provides-Extra: pop
40
40
  Requires-Dist: cryptography>=42.0.0; extra == "pop"
41
41
  Provides-Extra: pydanticai
42
- Requires-Dist: pydantic-ai<=2.51.0,>=2.16.0; extra == "pydanticai"
42
+ Requires-Dist: pydantic-ai<=2.64.0,>=2.16.0; extra == "pydanticai"
43
43
  Requires-Dist: anyio>=4.0.0; extra == "pydanticai"
44
44
  Provides-Extra: pydantic
45
- Requires-Dist: pydantic-ai<=2.51.0,>=2.16.0; extra == "pydantic"
45
+ Requires-Dist: pydantic-ai<=2.64.0,>=2.16.0; extra == "pydantic"
46
46
  Requires-Dist: anyio>=4.0.0; extra == "pydantic"
47
47
  Provides-Extra: langgraph
48
- Requires-Dist: langgraph<=1.2.12,>=1.2.9; extra == "langgraph"
49
- Requires-Dist: langchain-core<=1.6.6,>=1.5.0; extra == "langgraph"
48
+ Requires-Dist: langgraph<=1.2.19,>=1.2.9; extra == "langgraph"
49
+ Requires-Dist: langchain-core<=1.7.3,>=1.5.0; extra == "langgraph"
50
50
  Requires-Dist: langchain-openai==1.3.5; extra == "langgraph"
51
51
  Requires-Dist: anyio>=4.0.0; extra == "langgraph"
52
52
  Provides-Extra: microsoft
@@ -55,51 +55,55 @@ Requires-Dist: autogen-agentchat==0.7.5; extra == "autogen"
55
55
  Provides-Extra: microsoft-autogen
56
56
  Requires-Dist: autogen-agentchat==0.7.5; extra == "microsoft-autogen"
57
57
  Provides-Extra: foundry
58
- Requires-Dist: azure-ai-projects<=2.7.0,>=2.3.0; extra == "foundry"
59
- Requires-Dist: azure-identity==1.25.3; extra == "foundry"
58
+ Requires-Dist: azure-ai-projects<=2.10.0,>=2.3.0; extra == "foundry"
59
+ Requires-Dist: azure-identity<=1.27.0,>=1.25.3; extra == "foundry"
60
60
  Provides-Extra: agno
61
- Requires-Dist: agno<=3.0.11,>=2.8.0; extra == "agno"
61
+ Requires-Dist: agno<=3.1.12,>=2.8.0; extra == "agno"
62
62
  Provides-Extra: openai-agents
63
- Requires-Dist: openai-agents<=0.22.3,>=0.18.3; extra == "openai-agents"
63
+ Requires-Dist: openai-agents<=0.24.0,>=0.18.3; extra == "openai-agents"
64
64
  Provides-Extra: mcp
65
65
  Requires-Dist: mcp<=2.2.0,>=1.26.0; extra == "mcp"
66
+ Requires-Dist: jsonschema<5,>=4.23; extra == "mcp"
67
+ Requires-Dist: regex>=2024.11.6; extra == "mcp"
66
68
  Provides-Extra: bedrock
67
- Requires-Dist: boto3<=1.43.105,>=1.43.54; extra == "bedrock"
69
+ Requires-Dist: boto3<=1.43.123,>=1.43.54; extra == "bedrock"
68
70
  Provides-Extra: aws-bedrock
69
- Requires-Dist: boto3<=1.43.105,>=1.43.54; extra == "aws-bedrock"
71
+ Requires-Dist: boto3<=1.43.123,>=1.43.54; extra == "aws-bedrock"
70
72
  Provides-Extra: llamaindex
71
73
  Requires-Dist: llama-index<=0.14.25,>=0.14.23; extra == "llamaindex"
72
74
  Provides-Extra: llama-index
73
75
  Requires-Dist: llama-index<=0.14.25,>=0.14.23; extra == "llama-index"
74
76
  Provides-Extra: google-adk
75
- Requires-Dist: google-adk<=2.10.0,>=2.5.0; extra == "google-adk"
77
+ Requires-Dist: google-adk<=2.13.0,>=2.5.0; extra == "google-adk"
76
78
  Provides-Extra: adk
77
- Requires-Dist: google-adk<=2.10.0,>=2.5.0; extra == "adk"
79
+ Requires-Dist: google-adk<=2.13.0,>=2.5.0; extra == "adk"
78
80
  Provides-Extra: claude
79
- Requires-Dist: claude-agent-sdk<=0.2.162,>=0.2.126; extra == "claude"
81
+ Requires-Dist: claude-agent-sdk<=0.2.176,>=0.2.126; extra == "claude"
80
82
  Provides-Extra: claude-agent-sdk
81
- Requires-Dist: claude-agent-sdk<=0.2.162,>=0.2.126; extra == "claude-agent-sdk"
83
+ Requires-Dist: claude-agent-sdk<=0.2.176,>=0.2.126; extra == "claude-agent-sdk"
82
84
  Provides-Extra: smolagents
83
85
  Requires-Dist: smolagents==1.26.0; extra == "smolagents"
84
86
  Provides-Extra: all
85
- Requires-Dist: crewai<=1.15.23,>=1.15.5; extra == "all"
87
+ Requires-Dist: crewai<=1.15.34,>=1.15.5; extra == "all"
86
88
  Requires-Dist: redis>=4.5.0; extra == "all"
87
89
  Requires-Dist: cryptography>=42.0.0; extra == "all"
88
- Requires-Dist: pydantic-ai<=2.51.0,>=2.16.0; extra == "all"
90
+ Requires-Dist: pydantic-ai<=2.64.0,>=2.16.0; extra == "all"
89
91
  Requires-Dist: anyio>=4.0.0; extra == "all"
90
- Requires-Dist: langgraph<=1.2.12,>=1.2.9; extra == "all"
91
- Requires-Dist: langchain-core<=1.6.6,>=1.5.0; extra == "all"
92
+ Requires-Dist: langgraph<=1.2.19,>=1.2.9; extra == "all"
93
+ Requires-Dist: langchain-core<=1.7.3,>=1.5.0; extra == "all"
92
94
  Requires-Dist: langchain-openai==1.3.5; extra == "all"
93
95
  Requires-Dist: autogen-agentchat==0.7.5; extra == "all"
94
- Requires-Dist: agno<=3.0.11,>=2.8.0; extra == "all"
95
- Requires-Dist: azure-ai-projects<=2.7.0,>=2.3.0; extra == "all"
96
- Requires-Dist: azure-identity==1.25.3; extra == "all"
97
- Requires-Dist: openai-agents<=0.22.3,>=0.18.3; extra == "all"
96
+ Requires-Dist: agno<=3.1.12,>=2.8.0; extra == "all"
97
+ Requires-Dist: azure-ai-projects<=2.10.0,>=2.3.0; extra == "all"
98
+ Requires-Dist: azure-identity<=1.27.0,>=1.25.3; extra == "all"
99
+ Requires-Dist: openai-agents<=0.24.0,>=0.18.3; extra == "all"
98
100
  Requires-Dist: mcp<=2.2.0,>=1.26.0; extra == "all"
99
- Requires-Dist: boto3<=1.43.105,>=1.43.54; extra == "all"
101
+ Requires-Dist: boto3<=1.43.123,>=1.43.54; extra == "all"
102
+ Requires-Dist: jsonschema<5,>=4.23; extra == "all"
103
+ Requires-Dist: regex>=2024.11.6; extra == "all"
100
104
  Requires-Dist: llama-index<=0.14.25,>=0.14.23; extra == "all"
101
- Requires-Dist: google-adk<=2.10.0,>=2.5.0; extra == "all"
102
- Requires-Dist: claude-agent-sdk<=0.2.162,>=0.2.126; extra == "all"
105
+ Requires-Dist: google-adk<=2.13.0,>=2.5.0; extra == "all"
106
+ Requires-Dist: claude-agent-sdk<=0.2.176,>=0.2.126; extra == "all"
103
107
  Requires-Dist: smolagents==1.26.0; extra == "all"
104
108
  Provides-Extra: dev
105
109
  Requires-Dist: pytest>=8.0.0; extra == "dev"
@@ -1,5 +1,5 @@
1
- agenticdome_python_sdk-1.2.49.dist-info/licenses/LICENSE,sha256=z8d0m5b2O9McPEK1xHG_dWgUBT6EfBDz6wA0F7xSPTA,11358
2
- agenticdome_python_sdk-1.2.49.dist-info/licenses/NOTICE,sha256=obvKP6kV1Ny5R8_INFOpf0X5um9U2X43LGwQFobO9kg,550
1
+ agenticdome_python_sdk-1.2.50.dist-info/licenses/LICENSE,sha256=z8d0m5b2O9McPEK1xHG_dWgUBT6EfBDz6wA0F7xSPTA,11358
2
+ agenticdome_python_sdk-1.2.50.dist-info/licenses/NOTICE,sha256=obvKP6kV1Ny5R8_INFOpf0X5um9U2X43LGwQFobO9kg,550
3
3
  agenticdome_sdk/__init__.py,sha256=7nGHtISU9udPIEepFh2JFzZ8trV44ziv1o19RClpls0,1270
4
4
  agenticdome_sdk/_framework_firewall.py,sha256=87VViabk5bySrN36BCE_Wzooqlz653L21r6usyq_d_Q,32914
5
5
  agenticdome_sdk/_mode.py,sha256=XvOgh5sW-FG8S39V483h3uLiFh8wSt14OmYXz_6eDO8,1283
@@ -8,28 +8,30 @@ agenticdome_sdk/agno.py,sha256=L3yfjTBHW47xzT67a1DsjtwmvrAoYBkbxADpsr85Cp0,60766
8
8
  agenticdome_sdk/attestation.py,sha256=ij4cMff7nzLaIS0W02d2WURFcyKe72bcUlSz-dYkaLE,10310
9
9
  agenticdome_sdk/autogen.py,sha256=KP4qlIcsNXB-4ZT9D7Slc1xWEeWXRIWkc5HGW0U6k2c,29018
10
10
  agenticdome_sdk/aws_bedrock.py,sha256=2zD9j7xi0jna0sMeMf-hKZdc3Y4RPwzj6tMVOUGgIDQ,69581
11
- agenticdome_sdk/catalog_snapshot.json,sha256=FAyMJzT7mSreSSIm4ETCHENVKYNikHkVY47LVbvn_so,957
11
+ agenticdome_sdk/catalog_snapshot.json,sha256=txDICNBLC643wzxHDJZoAMtx1wAnjXYmGgq3Xhnxdj0,957
12
12
  agenticdome_sdk/claude.py,sha256=XeY9AUu61SYcJjQVz_AtL_WaN6X4KqP5nprEbbr4Q6A,17456
13
- agenticdome_sdk/client.py,sha256=ba9J2mtDpTtC6nejp0GpKb7V6UfUKgWCt_BySL0ua3k,87059
13
+ agenticdome_sdk/client.py,sha256=U7WJVO_3r9canagaiEpcVaYHV18l5mbhk4CF_i0A5Xc,88269
14
14
  agenticdome_sdk/connect.py,sha256=WOh9hEOEy6OmX4zrJEWZPsgYJUbl3PR03ukODe3WC4Q,18864
15
15
  agenticdome_sdk/copilot_ir.py,sha256=zT13tOX8xu11yrOtIPMRFVud8CQ81Gu3WxsXxyQ4XT0,17928
16
16
  agenticdome_sdk/copilot_ir_collector.cjs,sha256=oxLY8ByONo7Es4YjYiJuRz_A7IKL65Sy486UXnu-4Rs,9681
17
17
  agenticdome_sdk/crewai.py,sha256=sSJQ49O7-8kqOAD2_jrsMtMOmBOcJmFkeOv7S3-ayMs,52490
18
18
  agenticdome_sdk/demo.py,sha256=dyfqt2N_cJoyUWKnjPYuQxuw2hb2DrCNUf1jQKeYYoc,8350
19
+ agenticdome_sdk/docker_guard.py,sha256=ilzw-ZNE_ZL4RJ8CE8FES-ni10cwnG9Iti92x4nQaKM,5075
19
20
  agenticdome_sdk/existing_integration.py,sha256=O40rkFucrbuyQsezXhXm6txpt8T9PiXrmg4JmVSkYdw,11543
20
21
  agenticdome_sdk/framework_edits.py,sha256=4BgWHxWKEkex8_DMhjVxjovpUVkrMF7TsCZzlS94mpA,23344
21
22
  agenticdome_sdk/generic_python.py,sha256=JtXRcYEZ6_Dgxnnv4QgqeMZR8dFVr8EqFDM-XYQ-GMA,6823
22
23
  agenticdome_sdk/google_adk.py,sha256=2TA-tUhY0lOnkGcs1BN9CUEz67ebVX4HJ7mnNoRPcZs,57258
23
24
  agenticdome_sdk/guided_integration.py,sha256=4NBCacAcwEQkVct86G8NGYwrcTNT7xaxXGZ21aPaygY,52449
24
- agenticdome_sdk/hook_catalog.py,sha256=9rugYzDPBajlRtLeIZHdhcbKqLjlVmOzGnFZNIdARuE,29892
25
+ agenticdome_sdk/hook_catalog.py,sha256=rvM0mXHqID8jmDI8kI-rAqFgkRNtUlDnqYcJ8i8__uw,29905
25
26
  agenticdome_sdk/http_execution.py,sha256=85bBRxC0TBOKUaRmy4WHyyIoAub71_KkRL_--1YQrm4,3801
26
27
  agenticdome_sdk/identity.py,sha256=mrymGgZSVsKJ9THRde54qGmMT7j_uZHmPJ-HtWk7PXE,4635
27
28
  agenticdome_sdk/langgraph.py,sha256=FUvF6DSA5aZP3eoBoNeldgGtPrz-dO5xcVmrPPSBEhI,84312
28
29
  agenticdome_sdk/lifecycle.py,sha256=obRIbJ9H90TPpfa46pZRTilg9Q8nhLTP5P2bsFbChbI,15210
29
30
  agenticdome_sdk/llamaindex.py,sha256=BHplSUIsgMi7k8tBztprzaV9iaOXiljXbdeMRax_2h8,42860
30
- agenticdome_sdk/mcp_host.py,sha256=Arl5bpc0hTLy_4a33BQiWWtWNeAPh7nsRV6178h0ps0,72321
31
+ agenticdome_sdk/mcp_host.py,sha256=KCBUTZsNTQOg2GUFR1U-zD6wWgsVpWjS5uZ_4rB-wNM,76047
31
32
  agenticdome_sdk/mcp_http_gateway.py,sha256=XrTgj46ZHIKJ9xS3EQPsac2C9OGUZnrOXomcLdkMk_Y,13629
32
33
  agenticdome_sdk/mcp_rehearsal_server.py,sha256=cox4XqUTL8d0gaDzqxDZcEALkaz8otjOjOqHvoUeeCo,2118
34
+ agenticdome_sdk/mcp_schema.py,sha256=OHnh9mWtkxKjmR7OJUWuQYu35w9HYJ0W4wEIxSS22DM,12231
33
35
  agenticdome_sdk/mcp_verification.py,sha256=WtRhAFVPTBqGOcHNf_db1m4jX9_TO0oxP98XWk4_ISY,14551
34
36
  agenticdome_sdk/microsoft_agent_framework.py,sha256=GfIIuk0n-VhsZaTyoB7P6ilpz9bFLD95TWuX0rFSWeU,67219
35
37
  agenticdome_sdk/microsoft_ai_foundry.py,sha256=YlO968s1dbAYcaEqhqufL92NFR66GuTtngnCv7-1mYc,56911
@@ -43,8 +45,8 @@ agenticdome_sdk/pydantic.py,sha256=WKb8X0Fgydfid-ep8E-M8Yslz2pWcCP6w7n_aBxt1rI,5
43
45
  agenticdome_sdk/report_scope.py,sha256=Waoaal9hkZsNF5G-ifDXNO_3an0ZjQJVv6-Uzg94oOM,3575
44
46
  agenticdome_sdk/simulation.py,sha256=UCbZy3u9AzfxQCfY38SCV3CxGxhinV9EA4aHMPlK4mc,8426
45
47
  agenticdome_sdk/smolagents.py,sha256=wjMA1HVAQ-9wRNM38Jr9wlCpKMhF-9vxtTk6R-kwQhs,19094
46
- agenticdome_python_sdk-1.2.49.dist-info/METADATA,sha256=uUM70exTkl52dY9IQod2_wiR_-vrE61z4vbWADTkYKY,147841
47
- agenticdome_python_sdk-1.2.49.dist-info/WHEEL,sha256=mOdXR9C3wMVov7cSY8PY-XCzo3SmmWCHvGQr5csJoao,91
48
- agenticdome_python_sdk-1.2.49.dist-info/entry_points.txt,sha256=cRfCphkr5gLrkGIzXJEtL50HdHLajoZLbZtcMLE8NoY,113
49
- agenticdome_python_sdk-1.2.49.dist-info/top_level.txt,sha256=LZbbjXco5mqDrGwlTJpIKI5Sp6R_njzHHjExxAs9c3s,16
50
- agenticdome_python_sdk-1.2.49.dist-info/RECORD,,
48
+ agenticdome_python_sdk-1.2.50.dist-info/METADATA,sha256=q92dUdi5nTk83IrIuKbqIQH7Q3lJcFwEMpEZ4CQ1HHs,148059
49
+ agenticdome_python_sdk-1.2.50.dist-info/WHEEL,sha256=mOdXR9C3wMVov7cSY8PY-XCzo3SmmWCHvGQr5csJoao,91
50
+ agenticdome_python_sdk-1.2.50.dist-info/entry_points.txt,sha256=0ObUYdthZhY_pEr8pPH-v6IxWRjUSkgdFVyx-w6u4fc,174
51
+ agenticdome_python_sdk-1.2.50.dist-info/top_level.txt,sha256=LZbbjXco5mqDrGwlTJpIKI5Sp6R_njzHHjExxAs9c3s,16
52
+ agenticdome_python_sdk-1.2.50.dist-info/RECORD,,
@@ -1,3 +1,4 @@
1
1
  [console_scripts]
2
2
  agenticdome = agenticdome_sdk.onboarding_cli:main
3
3
  agenticdome-demo = agenticdome_sdk.demo:main
4
+ agenticdome-docker-guard = agenticdome_sdk.docker_guard:main
@@ -1,13 +1,13 @@
1
1
  {
2
2
  "schema": "agenticdome.catalog-snapshot.v1",
3
3
  "catalog_schema": "agenticdome.hook-catalog.v1",
4
- "verified_at": "2026-10-12",
5
- "python_sdk_version": "1.2.49",
4
+ "verified_at": "2026-11-02",
5
+ "python_sdk_version": "1.2.50",
6
6
  "published_packages": {
7
7
  "agenticdome-python-sdk": {
8
8
  "registry": "pypi",
9
- "version": "1.2.49",
10
- "url": "https://pypi.org/project/agenticdome-python-sdk/1.2.49/"
9
+ "version": "1.2.50",
10
+ "url": "https://pypi.org/project/agenticdome-python-sdk/1.2.50/"
11
11
  },
12
12
  "agenticdome-sdk": {
13
13
  "registry": "npm",
agenticdome_sdk/client.py CHANGED
@@ -542,6 +542,7 @@ class AgenticDomeClient:
542
542
  use_bearer: bool = False,
543
543
  extra_headers: Optional[Dict[str, str]] = None,
544
544
  timeout: Optional[Union[int, float, Tuple[float, float]]] = None,
545
+ allow_redirects: Optional[bool] = None,
545
546
  ) -> Dict[str, Any]:
546
547
  if self.is_simulation:
547
548
  return self._simulation.request(method, path, json_body)
@@ -552,16 +553,24 @@ class AgenticDomeClient:
552
553
  use_bearer=use_bearer,
553
554
  extra_headers=extra_headers,
554
555
  )
555
- headers=self._managed_headers(path,json_body,headers)
556
+ # Gateway guards already verify direct deployment/workload proofs. A
557
+ # short-lived Docker hook must not mint a token in an extra HTTP exchange
558
+ # on every call. Existing SDK endpoints keep their token lifecycle.
559
+ if path not in {"/gateway/v1/guard","/gateway/v1/guard/ready"}:
560
+ headers=self._managed_headers(path,json_body,headers)
556
561
 
562
+ request_options = {} if allow_redirects is None else {"allow_redirects": allow_redirects}
557
563
  response = self.session.request(
558
564
  method=method.upper(),
559
565
  url=url,
560
566
  headers=headers,
561
567
  json=json_body,
562
568
  timeout=self._timeout_tuple(timeout),
569
+ **request_options,
563
570
  )
564
571
 
572
+ if allow_redirects is False and 300 <= response.status_code < 400:
573
+ raise AgenticDomeHTTPError(response.status_code, "Gateway redirects are not allowed", "")
565
574
  if not response.ok:
566
575
  try:
567
576
  payload = response.json()
@@ -709,6 +718,15 @@ class AgenticDomeClient:
709
718
  # ------------------------------------------------------------------
710
719
  # REST Guardrail / Runtime
711
720
  # ------------------------------------------------------------------
721
+ def guard_native_tool(self, event: Dict[str, Any]) -> Dict[str, Any]:
722
+ """Check a Docker mandatory guard event; does not execute or cache permits."""
723
+ from .docker_guard import event_payload
724
+ return self._request("POST", "/gateway/v1/guard", json_body=event_payload(event), allow_redirects=False)
725
+
726
+ def native_guard_ready(self) -> Dict[str, Any]:
727
+ """Verify assigned Gateway/identity readiness without executing a tool."""
728
+ return self._request("GET", "/gateway/v1/guard/ready", allow_redirects=False)
729
+
712
730
  def guardrail_validate(
713
731
  self,
714
732
  *,
@@ -0,0 +1,91 @@
1
+ """Docker Agent mandatory guard adapter. JSON in/out; fail closed; never execute."""
2
+ from __future__ import annotations
3
+ import hashlib
4
+ import json
5
+ import os
6
+ import sys
7
+ from urllib.parse import urlsplit
8
+
9
+
10
+ def event_payload(event):
11
+ if not isinstance(event, dict) or event.get("hook_event_name") != "tool_guard":
12
+ raise ValueError("Expected a Docker tool_guard event")
13
+ payload = {key: event.get(key, default) for key, default in {
14
+ "hook_event_name": "", "agent_name": "", "tool_name": "", "tool_input": None,
15
+ "session_id": "", "tool_use_id": "", "tool_category": "unknown", "cwd": ""}.items()}
16
+ if not isinstance(payload["tool_input"], dict): raise ValueError("Expected tool input object")
17
+ if any(not isinstance(payload[key], str) or not payload[key] for key in ("agent_name", "tool_name", "session_id", "tool_use_id")):
18
+ raise ValueError("Incomplete tool guard identity")
19
+ raw=json.dumps(payload,allow_nan=False)
20
+ if len(raw.encode()) > 131072: raise ValueError("Tool input exceeds limit")
21
+ return json.loads(raw)
22
+
23
+
24
+ def configured_client():
25
+ from .client import AgenticDomeClient
26
+ gateway = os.environ["AGENTICDOME_GATEWAY_URL"].rstrip("/")
27
+ parsed = urlsplit(gateway)
28
+ if (parsed.path != "/gateway/v1" or parsed.query or parsed.fragment or not parsed.hostname
29
+ or parsed.username is not None or parsed.password is not None or any(ord(c)<=32 for c in gateway)):
30
+ raise ValueError("Use the assigned Gateway URL ending in /gateway/v1")
31
+ if parsed.scheme != "https" and not (parsed.scheme == "http" and parsed.hostname in {"localhost", "127.0.0.1", "::1"}):
32
+ raise ValueError("Use HTTPS or a loopback sidecar")
33
+ return AgenticDomeClient(api_base=gateway[:-len('/gateway/v1')], timeout=8, mode="live")
34
+
35
+
36
+ def check_tool(event, client=None):
37
+ payload = event_payload(event)
38
+ owned = client is None
39
+ if owned: client = configured_client()
40
+ try:
41
+ expected = hashlib.sha256(json.dumps(payload, sort_keys=True, separators=(",", ":"), ensure_ascii=False).encode()).hexdigest()
42
+ result = client.guard_native_tool(payload)
43
+ if (not isinstance(result, dict) or result.get("schema") != "agenticdome.native-tool-decision.v1"
44
+ or result.get("request_sha256") != expected or result.get("decision") not in {"allow", "deny"}
45
+ or not isinstance(result.get("decision_id"), str) or not result["decision_id"]):
46
+ raise ValueError("Unbound or incomplete native tool decision")
47
+ return {"hook_specific_output": {"hook_event_name": "tool_guard", "permission_decision": result["decision"],
48
+ "permission_decision_reason": "Allowed by AgenticDome policy" if result["decision"] == "allow" else "Blocked by AgenticDome policy",
49
+ "metadata": {"agenticdome_decision_id": result["decision_id"], "evidence_scope": "pre_execution_policy_only"}}}
50
+ finally:
51
+ if owned: client.close()
52
+
53
+
54
+ def main():
55
+ try:
56
+ if sys.argv[1:] == ["--check"]:
57
+ client = configured_client()
58
+ try: report = client.native_guard_ready()
59
+ finally: client.close()
60
+ if (not isinstance(report, dict) or report.get("schema") != "agenticdome.native-guard-readiness.v1"
61
+ or report.get("ready") is not True or report.get("native_tool_guard") is not True):
62
+ raise ValueError("Updated Gateway guard capability is required")
63
+ print(json.dumps(report))
64
+ return 0
65
+ if sys.argv[1:]: raise ValueError("Unknown guard option")
66
+ raw = sys.stdin.buffer.read(131073)
67
+ if len(raw) > 131072: raise ValueError("Input exceeds limit")
68
+ def unique(pairs):
69
+ result = {}
70
+ for key, value in pairs:
71
+ if key in result: raise ValueError("Duplicate input member")
72
+ result[key] = value
73
+ return result
74
+ event = json.loads(raw, object_pairs_hook=unique, parse_constant=lambda _: (_ for _ in ()).throw(ValueError("Non-finite JSON")))
75
+ print(json.dumps(check_tool(event)))
76
+ return 0
77
+ except Exception as exc:
78
+ # Never expose tool arguments, credentials, exception URLs or response bodies.
79
+ if sys.argv[1:]==["--check"]:
80
+ status=getattr(exc,"status_code",None)
81
+ reasons={401:"Caller credentials or identity were rejected",403:"Caller is outside the approved Gateway boundary",
82
+ 404:"The assigned sidecar needs the native guard update",503:"The assigned Gateway is not security ready"}
83
+ print(json.dumps({"schema":"agenticdome.native-guard-readiness.v1","ready":False,
84
+ "reason":reasons.get(status,"Load the generated Gateway, tenant, Runtime API key and approved identity settings"),
85
+ "tool_executed":False}))
86
+ return 2
87
+ print(json.dumps({"decision": "block", "reason": "AgenticDome tool check failed. Verify the assigned Gateway, identity and runtime readiness."}))
88
+ return 2
89
+
90
+
91
+ if __name__ == "__main__": raise SystemExit(main())
@@ -51,7 +51,7 @@ PUBLISHED_AGENTICDOME_PACKAGES: Dict[str, Dict[str, str]] = {
51
51
 
52
52
  # Prepared artifacts are kept separate from registry-verified published releases.
53
53
  RELEASE_CANDIDATE_PACKAGES = {
54
- 'agenticdome-python-sdk': {'version': '1.2.48', 'status': 'unpublished'},
54
+ 'agenticdome-python-sdk': {'version': '1.2.50', 'status': 'unpublished'},
55
55
  'agenticdome-sdk': {'version': '0.6.16', 'status': 'unpublished'},
56
56
  }
57
57
 
@@ -92,7 +92,7 @@ FRAMEWORK_HOOK_CATALOG: Dict[str, Dict[str, Any]] = {
92
92
  "agenticdome_sdk.integrations.crewai",
93
93
  "AgenticDomeCrewAIFirewall",
94
94
  ["attach", "secure_tool"],
95
- packages={"crewai": {"min":"1.15.5","max":"1.15.23"}},
95
+ packages={"crewai": {"min":"1.15.5","max":"1.15.34"}},
96
96
  native_modules=[
97
97
  {
98
98
  "module": "crewai.hooks",
@@ -122,7 +122,7 @@ FRAMEWORK_HOOK_CATALOG: Dict[str, Dict[str, Any]] = {
122
122
  "agenticdome_sdk.integrations.pydanticai",
123
123
  "CyberSecFirewall",
124
124
  ["install_native_hooks", "secure_tool"],
125
- packages={"pydantic-ai": {"min":"2.16.0","max":"2.51.0"}},
125
+ packages={"pydantic-ai": {"min":"2.16.0","max":"2.64.0"}},
126
126
  native_modules=[{"module": "pydantic_ai", "attrs": ["Agent", "RunContext"]}],
127
127
  adapter_attrs=[
128
128
  {
@@ -139,8 +139,8 @@ FRAMEWORK_HOOK_CATALOG: Dict[str, Dict[str, Any]] = {
139
139
  "AgenticDomeLangGraphFirewall",
140
140
  ["input_node", "transition_node", "output_node", "as_langchain_middleware"],
141
141
  packages={
142
- "langgraph": {"min":"1.2.9","max":"1.2.12"},
143
- "langchain-core": {"min":"1.5.0","max":"1.6.6"},
142
+ "langgraph": {"min":"1.2.9","max":"1.2.19"},
143
+ "langchain-core": {"min":"1.5.0","max":"1.7.3"},
144
144
  },
145
145
  native_modules=[
146
146
  {"module": "langgraph.graph", "attrs": ["StateGraph"]},
@@ -182,8 +182,8 @@ FRAMEWORK_HOOK_CATALOG: Dict[str, Dict[str, Any]] = {
182
182
  "AgenticDomeMicrosoftAIFoundryFirewall",
183
183
  ["install_on_client", "wrap_tool_executor", "run_secure"],
184
184
  packages={
185
- "azure-ai-projects": {"min":"2.3.0","max":"2.7.0"},
186
- "azure-identity": {"exact": "1.25.3"},
185
+ "azure-ai-projects": {"min":"2.3.0","max":"2.10.0"},
186
+ "azure-identity": {"min":"1.25.3","max":"1.27.0"},
187
187
  },
188
188
  native_modules=[
189
189
  {"module": "azure.ai.projects", "attrs": ["AIProjectClient"]},
@@ -197,7 +197,7 @@ FRAMEWORK_HOOK_CATALOG: Dict[str, Dict[str, Any]] = {
197
197
  "agenticdome_sdk.integrations.openai_agents",
198
198
  "AgenticDomeOpenAIAgentsFirewall",
199
199
  ["run_agent_securely", "wrap_tool_handler", "create_input_guardrail"],
200
- packages={"openai-agents": {"min":"0.18.3","max":"0.22.3"}},
200
+ packages={"openai-agents": {"min":"0.18.3","max":"0.24.0"}},
201
201
  native_modules=[{"module": "agents", "attrs": ["Agent", "Runner", "function_tool"]}],
202
202
  native_smoke={"module": "agenticdome_sdk.integrations.openai_agents", "call": "create_input_guardrail"},
203
203
  docs="docs/frameworks/openai-agents.md",
@@ -207,7 +207,7 @@ FRAMEWORK_HOOK_CATALOG: Dict[str, Dict[str, Any]] = {
207
207
  "agenticdome_sdk.integrations.claude",
208
208
  "AgenticDomeClaudeFirewall",
209
209
  ["install_on_options", "secure_query", "run_client_securely", "secure_sdk_tool"],
210
- packages={"claude-agent-sdk": {"min":"0.2.126","max":"0.2.162"}},
210
+ packages={"claude-agent-sdk": {"min":"0.2.126","max":"0.2.176"}},
211
211
  native_modules=[
212
212
  {
213
213
  "module": "claude_agent_sdk",
@@ -232,7 +232,7 @@ FRAMEWORK_HOOK_CATALOG: Dict[str, Dict[str, Any]] = {
232
232
  "agenticdome_sdk.integrations.agno",
233
233
  "AgenticDomeAgnoFirewall",
234
234
  ["attach_firewall", "secure_tool", "create_hook_bundle"],
235
- packages={"agno": {"min":"2.8.0","max":"3.0.11"}},
235
+ packages={"agno": {"min":"2.8.0","max":"3.1.12"}},
236
236
  native_modules=[{"module": "agno.agent", "attrs": ["Agent"]}],
237
237
  native_smoke={"module": "agenticdome_sdk.integrations.agno", "call": "attach_firewall"},
238
238
  docs="docs/frameworks/agno.md",
@@ -242,7 +242,7 @@ FRAMEWORK_HOOK_CATALOG: Dict[str, Dict[str, Any]] = {
242
242
  "agenticdome_sdk.integrations.google_adk",
243
243
  "AgenticDomeGoogleADKFirewall",
244
244
  ["build_callback_kwargs", "install_on_agent", "wrap_tool_handler"],
245
- packages={"google-adk": {"min":"2.5.0","max":"2.10.0"}},
245
+ packages={"google-adk": {"min":"2.5.0","max":"2.13.0"}},
246
246
  native_modules=[
247
247
  {"module": "google.adk.agents", "attrs": ["Agent"]},
248
248
  {"module": "google.adk.tools", "attrs": ["FunctionTool"]},
@@ -268,7 +268,7 @@ FRAMEWORK_HOOK_CATALOG: Dict[str, Dict[str, Any]] = {
268
268
  "agenticdome_sdk.integrations.aws_bedrock",
269
269
  "AgenticDomeAWSBedrockFirewall",
270
270
  ["converse_securely", "wrap_tool_handler", "wrap_action_group_lambda"],
271
- packages={"boto3": {"min":"1.43.54","max":"1.43.105"}},
271
+ packages={"boto3": {"min":"1.43.54","max":"1.43.123"}},
272
272
  native_modules=[{"module": "boto3", "attrs": ["client"]}],
273
273
  native_smoke={"module": "agenticdome_sdk.integrations.aws_bedrock", "call": "wrap_tool_handler"},
274
274
  docs="docs/frameworks/aws-bedrock.md",
@@ -451,18 +451,18 @@ _HARNESS_VERIFICATION: Dict[str, Dict[str, Any]] = {
451
451
  }
452
452
 
453
453
  _PACKAGE_CERTIFICATION_DATES: Dict[str, Dict[str, str]] = {
454
- "crewai": {"crewai":"2026-09-29"},
455
- "pydanticai": {"pydantic-ai": "2026-09-26"},
456
- "langgraph": {"langgraph": "2026-09-26", "langchain-core": "2026-09-29"},
454
+ "crewai": {"crewai":"2026-11-02"},
455
+ "pydanticai": {"pydantic-ai": "2026-11-02"},
456
+ "langgraph": {"langgraph": "2026-11-02", "langchain-core": "2026-11-02"},
457
457
  "autogen": {"autogen-agentchat": "2026-07-26"},
458
- "foundry": {"azure-ai-projects": "2026-09-26", "azure-identity": "2026-07-10"},
459
- "openai-agents": {"openai-agents": "2026-09-26"},
460
- "claude": {"claude-agent-sdk": "2026-09-29"},
458
+ "foundry": {"azure-ai-projects": "2026-11-02", "azure-identity": "2026-11-02"},
459
+ "openai-agents": {"openai-agents": "2026-11-02"},
460
+ "claude": {"claude-agent-sdk": "2026-11-02"},
461
461
  "smolagents": {"smolagents": "2026-07-23"},
462
- "agno": {"agno": "2026-09-26"},
463
- "google-adk": {"google-adk": "2026-09-26"},
462
+ "agno": {"agno": "2026-11-02"},
463
+ "google-adk": {"google-adk": "2026-11-02"},
464
464
  "llamaindex": {"llama-index": "2026-09-26"},
465
- "bedrock": {"boto3": "2026-09-29"},
465
+ "bedrock": {"boto3": "2026-11-02"},
466
466
  "mcp": {"mcp": "2026-09-09"},
467
467
  }
468
468
 
@@ -364,6 +364,7 @@ class AgenticDomeMCPHostFirewall:
364
364
  provider_action_rules: Optional[Dict[str, "ProviderActionRule"]] = None,
365
365
  resolve_provider_facts: Optional[Callable[[str, Dict[str, Any]], Any]] = None,
366
366
  ownership_guard=None,
367
+ require_mcp_schema: bool = False,
367
368
  ) -> None:
368
369
  self.config = config or load_config()
369
370
  if not credentials_or_local_sim(self.config.api_base, self.config.api_key, self.config.tenant_id):
@@ -384,6 +385,10 @@ class AgenticDomeMCPHostFirewall:
384
385
  self.provider_action_rules = dict(provider_action_rules or {})
385
386
  self.resolve_provider_facts = resolve_provider_facts
386
387
  self.ownership_guard = ownership_guard
388
+ from .mcp_schema import McpSchemaCache
389
+ self.mcp_schemas = McpSchemaCache()
390
+ self.require_mcp_schema = require_mcp_schema
391
+ self._schema_pages = {}
387
392
  self._rate_lock = Lock()
388
393
  self._rate_events: Dict[str, Deque[float]] = defaultdict(deque)
389
394
 
@@ -944,14 +949,27 @@ class AgenticDomeMCPHostFirewall:
944
949
  self._fail_or_raise(f"AgenticDome MCP authorization failed: {exc}", exc=exc)
945
950
  return {"verdict": "ALLOWED", "reason": "fail-open"}
946
951
 
952
+ def _validate_mcp_input(self,tool_name,tool_args,context):
953
+ from .mcp_schema import McpSchemaError
954
+ scope = self._schema_scope(context)
955
+ if scope and self.mcp_schemas.available(scope, tool_name):
956
+ try: self.mcp_schemas.validate(scope, tool_name, tool_args)
957
+ except McpSchemaError as exc: raise MCPToolBlocked(str(exc)) from None
958
+ elif self.require_mcp_schema:
959
+ raise MCPToolBlocked("Fetch this server's tools/list catalogue before authorizing a tool call")
960
+ return scope
961
+
947
962
  async def authorize_mcp_tool_call(self, *, tool_name: str, tool_args: Dict[str, Any], context: Dict[str, Any]) -> Dict[str, Any]:
948
- return await self._mcp_guardrail(
949
- operation_name=tool_name,
950
- operation_args=tool_args,
951
- context=context,
963
+ from .mcp_schema import McpSchemaError
964
+ scope=self._validate_mcp_input(tool_name,tool_args,context)
965
+ decision = await self._mcp_guardrail(operation_name=tool_name, operation_args=tool_args, context=context,
952
966
  request_purpose="mcp_tool_execution",
953
- text=self._safe_str(context.get("user_prompt") or context.get("request_text") or f"MCP host is attempting to call tool: {tool_name}"),
954
- )
967
+ text=self._safe_str(context.get("user_prompt") or context.get("request_text") or f"MCP host is attempting to call tool: {tool_name}"))
968
+ sanitized = self._sanitized_args(decision, explicit_only=True)
969
+ if sanitized is not None and scope and self.mcp_schemas.available(scope, tool_name):
970
+ try: self.mcp_schemas.validate(scope, tool_name, sanitized)
971
+ except McpSchemaError as exc: raise MCPToolBlocked(str(exc)) from None
972
+ return decision
955
973
 
956
974
  async def authorize_mcp_resource_read(self, *, uri: str, params: Dict[str, Any], context: Dict[str, Any]) -> Dict[str, Any]:
957
975
  return await self._mcp_guardrail(
@@ -972,13 +990,23 @@ class AgenticDomeMCPHostFirewall:
972
990
  )
973
991
 
974
992
  async def authorize_mcp_method(self, *, method: str, params: Dict[str, Any], context: Dict[str, Any], request_purpose: str) -> Dict[str, Any]:
975
- return await self._mcp_guardrail(
993
+ if method == "tools/call":
994
+ if not isinstance(params.get("name"),str) or not isinstance(params.get("arguments",{}),dict):
995
+ raise MCPToolBlocked("Invalid MCP tool call")
996
+ self._validate_mcp_input(params["name"],params.get("arguments",{}),context)
997
+ decision = await self._mcp_guardrail(
976
998
  operation_name=f"mcp.{method}",
977
999
  operation_args={"method": method, **params},
978
1000
  context=context,
979
1001
  request_purpose=request_purpose,
980
1002
  text=self._safe_str(context.get("user_prompt") or context.get("request_text") or f"MCP host is attempting JSON-RPC method: {method}"),
981
1003
  )
1004
+ if method=="tools/call":
1005
+ sanitized=self._sanitized_args(decision,explicit_only=True)
1006
+ if sanitized is not None:
1007
+ if sanitized.get("name",params["name"])!=params["name"]:raise MCPToolBlocked("Schema review cannot change the MCP tool identity")
1008
+ self._validate_mcp_input(params["name"],sanitized.get("arguments",{}),context)
1009
+ return decision
982
1010
 
983
1011
  async def _handle_blocking_decision(self, *, decision: Dict[str, Any], rid: Any, context: Dict[str, Any], method: str, operation: str) -> Optional[Dict[str, Any]]:
984
1012
  evidence = _lifecycle_decision.get()
@@ -1142,7 +1170,7 @@ class AgenticDomeMCPHostFirewall:
1142
1170
  return filtered
1143
1171
 
1144
1172
  async def filter_tools_list_result(self, *, tools_result: Any, context: Dict[str, Any]) -> Any:
1145
- return await self._filter_named_list_result(
1173
+ result = await self._filter_named_list_result(
1146
1174
  list_result=tools_result,
1147
1175
  context=context,
1148
1176
  method="tools/list",
@@ -1152,6 +1180,32 @@ class AgenticDomeMCPHostFirewall:
1152
1180
  allowed_keys=("allowed_tools", "visible_tools"),
1153
1181
  blocked_keys=("blocked_tools", "hidden_tools"),
1154
1182
  )
1183
+ tools = result.get("tools", []) if isinstance(result, dict) else result
1184
+ scope = self._schema_scope(context)
1185
+ if scope and isinstance(tools, list):
1186
+ schemas = [tool for tool in tools if isinstance(tool, dict) and "inputSchema" in tool]
1187
+ if self.require_mcp_schema and len(schemas)!=len(tools): raise MCPToolBlocked("MCP tool definition omitted inputSchema")
1188
+ from .mcp_schema import McpSchemaError
1189
+ more = isinstance(result,dict) and bool(result.get("nextCursor"))
1190
+ previous = self._schema_pages.pop(scope, (0,set()))
1191
+ names = previous[1] if previous[0]>time.monotonic() else set()
1192
+ new_names = {tool.get("name","") for tool in schemas}
1193
+ if names.intersection(new_names): raise MCPToolBlocked("MCP catalogue repeated a tool across pages")
1194
+ names |= new_names
1195
+ if len(names)>256 or sum(len(name) for name in names)>32768: raise MCPToolBlocked("MCP catalogue exceeds tool limit")
1196
+ try: self.mcp_schemas.install(scope, schemas)
1197
+ except McpSchemaError as exc: raise MCPToolBlocked(str(exc)) from None
1198
+ if more:
1199
+ if len(self._schema_pages)>=32: self._schema_pages.pop(next(iter(self._schema_pages)))
1200
+ self._schema_pages[scope] = (time.monotonic()+300,names)
1201
+ else: self.mcp_schemas.retain_names(scope,names)
1202
+ return result
1203
+
1204
+ def _schema_scope(self, context):
1205
+ server = self._server_context(context)
1206
+ if not server.get("mcp_server_id") and not server.get("mcp_server_url"): return None
1207
+ return json.dumps([self.config.tenant_id, server, context.get("session_id"), context.get("user_id"),
1208
+ context.get("agent_id"), context.get("server_authorization_scope")], sort_keys=True, default=str)
1155
1209
 
1156
1210
  async def filter_resources_list_result(self, *, resources_result: Any, context: Dict[str, Any]) -> Any:
1157
1211
  return await self._filter_named_list_result(
@@ -0,0 +1,245 @@
1
+ """Bounded MCP input validation. No network access or framework imports.
2
+
3
+ Mirrored in app/security/mcp_schema_core.py for independent sidecar packaging.
4
+ The integration suite verifies byte-for-byte parity. Update both copies together.
5
+ """
6
+ from __future__ import annotations
7
+
8
+ import contextvars
9
+ import hashlib
10
+ import json
11
+ import time
12
+ import threading
13
+ from collections import OrderedDict
14
+
15
+
16
+ class McpSchemaError(ValueError):
17
+ pass
18
+
19
+
20
+ class McpSchemaUnavailable(McpSchemaError):
21
+ pass
22
+
23
+
24
+ _budget = contextvars.ContextVar("mcp_schema_budget", default=None)
25
+
26
+
27
+ def _bounded(value, *, nodes=4096, depth=32):
28
+ remaining = nodes
29
+ def visit(item, level):
30
+ nonlocal remaining
31
+ remaining -= 1
32
+ if remaining < 0 or level > depth:
33
+ raise McpSchemaError("MCP schema or arguments exceed validation complexity limits")
34
+ if isinstance(item, dict):
35
+ for child in item.values(): visit(child, level + 1)
36
+ elif isinstance(item, list):
37
+ for child in item: visit(child, level + 1)
38
+ visit(value, 0)
39
+
40
+
41
+ def _safe_schema(schema):
42
+ if not isinstance(schema, dict) or schema.get("type") != "object":
43
+ raise McpSchemaError("MCP inputSchema must describe an object")
44
+ _bounded(schema, nodes=1024, depth=20)
45
+ raw = json.dumps(schema, sort_keys=True, separators=(",", ":"), allow_nan=False).encode()
46
+ if len(raw) > 32768:
47
+ raise McpSchemaError("MCP inputSchema exceeds 32 KiB")
48
+ visits = 4096
49
+ def walk(node, references=()):
50
+ nonlocal visits
51
+ visits -= 1
52
+ if visits < 0: raise McpSchemaError("Schema reference expansion exceeds limit")
53
+ if isinstance(node, dict):
54
+ # jsonschema.evolve otherwise switches nested dialect declarations
55
+ # back to an unbounded built-in validator, including its regex engine.
56
+ if node is not schema and "$schema" in node:
57
+ raise McpSchemaError("Nested schema dialect changes are unsupported")
58
+ if any(key in node for key in ("$dynamicRef", "$recursiveRef")):
59
+ raise McpSchemaError("Dynamic schema references are unsupported")
60
+ if "$id" in node:
61
+ raise McpSchemaError("Schema resource identifiers require a reviewed adapter")
62
+ ref = node.get("$ref")
63
+ if ref is not None:
64
+ if not isinstance(ref, str) or not ref.startswith("#/") or ref in references:
65
+ raise McpSchemaError("Only acyclic local JSON-pointer schema references are supported")
66
+ target = schema
67
+ try:
68
+ for part in ref[2:].split("/"):
69
+ target = target[part.replace("~1", "/").replace("~0", "~")]
70
+ except (KeyError, TypeError):
71
+ raise McpSchemaError("Unresolved local schema reference") from None
72
+ if len(references) >= 8: raise McpSchemaError("Schema reference depth exceeded")
73
+ walk(target, (*references, ref))
74
+ for key, child in node.items():
75
+ if key in {"oneOf", "anyOf", "allOf"} and isinstance(child, list) and len(child) > 16:
76
+ raise McpSchemaError("Schema alternatives exceed limit")
77
+ if key == "pattern" and (not isinstance(child, str) or len(child) > 1024):
78
+ raise McpSchemaError("Schema pattern exceeds limit")
79
+ walk(child, references)
80
+ elif isinstance(node, list):
81
+ for child in node: walk(child, references)
82
+ walk(schema)
83
+ return raw
84
+
85
+
86
+ def _compile(schema):
87
+ from jsonschema import Draft7Validator, Draft201909Validator, Draft202012Validator, ValidationError, validators
88
+ import regex
89
+ uri = schema.get("$schema", "https://json-schema.org/draft/2020-12/schema").rstrip("#")
90
+ base = {"https://json-schema.org/draft/2020-12/schema": Draft202012Validator,
91
+ "https://json-schema.org/draft/2019-09/schema": Draft201909Validator,
92
+ "https://json-schema.org/draft-07/schema": Draft7Validator,
93
+ "http://json-schema.org/draft-07/schema": Draft7Validator}.get(uri)
94
+ if base is None: raise McpSchemaError("Unsupported MCP JSON Schema dialect")
95
+ def tick():
96
+ budget = _budget.get()
97
+ if budget is not None:
98
+ budget[0] -= 1
99
+ if budget[0] < 0 or time.perf_counter() > budget[1]:
100
+ raise McpSchemaError("MCP schema validation budget exceeded")
101
+ def unique_key(item):
102
+ tick()
103
+ if isinstance(item, bool): return ("bool", item)
104
+ if isinstance(item, int): return ("number", item, 1)
105
+ if isinstance(item, float): return ("number", *item.as_integer_ratio())
106
+ if isinstance(item, dict): return ("object", tuple((k, unique_key(v)) for k, v in sorted(item.items())))
107
+ if isinstance(item, list): return ("array", tuple(unique_key(v) for v in item))
108
+ return ("scalar", item)
109
+ def bounded(keyword, validator):
110
+ def check(instance_validator, value, instance, schema_node):
111
+ tick()
112
+ if keyword == "pattern" and isinstance(instance, str):
113
+ try:
114
+ if not regex.search(value, instance, timeout=0.005):
115
+ yield ValidationError("String does not match the required pattern")
116
+ except (TimeoutError, regex.error):
117
+ raise McpSchemaError("MCP schema pattern is invalid or exceeds budget") from None
118
+ elif keyword == "patternProperties" and isinstance(instance, dict):
119
+ for pattern, subschema in value.items():
120
+ if len(pattern) > 1024: raise McpSchemaError("Schema pattern exceeds limit")
121
+ for name, item in instance.items():
122
+ tick()
123
+ try: matched = regex.search(pattern, name, timeout=0.005)
124
+ except (TimeoutError, regex.error): raise McpSchemaError("MCP schema pattern exceeds budget") from None
125
+ if matched: yield from instance_validator.descend(item, subschema, path=name, schema_path=pattern)
126
+ elif keyword == "additionalProperties" and isinstance(instance, dict):
127
+ properties = schema_node.get("properties", {})
128
+ patterns = schema_node.get("patternProperties", {})
129
+ for name, item in instance.items():
130
+ tick()
131
+ if name in properties: continue
132
+ try: matched = any(regex.search(p, name, timeout=0.005) for p in patterns)
133
+ except (TimeoutError, regex.error): raise McpSchemaError("MCP schema pattern exceeds budget") from None
134
+ if matched: continue
135
+ if value is False: yield ValidationError("Unexpected argument property")
136
+ elif isinstance(value, dict): yield from instance_validator.descend(item, value, path=name)
137
+ elif keyword == "uniqueItems" and value and isinstance(instance, list):
138
+ seen = set()
139
+ for item in instance:
140
+ key = unique_key(item)
141
+ if key in seen:
142
+ yield ValidationError("Array items must be unique")
143
+ break
144
+ seen.add(key)
145
+ else:
146
+ yield from validator(instance_validator, value, instance, schema_node)
147
+ return check
148
+ # Reject oversized property patterns before compiling the meta-schema.
149
+ def check_patterns(node):
150
+ if isinstance(node, dict):
151
+ if any(len(p) > 1024 for p in node.get("patternProperties", {})):
152
+ raise McpSchemaError("Schema pattern exceeds limit")
153
+ for child in node.values(): check_patterns(child)
154
+ elif isinstance(node, list):
155
+ for child in node: check_patterns(child)
156
+ check_patterns(schema)
157
+ try: base.check_schema(schema)
158
+ except Exception: raise McpSchemaError("Invalid MCP inputSchema") from None
159
+ cls = validators.extend(base, {key: bounded(key, value) for key, value in base.VALIDATORS.items()})
160
+ return cls(schema)
161
+
162
+
163
+ class McpSchemaCache:
164
+ """LRU cache partitioned by authenticated server/caller scope, with a lease."""
165
+ def __init__(self, *, ttl=300, max_entries=1024, max_bytes=4194304):
166
+ self.ttl, self.max_entries, self.max_bytes = ttl, max_entries, max_bytes
167
+ self.entries = OrderedDict()
168
+ self.bytes = 0
169
+ self.lock = threading.RLock()
170
+
171
+ def install(self, scope, tools, *, replace_scope=False):
172
+ if not isinstance(tools, list) or len(tools) > 256:
173
+ raise McpSchemaError("MCP tool catalogue exceeds limit")
174
+ prepared = []
175
+ seen = set()
176
+ for tool in tools:
177
+ if not isinstance(tool, dict) or not isinstance(tool.get("name"), str) or not 0 < len(tool["name"]) <= 2048:
178
+ raise McpSchemaError("Invalid MCP tool definition")
179
+ name = tool["name"]
180
+ if name in seen: raise McpSchemaError("Duplicate MCP tool definition")
181
+ seen.add(name)
182
+ schema = tool.get("inputSchema")
183
+ raw = _safe_schema(schema)
184
+ # Own an immutable snapshot, independent of response redaction/hooks.
185
+ schema = json.loads(raw)
186
+ digest = "sha256:" + hashlib.sha256(raw).hexdigest()
187
+ with self.lock: existing = self.entries.get((scope, name))
188
+ prepared.append((name, raw, existing[2] if existing and existing[1] == digest else _compile(schema)))
189
+ changes = []
190
+ with self.lock:
191
+ if replace_scope:
192
+ for key in list(self.entries):
193
+ if key[0] == scope and key[1] not in seen:
194
+ self.bytes -= self.entries.pop(key)[3]
195
+ for name, raw, validator in prepared:
196
+ key = (scope, name)
197
+ digest = "sha256:" + hashlib.sha256(raw).hexdigest()
198
+ old = self.entries.pop(key, None)
199
+ if old:
200
+ self.bytes -= old[3]
201
+ if old[1] != digest: changes.append(name)
202
+ self.entries[key] = (time.monotonic() + self.ttl, digest, validator, len(raw))
203
+ self.bytes += len(raw)
204
+ while len(self.entries) > self.max_entries or self.bytes > self.max_bytes:
205
+ _, item = self.entries.popitem(last=False)
206
+ self.bytes -= item[3]
207
+ return changes
208
+
209
+ def available(self, scope, name):
210
+ with self.lock:
211
+ entry = self.entries.get((scope, name))
212
+ return bool(entry and entry[0] > time.monotonic())
213
+
214
+ def fingerprint(self, scope, name):
215
+ with self.lock:
216
+ entry = self.entries.get((scope, name))
217
+ return entry[1] if entry and entry[0] > time.monotonic() else None
218
+
219
+ def retain_names(self, scope, names):
220
+ with self.lock:
221
+ for key in list(self.entries):
222
+ if key[0] == scope and key[1] not in names:
223
+ self.bytes -= self.entries.pop(key)[3]
224
+
225
+ def validate(self, scope, name, arguments, *, expected_digest=None):
226
+ key = (scope, name)
227
+ with self.lock:
228
+ entry = self.entries.get(key)
229
+ if not entry or entry[0] <= time.monotonic():
230
+ raise McpSchemaUnavailable("MCP tool schema is unavailable or expired")
231
+ self.entries.move_to_end(key)
232
+ if expected_digest and entry[1] != expected_digest:
233
+ raise McpSchemaError("MCP tool schema differs from its approved digest")
234
+ if not isinstance(arguments, dict): raise McpSchemaError("MCP tool arguments must be an object")
235
+ _bounded(arguments)
236
+ if len(json.dumps(arguments, allow_nan=False).encode()) > 131072:
237
+ raise McpSchemaError("MCP arguments exceed validation limit")
238
+ token = _budget.set([10000, time.perf_counter() + 0.025])
239
+ try:
240
+ error = next(entry[2].iter_errors(arguments), None)
241
+ if error:
242
+ # Values and schema messages can contain secrets. Return paths only.
243
+ raise McpSchemaError("MCP arguments do not satisfy inputSchema")
244
+ finally: _budget.reset(token)
245
+ return entry[1]