| 1 |
from __future__ import annotations |
| 2 |
|
| 3 |
import json |
| 4 |
|
| 5 |
import respx |
| 6 |
import httpx2 |
| 7 |
import pytest |
| 8 |
|
| 9 |
from anthropic import Anthropic, AsyncAnthropic, _compat |
| 10 |
from anthropic.types.beta import BetaToolParam |
| 11 |
from anthropic._base_client import _APPEND_HEADERS |
| 12 |
from anthropic.lib._stainless_helpers import ( |
| 13 |
STAINLESS_HELPER_HEADER, |
| 14 |
tag_helper, |
| 15 |
helper_header, |
| 16 |
) |
| 17 |
|
| 18 |
from ..conftest import base_url |
| 19 |
|
| 20 |
|
| 21 |
class _Tool: |
| 22 |
"""Stands in for a `@beta_tool` / toolset object: `tools=` takes anything with a `to_dict()`.""" |
| 23 |
|
| 24 |
def to_dict(self) -> BetaToolParam: |
| 25 |
return {"name": "t", "description": "d", "input_schema": {"type": "object"}} |
| 26 |
|
| 27 |
|
| 28 |
class _TaggedTuple(tuple): # type: ignore[type-arg] |
| 29 |
"""Same for file tuples, mirroring `mcp_resource_to_file`'s return value.""" |
| 30 |
|
| 31 |
|
| 32 |
def test_helper_header() -> None: |
| 33 |
assert helper_header("BetaToolRunner") == {STAINLESS_HELPER_HEADER: "BetaToolRunner"} |
| 34 |
|
| 35 |
|
| 36 |
def test_helper_header_is_an_append_header() -> None: |
| 37 |
# `merge_headers` only appends keys it knows about — keep this aligned |
| 38 |
assert STAINLESS_HELPER_HEADER in _APPEND_HEADERS |
| 39 |
|
| 40 |
|
| 41 |
def _message_json() -> dict[str, object]: |
| 42 |
return { |
| 43 |
"id": "msg_abc123", |
| 44 |
"type": "message", |
| 45 |
"role": "assistant", |
| 46 |
"model": "claude-sonnet-4-5", |
| 47 |
"content": [{"type": "text", "text": "hi"}], |
| 48 |
"stop_reason": "end_turn", |
| 49 |
"stop_sequence": None, |
| 50 |
"usage": {"input_tokens": 1, "output_tokens": 1}, |
| 51 |
} |
| 52 |
|
| 53 |
|
| 54 |
def _file_json() -> dict[str, object]: |
| 55 |
return { |
| 56 |
"id": "file_abc123", |
| 57 |
"type": "file", |
| 58 |
"created_at": "2026-01-01T00:00:00Z", |
| 59 |
"filename": "data.json", |
| 60 |
"mime_type": "application/json", |
| 61 |
"size_bytes": 2, |
| 62 |
} |
| 63 |
|
| 64 |
|
| 65 |
@pytest.mark.respx(base_url=base_url) |
| 66 |
class TestSyncWireHeaders: |
| 67 |
def test_caller_tag_is_appended_not_clobbered(self, client: Anthropic, respx_mock: respx.MockRouter) -> None: |
| 68 |
respx_mock.post("/v1/messages").mock(return_value=httpx2.Response(200, json=_message_json())) |
| 69 |
|
| 70 |
tool = _Tool() |
| 71 |
tag_helper(tool, "mcp_tool") |
| 72 |
client.beta.messages.create( |
| 73 |
model="claude-sonnet-4-5", |
| 74 |
max_tokens=16, |
| 75 |
messages=[{"role": "user", "content": "hello"}], |
| 76 |
tools=[tool], |
| 77 |
extra_headers={"X-Stainless-Helper": "caller-tag"}, |
| 78 |
) |
| 79 |
|
| 80 |
request = respx_mock.calls.last.request |
| 81 |
values = request.headers.get_list(STAINLESS_HELPER_HEADER) |
| 82 |
assert values == ["mcp_tool, caller-tag"] |
| 83 |
assert json.loads(request.content)["tools"] == [tool.to_dict()] |
| 84 |
|
| 85 |
def test_file_upload_tag_is_appended_not_clobbered(self, client: Anthropic, respx_mock: respx.MockRouter) -> None: |
| 86 |
respx_mock.post("/v1/files").mock(return_value=httpx2.Response(200, json=_file_json())) |
| 87 |
|
| 88 |
file = _TaggedTuple(("data.json", b"{}", "application/json")) |
| 89 |
tag_helper(file, "mcp_resource_to_file") |
| 90 |
client.files.upload(file=file, extra_headers={"X-Stainless-Helper": "caller-tag"}) |
| 91 |
|
| 92 |
request = respx_mock.calls.last.request |
| 93 |
values = request.headers.get_list(STAINLESS_HELPER_HEADER) |
| 94 |
assert values == ["mcp_resource_to_file, caller-tag"] |
| 95 |
|
| 96 |
@pytest.mark.skipif(_compat.PYDANTIC_V1, reason="parse() response post-parser is pydantic-v2 only") |
| 97 |
def test_parse_sends_single_header_line(self, client: Anthropic, respx_mock: respx.MockRouter) -> None: |
| 98 |
# regression: the literal tag and the collected tags used to land under |
| 99 |
# two casings of the key, producing two header lines on the wire |
| 100 |
respx_mock.post("/v1/messages").mock(return_value=httpx2.Response(200, json=_message_json())) |
| 101 |
|
| 102 |
client.beta.messages.parse( |
| 103 |
model="claude-sonnet-4-5", |
| 104 |
max_tokens=16, |
| 105 |
messages=[{"role": "user", "content": "hello"}], |
| 106 |
tools=[_Tool()], |
| 107 |
) |
| 108 |
|
| 109 |
request = respx_mock.calls.last.request |
| 110 |
values = request.headers.get_list(STAINLESS_HELPER_HEADER) |
| 111 |
assert values == ["beta.messages.parse"] |
| 112 |
assert json.loads(request.content)["tools"] == [_Tool().to_dict()] |
| 113 |
|
| 114 |
def test_count_tokens_takes_a_tool_object(self, client: Anthropic, respx_mock: respx.MockRouter) -> None: |
| 115 |
respx_mock.post("/v1/messages/count_tokens").mock(return_value=httpx2.Response(200, json={"input_tokens": 3})) |
| 116 |
result = client.beta.messages.count_tokens( |
| 117 |
model="claude-sonnet-4-5", messages=[{"role": "user", "content": "hello"}], tools=[_Tool()] |
| 118 |
) |
| 119 |
assert result.input_tokens == 3 |
| 120 |
assert json.loads(respx_mock.calls.last.request.content)["tools"] == [_Tool().to_dict()] |
| 121 |
|
| 122 |
@pytest.mark.skipif(_compat.PYDANTIC_V1, reason="parse() response post-parser is pydantic-v2 only") |
| 123 |
def test_parse_merges_caller_extra_headers(self, client: Anthropic, respx_mock: respx.MockRouter) -> None: |
| 124 |
# caller-supplied betas, user_profile_id, and extra_headers must all |
| 125 |
# survive parse()'s hand-written merge alongside the injected |
| 126 |
# structured-outputs beta and the helper tag |
| 127 |
respx_mock.post("/v1/messages").mock(return_value=httpx2.Response(200, json=_message_json())) |
| 128 |
|
| 129 |
client.beta.messages.parse( |
| 130 |
model="claude-sonnet-4-5", |
| 131 |
max_tokens=16, |
| 132 |
messages=[{"role": "user", "content": "hello"}], |
| 133 |
betas=["fake-beta-2026-01-01"], |
| 134 |
user_profile_id="upi_123", |
| 135 |
extra_headers={"X-Custom": "1", "X-Stainless-Helper": "caller-tag"}, |
| 136 |
) |
| 137 |
|
| 138 |
headers = respx_mock.calls.last.request.headers |
| 139 |
# injected structured-outputs beta is appended to caller betas, not dropped |
| 140 |
assert headers["anthropic-beta"] == "fake-beta-2026-01-01,structured-outputs-2025-12-15" |
| 141 |
assert headers["anthropic-user-profile-id"] == "upi_123" |
| 142 |
assert headers["X-Custom"] == "1" |
| 143 |
# helper tag accumulates with the caller's on one line (append-header semantics) |
| 144 |
assert headers.get_list(STAINLESS_HELPER_HEADER) == ["beta.messages.parse, caller-tag"] |
| 145 |
|
| 146 |
@pytest.mark.skipif(_compat.PYDANTIC_V1, reason="parse() response post-parser is pydantic-v2 only") |
| 147 |
def test_parse_caller_beta_header_overrides(self, client: Anthropic, respx_mock: respx.MockRouter) -> None: |
| 148 |
# extra_headers win outright on non-append headers, matching create() |
| 149 |
respx_mock.post("/v1/messages").mock(return_value=httpx2.Response(200, json=_message_json())) |
| 150 |
|
| 151 |
client.beta.messages.parse( |
| 152 |
model="claude-sonnet-4-5", |
| 153 |
max_tokens=16, |
| 154 |
messages=[{"role": "user", "content": "hello"}], |
| 155 |
extra_headers={"anthropic-beta": "explicit-only"}, |
| 156 |
) |
| 157 |
|
| 158 |
headers = respx_mock.calls.last.request.headers |
| 159 |
assert headers["anthropic-beta"] == "explicit-only" |
| 160 |
|
| 161 |
|
| 162 |
@pytest.mark.respx(base_url=base_url) |
| 163 |
class TestAsyncWireHeaders: |
| 164 |
async def test_caller_tag_is_appended_not_clobbered( |
| 165 |
self, async_client: AsyncAnthropic, respx_mock: respx.MockRouter |
| 166 |
) -> None: |
| 167 |
respx_mock.post("/v1/messages").mock(return_value=httpx2.Response(200, json=_message_json())) |
| 168 |
|
| 169 |
tool = _Tool() |
| 170 |
tag_helper(tool, "mcp_tool") |
| 171 |
await async_client.beta.messages.create( |
| 172 |
model="claude-sonnet-4-5", |
| 173 |
max_tokens=16, |
| 174 |
messages=[{"role": "user", "content": "hello"}], |
| 175 |
tools=[tool], |
| 176 |
extra_headers={"X-Stainless-Helper": "caller-tag"}, |
| 177 |
) |
| 178 |
|
| 179 |
request = respx_mock.calls.last.request |
| 180 |
values = request.headers.get_list(STAINLESS_HELPER_HEADER) |
| 181 |
assert values == ["mcp_tool, caller-tag"] |
| 182 |
assert json.loads(request.content)["tools"] == [tool.to_dict()] |
| 183 |
|
| 184 |
async def test_file_upload_tag_is_appended_not_clobbered( |
| 185 |
self, async_client: AsyncAnthropic, respx_mock: respx.MockRouter |
| 186 |
) -> None: |
| 187 |
respx_mock.post("/v1/files").mock(return_value=httpx2.Response(200, json=_file_json())) |
| 188 |
|
| 189 |
file = _TaggedTuple(("data.json", b"{}", "application/json")) |
| 190 |
tag_helper(file, "mcp_resource_to_file") |
| 191 |
await async_client.files.upload(file=file, extra_headers={"X-Stainless-Helper": "caller-tag"}) |
| 192 |
|
| 193 |
request = respx_mock.calls.last.request |
| 194 |
values = request.headers.get_list(STAINLESS_HELPER_HEADER) |
| 195 |
assert values == ["mcp_resource_to_file, caller-tag"] |
| 196 |
|
| 197 |
@pytest.mark.skipif(_compat.PYDANTIC_V1, reason="parse() response post-parser is pydantic-v2 only") |
| 198 |
async def test_parse_sends_single_header_line( |
| 199 |
self, async_client: AsyncAnthropic, respx_mock: respx.MockRouter |
| 200 |
) -> None: |
| 201 |
respx_mock.post("/v1/messages").mock(return_value=httpx2.Response(200, json=_message_json())) |
| 202 |
|
| 203 |
await async_client.beta.messages.parse( |
| 204 |
model="claude-sonnet-4-5", |
| 205 |
max_tokens=16, |
| 206 |
messages=[{"role": "user", "content": "hello"}], |
| 207 |
tools=[_Tool()], |
| 208 |
) |
| 209 |
|
| 210 |
request = respx_mock.calls.last.request |
| 211 |
values = request.headers.get_list(STAINLESS_HELPER_HEADER) |
| 212 |
assert values == ["beta.messages.parse"] |
| 213 |
assert json.loads(request.content)["tools"] == [_Tool().to_dict()] |
| 214 |
|
| 215 |
async def test_count_tokens_takes_a_tool_object( |
| 216 |
self, async_client: AsyncAnthropic, respx_mock: respx.MockRouter |
| 217 |
) -> None: |
| 218 |
respx_mock.post("/v1/messages/count_tokens").mock(return_value=httpx2.Response(200, json={"input_tokens": 3})) |
| 219 |
result = await async_client.beta.messages.count_tokens( |
| 220 |
model="claude-sonnet-4-5", messages=[{"role": "user", "content": "hello"}], tools=[_Tool()] |
| 221 |
) |
| 222 |
assert result.input_tokens == 3 |
| 223 |
assert json.loads(respx_mock.calls.last.request.content)["tools"] == [_Tool().to_dict()] |
| 224 |
|
| 225 |
@pytest.mark.skipif(_compat.PYDANTIC_V1, reason="parse() response post-parser is pydantic-v2 only") |
| 226 |
async def test_parse_merges_caller_extra_headers( |
| 227 |
self, async_client: AsyncAnthropic, respx_mock: respx.MockRouter |
| 228 |
) -> None: |
| 229 |
respx_mock.post("/v1/messages").mock(return_value=httpx2.Response(200, json=_message_json())) |
| 230 |
|
| 231 |
await async_client.beta.messages.parse( |
| 232 |
model="claude-sonnet-4-5", |
| 233 |
max_tokens=16, |
| 234 |
messages=[{"role": "user", "content": "hello"}], |
| 235 |
betas=["fake-beta-2026-01-01"], |
| 236 |
user_profile_id="upi_123", |
| 237 |
extra_headers={"X-Custom": "1", "X-Stainless-Helper": "caller-tag"}, |
| 238 |
) |
| 239 |
|
| 240 |
headers = respx_mock.calls.last.request.headers |
| 241 |
assert headers["anthropic-beta"] == "fake-beta-2026-01-01,structured-outputs-2025-12-15" |
| 242 |
assert headers["anthropic-user-profile-id"] == "upi_123" |
| 243 |
assert headers["X-Custom"] == "1" |
| 244 |
assert headers.get_list(STAINLESS_HELPER_HEADER) == ["beta.messages.parse, caller-tag"] |
| 245 |
|
| 246 |
@pytest.mark.skipif(_compat.PYDANTIC_V1, reason="parse() response post-parser is pydantic-v2 only") |
| 247 |
async def test_parse_caller_beta_header_overrides( |
| 248 |
self, async_client: AsyncAnthropic, respx_mock: respx.MockRouter |
| 249 |
) -> None: |
| 250 |
respx_mock.post("/v1/messages").mock(return_value=httpx2.Response(200, json=_message_json())) |
| 251 |
|
| 252 |
await async_client.beta.messages.parse( |
| 253 |
model="claude-sonnet-4-5", |
| 254 |
max_tokens=16, |
| 255 |
messages=[{"role": "user", "content": "hello"}], |
| 256 |
extra_headers={"anthropic-beta": "explicit-only"}, |
| 257 |
) |
| 258 |
|
| 259 |
headers = respx_mock.calls.last.request.headers |
| 260 |
assert headers["anthropic-beta"] == "explicit-only" |