agentlighthouse-core 0.4.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.
- agentlighthouse_core-0.4.0.dist-info/METADATA +358 -0
- agentlighthouse_core-0.4.0.dist-info/RECORD +78 -0
- agentlighthouse_core-0.4.0.dist-info/WHEEL +4 -0
- agentlighthouse_core-0.4.0.dist-info/entry_points.txt +2 -0
- agentlighthouse_core-0.4.0.dist-info/licenses/LICENSE +21 -0
- al_core/__init__.py +12 -0
- al_core/_bundled/configs/audit.yaml +12 -0
- al_core/_bundled/configs/balanced.yaml +36 -0
- al_core/_bundled/configs/strict.yaml +32 -0
- al_core/_bundled/dashboard/assets/index-CN2LU6nV.css +1 -0
- al_core/_bundled/dashboard/assets/index-DX6cZzRi.js +40 -0
- al_core/_bundled/dashboard/index.html +15 -0
- al_core/_bundled/policies/default-deny.yaml +37 -0
- al_core/a2a/__init__.py +25 -0
- al_core/a2a/envelope.py +60 -0
- al_core/a2a/mediator.py +221 -0
- al_core/app.py +427 -0
- al_core/audit/__init__.py +149 -0
- al_core/audit/db.py +481 -0
- al_core/audit/pg.py +350 -0
- al_core/audit/pool.py +260 -0
- al_core/audit/siem.py +97 -0
- al_core/capability/__init__.py +28 -0
- al_core/capability/budget.py +56 -0
- al_core/capability/gate.py +334 -0
- al_core/capability/hitl.py +331 -0
- al_core/capability/policy.py +270 -0
- al_core/capability/store.py +209 -0
- al_core/capability/taint.py +79 -0
- al_core/cli/__init__.py +1 -0
- al_core/cli/main.py +1275 -0
- al_core/config/__init__.py +436 -0
- al_core/config/watch.py +51 -0
- al_core/detect/__init__.py +23 -0
- al_core/detect/base.py +131 -0
- al_core/detect/bip39_words.py +267 -0
- al_core/detect/budget.py +92 -0
- al_core/detect/detect_secrets_adapter.py +110 -0
- al_core/detect/engine.py +270 -0
- al_core/detect/scanners.py +454 -0
- al_core/egress/__init__.py +27 -0
- al_core/egress/nftables.py +59 -0
- al_core/egress/selftest.py +94 -0
- al_core/embed.py +51 -0
- al_core/gateway/__init__.py +29 -0
- al_core/gateway/content.py +154 -0
- al_core/gateway/decision.py +124 -0
- al_core/gateway/dnspin.py +131 -0
- al_core/gateway/forward.py +261 -0
- al_core/gateway/policy.py +66 -0
- al_core/gateway/ssrf.py +178 -0
- al_core/gateway/vkeys.py +205 -0
- al_core/gateway/web.py +801 -0
- al_core/identity/__init__.py +209 -0
- al_core/jsonstore.py +73 -0
- al_core/keys/__init__.py +141 -0
- al_core/killswitch.py +130 -0
- al_core/learn/__init__.py +17 -0
- al_core/learn/bundle.py +76 -0
- al_core/learn/miner.py +156 -0
- al_core/learn/scanner.py +77 -0
- al_core/learn/testgen.py +107 -0
- al_core/mcp/__init__.py +25 -0
- al_core/mcp/chain.py +147 -0
- al_core/mcp/descriptors.py +111 -0
- al_core/mcp/mediator.py +150 -0
- al_core/mcp/proxy.py +161 -0
- al_core/mcp/session.py +537 -0
- al_core/memory/__init__.py +15 -0
- al_core/memory/guard.py +330 -0
- al_core/memory/store.py +80 -0
- al_core/normalize/__init__.py +254 -0
- al_core/principal.py +59 -0
- al_core/receipt/__init__.py +192 -0
- al_core/resources.py +33 -0
- al_core/runtime.py +471 -0
- al_core/skills/__init__.py +30 -0
- al_core/skills/guard.py +218 -0
al_core/mcp/session.py
ADDED
|
@@ -0,0 +1,537 @@
|
|
|
1
|
+
"""One mediated agent<->MCP-server conversation (transport-agnostic).
|
|
2
|
+
|
|
3
|
+
``McpSession`` filters JSON-RPC messages through :class:`McpMediator`; the
|
|
4
|
+
stdio and HTTP shells are dumb pumps around it, so every transport enforces
|
|
5
|
+
identically:
|
|
6
|
+
|
|
7
|
+
* ``tools/list`` **responses** — descriptors are pinned + poison-scanned;
|
|
8
|
+
blocked tools are removed before the agent ever sees them (receipted). Two
|
|
9
|
+
different descriptors under one name are ambiguous (the agent cannot tell
|
|
10
|
+
which one the server will run) and both are withheld; identical repeats
|
|
11
|
+
collapse to one.
|
|
12
|
+
* **The advertised tools are an allow-list.** A ``tools/call`` naming a tool
|
|
13
|
+
that was not in the last ``tools/list`` the agent received is denied before
|
|
14
|
+
the gate (receipted): a withheld tool must not be reachable by name. A list
|
|
15
|
+
requested without a ``cursor`` replaces the set; a paginated page adds to
|
|
16
|
+
it. ``notifications/tools/list_changed`` clears it, so the agent must list
|
|
17
|
+
again. A call before any list is denied.
|
|
18
|
+
* ``tools/call`` **requests** — authorized by the ActionGate (identity ->
|
|
19
|
+
policy -> chain -> HITL). A denial never reaches the server; the agent gets
|
|
20
|
+
a JSON-RPC error carrying the fixed ``block_reason`` (agent-legible denial,
|
|
21
|
+
plus ``hitl_request_id`` when the call is parked for approval). Once a human
|
|
22
|
+
approves, the agent retries the same call (optionally naming the request in
|
|
23
|
+
``params._meta["agentlighthouse/hitl_request_id"]``) and it is forwarded.
|
|
24
|
+
* ``tools/call`` **responses** — every string in the result is scanned (the
|
|
25
|
+
tool-response-injection attack, ASI01): text blocks, embedded resources,
|
|
26
|
+
``structuredContent``, ``_meta``. A base64 ``blob``/``data`` field is decoded
|
|
27
|
+
and scanned when it is UTF-8 text; binary media is skipped. block -> the
|
|
28
|
+
result is **withheld** and replaced with an explainable error; strip ->
|
|
29
|
+
strings are redacted in place. A content block of unknown ``type`` is
|
|
30
|
+
withheld (a new kind of content must not arrive unscanned).
|
|
31
|
+
* **Every other reply is scanned too** (``initialize`` instructions,
|
|
32
|
+
``resources/read``, ``prompts/get``, list descriptions, ...): scanning is the
|
|
33
|
+
default, not a per-method opt-in, so a method nobody listed is still covered.
|
|
34
|
+
A blocked reply becomes a JSON-RPC error.
|
|
35
|
+
* **Response ids are an allow-list.** A server reply is relayed only if it
|
|
36
|
+
answers a request that is still in flight, exactly once. A duplicate or
|
|
37
|
+
unknown id is dropped (receipted): otherwise the second answer to a scanned
|
|
38
|
+
call, or an answer to nothing, would reach the agent unscanned. The agent may
|
|
39
|
+
not reuse an id that is still in flight either, since that would relabel
|
|
40
|
+
what the pending reply is scanned as.
|
|
41
|
+
* **Server-initiated messages** (``sampling/createMessage``, elicitation,
|
|
42
|
+
notifications) flow into the agent's context too, so every string in them is
|
|
43
|
+
scanned; a blocked one is dropped, a stripped one is redacted. A blocked
|
|
44
|
+
*request* is still answered (``FilterOutcome.reply``), or the server waits
|
|
45
|
+
on it forever: ``elicitation/create`` with the spec's ``{"action":
|
|
46
|
+
"decline"}``, anything else with a JSON-RPC error.
|
|
47
|
+
* **The agent's replies to server requests** are an allow-list: one is
|
|
48
|
+
forwarded only if it answers a request the agent was shown, once. It is
|
|
49
|
+
DLP-scanned on the way out (a sampling result carries the agent's context
|
|
50
|
+
to the server); a blocked one is replaced by a refusal, so the server still
|
|
51
|
+
gets an answer. Receipted as ``mcp_client_reply``.
|
|
52
|
+
* Error replies are scanned the same way. A clean reply passes through
|
|
53
|
+
byte-for-byte — mediation must not break the protocol.
|
|
54
|
+
|
|
55
|
+
State per session: pending request-id -> method/tool maps, so responses can
|
|
56
|
+
be matched to what was asked, and the set of advertised tool names. IDs are
|
|
57
|
+
JSON-RPC ids (str | int).
|
|
58
|
+
"""
|
|
59
|
+
|
|
60
|
+
from __future__ import annotations
|
|
61
|
+
|
|
62
|
+
import base64
|
|
63
|
+
import binascii
|
|
64
|
+
import json
|
|
65
|
+
import re
|
|
66
|
+
from dataclasses import dataclass
|
|
67
|
+
from typing import Any, Callable
|
|
68
|
+
from urllib.parse import unquote
|
|
69
|
+
|
|
70
|
+
from ..detect import GateResult
|
|
71
|
+
from ..gateway.decision import BlockReason
|
|
72
|
+
from .descriptors import ToolDescriptor
|
|
73
|
+
from .mediator import McpMediator
|
|
74
|
+
|
|
75
|
+
_DENY_CODE = -32001 # implementation-defined JSON-RPC error space
|
|
76
|
+
_INVALID_REQUEST = -32600 # JSON-RPC 2.0: the message is not a valid request
|
|
77
|
+
|
|
78
|
+
#: Where an agent may name the approval it is retrying under.
|
|
79
|
+
HITL_META_KEY = "agentlighthouse/hitl_request_id"
|
|
80
|
+
|
|
81
|
+
|
|
82
|
+
@dataclass
|
|
83
|
+
class FilterOutcome:
|
|
84
|
+
"""What to do with one message, in either direction: ``forward`` it on to
|
|
85
|
+
its recipient (None = drop) and/or ``reply`` straight back to its sender
|
|
86
|
+
(a denial to the agent, a refusal to the server). A transport must send
|
|
87
|
+
both; neither is optional."""
|
|
88
|
+
|
|
89
|
+
forward: dict[str, Any] | None = None
|
|
90
|
+
reply: dict[str, Any] | None = None
|
|
91
|
+
|
|
92
|
+
|
|
93
|
+
#: MCP tool-result content block types; anything else is withheld.
|
|
94
|
+
_CONTENT_TYPES = frozenset({"text", "image", "audio", "resource", "resource_link"})
|
|
95
|
+
|
|
96
|
+
|
|
97
|
+
_URI_RE = re.compile(r"[A-Za-z][A-Za-z0-9+.-]*:(\S*)")
|
|
98
|
+
_MIME_RE = re.compile(r"[\w.+-]+/[\w.+-]+(?:\s*;\s*[\w.+-]+=[\w.+\"-]+)*")
|
|
99
|
+
|
|
100
|
+
|
|
101
|
+
def _scan_view(key: str | None, value: str) -> str:
|
|
102
|
+
"""The part of a string the scan sees. A resource ``uri`` is scanned
|
|
103
|
+
without its scheme, percent-decoded: ``file://`` — the scheme of every
|
|
104
|
+
filesystem MCP server — trips the dangerous-scheme rule, but prose hidden
|
|
105
|
+
in the rest of the URI is still read. A well-formed ``mimeType`` is a
|
|
106
|
+
label, not prose. Anything else, including a ``uri`` that does not parse,
|
|
107
|
+
is scanned as it is."""
|
|
108
|
+
if key == "uri" and (m := _URI_RE.fullmatch(value)):
|
|
109
|
+
return unquote(m.group(1)).lstrip("/")
|
|
110
|
+
if key == "mimeType" and _MIME_RE.fullmatch(value):
|
|
111
|
+
return ""
|
|
112
|
+
return value
|
|
113
|
+
|
|
114
|
+
|
|
115
|
+
def _is_binary_field(obj: dict[str, Any], key: str) -> bool:
|
|
116
|
+
"""A base64 payload: a resource ``blob``, or image/audio ``data``."""
|
|
117
|
+
return key == "blob" or (key == "data" and obj.get("type") in ("image", "audio"))
|
|
118
|
+
|
|
119
|
+
|
|
120
|
+
def _decode_text(value: str) -> tuple[str | None, bool]:
|
|
121
|
+
"""``(text, was_base64)`` for a binary field. A payload that decodes to
|
|
122
|
+
UTF-8 is text whatever its ``mimeType`` claims, so it is scanned; one that
|
|
123
|
+
does not is binary media (None) and is skipped — scanning base64 as a
|
|
124
|
+
string only trips the entropy scanners. A value that is not base64 at all
|
|
125
|
+
is already text."""
|
|
126
|
+
try:
|
|
127
|
+
raw = base64.b64decode("".join(value.split()), validate=True)
|
|
128
|
+
except (binascii.Error, ValueError):
|
|
129
|
+
return value, False
|
|
130
|
+
try:
|
|
131
|
+
return raw.decode("utf-8"), True
|
|
132
|
+
except UnicodeDecodeError:
|
|
133
|
+
return None, True
|
|
134
|
+
|
|
135
|
+
|
|
136
|
+
def _refusal(method: str, rid: Any, message: str, reason: str | None = None,
|
|
137
|
+
code: int = _DENY_CODE) -> dict[str, Any]:
|
|
138
|
+
"""An answer refusing a server request. Elicitation has a spec answer for
|
|
139
|
+
"no" (``{"action": "decline"}``), which a client-side form would give;
|
|
140
|
+
anything else gets a JSON-RPC error."""
|
|
141
|
+
if method == "elicitation/create":
|
|
142
|
+
result: dict[str, Any] = {"action": "decline"}
|
|
143
|
+
if reason:
|
|
144
|
+
result["_meta"] = {"agentlighthouse/block_reason": reason}
|
|
145
|
+
return {"jsonrpc": "2.0", "id": rid, "result": result}
|
|
146
|
+
return _rpc_error(rid, code, message, {"block_reason": reason} if reason else None)
|
|
147
|
+
|
|
148
|
+
|
|
149
|
+
def _is_valid_id(rid: Any) -> bool:
|
|
150
|
+
# JSON-RPC ids are strings or numbers. bool is an int subclass in Python
|
|
151
|
+
# (True == 1), and a list/dict is unhashable; both are refused.
|
|
152
|
+
return isinstance(rid, str) or (isinstance(rid, int) and not isinstance(rid, bool))
|
|
153
|
+
|
|
154
|
+
|
|
155
|
+
def _rpc_error(rid: Any, code: int, message: str, data: dict[str, Any] | None = None,
|
|
156
|
+
) -> dict[str, Any]:
|
|
157
|
+
error: dict[str, Any] = {"code": code, "message": message}
|
|
158
|
+
if data is not None:
|
|
159
|
+
error["data"] = data
|
|
160
|
+
return {"jsonrpc": "2.0", "id": rid, "error": error}
|
|
161
|
+
|
|
162
|
+
|
|
163
|
+
class _Withheld(Exception):
|
|
164
|
+
"""Internal: a scanned string was blocked (unwinds the payload walk)."""
|
|
165
|
+
|
|
166
|
+
def __init__(self, reason: str) -> None:
|
|
167
|
+
self.reason = reason
|
|
168
|
+
|
|
169
|
+
|
|
170
|
+
class McpSession:
|
|
171
|
+
def __init__(
|
|
172
|
+
self,
|
|
173
|
+
mediator: McpMediator,
|
|
174
|
+
*,
|
|
175
|
+
actor: str,
|
|
176
|
+
session_id: str = "default",
|
|
177
|
+
max_in_flight: int = 1024,
|
|
178
|
+
) -> None:
|
|
179
|
+
self._mediator = mediator
|
|
180
|
+
# Bounds each direction's unanswered requests: a peer that never
|
|
181
|
+
# answers must not grow the session's memory without limit.
|
|
182
|
+
self._max_in_flight = max_in_flight
|
|
183
|
+
self._actor = actor
|
|
184
|
+
self._session_id = session_id
|
|
185
|
+
self._pending: dict[Any, str] = {} # request id -> method
|
|
186
|
+
self._call_tool: dict[Any, str] = {} # tools/call id -> tool name
|
|
187
|
+
self._list_page: dict[Any, bool] = {} # tools/list id -> continues a paginated list
|
|
188
|
+
# Tool names the agent was shown; None until it has listed tools.
|
|
189
|
+
self._advertised: set[str] | None = None
|
|
190
|
+
self._server_pending: dict[Any, str] = {} # server request id shown to the agent -> method
|
|
191
|
+
|
|
192
|
+
# -- agent -> server ---------------------------------------------------------
|
|
193
|
+
|
|
194
|
+
def filter_request(self, msg: dict[str, Any]) -> FilterOutcome:
|
|
195
|
+
method = msg.get("method")
|
|
196
|
+
rid = msg.get("id")
|
|
197
|
+
|
|
198
|
+
if not method and rid is not None and ("result" in msg or "error" in msg):
|
|
199
|
+
return self._filter_agent_reply(msg, rid)
|
|
200
|
+
|
|
201
|
+
if method and rid is not None:
|
|
202
|
+
if not _is_valid_id(rid):
|
|
203
|
+
return FilterOutcome(reply=_rpc_error(
|
|
204
|
+
None, _INVALID_REQUEST, "AgentLighthouse: invalid request id"))
|
|
205
|
+
if rid in self._pending:
|
|
206
|
+
return FilterOutcome(reply=_rpc_error(
|
|
207
|
+
rid, _INVALID_REQUEST,
|
|
208
|
+
"AgentLighthouse: request id is already in flight"))
|
|
209
|
+
if len(self._pending) >= self._max_in_flight:
|
|
210
|
+
return FilterOutcome(reply=_rpc_error(
|
|
211
|
+
rid, _INVALID_REQUEST,
|
|
212
|
+
"AgentLighthouse: too many requests in flight"))
|
|
213
|
+
|
|
214
|
+
if method != "tools/call":
|
|
215
|
+
if rid is not None and method:
|
|
216
|
+
self._pending[rid] = method
|
|
217
|
+
if method == "tools/list":
|
|
218
|
+
params = msg.get("params")
|
|
219
|
+
self._list_page[rid] = isinstance(params, dict) and bool(params.get("cursor"))
|
|
220
|
+
return FilterOutcome(forward=msg)
|
|
221
|
+
|
|
222
|
+
params = msg.get("params") or {}
|
|
223
|
+
tool = params.get("name") or ""
|
|
224
|
+
if (not isinstance(tool, str) or self._advertised is None
|
|
225
|
+
or tool not in self._advertised):
|
|
226
|
+
decision = self._mediator.deny_unadvertised(
|
|
227
|
+
self._actor, tool, session_id=self._session_id)
|
|
228
|
+
return FilterOutcome(reply=_rpc_error(
|
|
229
|
+
rid, _DENY_CODE,
|
|
230
|
+
f"AgentLighthouse: tool call denied ({decision.block_reason}): "
|
|
231
|
+
"the tool is not in the current tools/list; call tools/list first",
|
|
232
|
+
{"block_reason": decision.block_reason}))
|
|
233
|
+
args = params.get("arguments") or {}
|
|
234
|
+
meta = params.get("_meta") if isinstance(params.get("_meta"), dict) else {}
|
|
235
|
+
named = meta.get(HITL_META_KEY)
|
|
236
|
+
outcome = self._mediator.authorize_call(
|
|
237
|
+
self._actor, tool, args, session_id=self._session_id,
|
|
238
|
+
hitl_request_id=named if isinstance(named, str) else None)
|
|
239
|
+
if not outcome.allowed:
|
|
240
|
+
reason = outcome.decision.block_reason or BlockReason.TOOL_NOT_ALLOWED
|
|
241
|
+
data: dict[str, Any] = {"block_reason": reason}
|
|
242
|
+
if outcome.hitl_request_id:
|
|
243
|
+
data["hitl_request_id"] = outcome.hitl_request_id
|
|
244
|
+
return FilterOutcome(reply=_rpc_error(
|
|
245
|
+
rid, _DENY_CODE, f"AgentLighthouse: tool call denied ({reason})", data))
|
|
246
|
+
if rid is not None:
|
|
247
|
+
self._pending[rid] = method
|
|
248
|
+
self._call_tool[rid] = tool
|
|
249
|
+
|
|
250
|
+
# Outbound DLP may have redacted the arguments. Forward what the gate
|
|
251
|
+
# returned, never what the agent sent — otherwise the redaction is a
|
|
252
|
+
# report, not a control, and the secret still reaches the server.
|
|
253
|
+
if outcome.redaction:
|
|
254
|
+
msg = {**msg, "params": {**params, "arguments": outcome.args}}
|
|
255
|
+
return FilterOutcome(forward=msg)
|
|
256
|
+
|
|
257
|
+
def _filter_agent_reply(self, msg: dict[str, Any], rid: Any) -> FilterOutcome:
|
|
258
|
+
"""The agent answering a server request. Forwarded only if it answers
|
|
259
|
+
one the agent was shown and nobody has answered yet: a request we
|
|
260
|
+
blocked was already answered by us, and an answer to nothing is a
|
|
261
|
+
message the server never asked for. Then DLP-scanned outbound."""
|
|
262
|
+
method = self._server_pending.pop(rid, None) if _is_valid_id(rid) else None
|
|
263
|
+
if method is None:
|
|
264
|
+
self._mediator.reject_message(
|
|
265
|
+
self._actor, f"mcp:client-reply:{rid!r}"[:200],
|
|
266
|
+
rule="mcp.reply.unmatched_id", session_id=self._session_id,
|
|
267
|
+
action="mcp_client_reply")
|
|
268
|
+
return FilterOutcome()
|
|
269
|
+
target = f"mcp:{method}:reply"
|
|
270
|
+
|
|
271
|
+
def scan(text: str) -> GateResult:
|
|
272
|
+
return self._mediator.scan_client_reply(
|
|
273
|
+
text, actor=self._actor, target=target, session_id=self._session_id)
|
|
274
|
+
|
|
275
|
+
try:
|
|
276
|
+
return FilterOutcome(forward=self._scan_payload(msg, scan))
|
|
277
|
+
except _Withheld as withheld:
|
|
278
|
+
# The server is waiting on this id: answer it, without the payload.
|
|
279
|
+
return FilterOutcome(forward=_refusal(
|
|
280
|
+
method, rid, f"AgentLighthouse: {method} reply withheld ({withheld.reason})",
|
|
281
|
+
withheld.reason))
|
|
282
|
+
|
|
283
|
+
def abandon(self, rid: Any) -> None:
|
|
284
|
+
"""Forget an in-flight request whose reply will never arrive (the
|
|
285
|
+
transport failed, or the upstream accepted it without answering), so
|
|
286
|
+
the agent may retry under the same id."""
|
|
287
|
+
if _is_valid_id(rid):
|
|
288
|
+
self._pending.pop(rid, None)
|
|
289
|
+
self._call_tool.pop(rid, None)
|
|
290
|
+
self._list_page.pop(rid, None)
|
|
291
|
+
|
|
292
|
+
# -- server -> agent ---------------------------------------------------------
|
|
293
|
+
|
|
294
|
+
def filter_response(self, msg: dict[str, Any]) -> FilterOutcome:
|
|
295
|
+
"""What to do with one server->agent message: ``forward`` it to the
|
|
296
|
+
agent and/or ``reply`` to the server (a refused server request)."""
|
|
297
|
+
if msg.get("method"):
|
|
298
|
+
return self._filter_server_message(msg)
|
|
299
|
+
|
|
300
|
+
rid = msg.get("id")
|
|
301
|
+
if not _is_valid_id(rid) or rid not in self._pending:
|
|
302
|
+
self._mediator.reject_message(
|
|
303
|
+
self._actor, f"mcp:response:{rid!r}"[:200],
|
|
304
|
+
rule="mcp.response.unmatched_id", session_id=self._session_id)
|
|
305
|
+
return FilterOutcome()
|
|
306
|
+
method = self._pending.pop(rid)
|
|
307
|
+
tool = self._call_tool.pop(rid, "")
|
|
308
|
+
continues_list = self._list_page.pop(rid, False)
|
|
309
|
+
return FilterOutcome(forward=self._filter_answer(
|
|
310
|
+
msg, rid, method, tool, continues_list=continues_list))
|
|
311
|
+
|
|
312
|
+
def _filter_answer(self, msg: dict[str, Any], rid: Any, method: str, tool: str,
|
|
313
|
+
*, continues_list: bool) -> dict[str, Any]:
|
|
314
|
+
"""The server's answer to an agent request, as the agent may see it."""
|
|
315
|
+
if "result" not in msg:
|
|
316
|
+
return self._filter_error(msg, tool or method)
|
|
317
|
+
if method == "tools/list":
|
|
318
|
+
if not isinstance(msg["result"], dict):
|
|
319
|
+
return _rpc_error(rid, _DENY_CODE,
|
|
320
|
+
"AgentLighthouse: malformed tools/list result withheld")
|
|
321
|
+
return self._filter_tools_list(msg, continues=continues_list)
|
|
322
|
+
if method == "tools/call":
|
|
323
|
+
if not isinstance(msg["result"], dict):
|
|
324
|
+
return self._withheld_result(msg, BlockReason.RESULT_BLOCKED)
|
|
325
|
+
return self._filter_tool_result(msg, tool)
|
|
326
|
+
return self._filter_reply(msg, method)
|
|
327
|
+
|
|
328
|
+
def _filter_reply(self, msg: dict[str, Any], method: str) -> dict[str, Any]:
|
|
329
|
+
"""Any other method's reply. Its strings reach the agent's context as
|
|
330
|
+
surely as a tool result's do (resources/read, prompts/get, initialize
|
|
331
|
+
instructions, list descriptions), so it gets the same scan."""
|
|
332
|
+
try:
|
|
333
|
+
return self._scan_payload(msg, self._inbound(f"mcp:{method}"))
|
|
334
|
+
except _Withheld as withheld:
|
|
335
|
+
return _rpc_error(msg.get("id"), _DENY_CODE,
|
|
336
|
+
f"AgentLighthouse: {method} reply withheld ({withheld.reason})",
|
|
337
|
+
{"block_reason": withheld.reason})
|
|
338
|
+
|
|
339
|
+
def _filter_tools_list(self, msg: dict[str, Any], *, continues: bool) -> dict[str, Any]:
|
|
340
|
+
tools = msg["result"].get("tools", []) or []
|
|
341
|
+
# First-seen order; identical repeats collapse, conflicting ones are
|
|
342
|
+
# withheld as a group. A name is only safe to advertise if exactly one
|
|
343
|
+
# descriptor claims it — the verdict for one twin must never admit the
|
|
344
|
+
# other.
|
|
345
|
+
groups: dict[str, list[dict[str, Any]]] = {}
|
|
346
|
+
for t in tools:
|
|
347
|
+
if isinstance(t, dict) and isinstance(t.get("name"), str) and t["name"]:
|
|
348
|
+
group = groups.setdefault(t["name"], [])
|
|
349
|
+
if t not in group:
|
|
350
|
+
group.append(t)
|
|
351
|
+
unique: list[dict[str, Any]] = []
|
|
352
|
+
for name, group in groups.items():
|
|
353
|
+
if len(group) == 1:
|
|
354
|
+
unique.append(group[0])
|
|
355
|
+
else:
|
|
356
|
+
self._mediator.withhold_ambiguous(name)
|
|
357
|
+
descriptors = [ToolDescriptor(t["name"], t.get("description", ""),
|
|
358
|
+
t.get("inputSchema"))
|
|
359
|
+
for t in unique]
|
|
360
|
+
review = self._mediator.review_tools(descriptors)
|
|
361
|
+
allowed = {id(d) for d in review.allowed}
|
|
362
|
+
shown = [t for t, d in zip(unique, descriptors) if id(d) in allowed]
|
|
363
|
+
names = {t["name"] for t in shown}
|
|
364
|
+
withheld = set(groups) - names
|
|
365
|
+
# A later page adds to the list; a list from the start replaces it, so
|
|
366
|
+
# a tool withheld now (drift) is no longer callable from an old list.
|
|
367
|
+
# A later page also revokes any name it withheld: a different twin of
|
|
368
|
+
# an earlier page's tool is D2 across pages, and the server may run
|
|
369
|
+
# either one.
|
|
370
|
+
if continues:
|
|
371
|
+
self._advertised = ((self._advertised or set()) | names) - withheld
|
|
372
|
+
else:
|
|
373
|
+
self._advertised = names
|
|
374
|
+
out = dict(msg)
|
|
375
|
+
out["result"] = {**msg["result"], "tools": shown}
|
|
376
|
+
return out
|
|
377
|
+
|
|
378
|
+
def _filter_tool_result(self, msg: dict[str, Any], tool: str) -> dict[str, Any]:
|
|
379
|
+
content = msg["result"].get("content")
|
|
380
|
+
if content is not None and not (
|
|
381
|
+
isinstance(content, list)
|
|
382
|
+
and all(isinstance(i, dict) and i.get("type") in _CONTENT_TYPES
|
|
383
|
+
for i in content)):
|
|
384
|
+
self._mediator.reject_message(
|
|
385
|
+
self._actor, f"tool:{tool}:result",
|
|
386
|
+
rule="mcp.result.unknown_content_type", session_id=self._session_id)
|
|
387
|
+
return self._withheld_result(msg, BlockReason.RESULT_BLOCKED)
|
|
388
|
+
try:
|
|
389
|
+
return self._scan_payload(msg, self._inbound(tool))
|
|
390
|
+
except _Withheld as withheld:
|
|
391
|
+
return self._withheld_result(msg, withheld.reason)
|
|
392
|
+
|
|
393
|
+
@staticmethod
|
|
394
|
+
def _withheld_result(msg: dict[str, Any], reason: str) -> dict[str, Any]:
|
|
395
|
+
out = {k: v for k, v in msg.items() if k != "error"}
|
|
396
|
+
out["result"] = {
|
|
397
|
+
"content": [{"type": "text",
|
|
398
|
+
"text": f"[AgentLighthouse] tool result withheld ({reason})"}],
|
|
399
|
+
"isError": True,
|
|
400
|
+
"_al": {"block_reason": reason},
|
|
401
|
+
}
|
|
402
|
+
return out
|
|
403
|
+
|
|
404
|
+
def _filter_error(self, msg: dict[str, Any], label: str) -> dict[str, Any]:
|
|
405
|
+
try:
|
|
406
|
+
return self._scan_payload(msg, self._inbound(label))
|
|
407
|
+
except _Withheld as withheld:
|
|
408
|
+
return _rpc_error(msg.get("id"), _DENY_CODE,
|
|
409
|
+
f"AgentLighthouse: error reply withheld ({withheld.reason})",
|
|
410
|
+
{"block_reason": withheld.reason})
|
|
411
|
+
|
|
412
|
+
def _filter_server_message(self, msg: dict[str, Any]) -> FilterOutcome:
|
|
413
|
+
"""A server-initiated request or notification. Its strings land in the
|
|
414
|
+
agent's (or its LLM's) context, so they get the tool-result scan. A
|
|
415
|
+
refused request is answered; a refused notification needs no answer."""
|
|
416
|
+
if msg.get("method") == "notifications/tools/list_changed":
|
|
417
|
+
# The server's tools changed: calls wait for a fresh, reviewed list.
|
|
418
|
+
# Cleared even if the scan drops the notification.
|
|
419
|
+
self._advertised = None
|
|
420
|
+
method = msg.get("method")
|
|
421
|
+
rid = msg.get("id")
|
|
422
|
+
try:
|
|
423
|
+
out = self._scan_payload(msg, self._inbound(f"server:{method}"))
|
|
424
|
+
except _Withheld as withheld:
|
|
425
|
+
# scan_result already receipted the block. A request (it has an
|
|
426
|
+
# id) still needs an answer, or the server waits on it forever.
|
|
427
|
+
if rid is None:
|
|
428
|
+
return FilterOutcome()
|
|
429
|
+
return FilterOutcome(reply=_refusal(
|
|
430
|
+
method, rid, f"AgentLighthouse: {method} request withheld ({withheld.reason})",
|
|
431
|
+
withheld.reason))
|
|
432
|
+
if _is_valid_id(rid):
|
|
433
|
+
if len(self._server_pending) >= self._max_in_flight:
|
|
434
|
+
return FilterOutcome(reply=_refusal(
|
|
435
|
+
method, rid, "AgentLighthouse: too many server requests awaiting the agent",
|
|
436
|
+
code=_INVALID_REQUEST))
|
|
437
|
+
self._server_pending[rid] = method
|
|
438
|
+
return FilterOutcome(forward=out)
|
|
439
|
+
|
|
440
|
+
def _inbound(self, label: str) -> Callable[[str], GateResult]:
|
|
441
|
+
"""The tool-result scan for server content (it taints the session on
|
|
442
|
+
a hostile hit)."""
|
|
443
|
+
return lambda text: self._mediator.scan_result(
|
|
444
|
+
text, actor=self._actor, tool=label, session_id=self._session_id)
|
|
445
|
+
|
|
446
|
+
def _scan_payload(self, msg: dict[str, Any],
|
|
447
|
+
scan: Callable[[str], GateResult]) -> dict[str, Any]:
|
|
448
|
+
"""Scan every string in ``msg`` (except the envelope) with ``scan``.
|
|
449
|
+
The block decision is made on joined text, as for a tool result, so a
|
|
450
|
+
payload split across fields is still seen whole. Raises ``_Withheld``
|
|
451
|
+
on a block; returns ``msg`` with stripped strings redacted otherwise."""
|
|
452
|
+
envelope = ("jsonrpc", "id", "method")
|
|
453
|
+
body = {k: v for k, v in msg.items() if k not in envelope}
|
|
454
|
+
|
|
455
|
+
def strings(value: Any, key: str | None = None) -> list[tuple[str | None, str]]:
|
|
456
|
+
if isinstance(value, str):
|
|
457
|
+
view = _scan_view(key, value)
|
|
458
|
+
return [(key, view)] if view else []
|
|
459
|
+
if isinstance(value, dict):
|
|
460
|
+
found: list[tuple[str | None, str]] = []
|
|
461
|
+
for k, v in value.items():
|
|
462
|
+
if isinstance(v, str) and _is_binary_field(value, k):
|
|
463
|
+
text, _ = _decode_text(v)
|
|
464
|
+
if text: # decoded text is prose the agent will read
|
|
465
|
+
found.append(("text", text))
|
|
466
|
+
else:
|
|
467
|
+
found.extend(strings(v, k))
|
|
468
|
+
return found
|
|
469
|
+
if isinstance(value, list):
|
|
470
|
+
return [s for v in value for s in strings(v, key)]
|
|
471
|
+
return []
|
|
472
|
+
|
|
473
|
+
found = strings(body)
|
|
474
|
+
# Two views: every string, and the prose alone (MCP content blocks keep
|
|
475
|
+
# it under "text"), so structural fields like "role"/"type" cannot sit
|
|
476
|
+
# between the halves of a split payload.
|
|
477
|
+
views = ("\n".join(v for _, v in found),
|
|
478
|
+
"\n".join(v for k, v in found if k == "text"))
|
|
479
|
+
verdicts = []
|
|
480
|
+
for text in views:
|
|
481
|
+
if not text:
|
|
482
|
+
continue
|
|
483
|
+
result = scan(text)
|
|
484
|
+
if result.blocked:
|
|
485
|
+
raise _Withheld(result.block_reason or BlockReason.RESULT_BLOCKED)
|
|
486
|
+
verdicts.append(result.verdict)
|
|
487
|
+
if "strip" not in verdicts:
|
|
488
|
+
return msg
|
|
489
|
+
|
|
490
|
+
def redact_text(value: str) -> str:
|
|
491
|
+
return scan(value).text
|
|
492
|
+
|
|
493
|
+
def redact_binary(value: str) -> str:
|
|
494
|
+
text, was_base64 = _decode_text(value)
|
|
495
|
+
if not text:
|
|
496
|
+
return value # binary media, or empty
|
|
497
|
+
clean = redact_text(text)
|
|
498
|
+
if clean == text:
|
|
499
|
+
return value # untouched: keep the original encoding
|
|
500
|
+
return base64.b64encode(clean.encode("utf-8")).decode("ascii") if was_base64 else clean
|
|
501
|
+
|
|
502
|
+
def redact(value: Any, key: str | None = None) -> Any:
|
|
503
|
+
if isinstance(value, str) and value:
|
|
504
|
+
# A uri or mimeType is kept whole: a redacted one names
|
|
505
|
+
# nothing. It was scanned, so a block would have fired.
|
|
506
|
+
return value if _scan_view(key, value) != value else redact_text(value)
|
|
507
|
+
if isinstance(value, dict):
|
|
508
|
+
return {k: (redact_binary(v) if isinstance(v, str) and _is_binary_field(value, k)
|
|
509
|
+
else redact(v, k))
|
|
510
|
+
for k, v in value.items()}
|
|
511
|
+
if isinstance(value, list):
|
|
512
|
+
return [redact(v, key) for v in value]
|
|
513
|
+
return value
|
|
514
|
+
|
|
515
|
+
return {k: (v if k in envelope else redact(v)) for k, v in msg.items()}
|
|
516
|
+
|
|
517
|
+
|
|
518
|
+
def parse_line(line: str) -> dict[str, Any] | None:
|
|
519
|
+
"""One newline-delimited JSON-RPC message; None for blank/garbage lines.
|
|
520
|
+
|
|
521
|
+
Garbage from a server is dropped (fail-closed for content, tolerant for
|
|
522
|
+
framing — a broken server must not crash the proxy)."""
|
|
523
|
+
line = line.strip()
|
|
524
|
+
if not line:
|
|
525
|
+
return None
|
|
526
|
+
try:
|
|
527
|
+
msg = json.loads(line)
|
|
528
|
+
except json.JSONDecodeError:
|
|
529
|
+
return None
|
|
530
|
+
return msg if isinstance(msg, dict) else None
|
|
531
|
+
|
|
532
|
+
|
|
533
|
+
def dump_line(msg: dict[str, Any]) -> str:
|
|
534
|
+
return json.dumps(msg, ensure_ascii=False, separators=(",", ":")) + "\n"
|
|
535
|
+
|
|
536
|
+
|
|
537
|
+
__all__ = ["FilterOutcome", "HITL_META_KEY", "McpSession", "dump_line", "parse_line"]
|
|
@@ -0,0 +1,15 @@
|
|
|
1
|
+
"""L5 Memory Guard (ASI06) — guarded memory store, integrity baselines,
|
|
2
|
+
quarantine, snapshot + rollback."""
|
|
3
|
+
|
|
4
|
+
from .guard import MemoryGuard, MemoryResult, RollbackInfo, SnapshotInfo
|
|
5
|
+
from .store import MemoryEntry, MemoryStore, value_hash
|
|
6
|
+
|
|
7
|
+
__all__ = [
|
|
8
|
+
"MemoryEntry",
|
|
9
|
+
"MemoryGuard",
|
|
10
|
+
"MemoryResult",
|
|
11
|
+
"MemoryStore",
|
|
12
|
+
"RollbackInfo",
|
|
13
|
+
"SnapshotInfo",
|
|
14
|
+
"value_hash",
|
|
15
|
+
]
|