Skip to content

LlamaFirewallProvider unable to run due to nested asyncio event loops #39

@xp4u1

Description

@xp4u1

I encountered an issue with the LlamaFirewall Guardrail-Provider and am a bit confused about its origin. Initially, I suspected it might be due to my setup, but after some investigation, it seems this issue should be affecting everyone.

ERROR:llama_firewall_provider:Error in LlamaFirewallProvider.check_tool_response
Traceback (most recent call last):
  File "xxx/mcp-context-protector/src/contextprotector/guardrail_providers/llama_firewall.py", line 124, in check_tool_response
    result = lf.scan(message)
             ^^^^^^^^^^^^^^^^
  File "xxx/mcp-context-protector/.venv/lib/python3.11/site-packages/llamafirewall/llamafirewall.py", line 122, in scan
    scanner_result = asyncio.run(scanner_instance.scan(input, trace))
                     ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
  File "/usr/lib/python3.11/asyncio/runners.py", line 186, in run
    raise RuntimeError(
RuntimeError: asyncio.run() cannot be called from a running event loop
WARNING:mcp_wrapper:Guardrail alert triggered for tool 'get_alerts': Error checking tool response: asyncio.run()
                    cannot be called from a running event loop

The following code causes this error, since asyncio does not allow nested event loops.

# external llamafirewall/llamafirewall.py
for scanner_type in scanners:
    scanner_instance = create_scanner(scanner_type)
    LOG.debug(
        f"[LlamaFirewall] Scanning with {scanner_instance.name}, for the input {str(input.content)[:20]}"
    )
    scanner_result = asyncio.run(scanner_instance.scan(input, trace)) # <-- this call fails

# src/contextprotector/__main__.py
def main() -> None:
    """Launch async main function."""
    asyncio.run(main_async()) # <-- entire mcp-context-protector already inside an event loop

The llamafirewall library includes a scan_async function. However, after a brief review of the codebase, it seems that some refactoring is necessary, as many functions need to be marked as async.


To reproduce the issue, use the official demo repo and run it using the inspector:

npx @modelcontextprotocol/inspector bash $PWD/mcp-context-protector.sh \
	--guardrail-provider LlamaFirewall --command-args $(which uv) run \
	--directory xxx/mcp-quickstart-resources/weather-server-python/ weather.py

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions