agent-countersign 0.1.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.
- agent_countersign/__init__.py +17 -0
- agent_countersign/cli.py +112 -0
- agent_countersign/gateway.py +188 -0
- agent_countersign/mcp_adapter.py +50 -0
- agent_countersign/policy.py +163 -0
- agent_countersign/redact.py +51 -0
- agent_countersign/store.py +173 -0
- agent_countersign-0.1.0.dist-info/METADATA +131 -0
- agent_countersign-0.1.0.dist-info/RECORD +14 -0
- agent_countersign-0.1.0.dist-info/WHEEL +5 -0
- agent_countersign-0.1.0.dist-info/entry_points.txt +2 -0
- agent_countersign-0.1.0.dist-info/licenses/LICENSE +201 -0
- agent_countersign-0.1.0.dist-info/licenses/NOTICE +4 -0
- agent_countersign-0.1.0.dist-info/top_level.txt +1 -0
|
@@ -0,0 +1,17 @@
|
|
|
1
|
+
"""agent-countersign: an open governance layer for AI agents.
|
|
2
|
+
|
|
3
|
+
Every tool call an agent makes passes through one gateway that applies a
|
|
4
|
+
readable policy, routes sensitive actions to a human, redacts PII, enforces
|
|
5
|
+
spend limits, and writes a tamper-evident audit trail. Vendor-neutral: it
|
|
6
|
+
works with any agent framework, and speaks MCP so Claude, ChatGPT, Copilot
|
|
7
|
+
and other MCP clients can use governed tools directly.
|
|
8
|
+
"""
|
|
9
|
+
|
|
10
|
+
from .gateway import ApprovalError, Gateway, Result, Tool
|
|
11
|
+
from .policy import Decision, Policy, PolicyError
|
|
12
|
+
from .redact import redact
|
|
13
|
+
from .store import Store
|
|
14
|
+
|
|
15
|
+
__all__ = ["Gateway", "Result", "Tool", "ApprovalError", "Policy", "PolicyError",
|
|
16
|
+
"Decision", "Store", "redact"]
|
|
17
|
+
__version__ = "0.1.0"
|
agent_countersign/cli.py
ADDED
|
@@ -0,0 +1,112 @@
|
|
|
1
|
+
"""Command line for the humans in the loop.
|
|
2
|
+
|
|
3
|
+
countersign approvals list what is waiting
|
|
4
|
+
countersign approve 3 --by finance-lead approve request #3
|
|
5
|
+
countersign deny 3 --by finance-lead --note "wrong customer"
|
|
6
|
+
countersign audit --limit 20 show the latest audit events
|
|
7
|
+
countersign verify check the audit trail has not been tampered with
|
|
8
|
+
countersign check policy.yaml send_email agent=billing-bot customer_id=7
|
|
9
|
+
dry-run a policy decision
|
|
10
|
+
"""
|
|
11
|
+
|
|
12
|
+
from __future__ import annotations
|
|
13
|
+
|
|
14
|
+
import argparse
|
|
15
|
+
import json
|
|
16
|
+
import sys
|
|
17
|
+
|
|
18
|
+
from .gateway import ApprovalError, Gateway
|
|
19
|
+
from .policy import Policy, PolicyError
|
|
20
|
+
from .store import Store
|
|
21
|
+
|
|
22
|
+
|
|
23
|
+
def _parse_kv(pairs: list[str]) -> dict[str, object]:
|
|
24
|
+
out: dict[str, object] = {}
|
|
25
|
+
for pair in pairs:
|
|
26
|
+
key, _, raw = pair.partition("=")
|
|
27
|
+
try:
|
|
28
|
+
out[key] = json.loads(raw)
|
|
29
|
+
except json.JSONDecodeError:
|
|
30
|
+
out[key] = raw
|
|
31
|
+
return out
|
|
32
|
+
|
|
33
|
+
|
|
34
|
+
def main(argv: list[str] | None = None) -> int:
|
|
35
|
+
ap = argparse.ArgumentParser(prog="countersign", description="Governance for AI agent tool calls.")
|
|
36
|
+
ap.add_argument("--db", default="countersign.db", help="SQLite store (default: countersign.db)")
|
|
37
|
+
ap.add_argument("--policy", default="policy.yaml", help="Policy file (default: policy.yaml)")
|
|
38
|
+
sub = ap.add_subparsers(dest="cmd", required=True)
|
|
39
|
+
|
|
40
|
+
p = sub.add_parser("approvals", help="List approval requests")
|
|
41
|
+
p.add_argument("--all", action="store_true", help="Include decided requests")
|
|
42
|
+
|
|
43
|
+
for name in ("approve", "deny"):
|
|
44
|
+
p = sub.add_parser(name, help=f"{name.title()} a pending request")
|
|
45
|
+
p.add_argument("id", type=int)
|
|
46
|
+
p.add_argument("--by", required=True, help="Your name or role, as listed in the policy")
|
|
47
|
+
p.add_argument("--note", default=None)
|
|
48
|
+
|
|
49
|
+
p = sub.add_parser("audit", help="Show audit events")
|
|
50
|
+
p.add_argument("--limit", type=int, default=20)
|
|
51
|
+
|
|
52
|
+
sub.add_parser("verify", help="Verify the audit hash chain")
|
|
53
|
+
|
|
54
|
+
p = sub.add_parser("check", help="Dry-run a policy decision")
|
|
55
|
+
p.add_argument("policy_file")
|
|
56
|
+
p.add_argument("tool")
|
|
57
|
+
p.add_argument("pairs", nargs="*", help="agent=NAME and key=value arguments")
|
|
58
|
+
|
|
59
|
+
a = ap.parse_args(argv)
|
|
60
|
+
|
|
61
|
+
if a.cmd == "check":
|
|
62
|
+
try:
|
|
63
|
+
policy = Policy.from_file(a.policy_file)
|
|
64
|
+
except PolicyError as exc:
|
|
65
|
+
print(f"Invalid policy: {exc}")
|
|
66
|
+
return 2
|
|
67
|
+
kv = _parse_kv(a.pairs)
|
|
68
|
+
agent = str(kv.pop("agent", "*"))
|
|
69
|
+
v = policy.evaluate(agent, a.tool, kv)
|
|
70
|
+
print(f"{v.decision.value} (rule: {v.rule})" + (f" approvers: {', '.join(v.approvers)}" if v.approvers else ""))
|
|
71
|
+
return 0
|
|
72
|
+
|
|
73
|
+
store = Store(a.db)
|
|
74
|
+
|
|
75
|
+
if a.cmd == "approvals":
|
|
76
|
+
rows = store.list_approvals(None if a.all else "pending")
|
|
77
|
+
if not rows:
|
|
78
|
+
print("Nothing waiting.")
|
|
79
|
+
for r in rows:
|
|
80
|
+
who = f" by {r.decided_by}" if r.decided_by else ""
|
|
81
|
+
print(f"#{r.id} {r.status:<9} {r.agent} -> {r.tool}({json.dumps(r.args)}) "
|
|
82
|
+
f"rule={r.rule} approvers={','.join(r.approvers) or 'any'}{who}")
|
|
83
|
+
return 0
|
|
84
|
+
|
|
85
|
+
if a.cmd in ("approve", "deny"):
|
|
86
|
+
gw = Gateway(Policy.from_file(a.policy), store)
|
|
87
|
+
try:
|
|
88
|
+
getattr(gw, a.cmd)(a.id, by=a.by, note=a.note)
|
|
89
|
+
except ApprovalError as exc:
|
|
90
|
+
print(f"Error: {exc}")
|
|
91
|
+
return 1
|
|
92
|
+
print(f"#{a.id} {a.cmd}d by {a.by}.")
|
|
93
|
+
return 0
|
|
94
|
+
|
|
95
|
+
if a.cmd == "audit":
|
|
96
|
+
for e in store.events(a.limit):
|
|
97
|
+
extra = " ".join(f"{k}={e[k]}" for k in ("decision", "rule", "actor", "approval_id") if e[k])
|
|
98
|
+
print(f"{e['id']:>4} {e['ts'][:19]} {e['event']:<9} {e['agent']} -> {e['tool']} {extra}"
|
|
99
|
+
+ (f" ({e['detail']})" if e["detail"] else ""))
|
|
100
|
+
return 0
|
|
101
|
+
|
|
102
|
+
if a.cmd == "verify":
|
|
103
|
+
ok, bad = store.verify_chain()
|
|
104
|
+
n = len(store.events())
|
|
105
|
+
print(f"OK: {n} events, chain intact." if ok else f"TAMPERED: chain breaks at event #{bad}.")
|
|
106
|
+
return 0 if ok else 1
|
|
107
|
+
|
|
108
|
+
return 1
|
|
109
|
+
|
|
110
|
+
|
|
111
|
+
if __name__ == "__main__":
|
|
112
|
+
sys.exit(main())
|
|
@@ -0,0 +1,188 @@
|
|
|
1
|
+
"""The Gateway: the single path every agent tool call goes through.
|
|
2
|
+
|
|
3
|
+
agent ──► Gateway.call() ──► policy ──► allow ────────► tool ──► redact ──► agent
|
|
4
|
+
│ deny ─────────────────────────────► agent
|
|
5
|
+
│ approval ─► queue ─► human ─► resume()
|
|
6
|
+
└──────► audit trail (every step, hash-chained)
|
|
7
|
+
"""
|
|
8
|
+
|
|
9
|
+
from __future__ import annotations
|
|
10
|
+
|
|
11
|
+
import inspect
|
|
12
|
+
from dataclasses import dataclass, field
|
|
13
|
+
from pathlib import Path
|
|
14
|
+
from typing import Any, Callable
|
|
15
|
+
|
|
16
|
+
from .policy import Decision, Policy
|
|
17
|
+
from .redact import redact
|
|
18
|
+
from .store import Store
|
|
19
|
+
|
|
20
|
+
|
|
21
|
+
class ApprovalError(RuntimeError):
|
|
22
|
+
pass
|
|
23
|
+
|
|
24
|
+
|
|
25
|
+
@dataclass
|
|
26
|
+
class Tool:
|
|
27
|
+
name: str
|
|
28
|
+
fn: Callable[..., Any]
|
|
29
|
+
cost_usd: float = 0.0
|
|
30
|
+
description: str = ""
|
|
31
|
+
|
|
32
|
+
|
|
33
|
+
@dataclass
|
|
34
|
+
class Result:
|
|
35
|
+
status: str # executed | denied | pending | failed
|
|
36
|
+
output: Any = None
|
|
37
|
+
reason: str = ""
|
|
38
|
+
rule: str = ""
|
|
39
|
+
approval_id: int | None = None
|
|
40
|
+
approvers: list[str] = field(default_factory=list)
|
|
41
|
+
|
|
42
|
+
def to_dict(self) -> dict[str, Any]:
|
|
43
|
+
d: dict[str, Any] = {"status": self.status}
|
|
44
|
+
if self.status == "executed":
|
|
45
|
+
d["output"] = self.output
|
|
46
|
+
if self.reason:
|
|
47
|
+
d["reason"] = self.reason
|
|
48
|
+
if self.rule:
|
|
49
|
+
d["rule"] = self.rule
|
|
50
|
+
if self.approval_id is not None:
|
|
51
|
+
d["approval_id"] = self.approval_id
|
|
52
|
+
if self.status == "pending":
|
|
53
|
+
d["message"] = ("This action needs human approval. Tell the user it is waiting "
|
|
54
|
+
f"for approval #{self.approval_id}; check back later.")
|
|
55
|
+
return d
|
|
56
|
+
|
|
57
|
+
|
|
58
|
+
class Gateway:
|
|
59
|
+
def __init__(self, policy: Policy | str | Path, store: Store | str | Path = "countersign.db"):
|
|
60
|
+
self.policy = policy if isinstance(policy, Policy) else Policy.from_file(policy)
|
|
61
|
+
self.store = store if isinstance(store, Store) else Store(store)
|
|
62
|
+
self.tools: dict[str, Tool] = {}
|
|
63
|
+
|
|
64
|
+
# ---- registration --------------------------------------------------
|
|
65
|
+
|
|
66
|
+
def tool(self, name: str | None = None, *, cost_usd: float = 0.0):
|
|
67
|
+
"""Decorator: register a function as a governed tool."""
|
|
68
|
+
def wrap(fn: Callable[..., Any]) -> Callable[..., Any]:
|
|
69
|
+
self.register(fn, name=name, cost_usd=cost_usd)
|
|
70
|
+
return fn
|
|
71
|
+
return wrap
|
|
72
|
+
|
|
73
|
+
def register(self, fn: Callable[..., Any], *, name: str | None = None,
|
|
74
|
+
cost_usd: float = 0.0) -> None:
|
|
75
|
+
tool_name = name or fn.__name__
|
|
76
|
+
self.tools[tool_name] = Tool(tool_name, fn, cost_usd, inspect.getdoc(fn) or "")
|
|
77
|
+
|
|
78
|
+
# ---- the governed call --------------------------------------------
|
|
79
|
+
|
|
80
|
+
def call(self, agent: str, tool: str, args: dict[str, Any] | None = None) -> Result:
|
|
81
|
+
args = dict(args or {})
|
|
82
|
+
logged_args = redact(args) if self.policy.redact_audit else args
|
|
83
|
+
|
|
84
|
+
if tool not in self.tools:
|
|
85
|
+
self.store.log(agent=agent, tool=tool, args=logged_args, event="decided",
|
|
86
|
+
decision="deny", rule="unknown-tool", detail="Tool is not registered.")
|
|
87
|
+
return Result("denied", reason=f"Unknown tool '{tool}'.", rule="unknown-tool")
|
|
88
|
+
|
|
89
|
+
verdict = self.policy.evaluate(agent, tool, args)
|
|
90
|
+
|
|
91
|
+
if verdict.decision is Decision.DENY:
|
|
92
|
+
self.store.log(agent=agent, tool=tool, args=logged_args, event="decided",
|
|
93
|
+
decision="deny", rule=verdict.rule, detail=verdict.reason)
|
|
94
|
+
return Result("denied", reason=verdict.reason or "Blocked by policy.", rule=verdict.rule)
|
|
95
|
+
|
|
96
|
+
budget_block = self._over_budget(agent, tool)
|
|
97
|
+
if budget_block:
|
|
98
|
+
self.store.log(agent=agent, tool=tool, args=logged_args, event="decided",
|
|
99
|
+
decision="deny", rule="budget", detail=budget_block)
|
|
100
|
+
return Result("denied", reason=budget_block, rule="budget")
|
|
101
|
+
|
|
102
|
+
if verdict.decision is Decision.REQUIRE_APPROVAL:
|
|
103
|
+
approval_id = self.store.create_approval(agent=agent, tool=tool, args=args,
|
|
104
|
+
rule=verdict.rule, approvers=verdict.approvers)
|
|
105
|
+
self.store.log(agent=agent, tool=tool, args=logged_args, event="decided",
|
|
106
|
+
decision="require_approval", rule=verdict.rule,
|
|
107
|
+
detail=verdict.reason, approval_id=approval_id)
|
|
108
|
+
return Result("pending", reason=verdict.reason, rule=verdict.rule,
|
|
109
|
+
approval_id=approval_id, approvers=verdict.approvers)
|
|
110
|
+
|
|
111
|
+
self.store.log(agent=agent, tool=tool, args=logged_args, event="decided",
|
|
112
|
+
decision="allow", rule=verdict.rule)
|
|
113
|
+
return self._execute(agent, tool, args, logged_args, rule=verdict.rule)
|
|
114
|
+
|
|
115
|
+
# ---- approvals -----------------------------------------------------
|
|
116
|
+
|
|
117
|
+
def approve(self, approval_id: int, *, by: str, note: str | None = None) -> None:
|
|
118
|
+
a = self._pending(approval_id, by)
|
|
119
|
+
self.store.set_approval_status(approval_id, "approved", by=by, note=note)
|
|
120
|
+
self.store.log(agent=a.agent, tool=a.tool, args=self._log_args(a.args), event="approved",
|
|
121
|
+
rule=a.rule, actor=by, detail=note, approval_id=approval_id)
|
|
122
|
+
|
|
123
|
+
def deny(self, approval_id: int, *, by: str, note: str | None = None) -> None:
|
|
124
|
+
a = self._pending(approval_id, by)
|
|
125
|
+
self.store.set_approval_status(approval_id, "denied", by=by, note=note)
|
|
126
|
+
self.store.log(agent=a.agent, tool=a.tool, args=self._log_args(a.args), event="denied",
|
|
127
|
+
rule=a.rule, actor=by, detail=note, approval_id=approval_id)
|
|
128
|
+
|
|
129
|
+
def resume(self, approval_id: int) -> Result:
|
|
130
|
+
"""Run an approved call, or report where it stands. Safe to call repeatedly."""
|
|
131
|
+
a = self.store.get_approval(approval_id)
|
|
132
|
+
if a is None:
|
|
133
|
+
return Result("failed", reason=f"No approval #{approval_id}.")
|
|
134
|
+
if a.status == "pending":
|
|
135
|
+
return Result("pending", reason="Still waiting for a human decision.",
|
|
136
|
+
rule=a.rule, approval_id=approval_id, approvers=a.approvers)
|
|
137
|
+
if a.status == "denied":
|
|
138
|
+
return Result("denied", reason=f"Denied by {a.decided_by}" +
|
|
139
|
+
(f": {a.note}" if a.note else "."), rule=a.rule)
|
|
140
|
+
if a.status == "executed":
|
|
141
|
+
return Result("failed", reason="Already executed; approvals are single-use.", rule=a.rule)
|
|
142
|
+
budget_block = self._over_budget(a.agent, a.tool)
|
|
143
|
+
if budget_block:
|
|
144
|
+
return Result("denied", reason=budget_block, rule="budget")
|
|
145
|
+
self.store.set_approval_status(approval_id, "executed")
|
|
146
|
+
return self._execute(a.agent, a.tool, a.args, self._log_args(a.args),
|
|
147
|
+
rule=a.rule, approval_id=approval_id, actor=a.decided_by)
|
|
148
|
+
|
|
149
|
+
# ---- internals -----------------------------------------------------
|
|
150
|
+
|
|
151
|
+
def _pending(self, approval_id: int, by: str):
|
|
152
|
+
a = self.store.get_approval(approval_id)
|
|
153
|
+
if a is None:
|
|
154
|
+
raise ApprovalError(f"No approval #{approval_id}.")
|
|
155
|
+
if a.status != "pending":
|
|
156
|
+
raise ApprovalError(f"Approval #{approval_id} is already {a.status}.")
|
|
157
|
+
if by == a.agent:
|
|
158
|
+
raise ApprovalError("An agent cannot approve its own request.")
|
|
159
|
+
if a.approvers and by not in a.approvers:
|
|
160
|
+
raise ApprovalError(f"'{by}' is not an approver for rule '{a.rule}' "
|
|
161
|
+
f"(allowed: {', '.join(a.approvers)}).")
|
|
162
|
+
return a
|
|
163
|
+
|
|
164
|
+
def _log_args(self, args: dict[str, Any]) -> dict[str, Any]:
|
|
165
|
+
return redact(args) if self.policy.redact_audit else args
|
|
166
|
+
|
|
167
|
+
def _over_budget(self, agent: str, tool: str) -> str:
|
|
168
|
+
budget = self.policy.budget_for(agent)
|
|
169
|
+
cost = self.tools[tool].cost_usd if tool in self.tools else 0.0
|
|
170
|
+
if budget and cost and self.store.spend_today(agent) + cost > budget.daily_usd:
|
|
171
|
+
return (f"Daily budget of ${budget.daily_usd:.2f} for '{agent}' would be exceeded "
|
|
172
|
+
f"(spent ${self.store.spend_today(agent):.2f}, this call ${cost:.2f}).")
|
|
173
|
+
return ""
|
|
174
|
+
|
|
175
|
+
def _execute(self, agent: str, tool: str, args: dict[str, Any], logged_args: dict[str, Any],
|
|
176
|
+
*, rule: str, approval_id: int | None = None, actor: str | None = None) -> Result:
|
|
177
|
+
t = self.tools[tool]
|
|
178
|
+
try:
|
|
179
|
+
output = t.fn(**args)
|
|
180
|
+
except Exception as exc: # the agent gets a clean error, the audit gets the detail
|
|
181
|
+
self.store.log(agent=agent, tool=tool, args=logged_args, event="failed", rule=rule,
|
|
182
|
+
detail=f"{type(exc).__name__}: {exc}", approval_id=approval_id, actor=actor)
|
|
183
|
+
return Result("failed", reason=f"Tool error: {exc}", rule=rule)
|
|
184
|
+
self.store.log(agent=agent, tool=tool, args=logged_args, event="executed", rule=rule,
|
|
185
|
+
approval_id=approval_id, actor=actor, cost_usd=t.cost_usd)
|
|
186
|
+
if self.policy.redact_outputs:
|
|
187
|
+
output = redact(output)
|
|
188
|
+
return Result("executed", output=output, rule=rule, approval_id=approval_id)
|
|
@@ -0,0 +1,50 @@
|
|
|
1
|
+
"""Expose governed tools over MCP (Model Context Protocol).
|
|
2
|
+
|
|
3
|
+
Any MCP client (Claude Desktop, Claude Code, ChatGPT, Copilot, Cursor and
|
|
4
|
+
others) sees the same tools it would see without agent-countersign, but every call
|
|
5
|
+
is checked, approved, redacted and audited by the Gateway first. One extra
|
|
6
|
+
tool, ``countersign_check_approval``, lets the agent pick up a call a human has
|
|
7
|
+
since approved.
|
|
8
|
+
"""
|
|
9
|
+
|
|
10
|
+
from __future__ import annotations
|
|
11
|
+
|
|
12
|
+
import functools
|
|
13
|
+
import inspect
|
|
14
|
+
from typing import Any
|
|
15
|
+
|
|
16
|
+
from mcp.server.mcpserver import MCPServer
|
|
17
|
+
|
|
18
|
+
from .gateway import Gateway
|
|
19
|
+
|
|
20
|
+
|
|
21
|
+
def build_server(gateway: Gateway, agent: str, name: str = "agent-countersign") -> MCPServer:
|
|
22
|
+
server = MCPServer(name=name, instructions=(
|
|
23
|
+
"Tools here are governed. Some calls run immediately, some are blocked, and some "
|
|
24
|
+
"wait for a human. When a result says 'pending', tell the user which approval it "
|
|
25
|
+
"is waiting on; later, call countersign_check_approval with that id."))
|
|
26
|
+
|
|
27
|
+
for tool in gateway.tools.values():
|
|
28
|
+
server.add_tool(_governed(gateway, agent, tool.name, tool.fn),
|
|
29
|
+
name=tool.name, description=tool.description or None)
|
|
30
|
+
|
|
31
|
+
def countersign_check_approval(approval_id: int) -> dict[str, Any]:
|
|
32
|
+
"""Check a pending approval. If a human approved it, the action runs now and its result is returned."""
|
|
33
|
+
return gateway.resume(approval_id).to_dict()
|
|
34
|
+
|
|
35
|
+
server.add_tool(countersign_check_approval, name="countersign_check_approval")
|
|
36
|
+
return server
|
|
37
|
+
|
|
38
|
+
|
|
39
|
+
def _governed(gateway: Gateway, agent: str, tool_name: str, fn):
|
|
40
|
+
sig = inspect.signature(fn)
|
|
41
|
+
|
|
42
|
+
@functools.wraps(fn)
|
|
43
|
+
def wrapper(**kwargs: Any) -> dict[str, Any]:
|
|
44
|
+
return gateway.call(agent, tool_name, kwargs).to_dict()
|
|
45
|
+
|
|
46
|
+
# Keep the original parameters so the MCP schema is unchanged, but always return a dict.
|
|
47
|
+
wrapper.__signature__ = sig.replace(return_annotation=dict[str, Any]) # type: ignore[attr-defined]
|
|
48
|
+
wrapper.__annotations__ = {**getattr(fn, "__annotations__", {}), "return": dict[str, Any]}
|
|
49
|
+
del wrapper.__wrapped__
|
|
50
|
+
return wrapper
|
|
@@ -0,0 +1,163 @@
|
|
|
1
|
+
"""Policy engine: decides whether an agent may call a tool with given arguments.
|
|
2
|
+
|
|
3
|
+
Policies are plain YAML so the people accountable for a process (not just
|
|
4
|
+
engineers) can read and review them. Rules are evaluated top to bottom and the
|
|
5
|
+
first matching rule wins. If nothing matches, the default decision applies,
|
|
6
|
+
which is ``deny`` unless the policy says otherwise.
|
|
7
|
+
"""
|
|
8
|
+
|
|
9
|
+
from __future__ import annotations
|
|
10
|
+
|
|
11
|
+
import fnmatch
|
|
12
|
+
import re
|
|
13
|
+
from dataclasses import dataclass, field
|
|
14
|
+
from enum import Enum
|
|
15
|
+
from pathlib import Path
|
|
16
|
+
from typing import Any
|
|
17
|
+
|
|
18
|
+
import yaml
|
|
19
|
+
|
|
20
|
+
|
|
21
|
+
class Decision(str, Enum):
|
|
22
|
+
ALLOW = "allow"
|
|
23
|
+
DENY = "deny"
|
|
24
|
+
REQUIRE_APPROVAL = "require_approval"
|
|
25
|
+
|
|
26
|
+
|
|
27
|
+
_OPERATORS = {"eq", "ne", "gt", "gte", "lt", "lte", "in", "not_in", "matches"}
|
|
28
|
+
|
|
29
|
+
|
|
30
|
+
class PolicyError(ValueError):
|
|
31
|
+
"""Raised when a policy file is malformed."""
|
|
32
|
+
|
|
33
|
+
|
|
34
|
+
@dataclass
|
|
35
|
+
class Rule:
|
|
36
|
+
name: str
|
|
37
|
+
decision: Decision
|
|
38
|
+
agents: list[str] = field(default_factory=lambda: ["*"])
|
|
39
|
+
tools: list[str] = field(default_factory=lambda: ["*"])
|
|
40
|
+
when: dict[str, dict[str, Any]] = field(default_factory=dict)
|
|
41
|
+
approvers: list[str] = field(default_factory=list)
|
|
42
|
+
reason: str = ""
|
|
43
|
+
|
|
44
|
+
def matches(self, agent: str, tool: str, args: dict[str, Any]) -> bool:
|
|
45
|
+
if not any(fnmatch.fnmatchcase(agent, p) for p in self.agents):
|
|
46
|
+
return False
|
|
47
|
+
if not any(fnmatch.fnmatchcase(tool, p) for p in self.tools):
|
|
48
|
+
return False
|
|
49
|
+
return all(_check(args.get(arg), cond) for arg, cond in self.when.items())
|
|
50
|
+
|
|
51
|
+
|
|
52
|
+
@dataclass
|
|
53
|
+
class Budget:
|
|
54
|
+
agent: str
|
|
55
|
+
daily_usd: float
|
|
56
|
+
|
|
57
|
+
|
|
58
|
+
@dataclass
|
|
59
|
+
class Verdict:
|
|
60
|
+
decision: Decision
|
|
61
|
+
rule: str
|
|
62
|
+
reason: str = ""
|
|
63
|
+
approvers: list[str] = field(default_factory=list)
|
|
64
|
+
|
|
65
|
+
|
|
66
|
+
@dataclass
|
|
67
|
+
class Policy:
|
|
68
|
+
rules: list[Rule]
|
|
69
|
+
default: Decision = Decision.DENY
|
|
70
|
+
budgets: list[Budget] = field(default_factory=list)
|
|
71
|
+
redact_audit: bool = True
|
|
72
|
+
redact_outputs: bool = True
|
|
73
|
+
|
|
74
|
+
def evaluate(self, agent: str, tool: str, args: dict[str, Any]) -> Verdict:
|
|
75
|
+
for rule in self.rules:
|
|
76
|
+
if rule.matches(agent, tool, args):
|
|
77
|
+
return Verdict(rule.decision, rule.name, rule.reason, list(rule.approvers))
|
|
78
|
+
return Verdict(self.default, "default", "No rule matched this call.")
|
|
79
|
+
|
|
80
|
+
def budget_for(self, agent: str) -> Budget | None:
|
|
81
|
+
for b in self.budgets:
|
|
82
|
+
if fnmatch.fnmatchcase(agent, b.agent):
|
|
83
|
+
return b
|
|
84
|
+
return None
|
|
85
|
+
|
|
86
|
+
# ---- loading -------------------------------------------------------
|
|
87
|
+
|
|
88
|
+
@classmethod
|
|
89
|
+
def from_file(cls, path: str | Path) -> "Policy":
|
|
90
|
+
return cls.from_dict(yaml.safe_load(Path(path).read_text()))
|
|
91
|
+
|
|
92
|
+
@classmethod
|
|
93
|
+
def from_yaml(cls, text: str) -> "Policy":
|
|
94
|
+
return cls.from_dict(yaml.safe_load(text))
|
|
95
|
+
|
|
96
|
+
@classmethod
|
|
97
|
+
def from_dict(cls, data: dict[str, Any]) -> "Policy":
|
|
98
|
+
if not isinstance(data, dict):
|
|
99
|
+
raise PolicyError("Policy must be a mapping.")
|
|
100
|
+
defaults = data.get("defaults") or {}
|
|
101
|
+
rules = []
|
|
102
|
+
for i, raw in enumerate(data.get("rules") or []):
|
|
103
|
+
name = raw.get("name") or f"rule-{i + 1}"
|
|
104
|
+
try:
|
|
105
|
+
decision = Decision(raw["decision"])
|
|
106
|
+
except (KeyError, ValueError) as exc:
|
|
107
|
+
raise PolicyError(f"Rule '{name}': decision must be one of "
|
|
108
|
+
f"{[d.value for d in Decision]}") from exc
|
|
109
|
+
when = raw.get("when") or {}
|
|
110
|
+
for arg, cond in when.items():
|
|
111
|
+
if not isinstance(cond, dict) or not set(cond) <= _OPERATORS:
|
|
112
|
+
raise PolicyError(f"Rule '{name}': condition on '{arg}' must use "
|
|
113
|
+
f"operators {sorted(_OPERATORS)}")
|
|
114
|
+
rules.append(Rule(
|
|
115
|
+
name=name,
|
|
116
|
+
decision=decision,
|
|
117
|
+
agents=_as_list(raw.get("agents", ["*"])),
|
|
118
|
+
tools=_as_list(raw.get("tools", ["*"])),
|
|
119
|
+
when=when,
|
|
120
|
+
approvers=_as_list(raw.get("approvers", [])),
|
|
121
|
+
reason=raw.get("reason", ""),
|
|
122
|
+
))
|
|
123
|
+
budgets = [Budget(agent=b.get("agent", "*"), daily_usd=float(b["daily_usd"]))
|
|
124
|
+
for b in data.get("budgets") or []]
|
|
125
|
+
return cls(
|
|
126
|
+
rules=rules,
|
|
127
|
+
default=Decision(defaults.get("decision", "deny")),
|
|
128
|
+
budgets=budgets,
|
|
129
|
+
redact_audit=bool(defaults.get("redact_audit", True)),
|
|
130
|
+
redact_outputs=bool(defaults.get("redact_outputs", True)),
|
|
131
|
+
)
|
|
132
|
+
|
|
133
|
+
|
|
134
|
+
def _as_list(value: Any) -> list[str]:
|
|
135
|
+
return [value] if isinstance(value, str) else list(value)
|
|
136
|
+
|
|
137
|
+
|
|
138
|
+
def _check(value: Any, cond: dict[str, Any]) -> bool:
|
|
139
|
+
for op, expected in cond.items():
|
|
140
|
+
if op == "eq" and value != expected:
|
|
141
|
+
return False
|
|
142
|
+
if op == "ne" and value == expected:
|
|
143
|
+
return False
|
|
144
|
+
if op == "in" and value not in expected:
|
|
145
|
+
return False
|
|
146
|
+
if op == "not_in" and value in expected:
|
|
147
|
+
return False
|
|
148
|
+
if op == "matches" and (value is None or not re.search(expected, str(value))):
|
|
149
|
+
return False
|
|
150
|
+
if op in {"gt", "gte", "lt", "lte"}:
|
|
151
|
+
try:
|
|
152
|
+
v = float(value)
|
|
153
|
+
except (TypeError, ValueError):
|
|
154
|
+
return False
|
|
155
|
+
if op == "gt" and not v > expected:
|
|
156
|
+
return False
|
|
157
|
+
if op == "gte" and not v >= expected:
|
|
158
|
+
return False
|
|
159
|
+
if op == "lt" and not v < expected:
|
|
160
|
+
return False
|
|
161
|
+
if op == "lte" and not v <= expected:
|
|
162
|
+
return False
|
|
163
|
+
return True
|
|
@@ -0,0 +1,51 @@
|
|
|
1
|
+
"""PII redaction applied before data reaches a model or the audit log.
|
|
2
|
+
|
|
3
|
+
Deliberately conservative pattern matching. It is a safety net, not a
|
|
4
|
+
substitute for keeping sensitive data out of model context by design.
|
|
5
|
+
"""
|
|
6
|
+
|
|
7
|
+
from __future__ import annotations
|
|
8
|
+
|
|
9
|
+
import re
|
|
10
|
+
from typing import Any
|
|
11
|
+
|
|
12
|
+
_PATTERNS: list[tuple[str, re.Pattern[str]]] = [
|
|
13
|
+
("EMAIL", re.compile(r"[A-Za-z0-9._%+-]+@[A-Za-z0-9.-]+\.[A-Za-z]{2,}")),
|
|
14
|
+
("SSN", re.compile(r"\b\d{3}-\d{2}-\d{4}\b")),
|
|
15
|
+
("CARD", re.compile(r"\b(?:\d[ -]?){13,19}\b")),
|
|
16
|
+
("PHONE", re.compile(r"(?:\+?1[ .-]?)?\(?\b\d{3}\)?[ .-]?\d{3}[ .-]?\d{4}\b")),
|
|
17
|
+
]
|
|
18
|
+
|
|
19
|
+
|
|
20
|
+
def _luhn_ok(digits: str) -> bool:
|
|
21
|
+
nums = [int(d) for d in digits if d.isdigit()]
|
|
22
|
+
if not 13 <= len(nums) <= 19:
|
|
23
|
+
return False
|
|
24
|
+
total = 0
|
|
25
|
+
for i, n in enumerate(reversed(nums)):
|
|
26
|
+
if i % 2:
|
|
27
|
+
n *= 2
|
|
28
|
+
if n > 9:
|
|
29
|
+
n -= 9
|
|
30
|
+
total += n
|
|
31
|
+
return total % 10 == 0
|
|
32
|
+
|
|
33
|
+
|
|
34
|
+
def redact_text(text: str) -> str:
|
|
35
|
+
for label, pattern in _PATTERNS:
|
|
36
|
+
if label == "CARD":
|
|
37
|
+
text = pattern.sub(lambda m: "[REDACTED:CARD]" if _luhn_ok(m.group()) else m.group(), text)
|
|
38
|
+
else:
|
|
39
|
+
text = pattern.sub(f"[REDACTED:{label}]", text)
|
|
40
|
+
return text
|
|
41
|
+
|
|
42
|
+
|
|
43
|
+
def redact(value: Any) -> Any:
|
|
44
|
+
"""Recursively redact strings inside dicts, lists and tuples."""
|
|
45
|
+
if isinstance(value, str):
|
|
46
|
+
return redact_text(value)
|
|
47
|
+
if isinstance(value, dict):
|
|
48
|
+
return {k: redact(v) for k, v in value.items()}
|
|
49
|
+
if isinstance(value, (list, tuple)):
|
|
50
|
+
return type(value)(redact(v) for v in value)
|
|
51
|
+
return value
|
|
@@ -0,0 +1,173 @@
|
|
|
1
|
+
"""SQLite store for the audit trail and the approval queue.
|
|
2
|
+
|
|
3
|
+
The audit trail is append-only and hash-chained: every event records the hash
|
|
4
|
+
of the event before it, so editing or deleting any past event breaks the chain
|
|
5
|
+
and ``verify_chain`` reports exactly where.
|
|
6
|
+
"""
|
|
7
|
+
|
|
8
|
+
from __future__ import annotations
|
|
9
|
+
|
|
10
|
+
import hashlib
|
|
11
|
+
import json
|
|
12
|
+
import sqlite3
|
|
13
|
+
import threading
|
|
14
|
+
from dataclasses import dataclass
|
|
15
|
+
from datetime import datetime, timezone
|
|
16
|
+
from pathlib import Path
|
|
17
|
+
from typing import Any
|
|
18
|
+
|
|
19
|
+
GENESIS = "0" * 64
|
|
20
|
+
|
|
21
|
+
_SCHEMA = """
|
|
22
|
+
CREATE TABLE IF NOT EXISTS audit (
|
|
23
|
+
id INTEGER PRIMARY KEY AUTOINCREMENT,
|
|
24
|
+
ts TEXT NOT NULL,
|
|
25
|
+
agent TEXT NOT NULL,
|
|
26
|
+
tool TEXT NOT NULL,
|
|
27
|
+
args TEXT NOT NULL,
|
|
28
|
+
event TEXT NOT NULL, -- decided | executed | failed | approved | denied
|
|
29
|
+
decision TEXT,
|
|
30
|
+
rule TEXT,
|
|
31
|
+
detail TEXT,
|
|
32
|
+
actor TEXT,
|
|
33
|
+
approval_id INTEGER,
|
|
34
|
+
cost_usd REAL NOT NULL DEFAULT 0,
|
|
35
|
+
prev_hash TEXT NOT NULL,
|
|
36
|
+
hash TEXT NOT NULL
|
|
37
|
+
);
|
|
38
|
+
CREATE TABLE IF NOT EXISTS approvals (
|
|
39
|
+
id INTEGER PRIMARY KEY AUTOINCREMENT,
|
|
40
|
+
created TEXT NOT NULL,
|
|
41
|
+
agent TEXT NOT NULL,
|
|
42
|
+
tool TEXT NOT NULL,
|
|
43
|
+
args TEXT NOT NULL, -- full arguments, needed to execute later
|
|
44
|
+
rule TEXT NOT NULL,
|
|
45
|
+
approvers TEXT NOT NULL,
|
|
46
|
+
status TEXT NOT NULL, -- pending | approved | denied | executed
|
|
47
|
+
decided_by TEXT,
|
|
48
|
+
decided_at TEXT,
|
|
49
|
+
note TEXT
|
|
50
|
+
);
|
|
51
|
+
"""
|
|
52
|
+
|
|
53
|
+
_HASHED_FIELDS = ("ts", "agent", "tool", "args", "event", "decision", "rule",
|
|
54
|
+
"detail", "actor", "approval_id", "cost_usd", "prev_hash")
|
|
55
|
+
|
|
56
|
+
|
|
57
|
+
def _now() -> str:
|
|
58
|
+
return datetime.now(timezone.utc).isoformat(timespec="microseconds")
|
|
59
|
+
|
|
60
|
+
|
|
61
|
+
def _hash(row: dict[str, Any]) -> str:
|
|
62
|
+
payload = json.dumps({k: row.get(k) for k in _HASHED_FIELDS}, sort_keys=True, default=str)
|
|
63
|
+
return hashlib.sha256(payload.encode()).hexdigest()
|
|
64
|
+
|
|
65
|
+
|
|
66
|
+
@dataclass
|
|
67
|
+
class Approval:
|
|
68
|
+
id: int
|
|
69
|
+
created: str
|
|
70
|
+
agent: str
|
|
71
|
+
tool: str
|
|
72
|
+
args: dict[str, Any]
|
|
73
|
+
rule: str
|
|
74
|
+
approvers: list[str]
|
|
75
|
+
status: str
|
|
76
|
+
decided_by: str | None
|
|
77
|
+
decided_at: str | None
|
|
78
|
+
note: str | None
|
|
79
|
+
|
|
80
|
+
|
|
81
|
+
class Store:
|
|
82
|
+
def __init__(self, path: str | Path = "countersign.db"):
|
|
83
|
+
self.path = str(path)
|
|
84
|
+
self._lock = threading.Lock()
|
|
85
|
+
self._db = sqlite3.connect(self.path, check_same_thread=False)
|
|
86
|
+
self._db.row_factory = sqlite3.Row
|
|
87
|
+
self._db.executescript(_SCHEMA)
|
|
88
|
+
self._db.commit()
|
|
89
|
+
|
|
90
|
+
# ---- audit ---------------------------------------------------------
|
|
91
|
+
|
|
92
|
+
def log(self, *, agent: str, tool: str, args: dict[str, Any], event: str,
|
|
93
|
+
decision: str | None = None, rule: str | None = None, detail: str | None = None,
|
|
94
|
+
actor: str | None = None, approval_id: int | None = None,
|
|
95
|
+
cost_usd: float = 0.0) -> int:
|
|
96
|
+
with self._lock:
|
|
97
|
+
last = self._db.execute("SELECT hash FROM audit ORDER BY id DESC LIMIT 1").fetchone()
|
|
98
|
+
row = {
|
|
99
|
+
"ts": _now(), "agent": agent, "tool": tool,
|
|
100
|
+
"args": json.dumps(args, sort_keys=True, default=str),
|
|
101
|
+
"event": event, "decision": decision, "rule": rule, "detail": detail,
|
|
102
|
+
"actor": actor, "approval_id": approval_id, "cost_usd": float(cost_usd),
|
|
103
|
+
"prev_hash": last["hash"] if last else GENESIS,
|
|
104
|
+
}
|
|
105
|
+
row["hash"] = _hash(row)
|
|
106
|
+
cols = ", ".join(row)
|
|
107
|
+
marks = ", ".join("?" for _ in row)
|
|
108
|
+
cur = self._db.execute(f"INSERT INTO audit ({cols}) VALUES ({marks})", list(row.values()))
|
|
109
|
+
self._db.commit()
|
|
110
|
+
return int(cur.lastrowid)
|
|
111
|
+
|
|
112
|
+
def events(self, limit: int | None = None) -> list[dict[str, Any]]:
|
|
113
|
+
sql = "SELECT * FROM audit ORDER BY id"
|
|
114
|
+
rows = self._db.execute(sql).fetchall()
|
|
115
|
+
out = [dict(r) for r in rows]
|
|
116
|
+
return out[-limit:] if limit else out
|
|
117
|
+
|
|
118
|
+
def verify_chain(self) -> tuple[bool, int | None]:
|
|
119
|
+
"""Return (ok, first_bad_event_id)."""
|
|
120
|
+
prev = GENESIS
|
|
121
|
+
for row in self.events():
|
|
122
|
+
if row["prev_hash"] != prev or _hash(row) != row["hash"]:
|
|
123
|
+
return False, row["id"]
|
|
124
|
+
prev = row["hash"]
|
|
125
|
+
return True, None
|
|
126
|
+
|
|
127
|
+
def spend_today(self, agent: str) -> float:
|
|
128
|
+
today = datetime.now(timezone.utc).date().isoformat()
|
|
129
|
+
r = self._db.execute(
|
|
130
|
+
"SELECT COALESCE(SUM(cost_usd), 0) AS s FROM audit "
|
|
131
|
+
"WHERE agent = ? AND event = 'executed' AND substr(ts, 1, 10) = ?",
|
|
132
|
+
(agent, today)).fetchone()
|
|
133
|
+
return float(r["s"])
|
|
134
|
+
|
|
135
|
+
# ---- approvals -----------------------------------------------------
|
|
136
|
+
|
|
137
|
+
def create_approval(self, *, agent: str, tool: str, args: dict[str, Any], rule: str,
|
|
138
|
+
approvers: list[str]) -> int:
|
|
139
|
+
with self._lock:
|
|
140
|
+
cur = self._db.execute(
|
|
141
|
+
"INSERT INTO approvals (created, agent, tool, args, rule, approvers, status) "
|
|
142
|
+
"VALUES (?, ?, ?, ?, ?, ?, 'pending')",
|
|
143
|
+
(_now(), agent, tool, json.dumps(args, default=str), rule, json.dumps(approvers)))
|
|
144
|
+
self._db.commit()
|
|
145
|
+
return int(cur.lastrowid)
|
|
146
|
+
|
|
147
|
+
def get_approval(self, approval_id: int) -> Approval | None:
|
|
148
|
+
r = self._db.execute("SELECT * FROM approvals WHERE id = ?", (approval_id,)).fetchone()
|
|
149
|
+
return _to_approval(r) if r else None
|
|
150
|
+
|
|
151
|
+
def list_approvals(self, status: str | None = "pending") -> list[Approval]:
|
|
152
|
+
if status:
|
|
153
|
+
rows = self._db.execute("SELECT * FROM approvals WHERE status = ? ORDER BY id", (status,))
|
|
154
|
+
else:
|
|
155
|
+
rows = self._db.execute("SELECT * FROM approvals ORDER BY id")
|
|
156
|
+
return [_to_approval(r) for r in rows.fetchall()]
|
|
157
|
+
|
|
158
|
+
def set_approval_status(self, approval_id: int, status: str, *, by: str | None = None,
|
|
159
|
+
note: str | None = None) -> None:
|
|
160
|
+
with self._lock:
|
|
161
|
+
self._db.execute(
|
|
162
|
+
"UPDATE approvals SET status = ?, decided_by = COALESCE(?, decided_by), "
|
|
163
|
+
"decided_at = CASE WHEN ? IS NULL THEN decided_at ELSE ? END, "
|
|
164
|
+
"note = COALESCE(?, note) WHERE id = ?",
|
|
165
|
+
(status, by, by, _now(), note, approval_id))
|
|
166
|
+
self._db.commit()
|
|
167
|
+
|
|
168
|
+
|
|
169
|
+
def _to_approval(r: sqlite3.Row) -> Approval:
|
|
170
|
+
return Approval(
|
|
171
|
+
id=r["id"], created=r["created"], agent=r["agent"], tool=r["tool"],
|
|
172
|
+
args=json.loads(r["args"]), rule=r["rule"], approvers=json.loads(r["approvers"]),
|
|
173
|
+
status=r["status"], decided_by=r["decided_by"], decided_at=r["decided_at"], note=r["note"])
|
|
@@ -0,0 +1,131 @@
|
|
|
1
|
+
Metadata-Version: 2.4
|
|
2
|
+
Name: agent-countersign
|
|
3
|
+
Version: 0.1.0
|
|
4
|
+
Summary: An open governance layer for AI agents: policies, human approval, PII redaction, spend limits and a tamper-evident audit trail for every tool call.
|
|
5
|
+
License-Expression: Apache-2.0
|
|
6
|
+
Keywords: ai-agents,governance,mcp,audit,human-in-the-loop,llm
|
|
7
|
+
Requires-Python: >=3.10
|
|
8
|
+
Description-Content-Type: text/markdown
|
|
9
|
+
License-File: LICENSE
|
|
10
|
+
License-File: NOTICE
|
|
11
|
+
Requires-Dist: pyyaml>=6
|
|
12
|
+
Provides-Extra: mcp
|
|
13
|
+
Requires-Dist: mcp>=2; extra == "mcp"
|
|
14
|
+
Provides-Extra: dev
|
|
15
|
+
Requires-Dist: pytest>=8; extra == "dev"
|
|
16
|
+
Requires-Dist: mcp>=2; extra == "dev"
|
|
17
|
+
Dynamic: license-file
|
|
18
|
+
|
|
19
|
+
# agent-countersign
|
|
20
|
+
|
|
21
|
+
**An open governance layer for AI agents.**
|
|
22
|
+
Every tool call an agent makes goes through one gateway that applies a readable policy, sends sensitive actions to a human, redacts PII, enforces spend limits and writes a tamper-evident audit trail. It is vendor-neutral and speaks MCP, so Claude, ChatGPT, Copilot, Cursor and any other MCP client can use governed tools without code changes.
|
|
23
|
+
|
|
24
|
+
Companies are deploying agents from many vendors at once, and each vendor governs only its own. Nobody can answer the questions a CFO, CISO or auditor will ask: *What can this agent do? Who approved that? What did it cost? Can you prove the log wasn't edited?* agent-countersign answers them in one place, for every agent.
|
|
25
|
+
|
|
26
|
+
```
|
|
27
|
+
agent ──► Gateway.call() ──► policy ──► allow ─────────────► tool ──► redact ──► agent
|
|
28
|
+
(any vendor, │ deny ────────────────────────────────► agent
|
|
29
|
+
or MCP) │ require_approval ─► queue ─► human ─► resume()
|
|
30
|
+
└──────► audit trail (every step, hash-chained)
|
|
31
|
+
```
|
|
32
|
+
|
|
33
|
+
## What it does
|
|
34
|
+
|
|
35
|
+
| Control | How |
|
|
36
|
+
|---|---|
|
|
37
|
+
| **Policy as plain YAML** | Rules a process owner can read and sign off on. First match wins; anything not covered is denied. Match on agent, tool and argument values (`amount > 500`, regex, lists). |
|
|
38
|
+
| **Human in the loop** | `require_approval` rules queue the call. Named approvers decide from the CLI (or your own UI). Agents can't approve their own requests, and approvals are single-use. |
|
|
39
|
+
| **Tamper-evident audit** | Every decision, approval and execution is logged with a SHA-256 chain. Edit or delete one row and `countersign verify` names the event where the chain breaks. |
|
|
40
|
+
| **PII redaction** | Emails, phone numbers, SSNs and card numbers (Luhn-checked) are stripped from the audit log and from what the model sees. Tools look up sensitive values themselves, so the model never needs them. |
|
|
41
|
+
| **Spend limits** | Give each tool a cost; set daily budgets per agent. |
|
|
42
|
+
| **MCP adapter** | Wrap your tools once; every MCP client gets the governed versions plus `countersign_check_approval`. |
|
|
43
|
+
|
|
44
|
+
## Quick start
|
|
45
|
+
|
|
46
|
+
```bash
|
|
47
|
+
pip install -e ".[mcp]"
|
|
48
|
+
python examples/overdue_invoices/run_demo.py
|
|
49
|
+
```
|
|
50
|
+
|
|
51
|
+
The demo runs a scripted accounts-receivable agent with no LLM, so you can see every control fire: an allowed lookup with redacted output, a customer email held for approval, a $900 refund blocked by policy, a self-approval refused, the approved email sent, a replay refused, and then tampering with the audit log detected.
|
|
52
|
+
|
|
53
|
+
## Use it in your code
|
|
54
|
+
|
|
55
|
+
```python
|
|
56
|
+
from agent_countersign import Gateway
|
|
57
|
+
|
|
58
|
+
gw = Gateway("policy.yaml", "countersign.db")
|
|
59
|
+
|
|
60
|
+
@gw.tool(cost_usd=0.01)
|
|
61
|
+
def send_email(customer_id: int, subject: str, body: str) -> str:
|
|
62
|
+
"""Send an email to a customer."""
|
|
63
|
+
...
|
|
64
|
+
|
|
65
|
+
result = gw.call("billing-bot", "send_email", {"customer_id": 1, "subject": "...", "body": "..."})
|
|
66
|
+
result.status # "executed" | "denied" | "pending" | "failed"
|
|
67
|
+
```
|
|
68
|
+
|
|
69
|
+
## Policy example
|
|
70
|
+
|
|
71
|
+
```yaml
|
|
72
|
+
defaults:
|
|
73
|
+
decision: deny
|
|
74
|
+
budgets:
|
|
75
|
+
- {agent: "*", daily_usd: 1.00}
|
|
76
|
+
rules:
|
|
77
|
+
- name: read-only lookups
|
|
78
|
+
tools: [list_overdue_invoices, get_customer]
|
|
79
|
+
decision: allow
|
|
80
|
+
- name: no refunds over $500
|
|
81
|
+
tools: [issue_refund]
|
|
82
|
+
when: {amount: {gt: 500}}
|
|
83
|
+
decision: deny
|
|
84
|
+
- name: customer emails need a human
|
|
85
|
+
tools: [send_email]
|
|
86
|
+
decision: require_approval
|
|
87
|
+
approvers: [ar-manager, controller]
|
|
88
|
+
```
|
|
89
|
+
|
|
90
|
+
Dry-run a decision before you deploy:
|
|
91
|
+
|
|
92
|
+
```bash
|
|
93
|
+
countersign check policy.yaml issue_refund agent=billing-bot amount=200
|
|
94
|
+
# require_approval (rule: small refunds need the controller) approvers: controller
|
|
95
|
+
```
|
|
96
|
+
|
|
97
|
+
## Governed MCP server
|
|
98
|
+
|
|
99
|
+
```python
|
|
100
|
+
from agent_countersign.mcp_adapter import build_server
|
|
101
|
+
build_server(gw, agent="billing-bot").run()
|
|
102
|
+
```
|
|
103
|
+
|
|
104
|
+
See `examples/overdue_invoices/server.py` for a ready-to-run server and Claude Desktop config. Approve from a terminal:
|
|
105
|
+
|
|
106
|
+
```bash
|
|
107
|
+
countersign approvals
|
|
108
|
+
countersign approve 1 --by ar-manager --note "tone is fine"
|
|
109
|
+
countersign audit
|
|
110
|
+
countersign verify
|
|
111
|
+
```
|
|
112
|
+
|
|
113
|
+
## Roadmap
|
|
114
|
+
|
|
115
|
+
- Authenticated approvers (SSO / signed approvals)
|
|
116
|
+
- MCP **proxy** mode: govern any existing MCP server without touching its code
|
|
117
|
+
- Approvals in Slack, Teams and email
|
|
118
|
+
- Per-model cost tracking from LLM usage data
|
|
119
|
+
- Signed audit checkpoints and export for SOX/HIPAA evidence
|
|
120
|
+
- Policy packs for common regulated workflows (AP/AR, healthcare scheduling, claims)
|
|
121
|
+
- Postgres store and a small web console
|
|
122
|
+
|
|
123
|
+
## Status
|
|
124
|
+
|
|
125
|
+
v0.1. Small core, fully tested, meant to be read in an afternoon. Issues and pull requests welcome.
|
|
126
|
+
|
|
127
|
+
Known limits in v0.1: approver identity comes from `--by` and is not yet authenticated (put the CLI behind your own access controls, or wire approvals to SSO); redaction is pattern-based and is a safety net, not a substitute for keeping sensitive data out of model context by design.
|
|
128
|
+
|
|
129
|
+
## License
|
|
130
|
+
|
|
131
|
+
Apache-2.0
|
|
@@ -0,0 +1,14 @@
|
|
|
1
|
+
agent_countersign/__init__.py,sha256=oE0NMCbSH6LFwnkbXYtbH9l-pA8LPXbEXpCyLC8h4uI,728
|
|
2
|
+
agent_countersign/cli.py,sha256=AwK4jDUgZor4a7kOiiErrCD5Y1bhpmojDl5OCqX0GU4,4181
|
|
3
|
+
agent_countersign/gateway.py,sha256=W7otbXCesKbB1hYZRni0yVcHTp0tVYDzVXLdLvP1P8I,9257
|
|
4
|
+
agent_countersign/mcp_adapter.py,sha256=dHeJd8d55MVaE_1khgPxgN8MlNUuRWmz5gh3hYwmD1k,2075
|
|
5
|
+
agent_countersign/policy.py,sha256=T80eOj0zc0PFm92WC1Le4ozZLVHhwe0As4mUuewZolc,5586
|
|
6
|
+
agent_countersign/redact.py,sha256=5-X-c4B-QH-G9fquN_HOVyL7xNoxw6GGczeRAJBM3vA,1594
|
|
7
|
+
agent_countersign/store.py,sha256=hmEZTHSai1c-HTgTaCK6l8_wkzxU3eUtdmO5qBd9yKg,6647
|
|
8
|
+
agent_countersign-0.1.0.dist-info/licenses/LICENSE,sha256=xx0jnfkXJvxRnG63LTGOxlggYnIysveWIZ6H3PNdCrQ,11357
|
|
9
|
+
agent_countersign-0.1.0.dist-info/licenses/NOTICE,sha256=0-bGNqPBazAClDatZt4vi-OzloI5ztg3c2iIpZWI0gA,112
|
|
10
|
+
agent_countersign-0.1.0.dist-info/METADATA,sha256=nQTrxAygeH7WO2_FP9fvnqP-V2awsM8gb8jPq63sQ9Y,5651
|
|
11
|
+
agent_countersign-0.1.0.dist-info/WHEEL,sha256=mOdXR9C3wMVov7cSY8PY-XCzo3SmmWCHvGQr5csJoao,91
|
|
12
|
+
agent_countersign-0.1.0.dist-info/entry_points.txt,sha256=e4CZ8wUX02Cu580myJlTil6d5x5ne4dZk7WC0CFxLKE,59
|
|
13
|
+
agent_countersign-0.1.0.dist-info/top_level.txt,sha256=BE6-rML-0TL5z2yNzn8t72KCI5JbJg8TxLTIRqK-s_g,18
|
|
14
|
+
agent_countersign-0.1.0.dist-info/RECORD,,
|
|
@@ -0,0 +1,201 @@
|
|
|
1
|
+
Apache License
|
|
2
|
+
Version 2.0, January 2004
|
|
3
|
+
http://www.apache.org/licenses/
|
|
4
|
+
|
|
5
|
+
TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
|
|
6
|
+
|
|
7
|
+
1. Definitions.
|
|
8
|
+
|
|
9
|
+
"License" shall mean the terms and conditions for use, reproduction,
|
|
10
|
+
and distribution as defined by Sections 1 through 9 of this document.
|
|
11
|
+
|
|
12
|
+
"Licensor" shall mean the copyright owner or entity authorized by
|
|
13
|
+
the copyright owner that is granting the License.
|
|
14
|
+
|
|
15
|
+
"Legal Entity" shall mean the union of the acting entity and all
|
|
16
|
+
other entities that control, are controlled by, or are under common
|
|
17
|
+
control with that entity. For the purposes of this definition,
|
|
18
|
+
"control" means (i) the power, direct or indirect, to cause the
|
|
19
|
+
direction or management of such entity, whether by contract or
|
|
20
|
+
otherwise, or (ii) ownership of fifty percent (50%) or more of the
|
|
21
|
+
outstanding shares, or (iii) beneficial ownership of such entity.
|
|
22
|
+
|
|
23
|
+
"You" (or "Your") shall mean an individual or Legal Entity
|
|
24
|
+
exercising permissions granted by this License.
|
|
25
|
+
|
|
26
|
+
"Source" form shall mean the preferred form for making modifications,
|
|
27
|
+
including but not limited to software source code, documentation
|
|
28
|
+
source, and configuration files.
|
|
29
|
+
|
|
30
|
+
"Object" form shall mean any form resulting from mechanical
|
|
31
|
+
transformation or translation of a Source form, including but
|
|
32
|
+
not limited to compiled object code, generated documentation,
|
|
33
|
+
and conversions to other media types.
|
|
34
|
+
|
|
35
|
+
"Work" shall mean the work of authorship, whether in Source or
|
|
36
|
+
Object form, made available under the License, as indicated by a
|
|
37
|
+
copyright notice that is included in or attached to the work
|
|
38
|
+
(an example is provided in the Appendix below).
|
|
39
|
+
|
|
40
|
+
"Derivative Works" shall mean any work, whether in Source or Object
|
|
41
|
+
form, that is based on (or derived from) the Work and for which the
|
|
42
|
+
editorial revisions, annotations, elaborations, or other modifications
|
|
43
|
+
represent, as a whole, an original work of authorship. For the purposes
|
|
44
|
+
of this License, Derivative Works shall not include works that remain
|
|
45
|
+
separable from, or merely link (or bind by name) to the interfaces of,
|
|
46
|
+
the Work and Derivative Works thereof.
|
|
47
|
+
|
|
48
|
+
"Contribution" shall mean any work of authorship, including
|
|
49
|
+
the original version of the Work and any modifications or additions
|
|
50
|
+
to that Work or Derivative Works thereof, that is intentionally
|
|
51
|
+
submitted to Licensor for inclusion in the Work by the copyright owner
|
|
52
|
+
or by an individual or Legal Entity authorized to submit on behalf of
|
|
53
|
+
the copyright owner. For the purposes of this definition, "submitted"
|
|
54
|
+
means any form of electronic, verbal, or written communication sent
|
|
55
|
+
to the Licensor or its representatives, including but not limited to
|
|
56
|
+
communication on electronic mailing lists, source code control systems,
|
|
57
|
+
and issue tracking systems that are managed by, or on behalf of, the
|
|
58
|
+
Licensor for the purpose of discussing and improving the Work, but
|
|
59
|
+
excluding communication that is conspicuously marked or otherwise
|
|
60
|
+
designated in writing by the copyright owner as "Not a Contribution."
|
|
61
|
+
|
|
62
|
+
"Contributor" shall mean Licensor and any individual or Legal Entity
|
|
63
|
+
on behalf of whom a Contribution has been received by Licensor and
|
|
64
|
+
subsequently incorporated within the Work.
|
|
65
|
+
|
|
66
|
+
2. Grant of Copyright License. Subject to the terms and conditions of
|
|
67
|
+
this License, each Contributor hereby grants to You a perpetual,
|
|
68
|
+
worldwide, non-exclusive, no-charge, royalty-free, irrevocable
|
|
69
|
+
copyright license to reproduce, prepare Derivative Works of,
|
|
70
|
+
publicly display, publicly perform, sublicense, and distribute the
|
|
71
|
+
Work and such Derivative Works in Source or Object form.
|
|
72
|
+
|
|
73
|
+
3. Grant of Patent License. Subject to the terms and conditions of
|
|
74
|
+
this License, each Contributor hereby grants to You a perpetual,
|
|
75
|
+
worldwide, non-exclusive, no-charge, royalty-free, irrevocable
|
|
76
|
+
(except as stated in this section) patent license to make, have made,
|
|
77
|
+
use, offer to sell, sell, import, and otherwise transfer the Work,
|
|
78
|
+
where such license applies only to those patent claims licensable
|
|
79
|
+
by such Contributor that are necessarily infringed by their
|
|
80
|
+
Contribution(s) alone or by combination of their Contribution(s)
|
|
81
|
+
with the Work to which such Contribution(s) was submitted. If You
|
|
82
|
+
institute patent litigation against any entity (including a
|
|
83
|
+
cross-claim or counterclaim in a lawsuit) alleging that the Work
|
|
84
|
+
or a Contribution incorporated within the Work constitutes direct
|
|
85
|
+
or contributory patent infringement, then any patent licenses
|
|
86
|
+
granted to You under this License for that Work shall terminate
|
|
87
|
+
as of the date such litigation is filed.
|
|
88
|
+
|
|
89
|
+
4. Redistribution. You may reproduce and distribute copies of the
|
|
90
|
+
Work or Derivative Works thereof in any medium, with or without
|
|
91
|
+
modifications, and in Source or Object form, provided that You
|
|
92
|
+
meet the following conditions:
|
|
93
|
+
|
|
94
|
+
(a) You must give any other recipients of the Work or
|
|
95
|
+
Derivative Works a copy of this License; and
|
|
96
|
+
|
|
97
|
+
(b) You must cause any modified files to carry prominent notices
|
|
98
|
+
stating that You changed the files; and
|
|
99
|
+
|
|
100
|
+
(c) You must retain, in the Source form of any Derivative Works
|
|
101
|
+
that You distribute, all copyright, patent, trademark, and
|
|
102
|
+
attribution notices from the Source form of the Work,
|
|
103
|
+
excluding those notices that do not pertain to any part of
|
|
104
|
+
the Derivative Works; and
|
|
105
|
+
|
|
106
|
+
(d) If the Work includes a "NOTICE" text file as part of its
|
|
107
|
+
distribution, then any Derivative Works that You distribute must
|
|
108
|
+
include a readable copy of the attribution notices contained
|
|
109
|
+
within such NOTICE file, excluding those notices that do not
|
|
110
|
+
pertain to any part of the Derivative Works, in at least one
|
|
111
|
+
of the following places: within a NOTICE text file distributed
|
|
112
|
+
as part of the Derivative Works; within the Source form or
|
|
113
|
+
documentation, if provided along with the Derivative Works; or,
|
|
114
|
+
within a display generated by the Derivative Works, if and
|
|
115
|
+
wherever such third-party notices normally appear. The contents
|
|
116
|
+
of the NOTICE file are for informational purposes only and
|
|
117
|
+
do not modify the License. You may add Your own attribution
|
|
118
|
+
notices within Derivative Works that You distribute, alongside
|
|
119
|
+
or as an addendum to the NOTICE text from the Work, provided
|
|
120
|
+
that such additional attribution notices cannot be construed
|
|
121
|
+
as modifying the License.
|
|
122
|
+
|
|
123
|
+
You may add Your own copyright statement to Your modifications and
|
|
124
|
+
may provide additional or different license terms and conditions
|
|
125
|
+
for use, reproduction, or distribution of Your modifications, or
|
|
126
|
+
for any such Derivative Works as a whole, provided Your use,
|
|
127
|
+
reproduction, and distribution of the Work otherwise complies with
|
|
128
|
+
the conditions stated in this License.
|
|
129
|
+
|
|
130
|
+
5. Submission of Contributions. Unless You explicitly state otherwise,
|
|
131
|
+
any Contribution intentionally submitted for inclusion in the Work
|
|
132
|
+
by You to the Licensor shall be under the terms and conditions of
|
|
133
|
+
this License, without any additional terms or conditions.
|
|
134
|
+
Notwithstanding the above, nothing herein shall supersede or modify
|
|
135
|
+
the terms of any separate license agreement you may have executed
|
|
136
|
+
with Licensor regarding such Contributions.
|
|
137
|
+
|
|
138
|
+
6. Trademarks. This License does not grant permission to use the trade
|
|
139
|
+
names, trademarks, service marks, or product names of the Licensor,
|
|
140
|
+
except as required for reasonable and customary use in describing the
|
|
141
|
+
origin of the Work and reproducing the content of the NOTICE file.
|
|
142
|
+
|
|
143
|
+
7. Disclaimer of Warranty. Unless required by applicable law or
|
|
144
|
+
agreed to in writing, Licensor provides the Work (and each
|
|
145
|
+
Contributor provides its Contributions) on an "AS IS" BASIS,
|
|
146
|
+
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
|
|
147
|
+
implied, including, without limitation, any warranties or conditions
|
|
148
|
+
of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A
|
|
149
|
+
PARTICULAR PURPOSE. You are solely responsible for determining the
|
|
150
|
+
appropriateness of using or redistributing the Work and assume any
|
|
151
|
+
risks associated with Your exercise of permissions under this License.
|
|
152
|
+
|
|
153
|
+
8. Limitation of Liability. In no event and under no legal theory,
|
|
154
|
+
whether in tort (including negligence), contract, or otherwise,
|
|
155
|
+
unless required by applicable law (such as deliberate and grossly
|
|
156
|
+
negligent acts) or agreed to in writing, shall any Contributor be
|
|
157
|
+
liable to You for damages, including any direct, indirect, special,
|
|
158
|
+
incidental, or consequential damages of any character arising as a
|
|
159
|
+
result of this License or out of the use or inability to use the
|
|
160
|
+
Work (including but not limited to damages for loss of goodwill,
|
|
161
|
+
work stoppage, computer failure or malfunction, or any and all
|
|
162
|
+
other commercial damages or losses), even if such Contributor
|
|
163
|
+
has been advised of the possibility of such damages.
|
|
164
|
+
|
|
165
|
+
9. Accepting Warranty or Additional Liability. While redistributing
|
|
166
|
+
the Work or Derivative Works thereof, You may choose to offer,
|
|
167
|
+
and charge a fee for, acceptance of support, warranty, indemnity,
|
|
168
|
+
or other liability obligations and/or rights consistent with this
|
|
169
|
+
License. However, in accepting such obligations, You may act only
|
|
170
|
+
on Your own behalf and on Your sole responsibility, not on behalf
|
|
171
|
+
of any other Contributor, and only if You agree to indemnify,
|
|
172
|
+
defend, and hold each Contributor harmless for any liability
|
|
173
|
+
incurred by, or claims asserted against, such Contributor by reason
|
|
174
|
+
of your accepting any such warranty or additional liability.
|
|
175
|
+
|
|
176
|
+
END OF TERMS AND CONDITIONS
|
|
177
|
+
|
|
178
|
+
APPENDIX: How to apply the Apache License to your work.
|
|
179
|
+
|
|
180
|
+
To apply the Apache License to your work, attach the following
|
|
181
|
+
boilerplate notice, with the fields enclosed by brackets "[]"
|
|
182
|
+
replaced with your own identifying information. (Don't include
|
|
183
|
+
the brackets!) The text should be enclosed in the appropriate
|
|
184
|
+
comment syntax for the file format. We also recommend that a
|
|
185
|
+
file or class name and description of purpose be included on the
|
|
186
|
+
same "printed page" as the copyright notice for easier
|
|
187
|
+
identification within third-party archives.
|
|
188
|
+
|
|
189
|
+
Copyright [yyyy] [name of copyright owner]
|
|
190
|
+
|
|
191
|
+
Licensed under the Apache License, Version 2.0 (the "License");
|
|
192
|
+
you may not use this file except in compliance with the License.
|
|
193
|
+
You may obtain a copy of the License at
|
|
194
|
+
|
|
195
|
+
http://www.apache.org/licenses/LICENSE-2.0
|
|
196
|
+
|
|
197
|
+
Unless required by applicable law or agreed to in writing, software
|
|
198
|
+
distributed under the License is distributed on an "AS IS" BASIS,
|
|
199
|
+
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
|
200
|
+
See the License for the specific language governing permissions and
|
|
201
|
+
limitations under the License.
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
agent_countersign
|