Skip to content

The agent that grows with you

test: SDK oracle checks every content block against its request Param (assistant blocks were unchecked)

teknium14f9cf2a31e06
diff --git a/tests/e2e/core/providers/test_anthropic_oracle.py b/tests/e2e/core/providers/test_anthropic_oracle.py
new file mode 100644
index 00000000000..979bf6a8eab
--- /dev/null
+++ b/tests/e2e/core/providers/test_anthropic_oracle.py
@@ -0,0 +1,89 @@
+"""The SDK-oracle fake itself: it must be able to fail.
+
+Every wire-conformance cell in this directory ends with ``schema_errors() == []``;
+that assertion is only worth something if the oracle reports what the real API
+rejects. The real Messages API answers 400 ``Extra inputs are not permitted`` for
+an unknown key on ANY content block, including replayed assistant blocks — which
+the SDK's request union would otherwise accept through its permissive response
+models. Record mode is exercised against a second local fake (never a real key).
+"""
+
+from __future__ import annotations
+
+import copy
+import json
+import urllib.request
+
+import pytest
+
+from tests.fakes.providers.anthropic_messages import AnthropicMessagesServer, Reply, Text, validate_request
+
+SIGNED = {"type": "thinking", "thinking": "weigh it", "signature": "EqSig+/=="}
+TOOL_USE = {"type": "tool_use", "id": "toolu_1", "name": "read_file", "input": {"path": "a.txt"}}
+
+
+def _body() -> dict:
+ return {
+ "model": "claude-sonnet-4-5", "max_tokens": 64,
+ "system": [{"type": "text", "text": "you are terse", "cache_control": {"type": "ephemeral"}}],
+ "tools": [{"name": "read_file", "description": "read", "input_schema": {"type": "object"}}],
+ "messages": [
+ {"role": "user", "content": "read a.txt"},
+ {"role": "assistant", "content": [copy.deepcopy(SIGNED), {"type": "text", "text": "reading"},
+ copy.deepcopy(TOOL_USE)]},
+ {"role": "user", "content": [{"type": "tool_result", "tool_use_id": "toolu_1",
+ "content": [{"type": "text", "text": "A"}]}]},
+ ],
+ }
+
+
[email protected]("beta", [False, True], ids=["ga", "beta"])
+def test_conformant_body_has_no_schema_errors(beta: bool) -> None:
+ assert validate_request(_body(), beta=beta) == []
+
+
[email protected]("beta", [False, True], ids=["ga", "beta"])
+ ("messages", 1, 0), # assistant thinking (what _replay_thinking builds)
+ ("messages", 1, 1), # assistant text
+ ("messages", 1, 2), # assistant tool_use
+ ("messages", 2, 0), # user tool_result
+ ("system", None, 0), # system text block
+], ids=["assistant_thinking", "assistant_text", "assistant_tool_use", "user_tool_result", "system_text"])
+def test_unknown_key_in_any_content_block_is_reported(where: tuple, beta: bool) -> None:
+ body = _body()
+ field, msg, idx = where
+ block = body["system"][idx] if field == "system" else body["messages"][msg]["content"][idx]
+ block["e2e_bogus_field"] = 1
+ path = f"$.system[{idx}]" if field == "system" else f"$.messages[{msg}].content[{idx}]"
+ assert f"unknown key {path}.e2e_bogus_field" in validate_request(body, beta=beta)
+
+
[email protected]("beta", [False, True], ids=["ga", "beta"])
+def test_response_only_block_type_in_request_is_reported(beta: bool) -> None:
+ body = _body()
+ body["messages"][1]["content"][0]["type"] = "thinking_delta"
+ assert any("$.messages[1].content[0]" in p for p in validate_request(body, beta=beta))
+
+
+def test_record_mode_writes_a_sanitised_cassette(tmp_path) -> None:
+ secret_key, secret_bearer = "sk-ant-api03-RECORD-PROBE-KEY", "sk-ant-oat01-RECORD-PROBE-BEARER"
+ with AnthropicMessagesServer([Reply([Text("UPSTREAM-ANSWER")])]) as upstream, \
+ AnthropicMessagesServer(record_upstream=upstream.base_url, cassette="probe",
+ cassette_dir=tmp_path) as recorder:
+ req = urllib.request.Request(
+ recorder.base_url + "/v1/messages", data=json.dumps(_body()).encode(), method="POST",
+ headers={"content-type": "application/json", "x-api-key": secret_key,
+ "authorization": f"Bearer {secret_bearer}", "anthropic-version": "2023-06-01"})
+ with urllib.request.urlopen(req, timeout=30) as resp: # noqa: S310 - loopback fake
+ answer = json.loads(resp.read())
+ assert upstream.requests[0]["x_api_key"] == secret_key, "record mode must forward the request's auth"
+ assert answer["content"][0]["text"] == "UPSTREAM-ANSWER"
+ lines = (tmp_path / "probe.jsonl").read_text(encoding="utf-8").splitlines()
+ assert len(lines) == 1
+ exchange = json.loads(lines[0])
+ assert exchange["request"]["body"] == _body() and exchange["response"]["status"] == 200
+ assert "UPSTREAM-ANSWER" in exchange["response"]["body"]
+ raw = lines[0].lower()
+ assert secret_key.lower() not in raw and secret_bearer.lower() not in raw
+ assert not {"authorization", "x-api-key"} & set(exchange["request"]["headers"])
diff --git a/tests/fakes/providers/anthropic_messages.py b/tests/fakes/providers/anthropic_messages.py
index 0aefb02941d..e46bb9b4394 100644
--- a/tests/fakes/providers/anthropic_messages.py
+++ b/tests/fakes/providers/anthropic_messages.py
@@ -20,7 +20,12 @@ Record mode (documented, never run in CI or against a paid key by this suite):
``AnthropicMessagesServer(record_upstream="https://api.anthropic.com",
cassette="<name>")`` proxies each POST to the upstream base URL and appends a
sanitised exchange (no auth headers, no API keys) to
-``tests/fakes/providers/cassettes/anthropic/<name>.jsonl``.
+``tests/fakes/providers/cassettes/anthropic/<name>.jsonl`` (``cassette_dir``
+overrides the directory).
+
+A ``Responder`` runs on the request's handler thread, so it may block (hold a
+reply until an event fires) and decide at send time; each request record
+carries ``bearer`` / ``x_api_key`` so a responder can branch on the credential.
"""
from __future__ import annotations
@@ -28,6 +33,7 @@ from __future__ import annotations
import json
import threading
import time
+import typing
import urllib.error
import urllib.request
import uuid
@@ -37,7 +43,9 @@ from pathlib import Path
from typing import Any, Callable, Union
import anthropic.types as at
+import typing_extensions
from anthropic.types import message_create_params as ga_params
+from anthropic.types.beta import BetaMessageParam
from anthropic.types.beta import message_create_params as beta_params
from anthropic.types.raw_message_delta_event import Delta as MessageDelta
from pydantic import TypeAdapter, ValidationError
@@ -130,7 +138,29 @@ def _materialise(value: Any) -> Any:
return value
+def _param_adapters(message_param: Any) -> dict[str, TypeAdapter]:
+ """``type`` literal -> TypeAdapter of each request-side ``*Param`` TypedDict in a message's content union."""
+ content = typing.get_type_hints(message_param)["content"]
+ iterable = next(arg for arg in typing.get_args(content) if arg is not str)
+ out: dict[str, TypeAdapter] = {}
+ for member in typing.get_args(typing.get_args(iterable)[0]):
+ if typing_extensions.is_typeddict(member): # the SDK builds its Params with typing_extensions
+ for literal in typing.get_args(typing.get_type_hints(member)["type"]):
+ out[literal] = TypeAdapter(member)
+ return out
+
+
+# A message's content union also admits the RESPONSE BaseModels (ThinkingBlock, ToolUseBlock ...),
+# which accept extra keys, so a replayed assistant block would validate with any bogus key. Content
+# blocks are re-validated against the request-side *Param TypedDicts only: the shapes the real API
+# holds a body to (it 400s "Extra inputs are not permitted").
+_GA_BLOCKS = _param_adapters(at.MessageParam)
+_BETA_BLOCKS = _param_adapters(BetaMessageParam)
+
+
def _unknown_keys(sent: Any, known: Any, path: str = "$") -> list[str]:
+ # A block the union resolved to a (permissive) response BaseModel stops this walk; content
+ # blocks are checked key-for-key against their *Param TypedDict by _block_problems instead.
if isinstance(sent, dict) and isinstance(known, dict):
out = [f"{path}.{k}" for k in sent if k not in known]
for k in sent:
@@ -147,9 +177,41 @@ def validate_request(body: dict[str, Any], *, beta: bool) -> list[str]:
adapter = _BETA_ADAPTER if beta else _GA_ADAPTER
try:
known = _materialise(adapter.validate_python(body))
+ problems = [f"unknown key {p}" for p in _unknown_keys(body, known)]
+ except ValidationError as exc:
+ problems = [_loc(e, "$") for e in exc.errors()]
+ for path, block in _content_blocks(body):
+ problems += [p for p in _block_problems(block, _BETA_BLOCKS if beta else _GA_BLOCKS, path)
+ if p not in problems]
+ return problems
+
+
+def _loc(err: Any, prefix: str) -> str:
+ return f"{prefix}.{'.'.join(map(str, err['loc']))}: {err['msg']}"
+
+
+def _content_blocks(body: dict[str, Any]) -> list[tuple[str, Any]]:
+ out: list[tuple[str, Any]] = []
+ for i, msg in enumerate(body.get("messages") or []):
+ content = msg.get("content") if isinstance(msg, dict) else None
+ if isinstance(content, list):
+ out += [(f"$.messages[{i}].content[{j}]", b) for j, b in enumerate(content)]
+ if isinstance(body.get("system"), list):
+ out += [(f"$.system[{j}]", b) for j, b in enumerate(body["system"])]
+ return out
+
+
+def _block_problems(block: Any, adapters: dict[str, TypeAdapter], path: str) -> list[str]:
+ if not isinstance(block, dict):
+ return [f"{path}: content block is {type(block).__name__}, not an object"]
+ adapter = adapters.get(block.get("type"))
+ if adapter is None:
+ return [f"{path}.type: {block.get('type')!r} is not a request content block type"]
+ try:
+ known = _materialise(adapter.validate_python(block))
except ValidationError as exc:
- return [f"{'.'.join(map(str, e['loc']))}: {e['msg']}" for e in exc.errors()]
- return [f"unknown key {p}" for p in _unknown_keys(body, known)]
+ return [_loc(e, path) for e in exc.errors()]
+ return [f"unknown key {p}" for p in _unknown_keys(block, known, path)]
# SDK-built responses --------------------------------------------------------------
@@ -235,14 +297,15 @@ class AnthropicMessagesServer:
def __init__(self, script: list[Response] | Responder | None = None, *, default_text: str = "ok",
aux: Responder | None = None, models: list[str] | None = None,
- record_upstream: str | None = None, cassette: str = "session") -> None:
+ record_upstream: str | None = None, cassette: str = "session",
+ cassette_dir: Path = CASSETTE_DIR) -> None:
self._script: list[Response] = list(script) if isinstance(script, list) else []
self._responder: Responder | None = script if callable(script) else None
self.default_text = default_text
self._aux = aux or (lambda _r: Reply([Text("Fake summary of the earlier conversation.")]))
self.models = models or [MODEL_ID]
self.record_upstream = record_upstream
- self.cassette = CASSETTE_DIR / f"{cassette}.jsonl"
+ self.cassette = Path(cassette_dir) / f"{cassette}.jsonl"
self.requests: list[dict[str, Any]] = []
self.gets: list[dict[str, Any]] = []
self._lock = threading.Lock()
@@ -356,6 +419,8 @@ def _handler_for(server: AnthropicMessagesServer) -> type[BaseHTTPRequestHandler
headers = {k.lower(): v for k, v in self.headers.items()}
record = {
"path": self.path, "headers": headers, "body": body, "t": time.monotonic(),
+ "bearer": headers.get("authorization", "").removeprefix("Bearer ").strip(),
+ "x_api_key": headers.get("x-api-key", ""),
"kind": "main" if body.get("tools") else "aux",
"schema_errors": validate_request(body, beta=bool(headers.get("anthropic-beta"))),
}