toolairlock 0.3.0__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.
Files changed (61) hide show
  1. toolairlock/__init__.py +83 -0
  2. toolairlock/__main__.py +53 -0
  3. toolairlock/_version.py +5 -0
  4. toolairlock/adapters/__init__.py +36 -0
  5. toolairlock/adapters/langgraph.py +94 -0
  6. toolairlock/adapters/mcp.py +111 -0
  7. toolairlock/adapters/providers.py +473 -0
  8. toolairlock/adapters/tool_calling.py +228 -0
  9. toolairlock/approvals.py +130 -0
  10. toolairlock/audit.py +124 -0
  11. toolairlock/budget.py +106 -0
  12. toolairlock/dataflow.py +219 -0
  13. toolairlock/errors.py +100 -0
  14. toolairlock/gateway/__init__.py +29 -0
  15. toolairlock/gateway/cli.py +280 -0
  16. toolairlock/gateway/config.py +396 -0
  17. toolairlock/gateway/core.py +1224 -0
  18. toolairlock/gateway/http.py +254 -0
  19. toolairlock/gateway/jsonrpc.py +235 -0
  20. toolairlock/gateway/pins.py +138 -0
  21. toolairlock/gateway/ui.py +85 -0
  22. toolairlock/gateway/upstream.py +392 -0
  23. toolairlock/govern/__init__.py +42 -0
  24. toolairlock/govern/catalog.py +365 -0
  25. toolairlock/govern/checks.py +636 -0
  26. toolairlock/govern/classify.py +62 -0
  27. toolairlock/govern/cli.py +222 -0
  28. toolairlock/govern/engine.py +86 -0
  29. toolairlock/govern/live.py +179 -0
  30. toolairlock/govern/model.py +139 -0
  31. toolairlock/govern/register.py +267 -0
  32. toolairlock/govern/report.py +191 -0
  33. toolairlock/govern/scaffold.py +388 -0
  34. toolairlock/govern/scan.py +759 -0
  35. toolairlock/govern/templates/action_guard.py.tmpl +41 -0
  36. toolairlock/govern/templates/env.example.tmpl +7 -0
  37. toolairlock/govern/templates/github-workflow.yml.tmpl +35 -0
  38. toolairlock/govern/templates/gitlab-ci.yml.tmpl +21 -0
  39. toolairlock/govern/templates/llm_client.py.tmpl +52 -0
  40. toolairlock/govern/templates/pii_guard.py.tmpl +50 -0
  41. toolairlock/govern/templates/stack/README.md +39 -0
  42. toolairlock/govern/templates/stack/docker-compose.yml +66 -0
  43. toolairlock/govern/templates/stack/env.example +14 -0
  44. toolairlock/govern/templates/stack/litellm-config.yaml +36 -0
  45. toolairlock/govern/templates/stack/new-app-key.sh +12 -0
  46. toolairlock/govern/templates/system_prompt.yaml.tmpl +7 -0
  47. toolairlock/govern/testing.py +185 -0
  48. toolairlock/guard.py +757 -0
  49. toolairlock/injection.py +209 -0
  50. toolairlock/policy.py +92 -0
  51. toolairlock/provenance.py +201 -0
  52. toolairlock/py.typed +0 -0
  53. toolairlock/redact.py +177 -0
  54. toolairlock/schema.py +86 -0
  55. toolairlock/store.py +226 -0
  56. toolairlock/types.py +183 -0
  57. toolairlock-0.3.0.dist-info/METADATA +709 -0
  58. toolairlock-0.3.0.dist-info/RECORD +61 -0
  59. toolairlock-0.3.0.dist-info/WHEEL +4 -0
  60. toolairlock-0.3.0.dist-info/entry_points.txt +2 -0
  61. toolairlock-0.3.0.dist-info/licenses/LICENSE +21 -0
@@ -0,0 +1,83 @@
1
+ """toolairlock: preview, approve, dedupe, cap and audit every side effect an AI agent takes."""
2
+
3
+ from ._version import __version__
4
+ from .approvals import AutoApprove, CallbackApprover, CLIApprover, DenyAll, WebhookApprover
5
+ from .audit import JSONLAuditLog, MemoryAuditLog, verify_chain
6
+ from .budget import Limit
7
+ from .errors import (
8
+ AirlockBlocked,
9
+ AirlockError,
10
+ ApprovalDenied,
11
+ ApprovalRequired,
12
+ BudgetExceeded,
13
+ DryRunBlocked,
14
+ DuplicateInFlight,
15
+ InjectionBlocked,
16
+ InvalidArguments,
17
+ InvalidToken,
18
+ KillSwitchEngaged,
19
+ PolicyDenied,
20
+ RateLimited,
21
+ TaintedArgument,
22
+ TokenAlreadyUsed,
23
+ TokenExpired,
24
+ UnknownTool,
25
+ )
26
+ from .guard import Airlock
27
+ from .injection import Finding, Risk, scan, spotlight, spotlight_instructions
28
+ from .policy import Policy
29
+ from .provenance import check_senders, lookalike_of, sender_findings
30
+ from .redact import Redactor
31
+ from .store import MemoryStore, SQLiteStore
32
+ from .types import ApprovalDecision, ApprovalMode, ApprovalRequest, CallResult, Effect, Mode, Preview, ToolSpec
33
+
34
+ __all__ = [
35
+ "Airlock",
36
+ "AirlockBlocked",
37
+ "AirlockError",
38
+ "ApprovalDecision",
39
+ "ApprovalDenied",
40
+ "ApprovalMode",
41
+ "ApprovalRequest",
42
+ "ApprovalRequired",
43
+ "AutoApprove",
44
+ "BudgetExceeded",
45
+ "CLIApprover",
46
+ "CallResult",
47
+ "CallbackApprover",
48
+ "DenyAll",
49
+ "DryRunBlocked",
50
+ "DuplicateInFlight",
51
+ "Effect",
52
+ "Finding",
53
+ "InjectionBlocked",
54
+ "InvalidArguments",
55
+ "InvalidToken",
56
+ "JSONLAuditLog",
57
+ "KillSwitchEngaged",
58
+ "Limit",
59
+ "MemoryAuditLog",
60
+ "MemoryStore",
61
+ "Mode",
62
+ "Policy",
63
+ "PolicyDenied",
64
+ "Preview",
65
+ "RateLimited",
66
+ "Redactor",
67
+ "Risk",
68
+ "SQLiteStore",
69
+ "TaintedArgument",
70
+ "TokenAlreadyUsed",
71
+ "TokenExpired",
72
+ "ToolSpec",
73
+ "UnknownTool",
74
+ "WebhookApprover",
75
+ "__version__",
76
+ "check_senders",
77
+ "lookalike_of",
78
+ "scan",
79
+ "sender_findings",
80
+ "spotlight",
81
+ "spotlight_instructions",
82
+ "verify_chain",
83
+ ]
@@ -0,0 +1,53 @@
1
+ """Command line: ``toolairlock verify audit.jsonl``, ``toolairlock scan "text"``, ``toolairlock gateway ...`` and
2
+ ``toolairlock govern ...``."""
3
+
4
+ from __future__ import annotations
5
+
6
+ import argparse
7
+ import json
8
+ import sys
9
+ from typing import Optional
10
+
11
+ from .audit import verify_chain
12
+ from .injection import scan
13
+
14
+
15
+ def main(argv: Optional[list[str]] = None) -> int:
16
+ argv = list(sys.argv[1:] if argv is None else argv)
17
+ if argv and argv[0] == "gateway":
18
+ from .gateway.cli import main as gateway_main
19
+
20
+ return gateway_main(argv[1:])
21
+ parser = argparse.ArgumentParser(prog="toolairlock")
22
+ sub = parser.add_subparsers(dest="cmd", required=True)
23
+ v = sub.add_parser("verify", help="verify an audit log's hash chain")
24
+ v.add_argument("path")
25
+ s = sub.add_parser("scan", help="scan text (or stdin with -) for prompt injection")
26
+ s.add_argument("text")
27
+ sub.add_parser("gateway", help="MCP gateway: toolairlock gateway --help")
28
+ from .govern.cli import add_parser as add_govern
29
+
30
+ add_govern(sub)
31
+ args = parser.parse_args(argv)
32
+
33
+ if args.cmd == "govern":
34
+ from .govern.cli import run as run_govern
35
+
36
+ return run_govern(args)
37
+
38
+ if args.cmd == "verify":
39
+ report = verify_chain(args.path)
40
+ if report.ok:
41
+ print(f"OK: {report.records} records, chain intact")
42
+ return 0
43
+ print(f"BROKEN at line {report.broken_at}: {report.reason} ({report.records} good records before it)")
44
+ return 1
45
+
46
+ text = sys.stdin.read() if args.text == "-" else args.text
47
+ rep = scan(text)
48
+ print(json.dumps(rep.to_dict(), indent=2))
49
+ return 2 if rep.risk.value == "high" else 0
50
+
51
+
52
+ if __name__ == "__main__": # pragma: no cover
53
+ sys.exit(main())
@@ -0,0 +1,5 @@
1
+ __version__ = "0.3.0"
2
+
3
+ USER_AGENT = f"toolairlock/{__version__} (+https://github.com/Eidaan/toolairlock)"
4
+ """Sent on every outgoing HTTP request. Some CDNs (for example Cloudflare in front of Groq)
5
+ reject Python's default ``Python-urllib`` user agent with a 403."""
@@ -0,0 +1,36 @@
1
+ """Framework adapters. Each one imports its framework lazily."""
2
+
3
+ from .providers import (
4
+ PROVIDERS,
5
+ AgentLoop,
6
+ AnthropicChat,
7
+ ChatProvider,
8
+ LoopResult,
9
+ OllamaChat,
10
+ OpenAICompatibleChat,
11
+ ProviderError,
12
+ Turn,
13
+ is_tool_call_error,
14
+ make_provider,
15
+ )
16
+ from .tool_calling import COMMIT_TOOL, ParsedCall, ToolDispatcher, ToolResult, parse_tool_call, tool_definitions
17
+
18
+ __all__ = [
19
+ "COMMIT_TOOL",
20
+ "PROVIDERS",
21
+ "AgentLoop",
22
+ "AnthropicChat",
23
+ "ChatProvider",
24
+ "LoopResult",
25
+ "OllamaChat",
26
+ "OpenAICompatibleChat",
27
+ "ParsedCall",
28
+ "ProviderError",
29
+ "ToolDispatcher",
30
+ "ToolResult",
31
+ "Turn",
32
+ "is_tool_call_error",
33
+ "make_provider",
34
+ "parse_tool_call",
35
+ "tool_definitions",
36
+ ]
@@ -0,0 +1,94 @@
1
+ """LangGraph integration: human approval through ``interrupt()``.
2
+
3
+ ``langgraph`` is optional and imported lazily. Typical use::
4
+
5
+ airlock = Airlock(mode="live", approvers=[interrupt_approver("manager")])
6
+ tools_node = guarded_tool_node(airlock, actor="planner")
7
+ graph.add_node("tools", tools_node)
8
+
9
+ When a call needs approval the node pauses with an interrupt payload of type
10
+ ``toolairlock_approval``. Resume the graph with ``Command(resume=True)`` or
11
+ ``Command(resume={"approved": False, "approver": "asha", "reason": "wrong vendor"})``.
12
+ LangGraph re-runs the node on resume; the airlock's idempotency store makes that safe.
13
+ """
14
+
15
+ from __future__ import annotations
16
+
17
+ from collections.abc import Callable
18
+ from typing import Any, Optional
19
+
20
+ from ..guard import Airlock
21
+ from ..types import ApprovalDecision, ApprovalRequest
22
+ from .tool_calling import ToolDispatcher, ToolResult
23
+
24
+
25
+ def _default_interrupt() -> Callable[[Any], Any]:
26
+ try:
27
+ from langgraph.types import interrupt
28
+ except ImportError as exc: # pragma: no cover - exercised only without the extra
29
+ raise ImportError("install the extra: pip install 'toolairlock[langgraph]'") from exc
30
+ return interrupt
31
+
32
+
33
+ def _interrupt_types() -> tuple[type[BaseException], ...]:
34
+ """LangGraph pauses a graph by raising; those exceptions must reach the runtime."""
35
+ try:
36
+ from langgraph.errors import GraphBubbleUp
37
+ except ImportError:
38
+ return ()
39
+ return (GraphBubbleUp,)
40
+
41
+
42
+ def interrupt_approver(name: str = "human", interrupt_fn: Optional[Callable[[Any], Any]] = None):
43
+ """An approver that pauses the graph and waits for a human to resume it."""
44
+
45
+ def approver(request: ApprovalRequest) -> ApprovalDecision:
46
+ fn = interrupt_fn or _default_interrupt()
47
+ answer = fn(
48
+ {
49
+ "type": "toolairlock_approval",
50
+ "approver": name,
51
+ "tool": request.tool,
52
+ "effect": request.effect.value,
53
+ "args": request.args,
54
+ "preview": request.preview,
55
+ "actor": request.actor,
56
+ "required_approvals": request.required,
57
+ "already_approved_by": list(request.already_approved_by),
58
+ }
59
+ )
60
+ if isinstance(answer, dict):
61
+ return ApprovalDecision(
62
+ bool(answer.get("approved")), str(answer.get("approver") or name), answer.get("reason")
63
+ )
64
+ return ApprovalDecision(bool(answer), name)
65
+
66
+ return approver
67
+
68
+
69
+ def guarded_tool_node(airlock: Airlock, *, actor: str = "agent", messages_key: str = "messages"):
70
+ """A LangGraph node that runs the last AI message's tool calls through the airlock.
71
+
72
+ Returns ``{"messages": [ToolMessage, ...]}``. Requires ``langchain-core``.
73
+ """
74
+ dispatcher = ToolDispatcher(airlock, actor=actor, auto_commit=True, passthrough=_interrupt_types())
75
+
76
+ def _to_message(result: ToolResult) -> Any:
77
+ try:
78
+ from langchain_core.messages import ToolMessage
79
+ except ImportError as exc: # pragma: no cover
80
+ raise ImportError("install the extra: pip install 'toolairlock[langgraph]'") from exc
81
+ return ToolMessage(
82
+ content=result.content,
83
+ tool_call_id=result.call_id,
84
+ name=result.name,
85
+ status="error" if result.is_error else "success",
86
+ )
87
+
88
+ def node(state: Any) -> dict[str, Any]:
89
+ msgs = state[messages_key] if isinstance(state, dict) else getattr(state, messages_key)
90
+ last = msgs[-1]
91
+ calls = getattr(last, "tool_calls", None) or (last.get("tool_calls") if isinstance(last, dict) else None) or []
92
+ return {messages_key: [_to_message(r) for r in dispatcher.handle_all(list(calls))]}
93
+
94
+ return node
@@ -0,0 +1,111 @@
1
+ """Expose airlock-guarded tools on an MCP server.
2
+
3
+ Works with the official Python SDK's server class (``MCPServer`` in mcp 2.x, ``FastMCP`` in
4
+ mcp 1.x; ``pip install 'toolairlock[mcp]'``) or anything with a compatible
5
+ ``add_tool(fn, name=..., description=..., annotations=...)`` method.
6
+
7
+ Every tool gets honest MCP annotations (``readOnlyHint``, ``destructiveHint``,
8
+ ``idempotentHint``, ``openWorldHint``) so clients can show the right warnings, and
9
+ side-effect tools follow the preview -> ``airlock_commit`` two-step.
10
+ """
11
+
12
+ from __future__ import annotations
13
+
14
+ import functools
15
+ import inspect
16
+ from typing import Any
17
+
18
+ from ..guard import Airlock
19
+ from ..types import Effect, ToolSpec
20
+ from .tool_calling import _COMMIT_DESC, _SIDE_EFFECT_NOTE, COMMIT_TOOL, ToolDispatcher
21
+
22
+
23
+ class AirlockToolError(RuntimeError):
24
+ """Raised inside MCP handlers so the server marks the result as an error."""
25
+
26
+
27
+ def mcp_annotations(spec: ToolSpec) -> dict[str, Any]:
28
+ return {
29
+ "title": spec.name.replace("_", " ").capitalize(),
30
+ "readOnlyHint": spec.effect is Effect.READ,
31
+ "destructiveHint": spec.effect is Effect.DESTRUCTIVE,
32
+ "idempotentHint": spec.idempotent or spec.effect is Effect.READ,
33
+ "openWorldHint": spec.effect is Effect.EXTERNAL,
34
+ }
35
+
36
+
37
+ def _annotations_obj(data: dict[str, Any]) -> Any:
38
+ try:
39
+ from mcp.types import ToolAnnotations
40
+ except ImportError:
41
+ return data
42
+ return ToolAnnotations(**data)
43
+
44
+
45
+ def register_mcp(airlock: Airlock, server: Any, *, actor: str = "mcp-client", two_step: bool = True) -> list[str]:
46
+ """Register every airlock tool on ``server``. Returns the registered names."""
47
+ dispatcher = ToolDispatcher(airlock, actor=actor, auto_commit=not two_step)
48
+ names: list[str] = []
49
+
50
+ def make_handler(name: str, func: Any) -> Any:
51
+ is_async = inspect.iscoroutinefunction(func)
52
+
53
+ if is_async:
54
+
55
+ @functools.wraps(func)
56
+ async def ahandler(**kwargs: Any) -> str:
57
+ res = await dispatcher.ahandle({"id": "mcp", "name": name, "input": kwargs})
58
+ if res.is_error:
59
+ raise AirlockToolError(res.content)
60
+ return res.content
61
+
62
+ return ahandler
63
+
64
+ @functools.wraps(func)
65
+ def handler(**kwargs: Any) -> str:
66
+ res = dispatcher.handle({"id": "mcp", "name": name, "input": kwargs})
67
+ if res.is_error:
68
+ raise AirlockToolError(res.content)
69
+ return res.content
70
+
71
+ return handler
72
+
73
+ side_effects = False
74
+ for spec in airlock.tools.values():
75
+ handler = make_handler(spec.name, spec.func)
76
+ handler.__signature__ = inspect.signature(spec.func).replace(return_annotation=str)
77
+ handler.__annotations__ = {**getattr(spec.func, "__annotations__", {}), "return": str}
78
+ desc = spec.description or spec.name
79
+ if spec.effect.has_side_effects and two_step:
80
+ desc += _SIDE_EFFECT_NOTE
81
+ side_effects = True
82
+ server.add_tool(handler, name=spec.name, description=desc, annotations=_annotations_obj(mcp_annotations(spec)))
83
+ names.append(spec.name)
84
+
85
+ if side_effects:
86
+
87
+ def airlock_commit(token: str) -> str:
88
+ res = dispatcher.handle({"id": "mcp", "name": COMMIT_TOOL, "input": {"token": token}})
89
+ if res.is_error:
90
+ raise AirlockToolError(res.content)
91
+ return res.content
92
+
93
+ server.add_tool(
94
+ airlock_commit,
95
+ name=COMMIT_TOOL,
96
+ description=_COMMIT_DESC,
97
+ annotations=_annotations_obj(
98
+ {
99
+ "title": "Commit previewed action",
100
+ "readOnlyHint": False,
101
+ "destructiveHint": True,
102
+ "idempotentHint": True,
103
+ "openWorldHint": True,
104
+ }
105
+ ),
106
+ )
107
+ names.append(COMMIT_TOOL)
108
+ return names
109
+
110
+
111
+ register_fastmcp = register_mcp # name kept for mcp 1.x users