From feffb76d6f0fd5efbf2c31bd41ef103487dec74b Mon Sep 17 00:00:00 2001 From: Devin AI <158243242+devin-ai-integration[bot]@users.noreply.github.com> Date: Mon, 30 Nov 2026 16:04:54 +0000 Subject: [PATCH 1/2] fix(agent): validate tool context against its schema before storing it --- src/openrouter_agent/tool_context.py | 36 ++++-- tests/unit/test_tool_context_validation.py | 122 +++++++++++++++++++++ 2 files changed, 146 insertions(+), 12 deletions(-) create mode 100644 tests/unit/test_tool_context_validation.py diff --git a/src/openrouter_agent/tool_context.py b/src/openrouter_agent/tool_context.py index 3b8d152..6c79351 100644 --- a/src/openrouter_agent/tool_context.py +++ b/src/openrouter_agent/tool_context.py @@ -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]: @@ -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) @@ -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( { diff --git a/tests/unit/test_tool_context_validation.py b/tests/unit/test_tool_context_validation.py new file mode 100644 index 0000000..e2029b3 --- /dev/null +++ b/tests/unit/test_tool_context_validation.py @@ -0,0 +1,122 @@ +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 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 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 == [] From 456f3654447f716944bf7642d9ecd12fd77f2771 Mon Sep 17 00:00:00 2001 From: Devin AI <158243242+devin-ai-integration[bot]@users.noreply.github.com> Date: Mon, 30 Nov 2026 16:06:03 +0000 Subject: [PATCH 2/2] test: narrow execute_tool result for mypy --- tests/unit/test_tool_context_validation.py | 2 ++ 1 file changed, 2 insertions(+) diff --git a/tests/unit/test_tool_context_validation.py b/tests/unit/test_tool_context_validation.py index e2029b3..651a790 100644 --- a/tests/unit/test_tool_context_validation.py +++ b/tests/unit/test_tool_context_validation.py @@ -42,6 +42,7 @@ def act(params, ctx): 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() == {} @@ -61,6 +62,7 @@ def run(params, ctx): 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"}