tool-guard-core 0.8.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.
- tool_guard_core-0.8.0/IMPLEMENTATION_NOTES.md +159 -0
- tool_guard_core-0.8.0/LICENSE +202 -0
- tool_guard_core-0.8.0/PKG-INFO +318 -0
- tool_guard_core-0.8.0/README.md +280 -0
- tool_guard_core-0.8.0/pyproject.toml +78 -0
- tool_guard_core-0.8.0/setup.cfg +4 -0
- tool_guard_core-0.8.0/tests/__init__.py +0 -0
- tool_guard_core-0.8.0/tests/test_autogen.py +135 -0
- tool_guard_core-0.8.0/tests/test_client.py +328 -0
- tool_guard_core-0.8.0/tests/test_contract.py +519 -0
- tool_guard_core-0.8.0/tests/test_coverage_extras.py +496 -0
- tool_guard_core-0.8.0/tests/test_langchain.py +211 -0
- tool_guard_core-0.8.0/tests/test_mcp.py +142 -0
- tool_guard_core-0.8.0/tests/test_memory_adapter.py +100 -0
- tool_guard_core-0.8.0/tests/test_native.py +226 -0
- tool_guard_core-0.8.0/tests/test_types.py +548 -0
- tool_guard_core-0.8.0/tool_guard_core.egg-info/PKG-INFO +318 -0
- tool_guard_core-0.8.0/tool_guard_core.egg-info/SOURCES.txt +31 -0
- tool_guard_core-0.8.0/tool_guard_core.egg-info/dependency_links.txt +1 -0
- tool_guard_core-0.8.0/tool_guard_core.egg-info/requires.txt +20 -0
- tool_guard_core-0.8.0/tool_guard_core.egg-info/scm_file_list.json +28 -0
- tool_guard_core-0.8.0/tool_guard_core.egg-info/scm_version.json +8 -0
- tool_guard_core-0.8.0/tool_guard_core.egg-info/top_level.txt +1 -0
- tool_guard_core-0.8.0/toolguard/__init__.py +75 -0
- tool_guard_core-0.8.0/toolguard/adapters/__init__.py +12 -0
- tool_guard_core-0.8.0/toolguard/adapters/autogen.py +119 -0
- tool_guard_core-0.8.0/toolguard/adapters/langchain.py +122 -0
- tool_guard_core-0.8.0/toolguard/adapters/mcp.py +76 -0
- tool_guard_core-0.8.0/toolguard/adapters/memory.py +84 -0
- tool_guard_core-0.8.0/toolguard/adapters/native.py +194 -0
- tool_guard_core-0.8.0/toolguard/client.py +368 -0
- tool_guard_core-0.8.0/toolguard/errors.py +42 -0
- tool_guard_core-0.8.0/toolguard/types.py +777 -0
|
@@ -0,0 +1,159 @@
|
|
|
1
|
+
# SDK Implementation Notes
|
|
2
|
+
|
|
3
|
+
## What was built
|
|
4
|
+
|
|
5
|
+
Full Python SDK (`toolguard`, initially built as unpublished v0.1.0; PyPI
|
|
6
|
+
distribution `tool-guard-core` begins with the lockstep v0.8.0 release) for
|
|
7
|
+
Tool Guard Core, shipped at `sdk/python/`. It turns the doc-pattern-only
|
|
8
|
+
LangChain/AutoGen/native
|
|
9
|
+
snippets in `docs/integration.md` into shipped, tested, importable code.
|
|
10
|
+
|
|
11
|
+
## File list
|
|
12
|
+
|
|
13
|
+
```
|
|
14
|
+
sdk/python/
|
|
15
|
+
├── toolguard/
|
|
16
|
+
│ ├── __init__.py — public exports
|
|
17
|
+
│ ├── types.py — dataclasses mirroring Go pkg/domain contracts
|
|
18
|
+
│ ├── client.py — ToolGuard (CLI + proxy backends)
|
|
19
|
+
│ ├── errors.py — ToolDenied / ToolEscalated
|
|
20
|
+
│ └── adapters/
|
|
21
|
+
│ ├── __init__.py
|
|
22
|
+
│ ├── langchain.py — ToolGuardCallbackHandler (BaseCallbackHandler)
|
|
23
|
+
│ ├── autogen.py — guarded() decorator + register_guarded()
|
|
24
|
+
│ ├── native.py — guard_tool_calls() (OpenAI + Anthropic)
|
|
25
|
+
│ └── mcp.py — guard_mcp_tool() decorator
|
|
26
|
+
├── tests/
|
|
27
|
+
│ ├── __init__.py
|
|
28
|
+
│ ├── test_types.py — JSON round-trip / field-name contract
|
|
29
|
+
│ ├── test_client.py — CLI mode (exit codes) + proxy mode (httpx mock)
|
|
30
|
+
│ ├── test_langchain.py — allow/deny/escalate through callback handler
|
|
31
|
+
│ ├── test_autogen.py — guarded() decorator allow/deny/escalate
|
|
32
|
+
│ ├── test_native.py — guard_tool_calls() OpenAI + Anthropic shapes
|
|
33
|
+
│ ├── test_mcp.py — guard_mcp_tool() decorator
|
|
34
|
+
│ ├── test_coverage_extras.py — targeted gap-filling for 90%+ coverage
|
|
35
|
+
│ └── test_contract.py — real engine contract (builds tg from source)
|
|
36
|
+
├── pyproject.toml — package metadata; core dep: httpx
|
|
37
|
+
├── README.md — per-framework usage examples
|
|
38
|
+
└── IMPLEMENTATION_NOTES.md — this file
|
|
39
|
+
```
|
|
40
|
+
|
|
41
|
+
Plus changes in the repo root:
|
|
42
|
+
- `CHANGELOG.md` — entry under `[0.5.0]`
|
|
43
|
+
- `Makefile` — `sdk-test:` target
|
|
44
|
+
- `docs/integration.md` — sections 3.2–3.4 replaced with SDK usage
|
|
45
|
+
|
|
46
|
+
## Test results
|
|
47
|
+
|
|
48
|
+
```
|
|
49
|
+
135 passed, 0 failed
|
|
50
|
+
Total coverage: 94.82% (exceeds the 90% gate)
|
|
51
|
+
```
|
|
52
|
+
|
|
53
|
+
Post-review update: 2 more passed since the initial 133 — added
|
|
54
|
+
`test_real_dispatcher_propagates_deny` and `test_init_sets_raise_error`
|
|
55
|
+
in `test_langchain.py` (see "Deferred / known gaps" — this closes the
|
|
56
|
+
gap that let the `raise_error` bug ship past the original 133).
|
|
57
|
+
|
|
58
|
+
Run:
|
|
59
|
+
```bash
|
|
60
|
+
cd sdk/python && .venv/bin/python -m pytest tests/ --cov-fail-under=90 -q
|
|
61
|
+
```
|
|
62
|
+
|
|
63
|
+
## JSON field names mirrored (for spot-check)
|
|
64
|
+
|
|
65
|
+
These are verbatim copies of the Go `json:"..."` struct tags from
|
|
66
|
+
`pkg/domain/envelope.go` and `pkg/domain/trace.go`:
|
|
67
|
+
|
|
68
|
+
**ActionEnvelope**:
|
|
69
|
+
`envelope_id`, `timestamp`, `agent_id`, `session_id`, `org_id`,
|
|
70
|
+
`agent_version`, `framework`, `turn_number`, `department`,
|
|
71
|
+
`tool_name`, `tool_server`, `tool_group`, `parameters`,
|
|
72
|
+
`parameters_redacted`, `context`, `integration_type`,
|
|
73
|
+
`proxy_version`, `tls_verified`
|
|
74
|
+
|
|
75
|
+
**EnvelopeContext** fields:
|
|
76
|
+
`verified`, `session_state`, `agent_supplied`
|
|
77
|
+
|
|
78
|
+
**VerifiedContext** fields (selected):
|
|
79
|
+
`customer_tier`, `customer_account_age_days`, `customer_lifetime_value`,
|
|
80
|
+
`customer_order_count`, `order_total`, `order_age_days`, `order_currency`,
|
|
81
|
+
`customer_id`, `order_id`, `order_item_count`, `product_category`,
|
|
82
|
+
`product_category_avg_price`, `return_request_reason`,
|
|
83
|
+
`return_request_status`, `economic_value_impact`,
|
|
84
|
+
`rolling_24h_total`, `rolling_24h_count`, `rolling_7d_total`, `rolling_7d_count`,
|
|
85
|
+
`agent_budget`, `agent_velocity`, `justification`,
|
|
86
|
+
`content_risk`, `content_categories`, `content_classifier_tier`,
|
|
87
|
+
`counter_agent_risk`, `counter_agent_categories`, `counter_agent_reasoning`
|
|
88
|
+
|
|
89
|
+
**AgentBudgetContext**: `total_limit`, `used_today`, `remaining`, `transactions_today`
|
|
90
|
+
|
|
91
|
+
**AgentVelocityContext**: `monetary_count_1h`, `monetary_sum_1h`,
|
|
92
|
+
`monetary_count_24h`, `monetary_sum_24h`, `token_count_1h`,
|
|
93
|
+
`token_count_24h`, `llm_cost_usd_1h`, `llm_cost_usd_24h`
|
|
94
|
+
|
|
95
|
+
**SessionStateContext**: `cumulative_amount`, `actions_in_session`,
|
|
96
|
+
`escalations_in_session`, `denied_in_session`, `tool_sequence`, `amount_trajectory`
|
|
97
|
+
|
|
98
|
+
**EvaluationResult** (trace.go:165):
|
|
99
|
+
`decision`, `action_taken`, `decision_reason`, `effective_mode`,
|
|
100
|
+
`policies_matched`, `rules_evaluated`, `rules_triggered`,
|
|
101
|
+
`rule_results`, `primary_citation`, `is_near_miss`, `suggested_response`
|
|
102
|
+
|
|
103
|
+
**Decision** wire values: `"allowed"`, `"denied"`, `"escalated"`, `"flagged"`
|
|
104
|
+
**ActionTaken** wire values: `"allowed"`, `"denied"`, `"escalated"`, `"flagged"`, `"allowed_shadow"`
|
|
105
|
+
|
|
106
|
+
**RuleResult**: `rule_id`, `rule_name`, `policy_id`, `policy_version`,
|
|
107
|
+
`matched`, `effect`, `severity`, `citation`, `details`
|
|
108
|
+
|
|
109
|
+
**Citation**: `document_id`, `document_title`, `section`, `page`, `line`, `excerpt`
|
|
110
|
+
|
|
111
|
+
## CLI backend details
|
|
112
|
+
|
|
113
|
+
`tg evaluate` reads one policy set (`-policy FILE` or `-policy-dir DIR`) and
|
|
114
|
+
one envelope JSON (`-call`) per invocation. The SDK writes the envelope to a
|
|
115
|
+
temp file and passes its configured policy file or directory to the Go engine
|
|
116
|
+
in one call. Evaluating the complete set together preserves mixed
|
|
117
|
+
shadow/enforcement behavior exactly instead of approximating it in Python.
|
|
118
|
+
|
|
119
|
+
Exit-code contract (from `cmd/tg/main.go` cmdEvaluate):
|
|
120
|
+
- `0` → allowed / allowed_shadow
|
|
121
|
+
- `3` → denied
|
|
122
|
+
- `4` → escalated
|
|
123
|
+
- `1` → internal error (raises `RuntimeError`)
|
|
124
|
+
- `2` → usage error (raises `RuntimeError`)
|
|
125
|
+
|
|
126
|
+
## Framework / integration_type stamps
|
|
127
|
+
|
|
128
|
+
| Adapter | framework | integration_type |
|
|
129
|
+
|---|---|---|
|
|
130
|
+
| Direct `ToolGuard()` | `"sdk"` | `"sdk"` |
|
|
131
|
+
| LangChain | `"langgraph"` | `"langgraph_middleware"` |
|
|
132
|
+
| AutoGen | `"sdk"` | `"sdk"` |
|
|
133
|
+
| Native OpenAI/Anthropic | `"sdk"` | `"sdk"` |
|
|
134
|
+
| MCP | `"mcp"` | `"mcp_proxy"` |
|
|
135
|
+
|
|
136
|
+
These match the Go constants (`domain.Framework*`, `domain.IntegrationType*`).
|
|
137
|
+
|
|
138
|
+
## Deferred / known gaps
|
|
139
|
+
|
|
140
|
+
- **`adapters/langchain.py` line 78–82, 104**: The `on_tool_start` error
|
|
141
|
+
case when input_str is a non-string type (line 104) and the `except`
|
|
142
|
+
branch for json.loads failure (lines 77–82) are hard to trigger with
|
|
143
|
+
simple unit tests. Covered at 78%; would reach ~85% with integration
|
|
144
|
+
tests using a real LangChain chain. Full coverage requires installing
|
|
145
|
+
langchain-core, which is an optional dep not in the test matrix.
|
|
146
|
+
|
|
147
|
+
- **`adapters/autogen.py` line 71**: The positional-args path (`_args`
|
|
148
|
+
key) is an edge case; AutoGen always passes kwargs. At 93%.
|
|
149
|
+
|
|
150
|
+
- **`client.py` lines 267–268**: The `httpx.ImportError` message path
|
|
151
|
+
is not covered because httpx is always installed in the test venv.
|
|
152
|
+
At 96%.
|
|
153
|
+
|
|
154
|
+
- **Async adapters**: LangGraph's async tool call path (using
|
|
155
|
+
`on_tool_start_async`) is not yet implemented. The synchronous handler
|
|
156
|
+
covers 95% of real LangChain usage.
|
|
157
|
+
|
|
158
|
+
- **Go CI integration**: done — `.github/workflows/ci.yml` now has an
|
|
159
|
+
`sdk-python` job (Python 3.10 + 3.12 matrix) running `make sdk-test`.
|
|
@@ -0,0 +1,202 @@
|
|
|
1
|
+
|
|
2
|
+
Apache License
|
|
3
|
+
Version 2.0, January 2004
|
|
4
|
+
http://www.apache.org/licenses/
|
|
5
|
+
|
|
6
|
+
TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
|
|
7
|
+
|
|
8
|
+
1. Definitions.
|
|
9
|
+
|
|
10
|
+
"License" shall mean the terms and conditions for use, reproduction,
|
|
11
|
+
and distribution as defined by Sections 1 through 9 of this document.
|
|
12
|
+
|
|
13
|
+
"Licensor" shall mean the copyright owner or entity authorized by
|
|
14
|
+
the copyright owner that is granting the License.
|
|
15
|
+
|
|
16
|
+
"Legal Entity" shall mean the union of the acting entity and all
|
|
17
|
+
other entities that control, are controlled by, or are under common
|
|
18
|
+
control with that entity. For the purposes of this definition,
|
|
19
|
+
"control" means (i) the power, direct or indirect, to cause the
|
|
20
|
+
direction or management of such entity, whether by contract or
|
|
21
|
+
otherwise, or (ii) ownership of fifty percent (50%) or more of the
|
|
22
|
+
outstanding shares, or (iii) beneficial ownership of such entity.
|
|
23
|
+
|
|
24
|
+
"You" (or "Your") shall mean an individual or Legal Entity
|
|
25
|
+
exercising permissions granted by this License.
|
|
26
|
+
|
|
27
|
+
"Source" form shall mean the preferred form for making modifications,
|
|
28
|
+
including but not limited to software source code, documentation
|
|
29
|
+
source, and configuration files.
|
|
30
|
+
|
|
31
|
+
"Object" form shall mean any form resulting from mechanical
|
|
32
|
+
transformation or translation of a Source form, including but
|
|
33
|
+
not limited to compiled object code, generated documentation,
|
|
34
|
+
and conversions to other media types.
|
|
35
|
+
|
|
36
|
+
"Work" shall mean the work of authorship, whether in Source or
|
|
37
|
+
Object form, made available under the License, as indicated by a
|
|
38
|
+
copyright notice that is included in or attached to the work
|
|
39
|
+
(an example is provided in the Appendix below).
|
|
40
|
+
|
|
41
|
+
"Derivative Works" shall mean any work, whether in Source or Object
|
|
42
|
+
form, that is based on (or derived from) the Work and for which the
|
|
43
|
+
editorial revisions, annotations, elaborations, or other modifications
|
|
44
|
+
represent, as a whole, an original work of authorship. For the purposes
|
|
45
|
+
of this License, Derivative Works shall not include works that remain
|
|
46
|
+
separable from, or merely link (or bind by name) to the interfaces of,
|
|
47
|
+
the Work and Derivative Works thereof.
|
|
48
|
+
|
|
49
|
+
"Contribution" shall mean any work of authorship, including
|
|
50
|
+
the original version of the Work and any modifications or additions
|
|
51
|
+
to that Work or Derivative Works thereof, that is intentionally
|
|
52
|
+
submitted to Licensor for inclusion in the Work by the copyright owner
|
|
53
|
+
or by an individual or Legal Entity authorized to submit on behalf of
|
|
54
|
+
the copyright owner. For the purposes of this definition, "submitted"
|
|
55
|
+
means any form of electronic, verbal, or written communication sent
|
|
56
|
+
to the Licensor or its representatives, including but not limited to
|
|
57
|
+
communication on electronic mailing lists, source code control systems,
|
|
58
|
+
and issue tracking systems that are managed by, or on behalf of, the
|
|
59
|
+
Licensor for the purpose of discussing and improving the Work, but
|
|
60
|
+
excluding communication that is conspicuously marked or otherwise
|
|
61
|
+
designated in writing by the copyright owner as "Not a Contribution."
|
|
62
|
+
|
|
63
|
+
"Contributor" shall mean Licensor and any individual or Legal Entity
|
|
64
|
+
on behalf of whom a Contribution has been received by Licensor and
|
|
65
|
+
subsequently incorporated within the Work.
|
|
66
|
+
|
|
67
|
+
2. Grant of Copyright License. Subject to the terms and conditions of
|
|
68
|
+
this License, each Contributor hereby grants to You a perpetual,
|
|
69
|
+
worldwide, non-exclusive, no-charge, royalty-free, irrevocable
|
|
70
|
+
copyright license to reproduce, prepare Derivative Works of,
|
|
71
|
+
publicly display, publicly perform, sublicense, and distribute the
|
|
72
|
+
Work and such Derivative Works in Source or Object form.
|
|
73
|
+
|
|
74
|
+
3. Grant of Patent License. Subject to the terms and conditions of
|
|
75
|
+
this License, each Contributor hereby grants to You a perpetual,
|
|
76
|
+
worldwide, non-exclusive, no-charge, royalty-free, irrevocable
|
|
77
|
+
(except as stated in this section) patent license to make, have made,
|
|
78
|
+
use, offer to sell, sell, import, and otherwise transfer the Work,
|
|
79
|
+
where such license applies only to those patent claims licensable
|
|
80
|
+
by such Contributor that are necessarily infringed by their
|
|
81
|
+
Contribution(s) alone or by combination of their Contribution(s)
|
|
82
|
+
with the Work to which such Contribution(s) was submitted. If You
|
|
83
|
+
institute patent litigation against any entity (including a
|
|
84
|
+
cross-claim or counterclaim in a lawsuit) alleging that the Work
|
|
85
|
+
or a Contribution incorporated within the Work constitutes direct
|
|
86
|
+
or contributory patent infringement, then any patent licenses
|
|
87
|
+
granted to You under this License for that Work shall terminate
|
|
88
|
+
as of the date such litigation is filed.
|
|
89
|
+
|
|
90
|
+
4. Redistribution. You may reproduce and distribute copies of the
|
|
91
|
+
Work or Derivative Works thereof in any medium, with or without
|
|
92
|
+
modifications, and in Source or Object form, provided that You
|
|
93
|
+
meet the following conditions:
|
|
94
|
+
|
|
95
|
+
(a) You must give any other recipients of the Work or
|
|
96
|
+
Derivative Works a copy of this License; and
|
|
97
|
+
|
|
98
|
+
(b) You must cause any modified files to carry prominent notices
|
|
99
|
+
stating that You changed the files; and
|
|
100
|
+
|
|
101
|
+
(c) You must retain, in the Source form of any Derivative Works
|
|
102
|
+
that You distribute, all copyright, patent, trademark, and
|
|
103
|
+
attribution notices from the Source form of the Work,
|
|
104
|
+
excluding those notices that do not pertain to any part of
|
|
105
|
+
the Derivative Works; and
|
|
106
|
+
|
|
107
|
+
(d) If the Work includes a "NOTICE" text file as part of its
|
|
108
|
+
distribution, then any Derivative Works that You distribute must
|
|
109
|
+
include a readable copy of the attribution notices contained
|
|
110
|
+
within such NOTICE file, excluding those notices that do not
|
|
111
|
+
pertain to any part of the Derivative Works, in at least one
|
|
112
|
+
of the following places: within a NOTICE text file distributed
|
|
113
|
+
as part of the Derivative Works; within the Source form or
|
|
114
|
+
documentation, if provided along with the Derivative Works; or,
|
|
115
|
+
within a display generated by the Derivative Works, if and
|
|
116
|
+
wherever such third-party notices normally appear. The contents
|
|
117
|
+
of the NOTICE file are for informational purposes only and
|
|
118
|
+
do not modify the License. You may add Your own attribution
|
|
119
|
+
notices within Derivative Works that You distribute, alongside
|
|
120
|
+
or as an addendum to the NOTICE text from the Work, provided
|
|
121
|
+
that such additional attribution notices cannot be construed
|
|
122
|
+
as modifying the License.
|
|
123
|
+
|
|
124
|
+
You may add Your own copyright statement to Your modifications and
|
|
125
|
+
may provide additional or different license terms and conditions
|
|
126
|
+
for use, reproduction, or distribution of Your modifications, or
|
|
127
|
+
for any such Derivative Works as a whole, provided Your use,
|
|
128
|
+
reproduction, and distribution of the Work otherwise complies with
|
|
129
|
+
the conditions stated in this License.
|
|
130
|
+
|
|
131
|
+
5. Submission of Contributions. Unless You explicitly state otherwise,
|
|
132
|
+
any Contribution intentionally submitted for inclusion in the Work
|
|
133
|
+
by You to the Licensor shall be under the terms and conditions of
|
|
134
|
+
this License, without any additional terms or conditions.
|
|
135
|
+
Notwithstanding the above, nothing herein shall supersede or modify
|
|
136
|
+
the terms of any separate license agreement you may have executed
|
|
137
|
+
with Licensor regarding such Contributions.
|
|
138
|
+
|
|
139
|
+
6. Trademarks. This License does not grant permission to use the trade
|
|
140
|
+
names, trademarks, service marks, or product names of the Licensor,
|
|
141
|
+
except as required for reasonable and customary use in describing the
|
|
142
|
+
origin of the Work and reproducing the content of the NOTICE file.
|
|
143
|
+
|
|
144
|
+
7. Disclaimer of Warranty. Unless required by applicable law or
|
|
145
|
+
agreed to in writing, Licensor provides the Work (and each
|
|
146
|
+
Contributor provides its Contributions) on an "AS IS" BASIS,
|
|
147
|
+
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
|
|
148
|
+
implied, including, without limitation, any warranties or conditions
|
|
149
|
+
of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A
|
|
150
|
+
PARTICULAR PURPOSE. You are solely responsible for determining the
|
|
151
|
+
appropriateness of using or redistributing the Work and assume any
|
|
152
|
+
risks associated with Your exercise of permissions under this License.
|
|
153
|
+
|
|
154
|
+
8. Limitation of Liability. In no event and under no legal theory,
|
|
155
|
+
whether in tort (including negligence), contract, or otherwise,
|
|
156
|
+
unless required by applicable law (such as deliberate and grossly
|
|
157
|
+
negligent acts) or agreed to in writing, shall any Contributor be
|
|
158
|
+
liable to You for damages, including any direct, indirect, special,
|
|
159
|
+
incidental, or consequential damages of any character arising as a
|
|
160
|
+
result of this License or out of the use or inability to use the
|
|
161
|
+
Work (including but not limited to damages for loss of goodwill,
|
|
162
|
+
work stoppage, computer failure or malfunction, or any and all
|
|
163
|
+
other commercial damages or losses), even if such Contributor
|
|
164
|
+
has been advised of the possibility of such damages.
|
|
165
|
+
|
|
166
|
+
9. Accepting Warranty or Additional Liability. While redistributing
|
|
167
|
+
the Work or Derivative Works thereof, You may choose to offer,
|
|
168
|
+
and charge a fee for, acceptance of support, warranty, indemnity,
|
|
169
|
+
or other liability obligations and/or rights consistent with this
|
|
170
|
+
License. However, in accepting such obligations, You may act only
|
|
171
|
+
on Your own behalf and on Your sole responsibility, not on behalf
|
|
172
|
+
of any other Contributor, and only if You agree to indemnify,
|
|
173
|
+
defend, and hold each Contributor harmless for any liability
|
|
174
|
+
incurred by, or claims asserted against, such Contributor by reason
|
|
175
|
+
of your accepting any such warranty or additional liability.
|
|
176
|
+
|
|
177
|
+
END OF TERMS AND CONDITIONS
|
|
178
|
+
|
|
179
|
+
APPENDIX: How to apply the Apache License to your work.
|
|
180
|
+
|
|
181
|
+
To apply the Apache License to your work, attach the following
|
|
182
|
+
boilerplate notice, with the fields enclosed by brackets "[]"
|
|
183
|
+
replaced with your own identifying information. (Don't include
|
|
184
|
+
the brackets!) The text should be enclosed in the appropriate
|
|
185
|
+
comment syntax for the file format. We also recommend that a
|
|
186
|
+
file or class name and description of purpose be included on the
|
|
187
|
+
same "printed page" as the copyright notice for easier
|
|
188
|
+
identification within third-party archives.
|
|
189
|
+
|
|
190
|
+
Copyright [yyyy] [name of copyright owner]
|
|
191
|
+
|
|
192
|
+
Licensed under the Apache License, Version 2.0 (the "License");
|
|
193
|
+
you may not use this file except in compliance with the License.
|
|
194
|
+
You may obtain a copy of the License at
|
|
195
|
+
|
|
196
|
+
http://www.apache.org/licenses/LICENSE-2.0
|
|
197
|
+
|
|
198
|
+
Unless required by applicable law or agreed to in writing, software
|
|
199
|
+
distributed under the License is distributed on an "AS IS" BASIS,
|
|
200
|
+
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
|
201
|
+
See the License for the specific language governing permissions and
|
|
202
|
+
limitations under the License.
|
|
@@ -0,0 +1,318 @@
|
|
|
1
|
+
Metadata-Version: 2.4
|
|
2
|
+
Name: tool-guard-core
|
|
3
|
+
Version: 0.8.0
|
|
4
|
+
Summary: Python SDK for Tool Guard Core — universal AI agent governance
|
|
5
|
+
Author: DIMAGGI AI
|
|
6
|
+
License-Expression: Apache-2.0
|
|
7
|
+
Project-URL: Homepage, https://dimaggi.ai/tool-guard
|
|
8
|
+
Project-URL: Documentation, https://github.com/dimaggi-ai/tool-guard-core/tree/main/sdk/python
|
|
9
|
+
Project-URL: Source, https://github.com/dimaggi-ai/tool-guard-core
|
|
10
|
+
Project-URL: Issues, https://github.com/dimaggi-ai/tool-guard-core/issues
|
|
11
|
+
Keywords: ai,agents,governance,policy,tool-guard
|
|
12
|
+
Classifier: Development Status :: 4 - Beta
|
|
13
|
+
Classifier: Intended Audience :: Developers
|
|
14
|
+
Classifier: Programming Language :: Python :: 3
|
|
15
|
+
Classifier: Programming Language :: Python :: 3.10
|
|
16
|
+
Classifier: Programming Language :: Python :: 3.11
|
|
17
|
+
Classifier: Programming Language :: Python :: 3.12
|
|
18
|
+
Classifier: Topic :: Software Development :: Libraries :: Python Modules
|
|
19
|
+
Requires-Python: >=3.10
|
|
20
|
+
Description-Content-Type: text/markdown
|
|
21
|
+
License-File: LICENSE
|
|
22
|
+
Requires-Dist: httpx>=0.27
|
|
23
|
+
Provides-Extra: langchain
|
|
24
|
+
Requires-Dist: langchain-core>=0.3; extra == "langchain"
|
|
25
|
+
Provides-Extra: autogen
|
|
26
|
+
Requires-Dist: pyautogen>=0.2; extra == "autogen"
|
|
27
|
+
Provides-Extra: openai
|
|
28
|
+
Requires-Dist: openai>=1.0; extra == "openai"
|
|
29
|
+
Provides-Extra: anthropic
|
|
30
|
+
Requires-Dist: anthropic>=0.30; extra == "anthropic"
|
|
31
|
+
Provides-Extra: dev
|
|
32
|
+
Requires-Dist: pytest>=8; extra == "dev"
|
|
33
|
+
Requires-Dist: pytest-cov>=5; extra == "dev"
|
|
34
|
+
Requires-Dist: pytest-asyncio>=0.24; extra == "dev"
|
|
35
|
+
Requires-Dist: httpx>=0.27; extra == "dev"
|
|
36
|
+
Requires-Dist: langchain-core>=0.3; extra == "dev"
|
|
37
|
+
Dynamic: license-file
|
|
38
|
+
|
|
39
|
+
# toolguard — Python SDK for Tool Guard Core
|
|
40
|
+
|
|
41
|
+
Universal AI agent governance: evaluate any tool call against configurable
|
|
42
|
+
policies before it executes. Drop-in adapters for LangChain, AutoGen,
|
|
43
|
+
native OpenAI/Anthropic tool use, and MCP. Two backends — CLI (`tg evaluate`)
|
|
44
|
+
and HTTP proxy (`tg-proxy /evaluate`) — so you can run locally or in production.
|
|
45
|
+
|
|
46
|
+
## Install
|
|
47
|
+
|
|
48
|
+
The PyPI distribution is named `tool-guard-core` because the unqualified
|
|
49
|
+
`toolguard` project belongs to an unrelated package. The import remains
|
|
50
|
+
`toolguard`. Tagged releases beginning with v0.8.0 install with:
|
|
51
|
+
|
|
52
|
+
```bash
|
|
53
|
+
pip install "tool-guard-core" # core only (httpx)
|
|
54
|
+
pip install "tool-guard-core[langchain]" # + langchain-core
|
|
55
|
+
pip install "tool-guard-core[autogen]" # + pyautogen
|
|
56
|
+
pip install "tool-guard-core[openai]" # + openai SDK
|
|
57
|
+
pip install "tool-guard-core[anthropic]" # + anthropic SDK
|
|
58
|
+
```
|
|
59
|
+
|
|
60
|
+
Before v0.8.0, or when testing an unreleased checkout, use
|
|
61
|
+
`pip install "./sdk/python[langchain]"` from the repository root.
|
|
62
|
+
|
|
63
|
+
## Quick start
|
|
64
|
+
|
|
65
|
+
```python
|
|
66
|
+
from toolguard import ToolGuard, ToolDenied
|
|
67
|
+
|
|
68
|
+
guard = ToolGuard(
|
|
69
|
+
mode="proxy", # or "cli" to run tg locally
|
|
70
|
+
proxy_url="http://localhost:9090",
|
|
71
|
+
agent_id="my-agent",
|
|
72
|
+
org_id="acme",
|
|
73
|
+
)
|
|
74
|
+
|
|
75
|
+
try:
|
|
76
|
+
result = guard.evaluate("issue_refund", {"amount": 1000})
|
|
77
|
+
# allowed — call the real tool
|
|
78
|
+
except ToolDenied as exc:
|
|
79
|
+
# exc.result.decision_reason, exc.result.suggested_response
|
|
80
|
+
print("Blocked:", exc)
|
|
81
|
+
```
|
|
82
|
+
|
|
83
|
+
### CLI mode (no running proxy)
|
|
84
|
+
|
|
85
|
+
```python
|
|
86
|
+
guard = ToolGuard(
|
|
87
|
+
mode="cli",
|
|
88
|
+
tg_bin="/usr/local/bin/tg", # or just "tg" if on PATH
|
|
89
|
+
policy_dir="/etc/tg/policies", # directory of *.yaml policies
|
|
90
|
+
agent_id="my-agent",
|
|
91
|
+
org_id="acme",
|
|
92
|
+
)
|
|
93
|
+
result = guard.evaluate_raw("issue_refund", {"amount": 100})
|
|
94
|
+
print(result.decision) # "allowed"
|
|
95
|
+
```
|
|
96
|
+
|
|
97
|
+
CLI mode evaluates the whole policy directory as one set. Each policy's YAML
|
|
98
|
+
mode owns its contribution: a `mode: shadow` policy remains observe-only under
|
|
99
|
+
the CLI's default `enforcement` call-site mode, while a `mode: enforcement`
|
|
100
|
+
policy cannot be downgraded by a shadow default. Mixed-mode behavior is pinned
|
|
101
|
+
against the real Go engine in `tests/test_contract.py`.
|
|
102
|
+
|
|
103
|
+
`evaluate()` raises `ToolDenied` or `ToolEscalated` on a block.
|
|
104
|
+
`evaluate_raw()` always returns the `EvaluationResult` without raising.
|
|
105
|
+
|
|
106
|
+
---
|
|
107
|
+
|
|
108
|
+
## LangChain / LangGraph
|
|
109
|
+
|
|
110
|
+
```python
|
|
111
|
+
from toolguard import ToolGuard
|
|
112
|
+
from toolguard.adapters.langchain import ToolGuardCallbackHandler
|
|
113
|
+
from langchain_openai import ChatOpenAI
|
|
114
|
+
from langchain.agents import AgentExecutor
|
|
115
|
+
|
|
116
|
+
guard = ToolGuard(mode="proxy", proxy_url="http://localhost:9090",
|
|
117
|
+
agent_id="lc-agent", org_id="acme")
|
|
118
|
+
|
|
119
|
+
handler = ToolGuardCallbackHandler(
|
|
120
|
+
guard,
|
|
121
|
+
tool_groups={"issue_refund": "monetary_outflow", "search": "read_ops"},
|
|
122
|
+
)
|
|
123
|
+
|
|
124
|
+
executor = AgentExecutor(agent=agent, tools=tools, callbacks=[handler])
|
|
125
|
+
# Every tool call goes through policy evaluation before execution.
|
|
126
|
+
```
|
|
127
|
+
|
|
128
|
+
The handler raises `ToolDenied` / `ToolEscalated` on a block, stopping
|
|
129
|
+
the chain. Flagged calls (recorded near-misses) proceed.
|
|
130
|
+
|
|
131
|
+
---
|
|
132
|
+
|
|
133
|
+
## Microsoft AutoGen
|
|
134
|
+
|
|
135
|
+
```python
|
|
136
|
+
from toolguard import ToolGuard
|
|
137
|
+
from toolguard.adapters.autogen import guarded
|
|
138
|
+
|
|
139
|
+
guard = ToolGuard(mode="proxy", proxy_url="http://localhost:9090",
|
|
140
|
+
agent_id="autogen-agent", org_id="acme")
|
|
141
|
+
|
|
142
|
+
@guarded(guard, tool_name="issue_refund", tool_group="monetary_outflow")
|
|
143
|
+
def issue_refund(order_id: str, amount: float) -> dict:
|
|
144
|
+
return {"status": "refunded", "amount": amount}
|
|
145
|
+
|
|
146
|
+
# Register with AutoGen as normal:
|
|
147
|
+
assistant.register_for_execution(name="issue_refund")(issue_refund)
|
|
148
|
+
```
|
|
149
|
+
|
|
150
|
+
On deny/escalate, `guarded` returns `{"error": "denied", "reason": "...",
|
|
151
|
+
"suggested_response": "..."}` — the conversation loop surfaces it to the LLM.
|
|
152
|
+
|
|
153
|
+
---
|
|
154
|
+
|
|
155
|
+
## Native OpenAI tool use
|
|
156
|
+
|
|
157
|
+
```python
|
|
158
|
+
import openai
|
|
159
|
+
from toolguard import ToolGuard
|
|
160
|
+
from toolguard.adapters.native import guard_tool_calls
|
|
161
|
+
|
|
162
|
+
client_oai = openai.OpenAI()
|
|
163
|
+
guard = ToolGuard(mode="proxy", proxy_url="http://localhost:9090",
|
|
164
|
+
agent_id="openai-agent", org_id="acme")
|
|
165
|
+
|
|
166
|
+
response = client_oai.chat.completions.create(
|
|
167
|
+
model="gpt-4o",
|
|
168
|
+
messages=messages,
|
|
169
|
+
tools=tools,
|
|
170
|
+
)
|
|
171
|
+
|
|
172
|
+
allowed, denied = guard_tool_calls(
|
|
173
|
+
response.choices[0].message.tool_calls,
|
|
174
|
+
guard,
|
|
175
|
+
provider="openai",
|
|
176
|
+
tool_groups={"issue_refund": "monetary_outflow"},
|
|
177
|
+
)
|
|
178
|
+
|
|
179
|
+
tool_results = []
|
|
180
|
+
for item in allowed:
|
|
181
|
+
call = item["call"]
|
|
182
|
+
output = MY_TOOLS[call.function.name](**json.loads(call.function.arguments))
|
|
183
|
+
tool_results.append({"role": "tool", "tool_call_id": call.id, "content": str(output)})
|
|
184
|
+
for item in denied:
|
|
185
|
+
tool_results.append(item["tool_result"]) # role=tool, error message
|
|
186
|
+
```
|
|
187
|
+
|
|
188
|
+
---
|
|
189
|
+
|
|
190
|
+
## Native Anthropic tool use
|
|
191
|
+
|
|
192
|
+
```python
|
|
193
|
+
import anthropic
|
|
194
|
+
from toolguard import ToolGuard
|
|
195
|
+
from toolguard.adapters.native import guard_tool_calls
|
|
196
|
+
|
|
197
|
+
client_ant = anthropic.Anthropic()
|
|
198
|
+
guard = ToolGuard(mode="proxy", proxy_url="http://localhost:9090",
|
|
199
|
+
agent_id="anthropic-agent", org_id="acme")
|
|
200
|
+
|
|
201
|
+
response = client_ant.messages.create(
|
|
202
|
+
model="claude-opus-4-5",
|
|
203
|
+
max_tokens=4096,
|
|
204
|
+
tools=tools,
|
|
205
|
+
messages=messages,
|
|
206
|
+
)
|
|
207
|
+
|
|
208
|
+
tool_use_blocks = [b for b in response.content if b.type == "tool_use"]
|
|
209
|
+
allowed, denied = guard_tool_calls(tool_use_blocks, guard, provider="anthropic")
|
|
210
|
+
|
|
211
|
+
tool_results = []
|
|
212
|
+
for item in allowed:
|
|
213
|
+
call = item["call"]
|
|
214
|
+
output = MY_TOOLS[call.name](**call.input)
|
|
215
|
+
tool_results.append({"type": "tool_result", "tool_use_id": call.id, "content": str(output)})
|
|
216
|
+
for item in denied:
|
|
217
|
+
tool_results.append(item["tool_result"]) # type=tool_result, is_error=True
|
|
218
|
+
```
|
|
219
|
+
|
|
220
|
+
---
|
|
221
|
+
|
|
222
|
+
## MCP server
|
|
223
|
+
|
|
224
|
+
```python
|
|
225
|
+
from toolguard import ToolGuard
|
|
226
|
+
from toolguard.adapters.mcp import guard_mcp_tool
|
|
227
|
+
|
|
228
|
+
guard = ToolGuard(mode="proxy", proxy_url="http://localhost:9090",
|
|
229
|
+
agent_id="mcp-server", org_id="acme")
|
|
230
|
+
|
|
231
|
+
@guard_mcp_tool(guard, tool_group="data_access")
|
|
232
|
+
def call_tool(tool_name: str, parameters: dict, **kwargs) -> dict:
|
|
233
|
+
return TOOLS[tool_name](**parameters)
|
|
234
|
+
```
|
|
235
|
+
|
|
236
|
+
---
|
|
237
|
+
|
|
238
|
+
## Errors
|
|
239
|
+
|
|
240
|
+
| Exception | When raised |
|
|
241
|
+
|---|---|
|
|
242
|
+
| `ToolDenied` | `action_taken` is anything other than `allowed`, `allowed_shadow`, `flagged`, or `escalated` (i.e. the call was actually blocked) |
|
|
243
|
+
| `ToolEscalated` | `action_taken == "escalated"` (wait for human approval) |
|
|
244
|
+
|
|
245
|
+
Raised on `action_taken`, not `decision` — deliberately. In shadow mode
|
|
246
|
+
the engine reports `decision="denied"` (what *would* happen) alongside
|
|
247
|
+
`action_taken="allowed_shadow"` (what *actually* happened, since shadow
|
|
248
|
+
mode never enforces); `evaluate()` never raises for that case, since
|
|
249
|
+
shadow mode exists specifically to observe without blocking.
|
|
250
|
+
|
|
251
|
+
Both carry a `.result` attribute with the full `EvaluationResult`:
|
|
252
|
+
`result.decision_reason`, `result.suggested_response`, `result.rule_results`, etc.
|
|
253
|
+
|
|
254
|
+
---
|
|
255
|
+
|
|
256
|
+
## Wire contract
|
|
257
|
+
|
|
258
|
+
The SDK mirrors the Go `pkg/domain` JSON contract exactly. Key field names:
|
|
259
|
+
|
|
260
|
+
**ActionEnvelope** (what the SDK sends to the engine):
|
|
261
|
+
`envelope_id`, `timestamp`, `agent_id`, `session_id`, `org_id`,
|
|
262
|
+
`framework` (`"mcp"` | `"langgraph"` | `"sdk"` | `"unknown"`),
|
|
263
|
+
`tool_name`, `tool_group`, `parameters`, `context.verified`,
|
|
264
|
+
`context.session_state`, `integration_type` (`"mcp_proxy"` |
|
|
265
|
+
`"langgraph_middleware"` | `"sdk"`).
|
|
266
|
+
|
|
267
|
+
**EvaluationResult** (what the engine returns):
|
|
268
|
+
`decision` (`"allowed"` | `"denied"` | `"escalated"` | `"flagged"`),
|
|
269
|
+
`action_taken`, `decision_reason`, `effective_mode`, `policies_matched`,
|
|
270
|
+
`rules_evaluated`, `rules_triggered`, `rule_results`, `applied_rule_results`,
|
|
271
|
+
`primary_citation`, `applied_primary_citation`, `is_near_miss`,
|
|
272
|
+
`suggested_response`, and the proxy-only optional `decision_receipt`. The
|
|
273
|
+
applied provenance fields explain `action_taken`;
|
|
274
|
+
the aggregate fields can point to stricter shadow-only telemetry.
|
|
275
|
+
|
|
276
|
+
**DecisionReceipt** (after a successful proxy audit append):
|
|
277
|
+
`receipt_version`, `trace_id`, `trace_hash`, `hash_algorithm`,
|
|
278
|
+
`canonical_trace_version`, `integrity_model`, `decision`, `action_taken`,
|
|
279
|
+
`timestamp`, optional `issuer`, and the opaque `receipt_uri`.
|
|
280
|
+
|
|
281
|
+
**Escalation** (poll/approve/deny responses): `id`, `state`, timestamps,
|
|
282
|
+
approver fields, `envelope`, `decision`, and an optional
|
|
283
|
+
`resolution_receipt` after the terminal resolution was audited.
|
|
284
|
+
|
|
285
|
+
## Decision-receipt helper
|
|
286
|
+
|
|
287
|
+
```python
|
|
288
|
+
from toolguard.adapters.memory import with_receipt_reference
|
|
289
|
+
|
|
290
|
+
result = guard.evaluate_raw("issue_refund", {"amount": 100})
|
|
291
|
+
event = with_receipt_reference(
|
|
292
|
+
{"tool": "issue_refund", "outcome": result.action_taken}, result
|
|
293
|
+
)
|
|
294
|
+
```
|
|
295
|
+
|
|
296
|
+
The helper adds `tool_guard_receipt_uri` only when the proxy supplied a real
|
|
297
|
+
receipt. It performs no storage or network operation and never fabricates a
|
|
298
|
+
fallback identifier. Absence is never authorization. The URN is a
|
|
299
|
+
tamper-evident hash-chain reference, not a signature or fetchable URL; see the
|
|
300
|
+
[full contract](../../docs/integration.md#7-decision-receipts).
|
|
301
|
+
|
|
302
|
+
---
|
|
303
|
+
|
|
304
|
+
## Development
|
|
305
|
+
|
|
306
|
+
```bash
|
|
307
|
+
cd sdk/python
|
|
308
|
+
python3 -m venv .venv
|
|
309
|
+
source .venv/bin/activate
|
|
310
|
+
pip install -e ".[dev]"
|
|
311
|
+
pytest tests/ --cov-fail-under=90
|
|
312
|
+
```
|
|
313
|
+
|
|
314
|
+
Or via the top-level Makefile:
|
|
315
|
+
|
|
316
|
+
```bash
|
|
317
|
+
make sdk-test
|
|
318
|
+
```
|