agentgate-mcp 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.
- agentgate/__init__.py +3 -0
- agentgate/__main__.py +3 -0
- agentgate/approvals.py +138 -0
- agentgate/audit.py +83 -0
- agentgate/cli.py +416 -0
- agentgate/config_audit.py +202 -0
- agentgate/detectors/__init__.py +2 -0
- agentgate/detectors/args_policy.py +196 -0
- agentgate/detectors/classifier.py +144 -0
- agentgate/detectors/judge.py +224 -0
- agentgate/detectors/manifest_guard.py +342 -0
- agentgate/detectors/poisoning.py +398 -0
- agentgate/detectors/posture.py +72 -0
- agentgate/detectors/secrets.py +191 -0
- agentgate/detectors/taint.py +296 -0
- agentgate/findings.py +59 -0
- agentgate/install.py +87 -0
- agentgate/pipeline.py +565 -0
- agentgate/policies/default.yaml +70 -0
- agentgate/policy.py +172 -0
- agentgate/protocol/__init__.py +0 -0
- agentgate/protocol/models.py +125 -0
- agentgate/report.py +90 -0
- agentgate/sinks.py +136 -0
- agentgate/transport/__init__.py +0 -0
- agentgate/transport/http.py +186 -0
- agentgate/transport/stdio.py +145 -0
- agentgate_mcp-0.1.0.dist-info/METADATA +223 -0
- agentgate_mcp-0.1.0.dist-info/RECORD +32 -0
- agentgate_mcp-0.1.0.dist-info/WHEEL +4 -0
- agentgate_mcp-0.1.0.dist-info/entry_points.txt +2 -0
- agentgate_mcp-0.1.0.dist-info/licenses/LICENSE +201 -0
agentgate/__init__.py
ADDED
agentgate/__main__.py
ADDED
agentgate/approvals.py
ADDED
|
@@ -0,0 +1,138 @@
|
|
|
1
|
+
"""Resolving `ask` decisions. stdio is owned by the MCP protocol, so a human can only be asked
|
|
2
|
+
out-of-band: on the controlling terminal (tty mode) or, later, a local web page / chat bot."""
|
|
3
|
+
|
|
4
|
+
from __future__ import annotations
|
|
5
|
+
|
|
6
|
+
import asyncio
|
|
7
|
+
import json
|
|
8
|
+
import os
|
|
9
|
+
import secrets
|
|
10
|
+
import time
|
|
11
|
+
import urllib.request
|
|
12
|
+
from typing import Any, Protocol
|
|
13
|
+
|
|
14
|
+
|
|
15
|
+
class Approver(Protocol):
|
|
16
|
+
async def ask(self, prompt: str) -> bool: ...
|
|
17
|
+
|
|
18
|
+
|
|
19
|
+
class DenyApprover:
|
|
20
|
+
"""No human available: `ask` fails closed."""
|
|
21
|
+
|
|
22
|
+
async def ask(self, prompt: str) -> bool:
|
|
23
|
+
return False
|
|
24
|
+
|
|
25
|
+
|
|
26
|
+
class TtyApprover:
|
|
27
|
+
"""Prompt on the controlling terminal. Only works when the client was started from one."""
|
|
28
|
+
|
|
29
|
+
def __init__(self, timeout_s: float = 60.0) -> None:
|
|
30
|
+
self.timeout_s = timeout_s
|
|
31
|
+
self._lock = asyncio.Lock()
|
|
32
|
+
|
|
33
|
+
async def ask(self, prompt: str) -> bool:
|
|
34
|
+
async with self._lock: # one prompt at a time
|
|
35
|
+
try:
|
|
36
|
+
return await asyncio.wait_for(
|
|
37
|
+
asyncio.to_thread(self._prompt, prompt), self.timeout_s
|
|
38
|
+
)
|
|
39
|
+
except (TimeoutError, OSError):
|
|
40
|
+
return False
|
|
41
|
+
|
|
42
|
+
@staticmethod
|
|
43
|
+
def _prompt(prompt: str) -> bool:
|
|
44
|
+
dev = "CON" if os.name == "nt" else "/dev/tty"
|
|
45
|
+
with open(dev, "r+", encoding="utf-8") as tty:
|
|
46
|
+
tty.write(f"\n[AgentGate] {prompt}\nAllow? [y/N] ")
|
|
47
|
+
tty.flush()
|
|
48
|
+
return tty.readline().strip().lower() in {"y", "yes"}
|
|
49
|
+
|
|
50
|
+
|
|
51
|
+
class TelegramApprover:
|
|
52
|
+
"""Ask on Telegram: sends the request with Allow/Deny buttons and waits for a tap.
|
|
53
|
+
|
|
54
|
+
Configure with TELEGRAM_BOT_TOKEN and TELEGRAM_CHAT_ID (create a bot with @BotFather and
|
|
55
|
+
send it one message first). No reply within the timeout means deny (fail closed).
|
|
56
|
+
"""
|
|
57
|
+
|
|
58
|
+
def __init__(
|
|
59
|
+
self,
|
|
60
|
+
token: str,
|
|
61
|
+
chat_id: str,
|
|
62
|
+
timeout_s: float = 120.0,
|
|
63
|
+
api_base: str = "https://api.telegram.org",
|
|
64
|
+
) -> None:
|
|
65
|
+
self.token, self.chat_id, self.timeout_s = token, chat_id, timeout_s
|
|
66
|
+
self.api = f"{api_base.rstrip('/')}/bot{token}"
|
|
67
|
+
self._lock = asyncio.Lock()
|
|
68
|
+
self._offset = 0
|
|
69
|
+
|
|
70
|
+
@classmethod
|
|
71
|
+
def from_env(cls) -> TelegramApprover | None:
|
|
72
|
+
token, chat = os.environ.get("TELEGRAM_BOT_TOKEN"), os.environ.get("TELEGRAM_CHAT_ID")
|
|
73
|
+
return cls(token, chat) if token and chat else None
|
|
74
|
+
|
|
75
|
+
def _call(self, method: str, payload: dict[str, object], timeout: float = 30.0) -> Any:
|
|
76
|
+
req = urllib.request.Request( # noqa: S310 - fixed https API (or a test base URL)
|
|
77
|
+
f"{self.api}/{method}",
|
|
78
|
+
data=json.dumps(payload).encode(),
|
|
79
|
+
headers={"Content-Type": "application/json"},
|
|
80
|
+
method="POST",
|
|
81
|
+
)
|
|
82
|
+
with urllib.request.urlopen(req, timeout=timeout) as r: # noqa: S310
|
|
83
|
+
return json.load(r)
|
|
84
|
+
|
|
85
|
+
def _ask_blocking(self, prompt: str) -> bool:
|
|
86
|
+
nonce = secrets.token_hex(6)
|
|
87
|
+
text = f"AgentGate approval needed\n\n{prompt[:3500]}"
|
|
88
|
+
self._call(
|
|
89
|
+
"sendMessage",
|
|
90
|
+
{
|
|
91
|
+
"chat_id": self.chat_id,
|
|
92
|
+
"text": text,
|
|
93
|
+
"reply_markup": {
|
|
94
|
+
"inline_keyboard": [
|
|
95
|
+
[
|
|
96
|
+
{"text": "Allow", "callback_data": f"allow:{nonce}"},
|
|
97
|
+
{"text": "Deny", "callback_data": f"deny:{nonce}"},
|
|
98
|
+
]
|
|
99
|
+
]
|
|
100
|
+
},
|
|
101
|
+
},
|
|
102
|
+
)
|
|
103
|
+
deadline = time.monotonic() + self.timeout_s
|
|
104
|
+
while time.monotonic() < deadline:
|
|
105
|
+
wait = int(min(20, max(1, deadline - time.monotonic())))
|
|
106
|
+
updates = self._call(
|
|
107
|
+
"getUpdates",
|
|
108
|
+
{"offset": self._offset, "timeout": wait, "allowed_updates": ["callback_query"]},
|
|
109
|
+
timeout=wait + 10,
|
|
110
|
+
).get("result", [])
|
|
111
|
+
for u in updates:
|
|
112
|
+
self._offset = max(self._offset, int(u["update_id"]) + 1)
|
|
113
|
+
cq = u.get("callback_query") or {}
|
|
114
|
+
data = str(cq.get("data", ""))
|
|
115
|
+
chat = str(((cq.get("message") or {}).get("chat") or {}).get("id", ""))
|
|
116
|
+
if data.endswith(f":{nonce}") and chat == str(self.chat_id):
|
|
117
|
+
self._call("answerCallbackQuery", {"callback_query_id": cq.get("id")})
|
|
118
|
+
return data.startswith("allow:")
|
|
119
|
+
return False
|
|
120
|
+
|
|
121
|
+
async def ask(self, prompt: str) -> bool:
|
|
122
|
+
async with self._lock: # one pending approval at a time
|
|
123
|
+
try:
|
|
124
|
+
return await asyncio.wait_for(
|
|
125
|
+
asyncio.to_thread(self._ask_blocking, prompt), self.timeout_s + 30
|
|
126
|
+
)
|
|
127
|
+
except (TimeoutError, OSError, ValueError, KeyError):
|
|
128
|
+
return False
|
|
129
|
+
|
|
130
|
+
|
|
131
|
+
def make_approver(mode: str) -> Approver:
|
|
132
|
+
if mode == "tty":
|
|
133
|
+
return TtyApprover()
|
|
134
|
+
if mode == "telegram":
|
|
135
|
+
tg = TelegramApprover.from_env()
|
|
136
|
+
if tg is not None:
|
|
137
|
+
return tg
|
|
138
|
+
return DenyApprover()
|
agentgate/audit.py
ADDED
|
@@ -0,0 +1,83 @@
|
|
|
1
|
+
"""Structured audit events (JSON lines, loosely aligned with OCSF). One event per decision."""
|
|
2
|
+
|
|
3
|
+
from __future__ import annotations
|
|
4
|
+
|
|
5
|
+
import json
|
|
6
|
+
import os
|
|
7
|
+
import sys
|
|
8
|
+
import threading
|
|
9
|
+
from datetime import UTC, datetime
|
|
10
|
+
from pathlib import Path
|
|
11
|
+
from typing import Any, TextIO
|
|
12
|
+
|
|
13
|
+
from agentgate.findings import Finding, Severity
|
|
14
|
+
|
|
15
|
+
_SEV_ORDER = [s.value for s in Severity]
|
|
16
|
+
|
|
17
|
+
|
|
18
|
+
class AuditLog:
|
|
19
|
+
"""Thread-safe JSONL writer. sink: a file path, or "stderr"."""
|
|
20
|
+
|
|
21
|
+
def __init__(
|
|
22
|
+
self,
|
|
23
|
+
sink: str | Path,
|
|
24
|
+
*,
|
|
25
|
+
session: str,
|
|
26
|
+
server: str,
|
|
27
|
+
client: str = "unknown",
|
|
28
|
+
extra_sinks: list[Any] | None = None,
|
|
29
|
+
):
|
|
30
|
+
self.session, self.server, self.client = session, server, client
|
|
31
|
+
self.extra_sinks = extra_sinks or []
|
|
32
|
+
self._lock = threading.Lock()
|
|
33
|
+
self._fh: TextIO
|
|
34
|
+
if str(sink) == "stderr":
|
|
35
|
+
self._fh, self._owned = sys.stderr, False
|
|
36
|
+
else:
|
|
37
|
+
p = Path(sink)
|
|
38
|
+
p.parent.mkdir(parents=True, exist_ok=True)
|
|
39
|
+
fd = os.open(p, os.O_WRONLY | os.O_CREAT | os.O_APPEND, 0o600)
|
|
40
|
+
self._fh, self._owned = os.fdopen(fd, "a", encoding="utf-8"), True
|
|
41
|
+
|
|
42
|
+
def emit(
|
|
43
|
+
self,
|
|
44
|
+
event: str,
|
|
45
|
+
*,
|
|
46
|
+
method: str | None = None,
|
|
47
|
+
tool: str | None = None,
|
|
48
|
+
decision: str | None = None,
|
|
49
|
+
rule: str | None = None,
|
|
50
|
+
findings: list[Finding] | None = None,
|
|
51
|
+
latency_ms: float | None = None,
|
|
52
|
+
**extra: Any,
|
|
53
|
+
) -> dict[str, Any]:
|
|
54
|
+
rec: dict[str, Any] = {
|
|
55
|
+
"ts": datetime.now(UTC).isoformat(timespec="milliseconds").replace("+00:00", "Z"),
|
|
56
|
+
"event": event,
|
|
57
|
+
"session": self.session,
|
|
58
|
+
"client": self.client,
|
|
59
|
+
"server": self.server,
|
|
60
|
+
}
|
|
61
|
+
for k, v in (("method", method), ("tool", tool), ("decision", decision), ("rule", rule)):
|
|
62
|
+
if v is not None:
|
|
63
|
+
rec[k] = v
|
|
64
|
+
if findings:
|
|
65
|
+
rec["findings"] = [f.to_dict() for f in findings]
|
|
66
|
+
# Flattened fields: SIEM rules match on these instead of nested arrays.
|
|
67
|
+
rec["finding_ids"] = sorted({f.id for f in findings})
|
|
68
|
+
rec["owasp"] = sorted({f.owasp for f in findings if f.owasp})
|
|
69
|
+
rec["severity"] = max((f.severity.value for f in findings), key=_SEV_ORDER.index)
|
|
70
|
+
if latency_ms is not None:
|
|
71
|
+
rec["latency_ms"] = round(latency_ms, 3)
|
|
72
|
+
rec.update({k: v for k, v in extra.items() if v is not None})
|
|
73
|
+
line = json.dumps(rec, ensure_ascii=False, default=str)
|
|
74
|
+
with self._lock:
|
|
75
|
+
self._fh.write(line + "\n")
|
|
76
|
+
self._fh.flush()
|
|
77
|
+
for sink in self.extra_sinks:
|
|
78
|
+
sink.send(rec)
|
|
79
|
+
return rec
|
|
80
|
+
|
|
81
|
+
def close(self) -> None:
|
|
82
|
+
if self._owned:
|
|
83
|
+
self._fh.close()
|
agentgate/cli.py
ADDED
|
@@ -0,0 +1,416 @@
|
|
|
1
|
+
"""Command-line interface: `agentgate wrap | approve | pins | forget | logs | version`."""
|
|
2
|
+
|
|
3
|
+
from __future__ import annotations
|
|
4
|
+
|
|
5
|
+
import asyncio
|
|
6
|
+
import json
|
|
7
|
+
import os
|
|
8
|
+
import uuid
|
|
9
|
+
from datetime import datetime
|
|
10
|
+
from pathlib import Path
|
|
11
|
+
from typing import Annotated
|
|
12
|
+
|
|
13
|
+
import typer
|
|
14
|
+
from rich.console import Console
|
|
15
|
+
from rich.table import Table
|
|
16
|
+
|
|
17
|
+
from agentgate import __version__
|
|
18
|
+
from agentgate.approvals import make_approver
|
|
19
|
+
from agentgate.audit import AuditLog
|
|
20
|
+
from agentgate.detectors.classifier import HFClassifier
|
|
21
|
+
from agentgate.detectors.judge import LLMJudge
|
|
22
|
+
from agentgate.detectors.manifest_guard import PinStore
|
|
23
|
+
from agentgate.detectors.taint import TaintStore
|
|
24
|
+
from agentgate.pipeline import Pipeline
|
|
25
|
+
from agentgate.policy import Policy, load_policy
|
|
26
|
+
from agentgate.sinks import HecSink
|
|
27
|
+
|
|
28
|
+
app = typer.Typer(
|
|
29
|
+
help="AgentGate: runtime security gateway for MCP servers.",
|
|
30
|
+
no_args_is_help=True,
|
|
31
|
+
add_completion=False,
|
|
32
|
+
)
|
|
33
|
+
# stdout belongs to the MCP protocol in `wrap`; human output goes to stderr.
|
|
34
|
+
err = Console(stderr=True)
|
|
35
|
+
|
|
36
|
+
|
|
37
|
+
def make_classifier(pol: Policy) -> HFClassifier | None:
|
|
38
|
+
c = pol.classifier
|
|
39
|
+
return HFClassifier(c.model, c.injection_label, revision=c.revision) if c.enabled else None
|
|
40
|
+
|
|
41
|
+
|
|
42
|
+
def home() -> Path:
|
|
43
|
+
return Path(os.environ.get("AGENTGATE_HOME", Path.home() / ".agentgate"))
|
|
44
|
+
|
|
45
|
+
|
|
46
|
+
def pins_path() -> Path:
|
|
47
|
+
return home() / "pins.db"
|
|
48
|
+
|
|
49
|
+
|
|
50
|
+
def audit_path() -> Path:
|
|
51
|
+
return Path(os.environ.get("AGENTGATE_AUDIT", home() / "audit.jsonl"))
|
|
52
|
+
|
|
53
|
+
|
|
54
|
+
@app.command(context_settings={"allow_interspersed_args": False})
|
|
55
|
+
def wrap(
|
|
56
|
+
command: Annotated[list[str], typer.Argument(help="Server command, after `--`.")],
|
|
57
|
+
server: Annotated[str, typer.Option("--server", "-s", help="Logical server name.")],
|
|
58
|
+
policy: Annotated[Path | None, typer.Option(help="Policy YAML file.")] = None,
|
|
59
|
+
client: Annotated[str, typer.Option(help="Client name recorded in audit logs.")] = "unknown",
|
|
60
|
+
audit: Annotated[str | None, typer.Option(help="Audit sink: file path or 'stderr'.")] = None,
|
|
61
|
+
) -> None:
|
|
62
|
+
"""Run an MCP stdio server behind AgentGate.
|
|
63
|
+
|
|
64
|
+
Example:
|
|
65
|
+
agentgate wrap --server fs -- npx -y @modelcontextprotocol/server-filesystem ~/projects
|
|
66
|
+
"""
|
|
67
|
+
from agentgate.transport.stdio import run_stdio_proxy
|
|
68
|
+
|
|
69
|
+
pol = load_policy(policy)
|
|
70
|
+
session = uuid.uuid4().hex[:12]
|
|
71
|
+
hec = HecSink.from_env()
|
|
72
|
+
log = AuditLog(
|
|
73
|
+
audit or audit_path(),
|
|
74
|
+
session=session,
|
|
75
|
+
server=server,
|
|
76
|
+
client=client,
|
|
77
|
+
extra_sinks=[hec] if hec else None,
|
|
78
|
+
)
|
|
79
|
+
store = PinStore(pins_path())
|
|
80
|
+
taint = TaintStore(home() / "taint.db")
|
|
81
|
+
pipe = Pipeline(
|
|
82
|
+
pol,
|
|
83
|
+
server,
|
|
84
|
+
store,
|
|
85
|
+
log,
|
|
86
|
+
make_approver(pol.defaults.approvals),
|
|
87
|
+
taint,
|
|
88
|
+
make_classifier(pol),
|
|
89
|
+
LLMJudge.from_policy(pol.judge, home()),
|
|
90
|
+
)
|
|
91
|
+
try:
|
|
92
|
+
code = asyncio.run(run_stdio_proxy(command, pipe))
|
|
93
|
+
finally:
|
|
94
|
+
store.close()
|
|
95
|
+
taint.close()
|
|
96
|
+
log.close()
|
|
97
|
+
if hec:
|
|
98
|
+
hec.close()
|
|
99
|
+
raise typer.Exit(code)
|
|
100
|
+
|
|
101
|
+
|
|
102
|
+
@app.command()
|
|
103
|
+
def approve(
|
|
104
|
+
server: str,
|
|
105
|
+
tool: Annotated[str | None, typer.Option(help="Approve only this tool.")] = None,
|
|
106
|
+
) -> None:
|
|
107
|
+
"""Approve pending (new or changed) tool definitions for a server."""
|
|
108
|
+
store = PinStore(pins_path())
|
|
109
|
+
pending = [
|
|
110
|
+
p
|
|
111
|
+
for p in store.all(server)
|
|
112
|
+
if p.status.value == "pending" and (tool is None or p.tool == tool)
|
|
113
|
+
]
|
|
114
|
+
if not pending:
|
|
115
|
+
err.print(f"No pending tools for [bold]{server}[/]" + (f"/{tool}" if tool else ""))
|
|
116
|
+
raise typer.Exit(1)
|
|
117
|
+
for p in pending:
|
|
118
|
+
err.print(f"\n[bold yellow]{server}/{p.tool}[/] pending definition:")
|
|
119
|
+
err.print_json(json.dumps(p.pending_manifest))
|
|
120
|
+
if not typer.confirm(f"Approve {len(pending)} tool definition(s)?", err=True):
|
|
121
|
+
raise typer.Exit(1)
|
|
122
|
+
done = store.approve(server, tool)
|
|
123
|
+
err.print(f"[green]Approved:[/] {', '.join(done)}")
|
|
124
|
+
|
|
125
|
+
|
|
126
|
+
@app.command()
|
|
127
|
+
def pins(server: Annotated[str | None, typer.Argument()] = None) -> None:
|
|
128
|
+
"""List pinned tool definitions and their status."""
|
|
129
|
+
store = PinStore(pins_path())
|
|
130
|
+
t = Table("server", "tool", "status", "approved hash", "updated")
|
|
131
|
+
for p in store.all(server):
|
|
132
|
+
style = "green" if p.status.value == "approved" else "yellow"
|
|
133
|
+
t.add_row(
|
|
134
|
+
p.server,
|
|
135
|
+
p.tool,
|
|
136
|
+
f"[{style}]{p.status.value}[/]",
|
|
137
|
+
(p.approved_hash or "-")[:12],
|
|
138
|
+
datetime.fromtimestamp(p.updated_at).strftime("%Y-%m-%d %H:%M"),
|
|
139
|
+
)
|
|
140
|
+
Console().print(t)
|
|
141
|
+
|
|
142
|
+
|
|
143
|
+
@app.command()
|
|
144
|
+
def forget(server: str) -> None:
|
|
145
|
+
"""Delete all pins for a server (it will be treated as first seen next time)."""
|
|
146
|
+
n = PinStore(pins_path()).forget(server)
|
|
147
|
+
err.print(f"Removed {n} pin(s) for {server}")
|
|
148
|
+
|
|
149
|
+
|
|
150
|
+
@app.command()
|
|
151
|
+
def logs(
|
|
152
|
+
tail: Annotated[int, typer.Option("--tail", "-n")] = 20,
|
|
153
|
+
only_findings: Annotated[
|
|
154
|
+
bool, typer.Option("--findings", help="Only events with findings")
|
|
155
|
+
] = False,
|
|
156
|
+
) -> None:
|
|
157
|
+
"""Show recent audit events."""
|
|
158
|
+
path = audit_path()
|
|
159
|
+
if not path.exists():
|
|
160
|
+
err.print(f"No audit log at {path}")
|
|
161
|
+
raise typer.Exit(1)
|
|
162
|
+
lines = path.read_text(encoding="utf-8").splitlines()
|
|
163
|
+
events = [json.loads(x) for x in lines if x.strip()]
|
|
164
|
+
if only_findings:
|
|
165
|
+
events = [e for e in events if e.get("findings")]
|
|
166
|
+
t = Table("ts", "server", "event", "tool", "decision", "rule")
|
|
167
|
+
colors = {"deny": "red", "flag": "yellow", "allow": "green", "drop": "red"}
|
|
168
|
+
for e in events[-tail:]:
|
|
169
|
+
d = e.get("decision", "")
|
|
170
|
+
t.add_row(
|
|
171
|
+
e["ts"][11:23],
|
|
172
|
+
e.get("server", ""),
|
|
173
|
+
e["event"],
|
|
174
|
+
e.get("tool", ""),
|
|
175
|
+
f"[{colors.get(d, 'white')}]{d}[/]",
|
|
176
|
+
e.get("rule") or "",
|
|
177
|
+
)
|
|
178
|
+
Console().print(t)
|
|
179
|
+
|
|
180
|
+
|
|
181
|
+
@app.command()
|
|
182
|
+
def version() -> None:
|
|
183
|
+
"""Print the version."""
|
|
184
|
+
typer.echo(__version__)
|
|
185
|
+
|
|
186
|
+
|
|
187
|
+
@app.command("scan-config")
|
|
188
|
+
def scan_config(
|
|
189
|
+
paths: Annotated[
|
|
190
|
+
list[Path] | None, typer.Argument(help="Config files (default: known)")
|
|
191
|
+
] = None,
|
|
192
|
+
sarif: Annotated[Path | None, typer.Option(help="Write SARIF 2.1.0 to this file.")] = None,
|
|
193
|
+
) -> None:
|
|
194
|
+
"""Statically audit MCP client config files (Claude Desktop, Cursor, VS Code, ...)."""
|
|
195
|
+
from agentgate.config_audit import audit_file, default_config_paths, to_sarif
|
|
196
|
+
|
|
197
|
+
files = [p for p in (paths or default_config_paths()) if p.is_file()]
|
|
198
|
+
findings = [f for p in files for f in audit_file(p)]
|
|
199
|
+
t = Table("severity", "rule", "server", "file", "message")
|
|
200
|
+
colors = {"high": "red", "critical": "red", "medium": "yellow"}
|
|
201
|
+
for f in findings:
|
|
202
|
+
sev = f.severity.value
|
|
203
|
+
t.add_row(
|
|
204
|
+
f"[{colors.get(sev, 'white')}]{sev}[/]", f.rule, f.server, Path(f.file).name, f.message
|
|
205
|
+
)
|
|
206
|
+
out = Console()
|
|
207
|
+
out.print(f"Scanned {len(files)} config file(s): " + ", ".join(str(p) for p in files))
|
|
208
|
+
out.print(t)
|
|
209
|
+
if sarif:
|
|
210
|
+
sarif.write_text(json.dumps(to_sarif(findings), indent=2), encoding="utf-8")
|
|
211
|
+
out.print(f"SARIF written to {sarif}")
|
|
212
|
+
raise typer.Exit(1 if any(f.severity.value in ("high", "critical") for f in findings) else 0)
|
|
213
|
+
|
|
214
|
+
|
|
215
|
+
@app.command()
|
|
216
|
+
def serve(
|
|
217
|
+
upstream: Annotated[
|
|
218
|
+
str, typer.Option(help="Upstream MCP endpoint, e.g. http://localhost:8000/mcp")
|
|
219
|
+
],
|
|
220
|
+
server: Annotated[str, typer.Option("--server", "-s", help="Logical server name.")],
|
|
221
|
+
host: Annotated[str, typer.Option(help="Interface to listen on.")] = "127.0.0.1",
|
|
222
|
+
port: Annotated[int, typer.Option(help="Port to listen on.")] = 8765,
|
|
223
|
+
policy: Annotated[Path | None, typer.Option(help="Policy YAML file.")] = None,
|
|
224
|
+
client: Annotated[str, typer.Option(help="Client name recorded in audit logs.")] = "unknown",
|
|
225
|
+
) -> None:
|
|
226
|
+
"""Run a Streamable HTTP MCP server behind AgentGate (reverse proxy).
|
|
227
|
+
|
|
228
|
+
Point the client at http://HOST:PORT/ instead of the upstream URL.
|
|
229
|
+
"""
|
|
230
|
+
try:
|
|
231
|
+
import uvicorn
|
|
232
|
+
|
|
233
|
+
from agentgate.transport.http import HttpGateway
|
|
234
|
+
except ImportError:
|
|
235
|
+
err.print("The HTTP proxy needs extras: pip install 'agentgate-mcp[http]'", markup=False)
|
|
236
|
+
raise typer.Exit(2) from None
|
|
237
|
+
|
|
238
|
+
pol = load_policy(policy)
|
|
239
|
+
store = PinStore(pins_path())
|
|
240
|
+
taint = TaintStore(home() / "taint.db")
|
|
241
|
+
approver = make_approver(pol.defaults.approvals)
|
|
242
|
+
hec = HecSink.from_env()
|
|
243
|
+
clf = make_classifier(pol)
|
|
244
|
+
llm = LLMJudge.from_policy(pol.judge, home())
|
|
245
|
+
|
|
246
|
+
def make_pipeline(session: str) -> Pipeline:
|
|
247
|
+
log = AuditLog(
|
|
248
|
+
audit_path(),
|
|
249
|
+
session=f"http-{uuid.uuid4().hex[:8]}",
|
|
250
|
+
server=server,
|
|
251
|
+
client=client,
|
|
252
|
+
extra_sinks=[hec] if hec else None,
|
|
253
|
+
)
|
|
254
|
+
return Pipeline(pol, server, store, log, approver, taint, clf, llm)
|
|
255
|
+
|
|
256
|
+
gw = HttpGateway(upstream, make_pipeline)
|
|
257
|
+
err.print(f"AgentGate: http://{host}:{port}/ -> {upstream} (server={server})")
|
|
258
|
+
try:
|
|
259
|
+
uvicorn.run(gw.app, host=host, port=port, log_level="warning")
|
|
260
|
+
finally:
|
|
261
|
+
store.close()
|
|
262
|
+
taint.close()
|
|
263
|
+
if hec:
|
|
264
|
+
hec.close()
|
|
265
|
+
|
|
266
|
+
|
|
267
|
+
@app.command()
|
|
268
|
+
def check(
|
|
269
|
+
server: Annotated[str, typer.Option("--server", "-s", help="Logical server name.")],
|
|
270
|
+
message: Annotated[
|
|
271
|
+
str | None, typer.Option("--input", help="JSON message; default stdin")
|
|
272
|
+
] = None,
|
|
273
|
+
manifest: Annotated[
|
|
274
|
+
Path | None, typer.Option(help="A tools/list result (JSON) to scan instead of a call")
|
|
275
|
+
] = None,
|
|
276
|
+
policy: Annotated[Path | None, typer.Option(help="Policy YAML file.")] = None,
|
|
277
|
+
) -> None:
|
|
278
|
+
"""Test a tool call or a tool manifest against the policy, without running a proxy.
|
|
279
|
+
|
|
280
|
+
Exit code 0 = allowed, 1 = denied or needs approval, 2 = bad input. Stateless: no pins,
|
|
281
|
+
no taint history (use the proxy for those).
|
|
282
|
+
"""
|
|
283
|
+
import sys
|
|
284
|
+
|
|
285
|
+
from agentgate.detectors import args_policy, poisoning, secrets
|
|
286
|
+
from agentgate.findings import Action
|
|
287
|
+
from agentgate.protocol import models as proto
|
|
288
|
+
|
|
289
|
+
pol = load_policy(policy)
|
|
290
|
+
out = Console()
|
|
291
|
+
try:
|
|
292
|
+
if manifest is not None:
|
|
293
|
+
doc = json.loads(manifest.read_text(encoding="utf-8"))
|
|
294
|
+
tools = doc.get("tools", doc) if isinstance(doc, dict) else doc
|
|
295
|
+
worst = Action.ALLOW
|
|
296
|
+
for tool in tools:
|
|
297
|
+
fs = poisoning.scan_tool(tool)
|
|
298
|
+
decision, rule = pol.decide(Action.ALLOW, fs)
|
|
299
|
+
worst = Action.strictest(worst, decision)
|
|
300
|
+
mark = {
|
|
301
|
+
"allow": "[green]ALLOW[/]",
|
|
302
|
+
"ask": "[yellow]ASK [/]",
|
|
303
|
+
"deny": "[red]DENY [/]",
|
|
304
|
+
}[decision.value]
|
|
305
|
+
out.print(f"{mark} {tool.get('name')}" + (f" ({rule})" if rule else ""))
|
|
306
|
+
for f in fs:
|
|
307
|
+
out.print(f" {f.id} {f.severity.value}: {f.evidence[:160]}", markup=False)
|
|
308
|
+
raise typer.Exit(0 if worst is Action.ALLOW else 1)
|
|
309
|
+
msg = proto.parse((message or sys.stdin.read()).strip())
|
|
310
|
+
except (OSError, ValueError, proto.ProtocolError) as e:
|
|
311
|
+
err.print(f"bad input: {e}", markup=False)
|
|
312
|
+
raise typer.Exit(2) from None
|
|
313
|
+
if msg.method != "tools/call":
|
|
314
|
+
err.print("expected a tools/call request")
|
|
315
|
+
raise typer.Exit(2)
|
|
316
|
+
name = str(msg.params.get("name", ""))
|
|
317
|
+
arguments = msg.params.get("arguments") or {}
|
|
318
|
+
findings = args_policy.check(pol, server, name, arguments)
|
|
319
|
+
findings += secrets.scan(proto.iter_string_args(arguments), "outgoing")
|
|
320
|
+
decision, rule = pol.decide(pol.base_action(server, name), findings)
|
|
321
|
+
color = {"allow": "green", "ask": "yellow", "deny": "red"}[decision.value]
|
|
322
|
+
out.print(
|
|
323
|
+
f"[{color}]{decision.value.upper()}[/] {server}/{name}" + (f" ({rule})" if rule else "")
|
|
324
|
+
)
|
|
325
|
+
for f in findings:
|
|
326
|
+
out.print(f" {f.id} {f.severity.value}: {f.evidence[:200]}", markup=False)
|
|
327
|
+
raise typer.Exit(0 if decision is Action.ALLOW else 1)
|
|
328
|
+
|
|
329
|
+
|
|
330
|
+
@app.command("pins-export")
|
|
331
|
+
def pins_export(
|
|
332
|
+
server: Annotated[str | None, typer.Argument()] = None,
|
|
333
|
+
output: Annotated[Path | None, typer.Option("--output", "-o")] = None,
|
|
334
|
+
) -> None:
|
|
335
|
+
"""Export approved tool definitions (with SHA-256) as JSON, e.g. to review in git."""
|
|
336
|
+
data = json.dumps(
|
|
337
|
+
{"version": 1, "pins": PinStore(pins_path()).export(server)},
|
|
338
|
+
indent=2,
|
|
339
|
+
ensure_ascii=False,
|
|
340
|
+
sort_keys=True,
|
|
341
|
+
)
|
|
342
|
+
if output:
|
|
343
|
+
output.write_text(data + "\n", encoding="utf-8")
|
|
344
|
+
err.print(f"Wrote {output}")
|
|
345
|
+
else:
|
|
346
|
+
typer.echo(data)
|
|
347
|
+
|
|
348
|
+
|
|
349
|
+
@app.command("pins-import")
|
|
350
|
+
def pins_import(path: Path) -> None:
|
|
351
|
+
"""Import approved tool definitions. Combined with `defaults.first_seen_tool: deny`, only
|
|
352
|
+
tools in the file are ever shown to the model (an allowlist)."""
|
|
353
|
+
try:
|
|
354
|
+
doc = json.loads(path.read_text(encoding="utf-8"))
|
|
355
|
+
n = PinStore(pins_path()).import_pins(doc["pins"])
|
|
356
|
+
except (OSError, ValueError, KeyError, TypeError) as e:
|
|
357
|
+
err.print(f"import failed: {e}", markup=False)
|
|
358
|
+
raise typer.Exit(1) from None
|
|
359
|
+
err.print(f"Imported {n} approved tool definition(s)")
|
|
360
|
+
|
|
361
|
+
|
|
362
|
+
@app.command()
|
|
363
|
+
def install(
|
|
364
|
+
client: Annotated[
|
|
365
|
+
str, typer.Option(help="claude-desktop | cursor | windsurf | vscode | claude-code")
|
|
366
|
+
],
|
|
367
|
+
config: Annotated[Path | None, typer.Option(help="Config file (default: the client's)")] = None,
|
|
368
|
+
do_apply: Annotated[
|
|
369
|
+
bool, typer.Option("--apply", help="Write the change (default: show diff)")
|
|
370
|
+
] = False,
|
|
371
|
+
) -> None:
|
|
372
|
+
"""Route every stdio MCP server of a client through `agentgate wrap`.
|
|
373
|
+
|
|
374
|
+
Shows the change as a diff; with --apply, writes it and keeps a .bak copy.
|
|
375
|
+
"""
|
|
376
|
+
from agentgate.install import apply, client_config_path, diff, plan_install
|
|
377
|
+
|
|
378
|
+
try:
|
|
379
|
+
path = config or client_config_path(client)
|
|
380
|
+
old, new, wrapped = plan_install(path, client)
|
|
381
|
+
except (OSError, ValueError) as e:
|
|
382
|
+
err.print(f"install: {e}", markup=False)
|
|
383
|
+
raise typer.Exit(1) from None
|
|
384
|
+
if not wrapped:
|
|
385
|
+
err.print(f"Nothing to do: every stdio server in {path} is already wrapped (or remote).")
|
|
386
|
+
raise typer.Exit(0)
|
|
387
|
+
Console().print(diff(old, new, path.name), markup=False, highlight=False)
|
|
388
|
+
if not do_apply:
|
|
389
|
+
err.print(
|
|
390
|
+
f"Would wrap {len(wrapped)} server(s): {', '.join(wrapped)}. Re-run with --apply."
|
|
391
|
+
)
|
|
392
|
+
raise typer.Exit(0)
|
|
393
|
+
backup = apply(path, new)
|
|
394
|
+
err.print(f"Wrapped {', '.join(wrapped)}. Backup: {backup}. Restart {client} to take effect.")
|
|
395
|
+
|
|
396
|
+
|
|
397
|
+
@app.command()
|
|
398
|
+
def report(
|
|
399
|
+
since: Annotated[float | None, typer.Option(help="Only the last N hours")] = None,
|
|
400
|
+
output: Annotated[
|
|
401
|
+
Path | None, typer.Option("--output", "-o", help="Write Markdown here")
|
|
402
|
+
] = None,
|
|
403
|
+
) -> None:
|
|
404
|
+
"""Summarise the audit log as Markdown: decisions, top findings, blocked actions by session."""
|
|
405
|
+
from agentgate.report import load_events, render
|
|
406
|
+
|
|
407
|
+
path = audit_path()
|
|
408
|
+
if not path.exists():
|
|
409
|
+
err.print(f"No audit log at {path}")
|
|
410
|
+
raise typer.Exit(1)
|
|
411
|
+
text = render(load_events(path, since))
|
|
412
|
+
if output:
|
|
413
|
+
output.write_text(text, encoding="utf-8")
|
|
414
|
+
err.print(f"Wrote {output}")
|
|
415
|
+
else:
|
|
416
|
+
typer.echo(text)
|