fullcourtdefense-agent 0.2.2__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 (49) hide show
  1. fullcourtdefense_agent-0.2.2/MANIFEST.in +3 -0
  2. fullcourtdefense_agent-0.2.2/PKG-INFO +132 -0
  3. fullcourtdefense_agent-0.2.2/README.md +111 -0
  4. fullcourtdefense_agent-0.2.2/pyproject.toml +46 -0
  5. fullcourtdefense_agent-0.2.2/setup.cfg +4 -0
  6. fullcourtdefense_agent-0.2.2/setup.py +21 -0
  7. fullcourtdefense_agent-0.2.2/src/fullcourtdefense_agent/__init__.py +51 -0
  8. fullcourtdefense_agent-0.2.2/src/fullcourtdefense_agent/_args_bounds.py +62 -0
  9. fullcourtdefense_agent-0.2.2/src/fullcourtdefense_agent/_autoguard.py +195 -0
  10. fullcourtdefense_agent-0.2.2/src/fullcourtdefense_agent/_failsafe.py +70 -0
  11. fullcourtdefense_agent-0.2.2/src/fullcourtdefense_agent/_http.py +251 -0
  12. fullcourtdefense_agent-0.2.2/src/fullcourtdefense_agent/_spool.py +122 -0
  13. fullcourtdefense_agent-0.2.2/src/fullcourtdefense_agent/_version.py +3 -0
  14. fullcourtdefense_agent-0.2.2/src/fullcourtdefense_agent/adk.py +237 -0
  15. fullcourtdefense_agent-0.2.2/src/fullcourtdefense_agent/circuit_breaker.py +182 -0
  16. fullcourtdefense_agent-0.2.2/src/fullcourtdefense_agent/errors.py +72 -0
  17. fullcourtdefense_agent-0.2.2/src/fullcourtdefense_agent/frameworks.py +249 -0
  18. fullcourtdefense_agent-0.2.2/src/fullcourtdefense_agent/gate.py +1448 -0
  19. fullcourtdefense_agent-0.2.2/src/fullcourtdefense_agent/identity.py +119 -0
  20. fullcourtdefense_agent-0.2.2/src/fullcourtdefense_agent/lambda_gate.py +514 -0
  21. fullcourtdefense_agent-0.2.2/src/fullcourtdefense_agent.egg-info/PKG-INFO +132 -0
  22. fullcourtdefense_agent-0.2.2/src/fullcourtdefense_agent.egg-info/SOURCES.txt +47 -0
  23. fullcourtdefense_agent-0.2.2/src/fullcourtdefense_agent.egg-info/dependency_links.txt +1 -0
  24. fullcourtdefense_agent-0.2.2/src/fullcourtdefense_agent.egg-info/requires.txt +3 -0
  25. fullcourtdefense_agent-0.2.2/src/fullcourtdefense_agent.egg-info/top_level.txt +1 -0
  26. fullcourtdefense_agent-0.2.2/src/fullcourtdefense_agent_autoguard.pth +1 -0
  27. fullcourtdefense_agent-0.2.2/tests/_wheel.py +44 -0
  28. fullcourtdefense_agent-0.2.2/tests/adk_stub/google/adk/__init__.py +1 -0
  29. fullcourtdefense_agent-0.2.2/tests/adk_stub/google/adk/plugins/__init__.py +1 -0
  30. fullcourtdefense_agent-0.2.2/tests/adk_stub/google/adk/plugins/base_plugin.py +15 -0
  31. fullcourtdefense_agent-0.2.2/tests/adk_stub/google/adk/plugins/plugin_manager.py +35 -0
  32. fullcourtdefense_agent-0.2.2/tests/adk_stub/google/adk/runners.py +39 -0
  33. fullcourtdefense_agent-0.2.2/tests/conftest.py +148 -0
  34. fullcourtdefense_agent-0.2.2/tests/exit_child.py +23 -0
  35. fullcourtdefense_agent-0.2.2/tests/test_adk_plugin.py +241 -0
  36. fullcourtdefense_agent-0.2.2/tests/test_adk_real.py +124 -0
  37. fullcourtdefense_agent-0.2.2/tests/test_args_bounds_and_key_modes.py +188 -0
  38. fullcourtdefense_agent-0.2.2/tests/test_autoguard_pth.py +80 -0
  39. fullcourtdefense_agent-0.2.2/tests/test_breaker_fast_path.py +119 -0
  40. fullcourtdefense_agent-0.2.2/tests/test_contract.py +98 -0
  41. fullcourtdefense_agent-0.2.2/tests/test_first_call_and_args.py +126 -0
  42. fullcourtdefense_agent-0.2.2/tests/test_gate.py +534 -0
  43. fullcourtdefense_agent-0.2.2/tests/test_http_keepalive.py +109 -0
  44. fullcourtdefense_agent-0.2.2/tests/test_http_transport.py +121 -0
  45. fullcourtdefense_agent-0.2.2/tests/test_identity_and_errors.py +245 -0
  46. fullcourtdefense_agent-0.2.2/tests/test_lambda_gate.py +472 -0
  47. fullcourtdefense_agent-0.2.2/tests/test_monitor_never_waits.py +94 -0
  48. fullcourtdefense_agent-0.2.2/tests/test_records_survive_exit.py +140 -0
  49. fullcourtdefense_agent-0.2.2/tests/test_requirements_pin.py +68 -0
@@ -0,0 +1,3 @@
1
+ include README.md
2
+ include src/fullcourtdefense_agent_autoguard.pth
3
+ recursive-include tests *.py
@@ -0,0 +1,132 @@
1
+ Metadata-Version: 2.4
2
+ Name: fullcourtdefense-agent
3
+ Version: 0.2.2
4
+ Summary: FullCourtDefense agent hook: checks every AI-agent tool call against your organisation's action policy before it runs. Standard library only; Google ADK plugin, OpenAI Agents SDK and LangChain tool wrappers, and an opt-in start-up hook (FCD_AUTOGUARD).
5
+ Author: Full Court Defense
6
+ License-Expression: MIT
7
+ Project-URL: Homepage, https://fullcourtdefense.ai
8
+ Keywords: ai-agent-security,tool-call,action-policy,google-adk,openai-agents,langchain,vertex-ai,agent-engine,fullcourtdefense
9
+ Classifier: Development Status :: 4 - Beta
10
+ Classifier: Intended Audience :: Developers
11
+ Classifier: Programming Language :: Python :: 3
12
+ Classifier: Programming Language :: Python :: 3.10
13
+ Classifier: Programming Language :: Python :: 3.11
14
+ Classifier: Programming Language :: Python :: 3.12
15
+ Classifier: Programming Language :: Python :: 3.13
16
+ Classifier: Topic :: Security
17
+ Requires-Python: >=3.10
18
+ Description-Content-Type: text/markdown
19
+ Provides-Extra: dev
20
+ Requires-Dist: pytest; extra == "dev"
21
+
22
+ # fullcourtdefense-agent
23
+
24
+ FullCourtDefense checks every tool call of an AI agent against your
25
+ organisation's action policy **before the tool runs**. This package is the
26
+ small agent hook: standard library only (no `httpx`, `requests` or `openai`),
27
+ so adding it to a deployed agent does not change the versions of anything the
28
+ agent already uses.
29
+
30
+ ## Install
31
+
32
+ Pin it exactly. Do not add `--hash`: pip's hash checking is all-or-nothing, so
33
+ one hashed line makes every other line of the file need a hash too, and an
34
+ agent's unpinned requirements stop building.
35
+
36
+ ```
37
+ fullcourtdefense-agent==0.2.2
38
+ ```
39
+
40
+ ## Configure
41
+
42
+ | Variable | Meaning |
43
+ |---|---|
44
+ | `FCD_SHIELD_ID` | The agent's shield (`sh_...`). Required. |
45
+ | `FCD_SHIELD_KEY` | The shield key. |
46
+ | `FCD_API_URL` | FullCourtDefense API (default `https://api.fullcourtdefense.ai`). |
47
+ | `FCD_AGENT_ID` | The agent's identity in the console (also read: `FULLCOURTDEFENSE_AGENT_ID`, `FCD_AGENT_NAME`, `FCD_WORKLOAD_NAME`). Unset: the name of the service the process runs as (`OTEL_SERVICE_NAME`, Cloud Run `K_SERVICE`, `AWS_LAMBDA_FUNCTION_NAME`, Azure `CONTAINER_APP_NAME` / `WEBSITE_SITE_NAME`, ...), else the main script, so agents never collapse into `unknown-agent`. Every call says which (`agentIdSource`: `config`, `env` or `default`). A name passed in code (`agent_id=` or `agent_name=` on the call or on `protect()`) is declared: `config`. |
48
+ | `FCD_FAIL_MODE` | What a **block-mode** shield does while FullCourtDefense cannot be reached. `tiered` (default when unset; owner decision 2026-10-27, replaces `closed`): only the agent's never-allowed rules (cached from the runtime bundle) stop a call; any other action runs, is logged as a warning and is reported to FullCourtDefense as "ran without a check" (`ranDuringOutage`) once it answers again, and a rule that needs a manager runs unattended with `wouldHaveNeeded: "manager"`. The built-in emergency list no longer stops anything. `closed`: no tool runs. `open`: nothing is stopped. An unknown value is read as `closed`. |
49
+ | `FCD_MODE_AT_PROTECT` | `monitor` or `block`: the shield's mode when the agent was protected. Used only until the live mode has been read once, so a monitor-mode agent that starts while the API is down still never blocks. Set it to avoid the one-time mode lookup on the first call (the cloud Protect and the init wizard already set it); without it the first call waits for that lookup (at most 1.5 s), so an Enforce shield's first call is checked. A check waits at most 1.5 s before the fail mode answers (`timeout=`); If FullCourtDefense hangs or cannot be reached, at most one call waits up to 1.5 s; after that, calls answer instantly (from the fail mode) until we're back. A hang or a network error opens the circuit breaker at once; while it is open one background probe runs every 10 s (calls never wait on it) and a successful probe restores live checks. HTTP answers (4xx / 5xx with a body) are handled as before. |
50
+ | `FCD_SDK_SPOOL` / `FCD_SDK_SPOOL_DIR` | Records a short-lived process could not send before it ended (the end of the process waits at most 1.5 s for them) are kept in a small file in the user cache directory (`~/.cache/fullcourtdefense/sdk-spool`, `%LOCALAPPDATA%`, `~/Library/Caches`) and sent by the next start with the same shield. `FCD_SDK_SPOOL=off` disables it; `FCD_SDK_SPOOL_DIR` moves it. |
51
+ | `FCD_AUTOGUARD` | `adk`: add the gate to every Google ADK `Runner` at start-up (below). Unset: the start-up hook does nothing. |
52
+ | `FCD_APPROVAL_MODE` | ADK plugin: `block` (default) stops a call that needs a manager's approval; `wait` holds it until a person decides (`FCD_APPROVAL_TIMEOUT_S`, default 900). |
53
+
54
+ A **monitor-mode** shield never blocks and never waits: the tool runs at once
55
+ and the call is recorded in the background.
56
+
57
+ ## Use
58
+
59
+ ```python
60
+ from fullcourtdefense_agent import ToolGate, ToolCallBlocked
61
+
62
+ gate = ToolGate.from_env()
63
+
64
+ # A function, checked before every call (sync or async def):
65
+ safe_refund = gate.protect(issue_refund, operation="refund")
66
+
67
+ # Or one call:
68
+ gate.guard_tool_call("issue_refund", lambda: issue_refund("o_1", 120),
69
+ tool_args={"order": "o_1", "amount": 120}, operation="refund")
70
+ ```
71
+
72
+ A blocked call raises `ToolCallBlocked`; the tool did not run.
73
+
74
+ **A wrong key, a refused or unknown shield, a refused request (HTTP 401 / 403 / 404 / 400)
75
+ is not an outage.** The fail mode does not apply: the tool does not run, the check is not
76
+ reported later as "ran without a check", and `FullCourtDefenseApiError` (a
77
+ `ToolCallBlocked` with `status` and `code`: `FCD_UNAUTHORIZED`, `FCD_FORBIDDEN`,
78
+ `FCD_SHIELD_NOT_FOUND`, `FCD_BAD_REQUEST`) says what to change. It is also logged once on the
79
+ `fullcourtdefense` logger. Any other 4xx except 408 / 429 (a 413, for example) is answered the same
80
+ way. Only a real outage (no answer, 5xx, 408, 429) is answered by the fail mode.
81
+
82
+ **On a monitor shield (owner decision O4)** a refused key or shield does not stop the tool: the mode
83
+ the gate knows (a live answer earlier in the process, else `FCD_MODE_AT_PROTECT`) is monitor, so the
84
+ tool runs and the call is still reported, and FullCourtDefense raises a "wrong or missing shield key"
85
+ alert. With no known mode the shield is treated as block.
86
+
87
+ **Arguments too deep or too large to check** (nested deeper than 32 levels, more than 20,000 values)
88
+ are never sent: in block mode the call is stopped (`ToolCallBlocked`, "too large to check safely"), in
89
+ monitor mode it runs and the record says what was not sent. Never an outage.
90
+
91
+ ### OpenAI Agents SDK and LangChain
92
+
93
+ ```python
94
+ from fullcourtdefense_agent.frameworks import protect_openai_agents_tool, protect_langchain_base_tool
95
+
96
+ agent = Agent(name="support", tools=[protect_openai_agents_tool(gate, lookup_customer)]) # still a FunctionTool
97
+ safe_sql = protect_langchain_base_tool(gate, sql_query) # still a BaseTool
98
+ ```
99
+
100
+ The full SDK (`pip install fullcourtdefense`) does the same with `fcd.protect(tool)`.
101
+
102
+ ### Google ADK
103
+
104
+ ```python
105
+ from google.adk.apps import App
106
+ from fullcourtdefense_agent.adk import FcdToolGuardPlugin
107
+
108
+ app = App(name="billing", root_agent=root_agent, plugins=[FcdToolGuardPlugin()])
109
+ ```
110
+
111
+ A blocked call is answered to the model as
112
+ `{"blocked": true, "reason": "...", "by": "FullCourtDefense"}` and the tool does
113
+ not run. Gemini's built-in tools (Google Search, built-in code execution,
114
+ Vertex AI Search grounding) run inside Google and are not checked.
115
+
116
+ ### Start-up hook (no code change)
117
+
118
+ The wheel installs `fullcourtdefense_agent_autoguard.pth` into site-packages.
119
+ Python runs its one line at start-up. **Without `FCD_AUTOGUARD` it only reads
120
+ that variable and stops.** With `FCD_AUTOGUARD=adk` it waits for
121
+ `google.adk.runners` to load and adds the plugin to every `Runner` the process
122
+ creates, after the agent's own plugins. Security scanners flag start-up lines
123
+ in `.pth` files as a supply-chain technique; this one is disclosed here, pinned
124
+ by exact version and inert unless the variable is set. If the plugin cannot be
125
+ added (an unsupported ADK version), the hook logs an error on the
126
+ `fullcourtdefense` logger and stderr; it never stops the agent from starting.
127
+
128
+ ## What leaves the agent
129
+
130
+ The tool name, the operation, the agent identity, the session id and the tool
131
+ arguments (the policy input; the server minimises them before storing). Never
132
+ the tool's result and never the text of an error the tool raised.
@@ -0,0 +1,111 @@
1
+ # fullcourtdefense-agent
2
+
3
+ FullCourtDefense checks every tool call of an AI agent against your
4
+ organisation's action policy **before the tool runs**. This package is the
5
+ small agent hook: standard library only (no `httpx`, `requests` or `openai`),
6
+ so adding it to a deployed agent does not change the versions of anything the
7
+ agent already uses.
8
+
9
+ ## Install
10
+
11
+ Pin it exactly. Do not add `--hash`: pip's hash checking is all-or-nothing, so
12
+ one hashed line makes every other line of the file need a hash too, and an
13
+ agent's unpinned requirements stop building.
14
+
15
+ ```
16
+ fullcourtdefense-agent==0.2.2
17
+ ```
18
+
19
+ ## Configure
20
+
21
+ | Variable | Meaning |
22
+ |---|---|
23
+ | `FCD_SHIELD_ID` | The agent's shield (`sh_...`). Required. |
24
+ | `FCD_SHIELD_KEY` | The shield key. |
25
+ | `FCD_API_URL` | FullCourtDefense API (default `https://api.fullcourtdefense.ai`). |
26
+ | `FCD_AGENT_ID` | The agent's identity in the console (also read: `FULLCOURTDEFENSE_AGENT_ID`, `FCD_AGENT_NAME`, `FCD_WORKLOAD_NAME`). Unset: the name of the service the process runs as (`OTEL_SERVICE_NAME`, Cloud Run `K_SERVICE`, `AWS_LAMBDA_FUNCTION_NAME`, Azure `CONTAINER_APP_NAME` / `WEBSITE_SITE_NAME`, ...), else the main script, so agents never collapse into `unknown-agent`. Every call says which (`agentIdSource`: `config`, `env` or `default`). A name passed in code (`agent_id=` or `agent_name=` on the call or on `protect()`) is declared: `config`. |
27
+ | `FCD_FAIL_MODE` | What a **block-mode** shield does while FullCourtDefense cannot be reached. `tiered` (default when unset; owner decision 2026-10-27, replaces `closed`): only the agent's never-allowed rules (cached from the runtime bundle) stop a call; any other action runs, is logged as a warning and is reported to FullCourtDefense as "ran without a check" (`ranDuringOutage`) once it answers again, and a rule that needs a manager runs unattended with `wouldHaveNeeded: "manager"`. The built-in emergency list no longer stops anything. `closed`: no tool runs. `open`: nothing is stopped. An unknown value is read as `closed`. |
28
+ | `FCD_MODE_AT_PROTECT` | `monitor` or `block`: the shield's mode when the agent was protected. Used only until the live mode has been read once, so a monitor-mode agent that starts while the API is down still never blocks. Set it to avoid the one-time mode lookup on the first call (the cloud Protect and the init wizard already set it); without it the first call waits for that lookup (at most 1.5 s), so an Enforce shield's first call is checked. A check waits at most 1.5 s before the fail mode answers (`timeout=`); If FullCourtDefense hangs or cannot be reached, at most one call waits up to 1.5 s; after that, calls answer instantly (from the fail mode) until we're back. A hang or a network error opens the circuit breaker at once; while it is open one background probe runs every 10 s (calls never wait on it) and a successful probe restores live checks. HTTP answers (4xx / 5xx with a body) are handled as before. |
29
+ | `FCD_SDK_SPOOL` / `FCD_SDK_SPOOL_DIR` | Records a short-lived process could not send before it ended (the end of the process waits at most 1.5 s for them) are kept in a small file in the user cache directory (`~/.cache/fullcourtdefense/sdk-spool`, `%LOCALAPPDATA%`, `~/Library/Caches`) and sent by the next start with the same shield. `FCD_SDK_SPOOL=off` disables it; `FCD_SDK_SPOOL_DIR` moves it. |
30
+ | `FCD_AUTOGUARD` | `adk`: add the gate to every Google ADK `Runner` at start-up (below). Unset: the start-up hook does nothing. |
31
+ | `FCD_APPROVAL_MODE` | ADK plugin: `block` (default) stops a call that needs a manager's approval; `wait` holds it until a person decides (`FCD_APPROVAL_TIMEOUT_S`, default 900). |
32
+
33
+ A **monitor-mode** shield never blocks and never waits: the tool runs at once
34
+ and the call is recorded in the background.
35
+
36
+ ## Use
37
+
38
+ ```python
39
+ from fullcourtdefense_agent import ToolGate, ToolCallBlocked
40
+
41
+ gate = ToolGate.from_env()
42
+
43
+ # A function, checked before every call (sync or async def):
44
+ safe_refund = gate.protect(issue_refund, operation="refund")
45
+
46
+ # Or one call:
47
+ gate.guard_tool_call("issue_refund", lambda: issue_refund("o_1", 120),
48
+ tool_args={"order": "o_1", "amount": 120}, operation="refund")
49
+ ```
50
+
51
+ A blocked call raises `ToolCallBlocked`; the tool did not run.
52
+
53
+ **A wrong key, a refused or unknown shield, a refused request (HTTP 401 / 403 / 404 / 400)
54
+ is not an outage.** The fail mode does not apply: the tool does not run, the check is not
55
+ reported later as "ran without a check", and `FullCourtDefenseApiError` (a
56
+ `ToolCallBlocked` with `status` and `code`: `FCD_UNAUTHORIZED`, `FCD_FORBIDDEN`,
57
+ `FCD_SHIELD_NOT_FOUND`, `FCD_BAD_REQUEST`) says what to change. It is also logged once on the
58
+ `fullcourtdefense` logger. Any other 4xx except 408 / 429 (a 413, for example) is answered the same
59
+ way. Only a real outage (no answer, 5xx, 408, 429) is answered by the fail mode.
60
+
61
+ **On a monitor shield (owner decision O4)** a refused key or shield does not stop the tool: the mode
62
+ the gate knows (a live answer earlier in the process, else `FCD_MODE_AT_PROTECT`) is monitor, so the
63
+ tool runs and the call is still reported, and FullCourtDefense raises a "wrong or missing shield key"
64
+ alert. With no known mode the shield is treated as block.
65
+
66
+ **Arguments too deep or too large to check** (nested deeper than 32 levels, more than 20,000 values)
67
+ are never sent: in block mode the call is stopped (`ToolCallBlocked`, "too large to check safely"), in
68
+ monitor mode it runs and the record says what was not sent. Never an outage.
69
+
70
+ ### OpenAI Agents SDK and LangChain
71
+
72
+ ```python
73
+ from fullcourtdefense_agent.frameworks import protect_openai_agents_tool, protect_langchain_base_tool
74
+
75
+ agent = Agent(name="support", tools=[protect_openai_agents_tool(gate, lookup_customer)]) # still a FunctionTool
76
+ safe_sql = protect_langchain_base_tool(gate, sql_query) # still a BaseTool
77
+ ```
78
+
79
+ The full SDK (`pip install fullcourtdefense`) does the same with `fcd.protect(tool)`.
80
+
81
+ ### Google ADK
82
+
83
+ ```python
84
+ from google.adk.apps import App
85
+ from fullcourtdefense_agent.adk import FcdToolGuardPlugin
86
+
87
+ app = App(name="billing", root_agent=root_agent, plugins=[FcdToolGuardPlugin()])
88
+ ```
89
+
90
+ A blocked call is answered to the model as
91
+ `{"blocked": true, "reason": "...", "by": "FullCourtDefense"}` and the tool does
92
+ not run. Gemini's built-in tools (Google Search, built-in code execution,
93
+ Vertex AI Search grounding) run inside Google and are not checked.
94
+
95
+ ### Start-up hook (no code change)
96
+
97
+ The wheel installs `fullcourtdefense_agent_autoguard.pth` into site-packages.
98
+ Python runs its one line at start-up. **Without `FCD_AUTOGUARD` it only reads
99
+ that variable and stops.** With `FCD_AUTOGUARD=adk` it waits for
100
+ `google.adk.runners` to load and adds the plugin to every `Runner` the process
101
+ creates, after the agent's own plugins. Security scanners flag start-up lines
102
+ in `.pth` files as a supply-chain technique; this one is disclosed here, pinned
103
+ by exact version and inert unless the variable is set. If the plugin cannot be
104
+ added (an unsupported ADK version), the hook logs an error on the
105
+ `fullcourtdefense` logger and stderr; it never stops the agent from starting.
106
+
107
+ ## What leaves the agent
108
+
109
+ The tool name, the operation, the agent identity, the session id and the tool
110
+ arguments (the policy input; the server minimises them before storing). Never
111
+ the tool's result and never the text of an error the tool raised.
@@ -0,0 +1,46 @@
1
+ [build-system]
2
+ requires = ["setuptools>=77.0"]
3
+ build-backend = "setuptools.build_meta"
4
+
5
+ [project]
6
+ name = "fullcourtdefense-agent"
7
+ dynamic = ["version"]
8
+ description = "FullCourtDefense agent hook: checks every AI-agent tool call against your organisation's action policy before it runs. Standard library only; Google ADK plugin, OpenAI Agents SDK and LangChain tool wrappers, and an opt-in start-up hook (FCD_AUTOGUARD)."
9
+ readme = "README.md"
10
+ license = "MIT"
11
+ requires-python = ">=3.10"
12
+ authors = [{name = "Full Court Defense"}]
13
+ # No runtime dependencies on purpose: this package is added to deployed agents
14
+ # (Vertex AI Agent Engine, Foundry hosted agents) and must never change the
15
+ # versions of anything the agent already uses.
16
+ dependencies = []
17
+ keywords = ["ai-agent-security", "tool-call", "action-policy", "google-adk", "openai-agents", "langchain", "vertex-ai", "agent-engine", "fullcourtdefense"]
18
+ classifiers = [
19
+ "Development Status :: 4 - Beta",
20
+ "Intended Audience :: Developers",
21
+ "Programming Language :: Python :: 3",
22
+ "Programming Language :: Python :: 3.10",
23
+ "Programming Language :: Python :: 3.11",
24
+ "Programming Language :: Python :: 3.12",
25
+ "Programming Language :: Python :: 3.13",
26
+ "Topic :: Security",
27
+ ]
28
+
29
+ [project.optional-dependencies]
30
+ dev = ["pytest"]
31
+
32
+ [project.urls]
33
+ Homepage = "https://fullcourtdefense.ai"
34
+
35
+ [tool.setuptools]
36
+ package-dir = {"" = "src"}
37
+
38
+ [tool.setuptools.packages.find]
39
+ where = ["src"]
40
+ include = ["fullcourtdefense_agent*"]
41
+
42
+ [tool.setuptools.dynamic]
43
+ version = {attr = "fullcourtdefense_agent._version.__version__"}
44
+
45
+ [tool.pytest.ini_options]
46
+ testpaths = ["tests"]
@@ -0,0 +1,4 @@
1
+ [egg_info]
2
+ tag_build =
3
+ tag_date = 0
4
+
@@ -0,0 +1,21 @@
1
+ """Build hook: put the start-up line (fullcourtdefense_agent_autoguard.pth) at the
2
+ root of the wheel, so it lands in site-packages next to the package. The line is
3
+ inert unless FCD_AUTOGUARD is set (src/fullcourtdefense_agent/_autoguard.py).
4
+ Everything else is declared in pyproject.toml."""
5
+
6
+ import os
7
+
8
+ from setuptools import setup
9
+ from setuptools.command.build_py import build_py
10
+
11
+ PTH = "fullcourtdefense_agent_autoguard.pth"
12
+ HERE = os.path.dirname(os.path.abspath(__file__))
13
+
14
+
15
+ class BuildPyWithStartupHook(build_py):
16
+ def run(self):
17
+ super().run()
18
+ self.copy_file(os.path.join(HERE, "src", PTH), os.path.join(self.build_lib, PTH), preserve_mode=0)
19
+
20
+
21
+ setup(cmdclass={"build_py": BuildPyWithStartupHook})
@@ -0,0 +1,51 @@
1
+ """FullCourtDefense agent hook: check every AI-agent tool call before it runs.
2
+
3
+ Standard library only (no httpx, requests or openai), so it can be added to a
4
+ deployed agent (Vertex AI Agent Engine, Azure AI Foundry hosted agents, a
5
+ container) without changing the versions of anything the agent already uses.
6
+
7
+ from fullcourtdefense_agent import ToolGate
8
+ gate = ToolGate.from_env() # FCD_SHIELD_ID, FCD_SHIELD_KEY, FCD_API_URL, FCD_AGENT_ID
9
+ safe_refund = gate.protect(issue_refund) # checked before every call
10
+
11
+ Google ADK: ``from fullcourtdefense_agent.adk import FcdToolGuardPlugin`` and add
12
+ it to the ``App`` / ``Runner`` plugins, or set ``FCD_AUTOGUARD=adk`` and the
13
+ start-up hook adds it to every ADK ``Runner`` with no code change.
14
+
15
+ OpenAI Agents SDK and LangChain: ``fullcourtdefense_agent.frameworks``
16
+ (``protect_openai_agents_tool`` returns a ``FunctionTool``,
17
+ ``protect_langchain_base_tool`` a ``BaseTool``); ``fullcourtdefense``'s
18
+ ``fcd.protect(tool)`` picks them automatically.
19
+ """
20
+
21
+ from ._version import __version__
22
+ from .circuit_breaker import CircuitBreaker, CircuitBreakerOptions
23
+ from .gate import (
24
+ EMERGENCY_WORDS,
25
+ FAIL_MODES,
26
+ FullCourtDefenseApiError,
27
+ ToolCallBlocked,
28
+ ToolCheck,
29
+ ToolGate,
30
+ default_tool_args,
31
+ protect_function,
32
+ resolve_fail_mode,
33
+ )
34
+ from .identity import default_agent_name, resolve_agent_id
35
+
36
+ __all__ = [
37
+ "__version__",
38
+ "CircuitBreaker",
39
+ "CircuitBreakerOptions",
40
+ "EMERGENCY_WORDS",
41
+ "FAIL_MODES",
42
+ "FullCourtDefenseApiError",
43
+ "ToolCallBlocked",
44
+ "ToolCheck",
45
+ "ToolGate",
46
+ "default_agent_name",
47
+ "default_tool_args",
48
+ "protect_function",
49
+ "resolve_agent_id",
50
+ "resolve_fail_mode",
51
+ ]
@@ -0,0 +1,62 @@
1
+ """A tool call's arguments the gate will not send for a check (review of #2729, finding 1).
2
+
3
+ A prompt-injected agent can add a junk argument nested a couple of thousand levels deep. ``json.dumps``
4
+ raises a ``RecursionError`` on it; before this check that error escaped the gate (and a Monitor record of
5
+ the call was lost in its background thread). Now the arguments are measured first, without recursion, with
6
+ the server's own limits (backend ``modules/runtime/tool-args-bounds.ts``: 32 levels, 20,000 values) and the
7
+ Node SDK's (``sdks/node/src/argsBounds.ts``), and a call beyond them, or one that cannot be encoded, gets a
8
+ DEFINITE answer: on Block the tool does not run; in Monitor it runs and the record carries a fact instead of
9
+ the arguments. Never an outage, never a circuit-breaker failure, never held as "ran without a check".
10
+ """
11
+
12
+ from __future__ import annotations
13
+
14
+ from typing import Any, Dict, List, Optional, Tuple
15
+
16
+ #: Deepest nesting of objects and arrays the server analyses (the top-level object is depth 1).
17
+ TOOL_ARGS_MAX_DEPTH = 32
18
+
19
+ #: Most values (objects, arrays, strings, numbers, booleans, nulls) the server analyses.
20
+ TOOL_ARGS_MAX_NODES = 20_000
21
+
22
+ #: The rule id the server uses for the same answer.
23
+ TOOL_ARGS_BOUNDS_RULE_ID = "args_beyond_bounds"
24
+
25
+
26
+ def tool_args_problem(value: Any) -> Optional[Dict[str, Any]]:
27
+ """The first bound ``value`` breaks (``{"kind": "depth" | "nodes", "limit": n}``), or None.
28
+ Iterative: any depth is measured without recursion. A cycle is infinitely deep, so it stops too."""
29
+ if value is None:
30
+ return None
31
+ stack: List[Tuple[Any, int]] = [(value, 1)]
32
+ nodes = 0
33
+ while stack:
34
+ current, depth = stack.pop()
35
+ nodes += 1
36
+ if nodes > TOOL_ARGS_MAX_NODES:
37
+ return {"kind": "nodes", "limit": TOOL_ARGS_MAX_NODES}
38
+ if isinstance(current, dict):
39
+ children = list(current.values())
40
+ elif isinstance(current, (list, tuple)):
41
+ children = list(current)
42
+ else:
43
+ continue # json_body sends any other value as one value (its text)
44
+ if depth > TOOL_ARGS_MAX_DEPTH:
45
+ return {"kind": "depth", "limit": TOOL_ARGS_MAX_DEPTH}
46
+ for child in children:
47
+ stack.append((child, depth + 1))
48
+ return None
49
+
50
+
51
+ def problem_words(problem: Dict[str, Any]) -> str:
52
+ kind = problem.get("kind")
53
+ if kind == "depth":
54
+ return f"nested deeper than {problem.get('limit')} levels"
55
+ if kind == "nodes":
56
+ return f"made of more than {problem.get('limit')} values"
57
+ return f"not encodable as JSON ({problem.get('error_type', 'Error')})"
58
+
59
+
60
+ def problem_summary(problem: Dict[str, Any]) -> Dict[str, str]:
61
+ """What is sent instead of the arguments: a fact, never the arguments."""
62
+ return {"argumentsNotRecorded": f"The arguments were {problem_words(problem)}, so they were not sent."}
@@ -0,0 +1,195 @@
1
+ """Start-up hook: add the FullCourtDefense tool gate to every Google ADK Runner.
2
+
3
+ ``fullcourtdefense_agent_autoguard.pth`` (installed next to this package) runs
4
+ one line at interpreter start. It does NOTHING unless ``FCD_AUTOGUARD`` is set:
5
+ it reads one environment variable and stops. With ``FCD_AUTOGUARD=adk`` it
6
+ calls ``install_from_env()``, which:
7
+
8
+ 1. registers an import hook for ``google.adk.runners`` (nothing of ADK is
9
+ imported here; the agent imports it when it starts), and
10
+ 2. when that module loads, wraps ``Runner.__init__`` so every runner the
11
+ process creates (Agent Engine's ``AdkApp``, ``adk api_server``, the
12
+ customer's own code) gets ``FcdToolGuardPlugin`` once, after its own plugins.
13
+
14
+ A start-up hook that runs code is a pattern security scanners flag; this one is
15
+ disclosed, pinned by exact version, inert without the variable and covered by
16
+ ``tests/test_autoguard_pth.py``. Every failure is caught and reported on the
17
+ ``fullcourtdefense`` logger and stderr: the hook never stops the agent from
18
+ starting.
19
+ """
20
+
21
+ from __future__ import annotations
22
+
23
+ import functools
24
+ import importlib.abc
25
+ import importlib.machinery
26
+ import logging
27
+ import os
28
+ import sys
29
+ import threading
30
+ from typing import Any, Callable, Dict, Optional
31
+
32
+ _logger = logging.getLogger("fullcourtdefense")
33
+
34
+ AUTOGUARD_ENV = "FCD_AUTOGUARD"
35
+ ADK_RUNNERS_MODULE = "google.adk.runners"
36
+ PLUGIN_NAME = "fullcourtdefense"
37
+ _OFF = ("", "0", "off", "false", "no")
38
+ _ADK = ("adk", "1", "on", "true", "yes")
39
+
40
+ _state: Dict[str, Any] = {"status": "off", "detail": "", "runners": 0}
41
+ _state_lock = threading.Lock()
42
+ _shared_plugin: Optional[Any] = None
43
+
44
+
45
+ def autoguard_status() -> Dict[str, Any]:
46
+ """What the start-up hook did in this process: ``off`` | ``waiting`` (hook set, ADK not
47
+ loaded yet) | ``active`` (Runner wrapped) | ``failed`` (with ``detail``)."""
48
+ with _state_lock:
49
+ return dict(_state)
50
+
51
+
52
+ def _set(status: str, detail: str = "") -> None:
53
+ with _state_lock:
54
+ _state["status"] = status
55
+ _state["detail"] = detail
56
+
57
+
58
+ def _report_failure(detail: str) -> None:
59
+ _set("failed", detail)
60
+ message = (
61
+ "[FullCourtDefense] FCD_AUTOGUARD is set but the tool gate could not be added to Google ADK "
62
+ f"({detail}). Tool calls of this agent are NOT checked. Pin a supported google-adk version "
63
+ "or add FcdToolGuardPlugin to the App plugins in code."
64
+ )
65
+ _logger.error(message)
66
+ try:
67
+ sys.stderr.write(message + "\n")
68
+ except Exception: # pragma: no cover
69
+ pass
70
+
71
+
72
+ class _PostImportLoader(importlib.abc.Loader):
73
+ """Runs the module's real loader, then ``hook(module)``."""
74
+
75
+ def __init__(self, loader: Any, hook: Callable[[Any], None]) -> None:
76
+ self._loader = loader
77
+ self._hook = hook
78
+
79
+ def create_module(self, spec): # noqa: D401 - importlib API
80
+ create = getattr(self._loader, "create_module", None)
81
+ return create(spec) if create is not None else None
82
+
83
+ def exec_module(self, module) -> None:
84
+ self._loader.exec_module(module)
85
+ try:
86
+ self._hook(module)
87
+ except Exception as error: # the hook never breaks the import
88
+ _report_failure(f"{type(error).__name__}: {error}")
89
+
90
+ def __getattr__(self, name: str) -> Any:
91
+ return getattr(self._loader, name)
92
+
93
+
94
+ class _PostImportFinder(importlib.abc.MetaPathFinder):
95
+ def __init__(self, hooks: Dict[str, Callable[[Any], None]]) -> None:
96
+ self._hooks = hooks
97
+ self._busy = threading.local()
98
+
99
+ def find_spec(self, fullname, path=None, target=None):
100
+ hook = self._hooks.get(fullname)
101
+ if hook is None or getattr(self._busy, "active", False):
102
+ return None
103
+ self._busy.active = True
104
+ try:
105
+ for finder in sys.meta_path:
106
+ if finder is self or not hasattr(finder, "find_spec"):
107
+ continue
108
+ spec = finder.find_spec(fullname, path, target)
109
+ if spec is not None:
110
+ break
111
+ else:
112
+ return None
113
+ finally:
114
+ self._busy.active = False
115
+ if spec.loader is None or not hasattr(spec.loader, "exec_module"):
116
+ return spec
117
+ spec.loader = _PostImportLoader(spec.loader, hook)
118
+ return spec
119
+
120
+
121
+ def _plugin() -> Any:
122
+ global _shared_plugin
123
+ if _shared_plugin is None:
124
+ from .adk import FcdToolGuardPlugin # imports google.adk: only once ADK itself is loading
125
+
126
+ _shared_plugin = FcdToolGuardPlugin()
127
+ return _shared_plugin
128
+
129
+
130
+ def attach_to_runner(runner: Any) -> bool:
131
+ """Add the gate to one ADK runner (idempotent). Returns True when it is attached."""
132
+ manager = getattr(runner, "plugin_manager", None)
133
+ if manager is None or not hasattr(manager, "register_plugin"):
134
+ raise RuntimeError("Runner has no plugin_manager.register_plugin")
135
+ get_plugin = getattr(manager, "get_plugin", None)
136
+ if callable(get_plugin) and get_plugin(PLUGIN_NAME) is not None:
137
+ return True
138
+ manager.register_plugin(_plugin())
139
+ with _state_lock:
140
+ _state["runners"] = int(_state.get("runners", 0)) + 1
141
+ return True
142
+
143
+
144
+ def patch_runners_module(module: Any) -> None:
145
+ runner_cls = getattr(module, "Runner", None)
146
+ init = getattr(runner_cls, "__init__", None)
147
+ if runner_cls is None or init is None:
148
+ _report_failure(f"{ADK_RUNNERS_MODULE}.Runner not found")
149
+ return
150
+ if getattr(init, "_fcd_autoguard", False):
151
+ _set("active")
152
+ return
153
+
154
+ @functools.wraps(init)
155
+ def __init__(self, *args: Any, **kwargs: Any) -> None:
156
+ init(self, *args, **kwargs)
157
+ try:
158
+ attach_to_runner(self)
159
+ except Exception as error:
160
+ _report_failure(f"{type(error).__name__}: {error}")
161
+
162
+ __init__._fcd_autoguard = True # type: ignore[attr-defined]
163
+ runner_cls.__init__ = __init__
164
+ _set("active")
165
+
166
+
167
+ def install(target: str = "adk") -> str:
168
+ """Install the hook for ``target`` (only ``adk`` today). Safe to call twice."""
169
+ if target != "adk":
170
+ _report_failure(f"unknown FCD_AUTOGUARD target {target!r}")
171
+ return "failed"
172
+ loaded = sys.modules.get(ADK_RUNNERS_MODULE)
173
+ if loaded is not None:
174
+ patch_runners_module(loaded)
175
+ return autoguard_status()["status"]
176
+ if not any(isinstance(f, _PostImportFinder) for f in sys.meta_path):
177
+ sys.meta_path.insert(0, _PostImportFinder({ADK_RUNNERS_MODULE: patch_runners_module}))
178
+ _set("waiting")
179
+ return "waiting"
180
+
181
+
182
+ def install_from_env(environ: Optional[Dict[str, str]] = None) -> str:
183
+ """Entry point of the .pth line. Never raises."""
184
+ try:
185
+ env = os.environ if environ is None else environ
186
+ value = (env.get(AUTOGUARD_ENV) or "").strip().lower()
187
+ if value in _OFF:
188
+ return "off"
189
+ if value in _ADK:
190
+ return install("adk")
191
+ _report_failure(f"unknown FCD_AUTOGUARD value {value!r} (expected adk)")
192
+ return "failed"
193
+ except Exception as error: # pragma: no cover - last resort: never stop the interpreter
194
+ _report_failure(f"{type(error).__name__}: {error}")
195
+ return "failed"