IBM Mellea
A plugin for IBM Mellea pipelines, no pipeline rewrite. It hooks GENERATION_PRE_CALL, GENERATION_POST_CALL, TOOL_PRE_INVOKE and TOOL_POST_INVOKE and sends each surface to Alice. The tool_output hook is the one that catches indirect prompt injection: text returned by tools, files and URLs is evaluated before it re-enters the model. Audit mode records every verdict; enforce mode halts the pipeline on BLOCK and rewrites writable fields on MASK.
Status: Generally available · Evaluates: Prompts, Responses, Tool calls · Vendor: IBM
User prompt, model response, tool call arguments, tool output.
Setup
pip install "mellea[hooks]>=0.8.0" "wonderfence-sdk>=3.1.0" # then copy alice_mellea_plugin.py into your project
Configuration: ALICE_API_KEY, ALICE_APP_ID, ALICE_URL_OVERRIDE (optional), ALICE_API_TIMEOUT (optional)
Note: Tool message types are opt-in. Off by default, tool input is screened as a prompt and tool output as a response, which works on every project. Turn on
tool_message_types=Trueonly once Alice has enabledWONDER_FENCE_AGENTIC_MESSAGE_TYPESon your project and your policies list Tool Call / Tool Result: a policy that lists only Prompt or Response does not screen tool traffic sent under its own message types. Turned on without the flag, the API answers 400 on the tool hooks andfail_closeddecides:False(the default) records a failed verdict and lets the tool traffic through unevaluated,Trueblocks it.
Example
usage (README.md)
import os
from mellea.plugins import PluginViolationError, unregister
from alice_mellea_plugin import register_alice_plugin
plugin = register_alice_plugin(
app_id=os.environ["ALICE_APP_ID"],
enforce=True, # False = audit-only, never blocks
fail_closed=False, # True = block when WonderFence is unreachable
tool_message_types=False, # True once the project has WONDER_FENCE_AGENTIC_MESSAGE_TYPES
)
try:
answer = run_pipeline(query)
except PluginViolationError as exc:
answer = f"Blocked by policy: {exc.reason}" # exc.code, e.g. alice_tool_output_blocked
finally:
unregister(plugin)
surface to SDK method (alice_mellea_plugin.py)
# The WonderFenceV2Client method each surface is evaluated with.
SDK_METHODS = {
"input": "evaluate_prompt_sync",
"output": "evaluate_response_sync",
"tool_input": "evaluate_prompt_sync",
"tool_output": "evaluate_response_sync",
}
# With tool_message_types: tool traffic under its own message types.
TOOL_LANE_SDK_METHODS = {
**SDK_METHODS,
"tool_input": "evaluate_tool_call_sync",
"tool_output": "evaluate_tool_result_sync",
}
_AliceBase._evaluate (alice_mellea_plugin.py)
# The SDK's aiohttp session binds to the event loop it was created on, and
# plugins are registered outside any loop. The requests-based sync client has
# no loop affinity; running it in ``to_thread`` keeps the loop free.
async def _evaluate(
self, surface: str, text: str, session_id: str | None, tool_name: str | None = None
) -> AliceVerdict:
if not text:
return AliceVerdict(surface=surface, action=Actions.NO_ACTION)
methods = TOOL_LANE_SDK_METHODS if self.tool_message_types else SDK_METHODS
call = getattr(self.client, methods[surface])
tool_lane = self.tool_message_types and surface.startswith("tool_")
tool_fields = {"tool_name": _valid_tool_name(tool_name)} if tool_lane else {}
context = AnalysisContext(session_id=session_id or self.default_session_id, user_id=self.user_id)
text = text[:TRUNCATE_CHARS]
log.debug("[alice] >>> %s app_id=%s session=%s text=%r", surface, self.app_id, context.session_id, text)
try:
resp = await asyncio.to_thread(call, self.app_id, context, text, **tool_fields)
except Exception as exc:
log.warning("[alice] <<< %s evaluation failed: %s", surface, exc)
return AliceVerdict(surface=surface, action=FAILED, error=str(exc))
return AliceVerdict(
surface=surface,
action=resp.action,
detections=[d.model_dump() for d in resp.detections],
correlation_id=resp.correlation_id,
action_text=resp.action_text,
)
register_alice_plugin (alice_mellea_plugin.py)
def register_alice_plugin(
app_id: str,
api_key: str | None = None,
enforce: bool = False,
user_id: str = "mellea",
fail_closed: bool = False,
*,
tool_message_types: bool = False,
) -> AliceAuditPlugin | AliceEnforcePlugin:
"""Register an Alice plugin on Mellea's global registry and return it.
:param app_id: WonderFence application UUID.
:param api_key: WonderFence API key; the SDK falls back to ``ALICE_API_KEY``.
:param enforce: ``True`` for SEQUENTIAL hooks that block/mask, ``False`` for audit-only.
:param user_id: ``user_id`` sent in every ``AnalysisContext``.
:param fail_closed: ``True`` turns an SDK failure into a block; ``False`` (default) logs and continues.
:param tool_message_types: ``False`` (default) evaluates tool input as a prompt and tool output as
a response. ``True`` sends them as ``tool_call`` / ``tool_result`` with the tool name; it needs
``WONDER_FENCE_AGENTIC_MESSAGE_TYPES`` on the project and policies that list Tool Call / Tool Result.
"""
plugin_cls = AliceEnforcePlugin if enforce else AliceAuditPlugin
plugin = plugin_cls(
app_id=app_id,
api_key=api_key,
user_id=user_id,
fail_closed=fail_closed,
tool_message_types=tool_message_types,
)
register(plugin)
log.info(
"Alice plugin registered (app_id=%s, mode=%s, fail_closed=%s, tool_message_types=%s)",
app_id,
plugin_cls.__name__,
fail_closed,
tool_message_types,
)
return plugin
AliceEnforcePlugin: tool hooks (alice_mellea_plugin.py)
@hook(HookType.TOOL_PRE_INVOKE, mode=PluginMode.SEQUENTIAL)
async def enforce_tool_input(self, payload: Any, ctx: Any) -> Any:
tool_call = payload.model_tool_call
v = await self._check(payload, "tool_input", _serialize_tool_call(tool_call), tool_call.name)
if v.action == Actions.MASK and v.action_text is not None:
new_args = _parse_redacted_args(v.action_text)
if new_args is not None:
return modify(payload, model_tool_call=dataclasses.replace(tool_call, args=new_args))
# Whole-string rewrite or unquoted token: passing the original
# args through would leak what Alice asked us to redact.
log.warning(
"[alice-enforce] MASK on tool_input but action_text is not a JSON envelope; "
"falling back to BLOCK. corr=%s",
v.correlation_id,
)
return self._block(
v,
f"tool input ({tool_call.name}): unparsable redaction",
tool=tool_call.name,
mask_action_text=v.action_text,
)
return self._blocked(v, f"tool input ({tool_call.name})", tool=tool_call.name)
@hook(HookType.TOOL_POST_INVOKE, mode=PluginMode.SEQUENTIAL)
async def enforce_tool_output(self, payload: Any, ctx: Any) -> Any:
name = _tool_name(payload)
v = await self._check(payload, "tool_output", str(payload.tool_output or ""), name)
if v.action == Actions.MASK and v.action_text is not None:
return modify(payload, tool_output=v.action_text)
return self._blocked(v, f"tool output ({name})", tool=name)
mellea_example.py: registration
def main() -> None:
parser = argparse.ArgumentParser(description=__doc__, formatter_class=argparse.RawDescriptionHelpFormatter)
parser.add_argument("question")
parser.add_argument("path")
args = parser.parse_args()
plugin = register_alice_plugin(app_id=os.environ["ALICE_APP_ID"], enforce=True)
try:
print(run_pipeline(args.question, args.path))
except PluginViolationError as exc:
print(f"Blocked by Alice policy: {exc.reason}", file=sys.stderr)
sys.exit(2)
finally:
unregister(plugin)
Good to know
MASK is honored where the Mellea hook allows the field to be rewritten (model_tool_call, tool_output). On generation hooks the framework drops the mutation, so hard prompt and response masking belongs at a proxy layer. fail_closed=False by default so an Alice outage never kills the pipeline. Each hook screens only the first 4,000 characters (TRUNCATE_CHARS in alice_mellea_plugin.py); on ALLOW the full text, including the unscreened remainder, reaches the model or tool.