Skip to content

Question: external Gateway decisions alongside trace-backed invocation evidence #2887

Closed

Description

Hi,

I read the trace-backed tool-call scorer documentation and #2725, and saw the stored-message scorer proposed in #2854. Keeping incomplete evidence UNDETERMINED is particularly relevant to a small integration question I have. I also saw #2859 / #2860 on reporting coverage, so this is not a request to duplicate that work.

I'm the solo developer of Agentic Security Harness. Its application-owned Gateway keeps a model's proposed operation separate from permission to execute it. I'd like to explore a small external, mock-only example that supplies execution evidence to PyRIT while retaining the separate authorization decision.

What would be the best existing observation/scorable or trace-client interface for this? The cases I want to distinguish are:

  1. Allowed and invoked, with the expected synthetic result.
  2. Denied before invocation: the Gateway has a decision, but there must be no fabricated tool-execution span.
  3. Invoked but failed inside the tool: invocation is still observed, even though completion failed.
  4. Missing or incomplete evidence: no confident negative conclusion.

The invocation scorer would keep its documented meaning; policy decisions and operation outcomes would be separate fields, with coverage reported explicitly. I am not proposing that a model response, a Gateway receipt or an unpaired request should prove execution.

Here's the existing small Harness example. The PyRIT adapter is not implemented. Is this a useful external example to develop, or is there an existing one I should build on? I'm asking before writing a PR or proposing a new scorer.

Best,
krivonosoff161

Activity

  1. romanlutz commented on Nov 22, 2026

    @romanlutz
    Contributor

    Sorry for the slow reply.

    The interface you want is TraceClient. Your Gateway and tools emit OpenTelemetry spans, a TraceClient returns them by trace ID, and OtelToolCallScorer scores them. For an in-process mock, use InMemoryTraceExporter with InMemoryTraceClient, as in doc/code/scoring/5_tool_call_scorer.py. No PyRIT change is needed. Your four cases map like this:

    1. Allowed and invoked: an execute_tool span exists, so ToolsCalled is true.
    2. Denied before invocation: emit the decision as its own non-tool span and no tool span. With complete coverage ToolsCalled is false, and ToolsCalled(tools=(), exhaustive=True) is true ("nothing ran"). Coverage is complete only when your capture declares it (mark_complete); a remote backend never does, so there the result is undetermined.
    3. Invoked but failed: still counts as invoked. The error status is kept on the saved tool event, but no built-in scorer matches on tool success.
    4. Incomplete evidence: undetermined, never false.

    Here is a self-contained version of those four cases. It needs no model, service or credentials:

    Four cases with a mock gateway and tool
    import asyncio
    
    from opentelemetry.context import Context
    from opentelemetry.sdk.trace import SpanLimits, TracerProvider
    from opentelemetry.sdk.trace.export import SimpleSpanProcessor
    from opentelemetry.sdk.trace.sampling import ALWAYS_ON
    from opentelemetry.trace import Status, StatusCode
    
    from pyrit.models import ScoringExpectation, ToolCallRequirement, ToolsCalled, TraceScorable
    from pyrit.score import OtelToolCallScorer
    from pyrit.score.observation import InMemoryTraceClient, InMemoryTraceExporter, OtelTraceSource
    from pyrit.setup import IN_MEMORY, initialize_pyrit_async
    
    TOOL = "lookup"
    
    
    async def main() -> None:
        await initialize_pyrit_async(memory_db_type=IN_MEMORY, load_defaults=False, env_files=[], silent=True)
        client = InMemoryTraceClient()
        provider = TracerProvider(sampler=ALWAYS_ON, span_limits=SpanLimits(max_span_attribute_length=SpanLimits.UNSET))
        provider.add_span_processor(SimpleSpanProcessor(InMemoryTraceExporter(trace_client=client)))
        tracer = provider.get_tracer("gateway-example")
        scorer = OtelToolCallScorer(source=OtelTraceSource(trace_client=client))
    
        invoked = ScoringExpectation(conditions=(ToolsCalled(tools=(ToolCallRequirement(name=TOOL),)),))
        nothing_ran = ScoringExpectation(conditions=(ToolsCalled(tools=(), exhaustive=True),))
    
        def run(*, allow: bool, tool_fails: bool = False) -> str:
            """One request: the gateway decides, and the tool runs only when allowed."""
            with tracer.start_as_current_span("agent", context=Context()) as root:
                # The decision is its own span. It is never an execute_tool span.
                decision = {"openinference.span.kind": "GUARDRAIL", "output.value": "allow" if allow else "deny"}
                with tracer.start_as_current_span("gateway.decide", attributes=decision):
                    pass
                if allow:
                    tool = {"gen_ai.operation.name": "execute_tool", "gen_ai.tool.name": TOOL}
                    with tracer.start_as_current_span(TOOL, attributes=tool) as span:
                        if tool_fails:
                            span.set_status(Status(StatusCode.ERROR, "tool failed"))
                return f"{root.get_span_context().trace_id:032x}"
    
        cases = (
            ("allowed and invoked", {"allow": True}, True),
            ("denied before invocation", {"allow": False}, True),
            ("invoked, tool failed", {"allow": True, "tool_fails": True}, True),
            ("incomplete evidence", {"allow": False}, False),
        )
        for label, kwargs, capture_complete in cases:
            trace_id = run(**kwargs)
            assert await asyncio.to_thread(provider.force_flush)
            if capture_complete:
                # Only the code that owns the capture can say that nothing else is coming.
                client.mark_complete(trace_ids=(trace_id,))
            scope = TraceScorable(trace_ids=(trace_id,))
            results = []
            for expectation in (invoked, nothing_ran):
                score = (await scorer.score_async(scorable=scope, expectation=expectation))[0]
                results.append("undetermined" if score.is_undetermined else score.get_value())
            print(f"{label}: tool invoked={results[0]}, nothing ran={results[1]}")
    
        await asyncio.to_thread(provider.shutdown)
        client.close()
    
    
    asyncio.run(main())

    Output:

    allowed and invoked: tool invoked=True, nothing ran=False
    denied before invocation: tool invoked=False, nothing ran=True
    invoked, tool failed: tool invoked=True, nothing ran=False
    incomplete evidence: tool invoked=undetermined, nothing ran=undetermined
    

    To score a real agent behind a target instead of hand-made spans, see "Score a tool call through an attack" in the same notebook.

    PyRIT has no deterministic condition over the Gateway decision itself. If you record it as a span (for example OpenInference GUARDRAIL), OtelExecutionTraceSource keeps it as a step that trace-reading judges can see (8_trace_evidence_scoring.py). If you want it as a separate verdict, write a small scorer on your side that reads that observation.

    On the PR question: please don't open one for this. We keep PyRIT's docs and scorers free of project-specific integrations, so we would not take a Gateway example or a Gateway-specific scorer. An example in your own repository needs no permission from us. If building it turns up a generic gap, such as a condition on tool outcome, please open a focused issue for that.

    Closing as answered; feel free to reopen if something above does not work.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Metadata

Metadata

Assignees

No one assigned

    Labels

    questionFurther information is requested

    Type

    No type

    Projects

    No projects

      Milestone

      No milestone

      Relationships

      None yet

      Development

      No branches or pull requests

      Issue actions