strands-revsec 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.
- strands_revsec/__init__.py +24 -0
- strands_revsec/_version.py +1 -0
- strands_revsec/hooks.py +287 -0
- strands_revsec/mcp.py +145 -0
- strands_revsec-0.1.0.dist-info/METADATA +175 -0
- strands_revsec-0.1.0.dist-info/RECORD +9 -0
- strands_revsec-0.1.0.dist-info/WHEEL +5 -0
- strands_revsec-0.1.0.dist-info/licenses/LICENSE +3 -0
- strands_revsec-0.1.0.dist-info/top_level.txt +1 -0
|
@@ -0,0 +1,24 @@
|
|
|
1
|
+
"""strands-revsec: RevSec for Strands agents.
|
|
2
|
+
|
|
3
|
+
Add one hook provider to the Agent: RevSec checks each tool call before it
|
|
4
|
+
runs (an MCP server's tool against that MCP server, the agent's own tools as
|
|
5
|
+
the agent's), what the user asks before it reaches the model, and what each
|
|
6
|
+
tool hands back before the model reads it; records what happened, and lists
|
|
7
|
+
the agent in your RevSec console with its model and tools.
|
|
8
|
+
|
|
9
|
+
from strands import Agent
|
|
10
|
+
from strands_revsec import RevSecHooks, revsec_mcp_client
|
|
11
|
+
|
|
12
|
+
notes = revsec_mcp_client("notes", command="npx", args=["-y", "@acme/notes-mcp"])
|
|
13
|
+
agent = Agent(tools=[notes, lookup_order], hooks=[RevSecHooks(agent_name="orders-agent")])
|
|
14
|
+
|
|
15
|
+
No AI gateway is needed. A team whose model calls go through the RevSec AI
|
|
16
|
+
gateway turns the prompt check here off: ``revsec.mcp.configure(check_prompts=False)``.
|
|
17
|
+
|
|
18
|
+
Set REVSEC_API_KEY and REVSEC_BASE_URL first (Settings → SDK in the console).
|
|
19
|
+
"""
|
|
20
|
+
from strands_revsec._version import __version__
|
|
21
|
+
from strands_revsec.hooks import RevSecHooks
|
|
22
|
+
from strands_revsec.mcp import note_mcp_server, revsec_mcp_client, revsec_mcp_servers
|
|
23
|
+
|
|
24
|
+
__all__ = ["RevSecHooks", "revsec_mcp_client", "revsec_mcp_servers", "note_mcp_server", "__version__"]
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
__version__ = "0.1.0"
|
strands_revsec/hooks.py
ADDED
|
@@ -0,0 +1,287 @@
|
|
|
1
|
+
"""RevSecHooks: RevSec checks for a Strands agent.
|
|
2
|
+
|
|
3
|
+
What it does, with nothing else to change in the agent:
|
|
4
|
+
|
|
5
|
+
* each tool call is checked by RevSec before it runs. A call to an MCP
|
|
6
|
+
server's tool is checked against that MCP server; a call to one of the
|
|
7
|
+
agent's own tools is checked as the agent's, against its hold and its
|
|
8
|
+
tool-call policies, and is never filed as an MCP server. A blocked call
|
|
9
|
+
never runs; the model gets a tool result saying why;
|
|
10
|
+
* what the user asks is checked before it reaches the model, and what each
|
|
11
|
+
tool hands back is checked before the model reads it, with RevSec's Model
|
|
12
|
+
Security check (instructions aimed at the model, secrets, personal data).
|
|
13
|
+
A stopped prompt never reaches the model or the conversation; a stopped
|
|
14
|
+
tool result is replaced with one saying it was withheld;
|
|
15
|
+
* the agent is put in RevSec's agent registry on its first request, with
|
|
16
|
+
the model and tools it was built with.
|
|
17
|
+
|
|
18
|
+
from strands import Agent
|
|
19
|
+
from strands_revsec import RevSecHooks
|
|
20
|
+
|
|
21
|
+
agent = Agent(tools=[lookup_order], hooks=[RevSecHooks(agent_name="orders-agent")])
|
|
22
|
+
|
|
23
|
+
No AI gateway is needed. If your model calls go through the RevSec AI gateway,
|
|
24
|
+
turn the prompt check here off with ``revsec.mcp.configure(check_prompts=False)``.
|
|
25
|
+
"""
|
|
26
|
+
from __future__ import annotations
|
|
27
|
+
|
|
28
|
+
import json
|
|
29
|
+
import logging
|
|
30
|
+
import os
|
|
31
|
+
import time
|
|
32
|
+
import uuid
|
|
33
|
+
from typing import Any, Dict, List, Optional, Tuple
|
|
34
|
+
|
|
35
|
+
from revsec import agent as _agent
|
|
36
|
+
from revsec import checks as _checks
|
|
37
|
+
from revsec import mcp as _mcp
|
|
38
|
+
from revsec import tools as _tools
|
|
39
|
+
from strands.hooks import (
|
|
40
|
+
AfterToolCallEvent,
|
|
41
|
+
BeforeInvocationEvent,
|
|
42
|
+
BeforeModelCallEvent,
|
|
43
|
+
BeforeToolCallEvent,
|
|
44
|
+
HookProvider,
|
|
45
|
+
HookRegistry,
|
|
46
|
+
)
|
|
47
|
+
|
|
48
|
+
from strands.tools.mcp import MCPAgentTool
|
|
49
|
+
|
|
50
|
+
from strands_revsec._version import __version__
|
|
51
|
+
from strands_revsec.mcp import identity_of
|
|
52
|
+
|
|
53
|
+
try: # Strands' named hook orders (interventions and later)
|
|
54
|
+
from strands.hooks import HookOrder
|
|
55
|
+
_CHECK_ORDER: Optional[float] = HookOrder.INTERVENTION_INPUT - 1
|
|
56
|
+
except ImportError: # pragma: no cover - an older Strands: default order
|
|
57
|
+
_CHECK_ORDER = None
|
|
58
|
+
|
|
59
|
+
logger = logging.getLogger("strands_revsec")
|
|
60
|
+
|
|
61
|
+
INTEGRATION = f"strands-revsec/{__version__}"
|
|
62
|
+
FRAMEWORK = "strands_agents" # RevSec's name for Strands Agents in its framework registry
|
|
63
|
+
# A conversation's Strands session id becomes its RevSec session id (a UUID), so the calls in one conversation show
|
|
64
|
+
# as one chain in the Activity Explorer.
|
|
65
|
+
_SESSION_NAMESPACE = uuid.UUID("2b8e6f1a-7c4d-4e5f-9a8b-1c2d3e4f5a6b")
|
|
66
|
+
_BLOCKED_KEY = "revsec_prompt_blocked"
|
|
67
|
+
# What stays in the conversation in place of a prompt RevSec stopped (the prompt itself is never stored).
|
|
68
|
+
WITHHELD_PROMPT = "[Prompt withheld by RevSec]"
|
|
69
|
+
|
|
70
|
+
|
|
71
|
+
def _text_of(content: Any) -> str:
|
|
72
|
+
"""The text in a list of Strands content blocks: the text blocks, else the JSON ones as text (a server that sends
|
|
73
|
+
structured content sends it as text too, so it is read once). Tool uses and images are left out."""
|
|
74
|
+
texts = [b["text"] for b in content or () if isinstance(b, dict) and isinstance(b.get("text"), str)]
|
|
75
|
+
if not any(t.strip() for t in texts):
|
|
76
|
+
texts = []
|
|
77
|
+
for block in content or ():
|
|
78
|
+
if isinstance(block, dict) and "json" in block:
|
|
79
|
+
try:
|
|
80
|
+
texts.append(json.dumps(block["json"], ensure_ascii=False, default=str))
|
|
81
|
+
except (TypeError, ValueError):
|
|
82
|
+
pass
|
|
83
|
+
return "\n".join(t for t in texts if t.strip())
|
|
84
|
+
|
|
85
|
+
|
|
86
|
+
def _user_text(messages: Any) -> str:
|
|
87
|
+
"""What the user sent in this request: the text of its user messages (never tool results)."""
|
|
88
|
+
return "\n".join(t for t in (_text_of(m.get("content")) for m in (messages or ())
|
|
89
|
+
if isinstance(m, dict) and m.get("role") == "user") if t)
|
|
90
|
+
|
|
91
|
+
|
|
92
|
+
def _model_id(agent: Any) -> Optional[str]:
|
|
93
|
+
try:
|
|
94
|
+
cfg = agent.model.get_config()
|
|
95
|
+
mid = cfg.get("model_id") if isinstance(cfg, dict) else None
|
|
96
|
+
return str(mid) if mid else None
|
|
97
|
+
except Exception: # noqa: BLE001
|
|
98
|
+
return None
|
|
99
|
+
|
|
100
|
+
|
|
101
|
+
class RevSecHooks(HookProvider):
|
|
102
|
+
"""Checks each request, tool call and tool result with RevSec and registers the agent.
|
|
103
|
+
|
|
104
|
+
Args:
|
|
105
|
+
agent_name: the agent's name in RevSec (one per agent; registering again updates the same agent).
|
|
106
|
+
api_key: a RevSec SDK key. Default: the REVSEC_API_KEY environment variable.
|
|
107
|
+
base_url: your RevSec address ending in /fcc. Default: REVSEC_BASE_URL. Leave both out if you already
|
|
108
|
+
called ``revsec.mcp.configure()``.
|
|
109
|
+
register: put the agent in RevSec's registry on its first request.
|
|
110
|
+
description, owner_email, environment, customer_facing: shown on the agent in RevSec (customer_facing
|
|
111
|
+
also feeds its setup rating).
|
|
112
|
+
on_block: "message" (default) tells the model, or the user for a stopped request, why; "raise" raises
|
|
113
|
+
``revsec.RevsecBlocked`` for a stopped request, and Strands' ``EventLoopException`` (with the
|
|
114
|
+
``RevsecBlocked`` as ``original_exception``) for a stopped tool call. A tool result RevSec stops is
|
|
115
|
+
always withheld (Strands does not let a raise after a tool through).
|
|
116
|
+
"""
|
|
117
|
+
|
|
118
|
+
def __init__(
|
|
119
|
+
self,
|
|
120
|
+
*,
|
|
121
|
+
agent_name: str,
|
|
122
|
+
api_key: Optional[str] = None,
|
|
123
|
+
base_url: Optional[str] = None,
|
|
124
|
+
register: bool = True,
|
|
125
|
+
description: Optional[str] = None,
|
|
126
|
+
owner_email: Optional[str] = None,
|
|
127
|
+
environment: Optional[str] = None,
|
|
128
|
+
customer_facing: Optional[bool] = None,
|
|
129
|
+
on_block: str = "message",
|
|
130
|
+
) -> None:
|
|
131
|
+
if not agent_name or not agent_name.strip():
|
|
132
|
+
raise ValueError("agent_name is required: the agent's name in RevSec")
|
|
133
|
+
if on_block not in ("message", "raise"):
|
|
134
|
+
raise ValueError("on_block must be 'message' or 'raise'")
|
|
135
|
+
key = api_key or (None if _mcp._config.api_key else os.environ.get("REVSEC_API_KEY"))
|
|
136
|
+
if key or base_url:
|
|
137
|
+
if not (key or _mcp._config.api_key):
|
|
138
|
+
raise ValueError("RevSec key not set: pass api_key= or set REVSEC_API_KEY")
|
|
139
|
+
_mcp.configure(api_key=key or _mcp._config.api_key, base_url=base_url)
|
|
140
|
+
elif not _mcp._config.api_key:
|
|
141
|
+
raise ValueError("RevSec key not set: pass api_key= or set REVSEC_API_KEY "
|
|
142
|
+
"(Settings → SDK in the RevSec console issues one)")
|
|
143
|
+
self.agent_name = agent_name.strip()
|
|
144
|
+
self.on_block = on_block
|
|
145
|
+
self._registered = not register
|
|
146
|
+
self._profile = {"description": description, "owner_email": owner_email, "environment": environment}
|
|
147
|
+
self._customer_facing = customer_facing
|
|
148
|
+
self.agent_id: Optional[str] = None
|
|
149
|
+
self.agent_status: Optional[str] = None
|
|
150
|
+
# What a checked call needs after it runs, by its toolUseId (tool calls of one turn run concurrently)
|
|
151
|
+
self._pending: Dict[str, Tuple[Optional[int], float, bool]] = {}
|
|
152
|
+
|
|
153
|
+
# ── wiring ────────────────────────────────────────────────────────────
|
|
154
|
+
|
|
155
|
+
def register_hooks(self, registry: HookRegistry, **kwargs: Any) -> None:
|
|
156
|
+
order = {} if _CHECK_ORDER is None else {"order": _CHECK_ORDER}
|
|
157
|
+
registry.add_callback(BeforeInvocationEvent, self._before_request, **order)
|
|
158
|
+
registry.add_callback(BeforeModelCallEvent, self._before_model)
|
|
159
|
+
registry.add_callback(BeforeToolCallEvent, self._before_tool, **order)
|
|
160
|
+
registry.add_callback(AfterToolCallEvent, self._after_tool)
|
|
161
|
+
|
|
162
|
+
# ── registration ──────────────────────────────────────────────────────
|
|
163
|
+
|
|
164
|
+
async def aregister_agent(self, *, models: Optional[List[str]] = None,
|
|
165
|
+
tools: Optional[List[str]] = None) -> Optional[str]:
|
|
166
|
+
"""Put the agent in RevSec's registry now (the hooks otherwise do it on the first request). Returns its id,
|
|
167
|
+
or None when RevSec refused or could not be reached: that is logged as an error and its calls are still
|
|
168
|
+
checked, without the agent."""
|
|
169
|
+
self._registered = True
|
|
170
|
+
try:
|
|
171
|
+
me = await _agent.aregister(
|
|
172
|
+
name=self.agent_name, framework=FRAMEWORK, models=[m for m in models or [] if m],
|
|
173
|
+
tools=[t for t in tools or [] if t], tags={"integration": INTEGRATION},
|
|
174
|
+
customer_facing=self._customer_facing, **{k: v for k, v in self._profile.items() if v})
|
|
175
|
+
except _agent.RegistrationFailed as e:
|
|
176
|
+
logger.error("RevSec did not register agent %r: %s. Its calls are still checked, but agent-level "
|
|
177
|
+
"rules can't apply to it.", self.agent_name, e)
|
|
178
|
+
return None
|
|
179
|
+
self.agent_id, self.agent_status = me.agent_id, me.status
|
|
180
|
+
return self.agent_id
|
|
181
|
+
|
|
182
|
+
def register_agent(self, **kwargs: Any) -> Optional[str]:
|
|
183
|
+
"""Sync form of ``aregister_agent``."""
|
|
184
|
+
return _mcp._run_async(self.aregister_agent(**kwargs))
|
|
185
|
+
|
|
186
|
+
@staticmethod
|
|
187
|
+
def _session_of(agent: Any) -> Optional[str]:
|
|
188
|
+
sid = getattr(agent, "session_id", None)
|
|
189
|
+
return str(uuid.uuid5(_SESSION_NAMESPACE, str(sid))) if sid else None
|
|
190
|
+
|
|
191
|
+
# ── the request, before the model ─────────────────────────────────────
|
|
192
|
+
|
|
193
|
+
async def _before_request(self, event: BeforeInvocationEvent) -> None:
|
|
194
|
+
agent = event.agent
|
|
195
|
+
if not self._registered:
|
|
196
|
+
await self.aregister_agent(models=[_model_id(agent)] if _model_id(agent) else [],
|
|
197
|
+
tools=list(getattr(agent, "tool_names", None) or []))
|
|
198
|
+
if not (_mcp._config.enabled and _mcp._config.check_prompts):
|
|
199
|
+
return
|
|
200
|
+
prompt = _user_text(event.messages)
|
|
201
|
+
if not prompt.strip():
|
|
202
|
+
return
|
|
203
|
+
verdict = await _checks.check_prompt(prompt, agent_id=self.agent_id, model=_model_id(agent),
|
|
204
|
+
session_id=self._session_of(agent))
|
|
205
|
+
if verdict.allowed:
|
|
206
|
+
return
|
|
207
|
+
if self.on_block == "raise":
|
|
208
|
+
raise _mcp.RevsecBlocked(verdict.as_decision())
|
|
209
|
+
why = (verdict.reason or verdict.rule_name or "a RevSec policy").rstrip(". ")
|
|
210
|
+
# The prompt never reaches the model or the conversation: a placeholder stands in its place, and the model
|
|
211
|
+
# call is cancelled with the reply (``_before_model``), so the turns still alternate.
|
|
212
|
+
event.messages = [{"role": "user", "content": [{"text": WITHHELD_PROMPT}]}]
|
|
213
|
+
event.invocation_state[_BLOCKED_KEY] = (f"Blocked by RevSec: {why}. "
|
|
214
|
+
"This request was not sent to the model.")
|
|
215
|
+
|
|
216
|
+
async def _before_model(self, event: BeforeModelCallEvent) -> None:
|
|
217
|
+
reply = event.invocation_state.pop(_BLOCKED_KEY, None)
|
|
218
|
+
if reply:
|
|
219
|
+
event.cancel = reply
|
|
220
|
+
|
|
221
|
+
# ── tool calls ────────────────────────────────────────────────────────
|
|
222
|
+
|
|
223
|
+
def _blocked(self, event: BeforeToolCallEvent, decision: Any) -> None:
|
|
224
|
+
if self.on_block == "raise":
|
|
225
|
+
raise _mcp.RevsecBlocked(decision)
|
|
226
|
+
reason = decision.reason or f"policy '{decision.policy_name or 'unnamed'}'"
|
|
227
|
+
event.cancel_tool = f"Blocked by RevSec: {reason}"
|
|
228
|
+
|
|
229
|
+
async def _before_tool(self, event: BeforeToolCallEvent) -> None:
|
|
230
|
+
tool, use = event.selected_tool, event.tool_use
|
|
231
|
+
if tool is None:
|
|
232
|
+
return # an unknown tool: Strands answers it, nothing runs
|
|
233
|
+
name = str(use.get("name") or "")
|
|
234
|
+
args = dict(use.get("input") or {}) if isinstance(use.get("input"), dict) else {}
|
|
235
|
+
session = self._session_of(event.agent)
|
|
236
|
+
if not isinstance(tool, MCPAgentTool):
|
|
237
|
+
# One of the agent's own tools: checked as the agent's, never as an MCP server's.
|
|
238
|
+
decision = await _tools.evaluate(tool=name, args=args, agent_id=self.agent_id, session_id=session)
|
|
239
|
+
if not decision.allowed and not decision.soft_launch_only:
|
|
240
|
+
return self._blocked(event, decision)
|
|
241
|
+
data = await _tools.scan_args(tool=name, args=args, agent_id=self.agent_id)
|
|
242
|
+
if data is not None:
|
|
243
|
+
return self._blocked(event, data)
|
|
244
|
+
self._pending[str(use.get("toolUseId"))] = (None, time.perf_counter(), False)
|
|
245
|
+
return
|
|
246
|
+
ident = identity_of(tool.mcp_client)
|
|
247
|
+
server, mcp_tool = ident["server"], getattr(getattr(tool, "mcp_tool", None), "name", None) or name
|
|
248
|
+
extra = {k: ident[k] for k in ("server_url", "package", "transport") if ident.get(k)}
|
|
249
|
+
decision = await _mcp.evaluate(server=server, tool=mcp_tool, args=args, agent_id=self.agent_id,
|
|
250
|
+
tool_input_redacted=_mcp._redact_payload(args), session_id=session, **extra)
|
|
251
|
+
if not decision.allowed and not decision.soft_launch_only:
|
|
252
|
+
await _mcp.record_outcome(event_id=decision.event_id, outcome="blocked", response_latency_ms=0)
|
|
253
|
+
return self._blocked(event, decision)
|
|
254
|
+
try: # what the tool sends out, with revsec.mcp.configure(dlp=True)
|
|
255
|
+
await _mcp._egress_dlp_gate(kwargs=args, server=server, tool=mcp_tool, agent_id=self.agent_id,
|
|
256
|
+
api_key=None, event_id=decision.event_id)
|
|
257
|
+
except _mcp.RevsecBlocked as blocked:
|
|
258
|
+
return self._blocked(event, blocked.decision)
|
|
259
|
+
self._pending[str(use.get("toolUseId"))] = (decision.event_id, time.perf_counter(), True)
|
|
260
|
+
|
|
261
|
+
async def _after_tool(self, event: AfterToolCallEvent) -> None:
|
|
262
|
+
use_id = str(event.tool_use.get("toolUseId"))
|
|
263
|
+
pending = self._pending.pop(use_id, None)
|
|
264
|
+
if event.cancel_message is not None or pending is None:
|
|
265
|
+
return # never ran (stopped here or by another hook)
|
|
266
|
+
event_id, started, is_mcp = pending
|
|
267
|
+
result = event.result or {}
|
|
268
|
+
failed = event.exception is not None or result.get("status") == "error"
|
|
269
|
+
if is_mcp:
|
|
270
|
+
content = result.get("content")
|
|
271
|
+
took = getattr(event, "duration", None)
|
|
272
|
+
await _mcp.record_outcome(
|
|
273
|
+
event_id=event_id, outcome="error" if failed else "success",
|
|
274
|
+
response_latency_ms=int((took if took is not None else time.perf_counter() - started) * 1000),
|
|
275
|
+
response_size_bytes=len(json.dumps(content, default=str).encode("utf-8")) if content else None)
|
|
276
|
+
if failed or not (_mcp._config.enabled and _mcp._config.check_tool_results):
|
|
277
|
+
return
|
|
278
|
+
text = _text_of(result.get("content"))
|
|
279
|
+
if not text.strip() and result.get("structuredContent") is not None:
|
|
280
|
+
text = json.dumps(result["structuredContent"], ensure_ascii=False, default=str)
|
|
281
|
+
if not text.strip():
|
|
282
|
+
return
|
|
283
|
+
verdict = await _checks.check_tool_result(text, tool=str(event.tool_use.get("name") or ""),
|
|
284
|
+
agent_id=self.agent_id, session_id=self._session_of(event.agent))
|
|
285
|
+
if not verdict.allowed:
|
|
286
|
+
event.result = {"toolUseId": result.get("toolUseId", use_id), "status": "error",
|
|
287
|
+
"content": [{"text": verdict.withheld_text("tool result")}]}
|
strands_revsec/mcp.py
ADDED
|
@@ -0,0 +1,145 @@
|
|
|
1
|
+
"""MCP servers that RevSec recognises.
|
|
2
|
+
|
|
3
|
+
Strands keeps an MCP server's tools on an ``MCPClient`` and tells them apart
|
|
4
|
+
from the agent's own tools, but it does not keep how the server is reached
|
|
5
|
+
(its address, or the package a local server runs), and that is what RevSec
|
|
6
|
+
files the server under. Build the client with ``revsec_mcp_client`` or
|
|
7
|
+
``revsec_mcp_servers`` and the server's identity is noted on it, so each call
|
|
8
|
+
is checked against that MCP server (its approval, its policies, its known
|
|
9
|
+
vulnerabilities) and attaches to the record RevSec already has for it.
|
|
10
|
+
|
|
11
|
+
from strands import Agent
|
|
12
|
+
from strands_revsec import RevSecHooks, revsec_mcp_client
|
|
13
|
+
|
|
14
|
+
github = revsec_mcp_client("github", url="https://api.githubcopilot.com/mcp/")
|
|
15
|
+
notes = revsec_mcp_client("notes", command="npx", args=["-y", "@acme/notes-mcp"])
|
|
16
|
+
agent = Agent(tools=[github, notes, lookup_order], hooks=[RevSecHooks(agent_name="orders-agent")])
|
|
17
|
+
|
|
18
|
+
An ``MCPClient`` you build yourself works too: note it with
|
|
19
|
+
``note_mcp_server(client, "github", url=...)``. Without a note, RevSec uses
|
|
20
|
+
the client's name and what Strands keeps of its connection.
|
|
21
|
+
"""
|
|
22
|
+
from __future__ import annotations
|
|
23
|
+
|
|
24
|
+
import json
|
|
25
|
+
import logging
|
|
26
|
+
import os
|
|
27
|
+
from typing import Any, Dict, List, Mapping, Optional, Sequence
|
|
28
|
+
|
|
29
|
+
from revsec._launch import package_from_launch
|
|
30
|
+
|
|
31
|
+
logger = logging.getLogger("strands_revsec")
|
|
32
|
+
|
|
33
|
+
# Where the server's identity is noted on an MCPClient.
|
|
34
|
+
IDENTITY_ATTR = "_revsec_mcp_server"
|
|
35
|
+
UNNAMED = "unnamed-mcp-server"
|
|
36
|
+
|
|
37
|
+
|
|
38
|
+
def server_identity(name: Optional[str], *, url: Optional[str] = None, command: Optional[str] = None,
|
|
39
|
+
args: Optional[Sequence[str]] = None) -> Dict[str, Any]:
|
|
40
|
+
"""How RevSec recognises a server: its name, and its address when remote or the package a runner starts when
|
|
41
|
+
local (never the launch's other arguments, which can carry tokens)."""
|
|
42
|
+
ident: Dict[str, Any] = {"server": name or UNNAMED}
|
|
43
|
+
if url:
|
|
44
|
+
ident.update(server_url=str(url), transport="remote")
|
|
45
|
+
elif command:
|
|
46
|
+
ident["transport"] = "stdio"
|
|
47
|
+
package = package_from_launch(str(command), [str(a) for a in (args or [])])
|
|
48
|
+
if package:
|
|
49
|
+
ident["package"] = package
|
|
50
|
+
return ident
|
|
51
|
+
|
|
52
|
+
|
|
53
|
+
def note_mcp_server(client: Any, name: str, *, url: Optional[str] = None, command: Optional[str] = None,
|
|
54
|
+
args: Optional[Sequence[str]] = None) -> Any:
|
|
55
|
+
"""Note on an ``MCPClient`` you built yourself which server it reaches. Returns the client."""
|
|
56
|
+
setattr(client, IDENTITY_ATTR, server_identity(name, url=url, command=command, args=args))
|
|
57
|
+
return client
|
|
58
|
+
|
|
59
|
+
|
|
60
|
+
def revsec_mcp_client(name: str, *, url: Optional[str] = None, command: Optional[str] = None,
|
|
61
|
+
args: Optional[Sequence[str]] = None, env: Optional[Mapping[str, str]] = None,
|
|
62
|
+
cwd: Optional[str] = None, **client_kwargs: Any) -> Any:
|
|
63
|
+
"""A Strands ``MCPClient`` for one server, with its identity noted: ``url=`` for a remote server (streamable
|
|
64
|
+
HTTP), ``command=`` and ``args=`` for a local one (stdio). Other keyword arguments go to ``MCPClient``."""
|
|
65
|
+
from strands.tools.mcp import MCPClient
|
|
66
|
+
if bool(url) == bool(command):
|
|
67
|
+
raise ValueError("give url= for a remote MCP server or command= for a local one")
|
|
68
|
+
client_kwargs.setdefault("application_name", name)
|
|
69
|
+
if url:
|
|
70
|
+
client = MCPClient(url=url, **client_kwargs)
|
|
71
|
+
else:
|
|
72
|
+
from mcp import StdioServerParameters
|
|
73
|
+
from mcp.client.stdio import stdio_client
|
|
74
|
+
params = StdioServerParameters(command=str(command), args=[str(a) for a in (args or [])],
|
|
75
|
+
env=dict(env) if env is not None else None, cwd=cwd)
|
|
76
|
+
client = MCPClient(lambda: stdio_client(params), **client_kwargs)
|
|
77
|
+
return note_mcp_server(client, name, url=url, command=command, args=args)
|
|
78
|
+
|
|
79
|
+
|
|
80
|
+
def _servers_mapping(config: Any) -> Dict[str, Dict[str, Any]]:
|
|
81
|
+
if isinstance(config, (str, os.PathLike)):
|
|
82
|
+
path = os.fspath(config)
|
|
83
|
+
path = path[len("file://"):] if path.startswith("file://") else path
|
|
84
|
+
with open(os.path.expanduser(path), encoding="utf-8") as f:
|
|
85
|
+
config = json.load(f)
|
|
86
|
+
if not isinstance(config, Mapping):
|
|
87
|
+
raise ValueError("an mcpServers config is a JSON object of server name to its settings")
|
|
88
|
+
inner = config.get("mcpServers", config)
|
|
89
|
+
return {str(k): v for k, v in inner.items()}
|
|
90
|
+
|
|
91
|
+
|
|
92
|
+
def revsec_mcp_servers(config: Any, **load_kwargs: Any) -> List[Any]:
|
|
93
|
+
"""``MCPClient.load_servers(config)`` (an ``mcpServers`` JSON file or mapping), with each server's identity
|
|
94
|
+
noted under its config key. Each server is loaded on its own, so its name is known for certain. Other keyword
|
|
95
|
+
arguments go to ``load_servers``."""
|
|
96
|
+
from strands.tools.mcp import MCPClient
|
|
97
|
+
clients: List[Any] = []
|
|
98
|
+
for name, cfg in _servers_mapping(config).items():
|
|
99
|
+
loaded = MCPClient.load_servers({name: cfg}, **load_kwargs)
|
|
100
|
+
settings = cfg if isinstance(cfg, Mapping) else {}
|
|
101
|
+
for client in loaded:
|
|
102
|
+
note_mcp_server(client, name, url=settings.get("url"), command=settings.get("command"),
|
|
103
|
+
args=settings.get("args"))
|
|
104
|
+
clients.append(client)
|
|
105
|
+
return clients
|
|
106
|
+
|
|
107
|
+
|
|
108
|
+
def _from_connection(client: Any) -> Dict[str, Any]:
|
|
109
|
+
"""What Strands keeps of a client's connection: the address or launch parameters its transport closes over (an
|
|
110
|
+
``MCPClient(url=...)`` or a ``load_servers`` client). Strands keeps these privately, so this is best effort and
|
|
111
|
+
finds nothing for a transport the caller built inside a lambda."""
|
|
112
|
+
found: Dict[str, Any] = {}
|
|
113
|
+
fn = getattr(client, "_transport_callable", None)
|
|
114
|
+
for cell in getattr(fn, "__closure__", None) or ():
|
|
115
|
+
try:
|
|
116
|
+
v = cell.cell_contents
|
|
117
|
+
except ValueError:
|
|
118
|
+
continue
|
|
119
|
+
if isinstance(v, str) and v.startswith(("http://", "https://")):
|
|
120
|
+
found["url"] = v
|
|
121
|
+
elif hasattr(v, "command") and hasattr(v, "args"):
|
|
122
|
+
found["command"], found["args"] = getattr(v, "command"), list(getattr(v, "args") or [])
|
|
123
|
+
return found
|
|
124
|
+
|
|
125
|
+
|
|
126
|
+
_warned: set = set()
|
|
127
|
+
|
|
128
|
+
|
|
129
|
+
def identity_of(client: Any) -> Dict[str, Any]:
|
|
130
|
+
"""The server an MCP tool's client reaches, for RevSec: the noted identity, else the client's name and what
|
|
131
|
+
Strands keeps of its connection, else an unnamed server (warned once per client)."""
|
|
132
|
+
noted = getattr(client, IDENTITY_ATTR, None)
|
|
133
|
+
if isinstance(noted, dict) and noted.get("server"):
|
|
134
|
+
return noted
|
|
135
|
+
# The name it reports to the server: ``client_name`` (Strands 1.6x), kept as ``_application_name`` before.
|
|
136
|
+
name = getattr(client, "client_name", None) or getattr(client, "_application_name", None)
|
|
137
|
+
try:
|
|
138
|
+
conn = _from_connection(client)
|
|
139
|
+
except Exception: # noqa: BLE001 — Strands' private layout changed: name only
|
|
140
|
+
conn = {}
|
|
141
|
+
if not name and id(client) not in _warned:
|
|
142
|
+
_warned.add(id(client))
|
|
143
|
+
logger.warning("An MCP server's tools were used with no name for RevSec: build the client with "
|
|
144
|
+
"revsec_mcp_client(name, ...) so its calls are filed under that server.")
|
|
145
|
+
return server_identity(name, url=conn.get("url"), command=conn.get("command"), args=conn.get("args"))
|
|
@@ -0,0 +1,175 @@
|
|
|
1
|
+
Metadata-Version: 2.4
|
|
2
|
+
Name: strands-revsec
|
|
3
|
+
Version: 0.1.0
|
|
4
|
+
Summary: RevSec for Strands Agents: check each tool call before it runs (MCP tools against their MCP server), each prompt and tool result, and register the agent.
|
|
5
|
+
Author-email: "RevSec / RevUp AI, Inc." <hello@revupai.com>
|
|
6
|
+
License-Expression: LicenseRef-Proprietary
|
|
7
|
+
Project-URL: Homepage, https://revsec.app
|
|
8
|
+
Project-URL: Start a free trial, https://app.revsec.app/start?from=strands
|
|
9
|
+
Keywords: strands,strands-agents,hooks,ai-agents,ai-security,guardrails,mcp,tool-calls
|
|
10
|
+
Classifier: Development Status :: 4 - Beta
|
|
11
|
+
Classifier: Intended Audience :: Developers
|
|
12
|
+
Classifier: Programming Language :: Python :: 3
|
|
13
|
+
Classifier: Programming Language :: Python :: 3.10
|
|
14
|
+
Classifier: Programming Language :: Python :: 3.11
|
|
15
|
+
Classifier: Programming Language :: Python :: 3.12
|
|
16
|
+
Classifier: Programming Language :: Python :: 3.13
|
|
17
|
+
Classifier: Topic :: Security
|
|
18
|
+
Requires-Python: >=3.10
|
|
19
|
+
Description-Content-Type: text/markdown
|
|
20
|
+
License-File: LICENSE
|
|
21
|
+
Requires-Dist: revsec-sdk<0.6,>=0.5.0
|
|
22
|
+
Requires-Dist: strands-agents<2,>=1.54
|
|
23
|
+
Provides-Extra: test
|
|
24
|
+
Requires-Dist: pytest>=7; extra == "test"
|
|
25
|
+
Requires-Dist: pytest-asyncio>=0.23; extra == "test"
|
|
26
|
+
Dynamic: license-file
|
|
27
|
+
|
|
28
|
+
# strands-revsec
|
|
29
|
+
|
|
30
|
+
RevSec for [Strands Agents](https://strandsagents.com). Add `RevSecHooks` to
|
|
31
|
+
your agent and RevSec checks each tool call before it runs: a call to an MCP
|
|
32
|
+
server's tool against that MCP server, a call to one of the agent's own tools
|
|
33
|
+
against the agent's own rules. A blocked call never runs, and the model is told
|
|
34
|
+
why. What the user asks is checked before it reaches the model, and what each
|
|
35
|
+
tool hands back before the model reads it. What happened is recorded, and the
|
|
36
|
+
agent is listed in your RevSec console with its model and tools.
|
|
37
|
+
|
|
38
|
+
Your rules live in RevSec, not in your code. If you ship agents to customers,
|
|
39
|
+
each customer account gets its own rules, approvals and evidence.
|
|
40
|
+
|
|
41
|
+
## Get a key
|
|
42
|
+
|
|
43
|
+
- **Shipping agents to your customers?** [Start a free trial](https://app.revsec.app/start?from=strands)
|
|
44
|
+
and choose "AI we ship to our customers". Your Sandbox key is shown once, when you sign up.
|
|
45
|
+
- **Building agents for your own company?** [Book a demo](mailto:sales@revupai.com?subject=Book%20a%20RevSec%20demo).
|
|
46
|
+
|
|
47
|
+
```bash
|
|
48
|
+
pip install strands-revsec
|
|
49
|
+
export REVSEC_API_KEY="<your key>"
|
|
50
|
+
export REVSEC_BASE_URL="https://app.revsec.app/fcc"
|
|
51
|
+
```
|
|
52
|
+
|
|
53
|
+
## Add it to your agent
|
|
54
|
+
|
|
55
|
+
Build your MCP clients with `revsec_mcp_client` (in place of `MCPClient`) and
|
|
56
|
+
add `RevSecHooks`:
|
|
57
|
+
|
|
58
|
+
```python
|
|
59
|
+
from strands import Agent, tool
|
|
60
|
+
from strands_revsec import RevSecHooks, revsec_mcp_client
|
|
61
|
+
|
|
62
|
+
github = revsec_mcp_client("github", url="https://api.githubcopilot.com/mcp/")
|
|
63
|
+
notes = revsec_mcp_client("notes", command="npx", args=["-y", "@acme/notes-mcp"])
|
|
64
|
+
|
|
65
|
+
@tool
|
|
66
|
+
def lookup_order(order_id: str) -> str:
|
|
67
|
+
"""Look up an order."""
|
|
68
|
+
...
|
|
69
|
+
|
|
70
|
+
agent = Agent(
|
|
71
|
+
tools=[github, notes, lookup_order],
|
|
72
|
+
hooks=[RevSecHooks(agent_name="orders-agent")],
|
|
73
|
+
)
|
|
74
|
+
agent("Where is order A1?")
|
|
75
|
+
```
|
|
76
|
+
|
|
77
|
+
That's all. Block a tool in RevSec and run the agent: the call doesn't run,
|
|
78
|
+
and the model gets a tool result saying `Blocked by RevSec: <the reason>`, so
|
|
79
|
+
it can tell the user or try something else.
|
|
80
|
+
|
|
81
|
+
- **MCP tools** are checked against their MCP server: the server's approval,
|
|
82
|
+
your MCP policies and its known vulnerabilities.
|
|
83
|
+
- **The agent's own tools** (functions in your code, like `lookup_order`) are
|
|
84
|
+
checked as the agent's: its status (a quarantined agent is stopped) and its
|
|
85
|
+
tool-call policies, such as "block `refund_order`". They are recorded with
|
|
86
|
+
the agent's tool calls, never as an MCP server.
|
|
87
|
+
- **What a tool sends out** (secrets, personal data) is scanned by your data
|
|
88
|
+
protection policies when you turn it on: `revsec.mcp.configure(..., dlp=True)`.
|
|
89
|
+
- **What a tool hands back** (a web page, a file, an MCP server's reply) is
|
|
90
|
+
checked before the model reads it: instructions hidden in it, secrets,
|
|
91
|
+
personal data. A result RevSec stops is replaced with one saying
|
|
92
|
+
`Withheld by RevSec: ...`; the call itself ran.
|
|
93
|
+
- **Calls RevSec stops, holds or flags** reach your SIEM, if one is connected
|
|
94
|
+
in the RevSec console.
|
|
95
|
+
|
|
96
|
+
## MCP servers
|
|
97
|
+
|
|
98
|
+
RevSec files each MCP server under the name you give it, and is told its
|
|
99
|
+
address, or for a local server the package it runs; never the rest of its
|
|
100
|
+
launch command (which can carry tokens).
|
|
101
|
+
|
|
102
|
+
- `revsec_mcp_client(name, url=...)` for a remote server, or
|
|
103
|
+
`revsec_mcp_client(name, command=..., args=..., env=...)` for a local one.
|
|
104
|
+
Other keyword arguments go to `MCPClient` (`prefix=`, `startup_timeout=`, ...).
|
|
105
|
+
- `revsec_mcp_servers("mcp.json")` in place of `MCPClient.load_servers(...)`:
|
|
106
|
+
each server is filed under its key in the `mcpServers` config.
|
|
107
|
+
- An `MCPClient` you build yourself: `note_mcp_server(client, "github", url=...)`.
|
|
108
|
+
|
|
109
|
+
Calls to an MCP client RevSec can't name are still checked as MCP calls, under
|
|
110
|
+
`unnamed-mcp-server`, and a warning says how to name it.
|
|
111
|
+
|
|
112
|
+
Strands' MCP router tool reaches servers through one tool of the agent's
|
|
113
|
+
(`mcp_router`), so RevSec checks those calls as that one tool. Give the agent
|
|
114
|
+
the MCP clients themselves to check each server's calls.
|
|
115
|
+
|
|
116
|
+
## Prompts
|
|
117
|
+
|
|
118
|
+
What the user asks is checked before it reaches the model, with the same Model
|
|
119
|
+
Security check RevSec runs for coding tools on a laptop: your prompt rules and
|
|
120
|
+
the built-in checks (prompt injection, secrets, personal data). A prompt
|
|
121
|
+
RevSec stops never reaches the model and isn't kept in the conversation; the
|
|
122
|
+
agent answers `Blocked by RevSec: <the reason>` instead, and the conversation
|
|
123
|
+
carries on. Each check is kept on the agent in RevSec, in the same
|
|
124
|
+
conversation as its tool calls, and the model it was about to call is listed
|
|
125
|
+
on the agent. No AI gateway is needed.
|
|
126
|
+
|
|
127
|
+
If your model calls go through the RevSec AI gateway (Settings → AI gateway in
|
|
128
|
+
the console), it checks prompts there; turn the check here off so each prompt
|
|
129
|
+
is checked once:
|
|
130
|
+
|
|
131
|
+
```python
|
|
132
|
+
from revsec import mcp
|
|
133
|
+
mcp.configure(api_key=os.environ["REVSEC_API_KEY"], check_prompts=False)
|
|
134
|
+
```
|
|
135
|
+
|
|
136
|
+
`check_tool_results=False` turns off the tool-result check.
|
|
137
|
+
|
|
138
|
+
## Options
|
|
139
|
+
|
|
140
|
+
| Option | Default | What it does |
|
|
141
|
+
|---|---|---|
|
|
142
|
+
| `agent_name` | required | The agent's name in RevSec. Registering again updates the same agent. |
|
|
143
|
+
| `api_key` | `REVSEC_API_KEY` | Your RevSec key. |
|
|
144
|
+
| `base_url` | `REVSEC_BASE_URL` | Your RevSec address, ending in `/fcc`. |
|
|
145
|
+
| `register` | `True` | List the agent in RevSec on its first request, with its model and tools. |
|
|
146
|
+
| `description`, `owner_email`, `environment` | none | Shown on the agent in RevSec. |
|
|
147
|
+
| `customer_facing` | none | `True` when the agent talks to your customers; shown on the agent and used in its setup rating. |
|
|
148
|
+
| `on_block` | `"message"` | `"raise"` raises instead of telling the model or the user: `revsec.RevsecBlocked` for a stopped prompt, and Strands' `EventLoopException` for a blocked tool call (the `RevsecBlocked` is its `original_exception`). A tool result RevSec stops is always withheld, since Strands doesn't pass on an error raised after a tool has run. |
|
|
149
|
+
|
|
150
|
+
A customer account key, such as the Sandbox key you get when you sign up,
|
|
151
|
+
checks the agent's tool calls and registers the agent in that customer account.
|
|
152
|
+
|
|
153
|
+
Calls and checks in one conversation (one `Agent`, or one session when you use
|
|
154
|
+
a Strands session manager) are grouped into one chain in RevSec's Activity
|
|
155
|
+
Explorer.
|
|
156
|
+
|
|
157
|
+
## When RevSec can't be reached
|
|
158
|
+
|
|
159
|
+
By default a call is allowed when RevSec can't be reached, so an outage never
|
|
160
|
+
stops your agent. To block instead:
|
|
161
|
+
|
|
162
|
+
```python
|
|
163
|
+
from revsec import mcp
|
|
164
|
+
mcp.configure(api_key=os.environ["REVSEC_API_KEY"], failure_mode="fail_closed")
|
|
165
|
+
```
|
|
166
|
+
|
|
167
|
+
`mcp.configure(api_key=..., enabled=False)` turns the checks off. This package
|
|
168
|
+
is built on [revsec-sdk](https://pypi.org/project/revsec-sdk/); its README
|
|
169
|
+
covers these settings.
|
|
170
|
+
|
|
171
|
+
Works with strands-agents 1.54 and later.
|
|
172
|
+
|
|
173
|
+
## License
|
|
174
|
+
|
|
175
|
+
Copyright (c) 2026 RevUp AI, Inc. Use is subject to the RevSec terms of service.
|
|
@@ -0,0 +1,9 @@
|
|
|
1
|
+
strands_revsec/__init__.py,sha256=AeLtkqwdkvUsjAx42RWbrlwj6yjb-neA0Ah4pjR8ols,1217
|
|
2
|
+
strands_revsec/_version.py,sha256=kUR5RAFc7HCeiqdlX36dZOHkUI5wI6V_43RpEcD8b-0,22
|
|
3
|
+
strands_revsec/hooks.py,sha256=wklh6Z3CpLmVyqNxBhN0ALCVszsog7kJO7tZ3jwWtwo,15637
|
|
4
|
+
strands_revsec/mcp.py,sha256=M8gVNKtlRG67x2ysiJUlPsaYJ_rVaWQl3MIdYglaw7M,7224
|
|
5
|
+
strands_revsec-0.1.0.dist-info/licenses/LICENSE,sha256=xQErOxfCrt4Sgbqz3EQHJvk8sWgCrAbjtjvqGyfa3ss,120
|
|
6
|
+
strands_revsec-0.1.0.dist-info/METADATA,sha256=rwEeS0MlQVkcwdUQNEic_5HkcRXC6Rqdxus9zFstJuA,7898
|
|
7
|
+
strands_revsec-0.1.0.dist-info/WHEEL,sha256=mOdXR9C3wMVov7cSY8PY-XCzo3SmmWCHvGQr5csJoao,91
|
|
8
|
+
strands_revsec-0.1.0.dist-info/top_level.txt,sha256=fr1bEfA47bqOssg83kwMpWyPadm0_irT8wWaq0JUSvk,15
|
|
9
|
+
strands_revsec-0.1.0.dist-info/RECORD,,
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
strands_revsec
|