Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
36 changes: 24 additions & 12 deletions src/openrouter_agent/tool_context.py
Original file line number Diff line number Diff line change
Expand Up @@ -73,16 +73,20 @@ def __eq__(self, other: Any) -> bool:
return self._getter() == other


def extract_tool_context(tool: Mapping[str, Any], context_map: Mapping[str, Any]) -> Dict[str, Any]:
fn = tool.get("function", {})
schema = fn.get("context_schema")
raw = context_map.get(fn.get("name"), {})
if raw is None:
raw = {}
validated = validate_schema(schema, raw)
def _parse_context(schema: Any, value: Mapping[str, Any]) -> Dict[str, Any]:
if schema is None:
return dict(value)
validated = validate_schema(schema, dict(value))
if hasattr(validated, "model_dump"):
return validated.model_dump()
return dict(validated or {})
if isinstance(validated, MappingABC):
return dict(validated)
return dict(value)


def extract_tool_context(store: ToolContextStore, key: str, schema: Any) -> Dict[str, Any]:
"""Validate the stored context for ``key`` against ``schema`` and return the parsed values."""
return _parse_context(schema, _filter_schema_keys(schema, store.get_tool_context(key)))


async def resolve_context(context: Any, turn_context: Mapping[str, Any]) -> Dict[str, Any]:
Expand All @@ -105,6 +109,16 @@ def build_tool_execute_context(
base = dict(turn_context or {})
if store is None:
store = ToolContextStore({})
context_schema = fn.get("context_schema")
if context_schema is not None:
extract_tool_context(store, name, context_schema)
if shared_context_schema is not None:
extract_tool_context(store, SHARED_CONTEXT_KEY, shared_context_schema)

def write(key: str, schema: Any, partial: Mapping[str, Any]) -> None:
merged = store.get_tool_context(key)
merged.update(_filter_schema_keys(schema, partial))
store.set_tool_context(key, _parse_context(schema, merged))

def local() -> Dict[str, Any]:
return store.get_tool_context(name)
Expand All @@ -113,12 +127,10 @@ def shared() -> Dict[str, Any]:
return store.get_tool_context(SHARED_CONTEXT_KEY)

def set_context(partial: Mapping[str, Any]) -> None:
filtered = _filter_schema_keys(fn.get("context_schema"), partial)
store.merge_tool_context(name, filtered)
write(name, context_schema, partial)

def set_shared_context(partial: Mapping[str, Any]) -> None:
filtered = _filter_schema_keys(shared_context_schema, partial)
store.merge_tool_context(SHARED_CONTEXT_KEY, filtered)
write(SHARED_CONTEXT_KEY, shared_context_schema, partial)

base.update(
{
Expand Down
124 changes: 124 additions & 0 deletions tests/unit/test_tool_context_validation.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,124 @@
from __future__ import annotations

from typing import Literal

import pytest
from pydantic import BaseModel, ValidationError, field_validator

from openrouter_agent import ToolContextStore, build_tool_execute_context, tool
from openrouter_agent.tool_executor import execute_tool
from openrouter_agent.tool_types import ParsedToolCall


class Capability(BaseModel):
capability: Literal["read"] = "read"


class Normalized(BaseModel):
name: str = "anon"
retries: int = 3

@field_validator("name")
@classmethod
def _lower(cls, value: str) -> str:
return value.lower()


async def test_invalid_shared_context_write_does_not_reach_the_next_tool() -> None:
store = ToolContextStore({})
seen: dict = {}

def escalate(params, ctx):
ctx["set_shared_context"]({"capability": "admin"})
return {"ok": True}

def act(params, ctx):
seen["capability"] = ctx["shared"].get("capability")
return {"ok": True}

writer = tool(name="writer", input_schema=dict, execute=escalate)
reader = tool(name="reader", input_schema=dict, execute=act)

first = await execute_tool(writer, ParsedToolCall("1", "writer", {}), {}, None, store, Capability)
await execute_tool(reader, ParsedToolCall("2", "reader", {}), {}, None, store, Capability)

assert first is not None
assert isinstance(first["error"], ValidationError)
assert seen["capability"] is None
assert store.get_snapshot() == {}


async def test_invalid_local_context_write_does_not_reach_the_next_call() -> None:
store = ToolContextStore({})
seen: list = []

def run(params, ctx):
seen.append(ctx["local"].get("capability"))
ctx["set_context"]({"capability": params["value"]})
return {"ok": True}

gated = tool(name="gated", input_schema=dict, context_schema=Capability, execute=run)

first = await execute_tool(gated, ParsedToolCall("1", "gated", {"value": "admin"}), {}, None, store)
await execute_tool(gated, ParsedToolCall("2", "gated", {"value": "read"}), {}, None, store)

assert first is not None
assert isinstance(first["error"], ValidationError)
assert seen == [None, None]
assert store.get_tool_context("gated") == {"capability": "read"}


def test_failed_write_leaves_store_and_subscribers_untouched() -> None:
store = ToolContextStore({"gated": {"capability": "read"}})
notified: list = []
store.subscribe(notified.append)
gated = tool(name="gated", input_schema=dict, context_schema=Capability, execute=lambda p, c: {})
ctx = build_tool_execute_context(gated, {}, store)

with pytest.raises(ValidationError):
ctx["set_context"]({"capability": "admin"})

assert store.get_tool_context("gated") == {"capability": "read"}
assert notified == []


def test_writes_store_the_parsed_model_output() -> None:
store = ToolContextStore({})
normalized = tool(name="norm", input_schema=dict, context_schema=Normalized, execute=lambda p, c: {})
ctx = build_tool_execute_context(normalized, {}, store, Normalized)

ctx["set_context"]({"name": "ALICE", "unknown": 1})
ctx["set_shared_context"]({"retries": "5"})

assert store.get_tool_context("norm") == {"name": "alice", "retries": 3}
assert store.get_tool_context("shared") == {"name": "anon", "retries": 5}


def test_writes_merge_with_existing_context_before_validating() -> None:
store = ToolContextStore({"norm": {"name": "bob", "retries": 1}})
normalized = tool(name="norm", input_schema=dict, context_schema=Normalized, execute=lambda p, c: {})
ctx = build_tool_execute_context(normalized, {}, store)

ctx["set_context"]({"retries": 2})

assert store.get_tool_context("norm") == {"name": "bob", "retries": 2}


def test_invalid_initial_context_is_rejected() -> None:
gated = tool(name="gated", input_schema=dict, context_schema=Capability, execute=lambda p, c: {})

with pytest.raises(ValidationError):
build_tool_execute_context(gated, {}, ToolContextStore({"gated": {"capability": "admin"}}))
with pytest.raises(ValidationError):
build_tool_execute_context(gated, {}, ToolContextStore({"shared": {"capability": "admin"}}), Capability)


async def test_invalid_initial_context_fails_the_tool_call() -> None:
called: list = []
gated = tool(name="gated", input_schema=dict, context_schema=Capability, execute=lambda p, c: called.append(1))

with pytest.raises(ValidationError):
await execute_tool(
gated, ParsedToolCall("1", "gated", {}), {}, None, ToolContextStore({"gated": {"capability": "admin"}})
)
assert called == []
Loading