Skip to content

Compress tool outputs, logs, files, and RAG chunks before they reach the LLM. 20% fewer tokens for coding agents, 60-95% fewer tokens for JSON, same answers. Library, proxy, MCP server.

fix(sdk): stop JSON-wrapping structured tool_result content in the Anthropic adapter (#3797)

Shubham Srivastava2e4a60ae3730
diff --git a/sdk/typescript/src/adapters/anthropic.ts b/sdk/typescript/src/adapters/anthropic.ts
index 67d529d2d..11693c7c5 100644
--- a/sdk/typescript/src/adapters/anthropic.ts
+++ b/sdk/typescript/src/adapters/anthropic.ts
@@ -1,6 +1,6 @@
import { compress } from "../compress.js";
-import type { CompressOptions, OpenAIMessage } from "../types.js";
-import type { AssistantMessage, ToolCall } from "../types.js";
+import type { CompressOptions } from "../types.js";
+import { anthropicToOpenAI, openAIToAnthropic } from "../utils/format.js";
/* eslint-disable @typescript-eslint/no-explicit-any */
@@ -11,185 +11,6 @@ interface AnthropicLike {
[key: string]: any;
}
-// Anthropic image block `source` -> OpenAI image_url url string, or null if unconvertible.
-function anthropicImageUrl(source: any): string | null {
- if (!source || typeof source !== "object") return null;
- if (source.type === "base64" && source.media_type && source.data) {
- return `data:${source.media_type};base64,${source.data}`;
- }
- if (source.type === "url" && typeof source.url === "string") return source.url;
- return null;
-}
-
-// OpenAI image_url url -> Anthropic image block. data: URIs become a base64 source; other urls a url source.
-function openAIImageBlock(url: string): any {
- const m = /^data:([^;,]+);base64,(.*)$/s.exec(url);
- if (m) return { type: "image", source: { type: "base64", media_type: m[1], data: m[2] } };
- return { type: "image", source: { type: "url", url } };
-}
-
-/**
- * Convert Anthropic messages to OpenAI format for compression.
- *
- * Anthropic format:
- * { role: 'user' | 'assistant', content: string | ContentBlock[] }
- * ContentBlock = { type: 'text', text } | { type: 'tool_use', ... } | { type: 'tool_result', ... }
- */
-function anthropicToOpenAI(messages: any[]): OpenAIMessage[] {
- const result: OpenAIMessage[] = [];
-
- for (const msg of messages) {
- if (msg.role === "user") {
- if (typeof msg.content === "string") {
- result.push({ role: "user", content: msg.content });
- } else if (Array.isArray(msg.content)) {
- const toolResults = msg.content.filter(
- (b: any) => b.type === "tool_result",
- );
- const hasImages = msg.content.some((b: any) => b.type === "image");
-
- if (hasImages) {
- const parts = msg.content
- .filter((b: any) => b.type === "text" || b.type === "image")
- .map((b: any) => {
- if (b.type === "text") return { type: "text" as const, text: b.text };
- const url = anthropicImageUrl(b.source);
- return url ? { type: "image_url" as const, image_url: { url } } : null;
- })
- .filter((p: any): p is NonNullable<typeof p> => p !== null);
-
- if (parts.length > 0) {
- result.push({ role: "user", content: parts });
- }
- } else {
- const textBlocks = msg.content.filter((b: any) => b.type === "text");
- if (textBlocks.length > 0) {
- result.push({
- role: "user",
- content: textBlocks.map((b: any) => b.text).join("\n"),
- });
- }
- }
- for (const tr of toolResults) {
- result.push({
- role: "tool",
- content:
- typeof tr.content === "string"
- ? tr.content
- : JSON.stringify(tr.content),
- tool_call_id: tr.tool_use_id,
- });
- }
- }
- continue;
- }
-
- if (msg.role === "assistant") {
- if (typeof msg.content === "string") {
- result.push({ role: "assistant", content: msg.content });
- } else if (Array.isArray(msg.content)) {
- const textBlocks = msg.content.filter((b: any) => b.type === "text");
- const toolUseBlocks = msg.content.filter(
- (b: any) => b.type === "tool_use",
- );
-
- const content =
- textBlocks.length > 0
- ? textBlocks.map((b: any) => b.text).join("\n")
- : null;
-
- const openaiMsg: AssistantMessage = { role: "assistant", content };
- if (toolUseBlocks.length > 0) {
- openaiMsg.tool_calls = toolUseBlocks.map(
- (b: any): ToolCall => ({
- id: b.id,
- type: "function",
- function: {
- name: b.name,
- arguments: JSON.stringify(b.input),
- },
- }),
- );
- }
- result.push(openaiMsg);
- }
- continue;
- }
- }
-
- return result;
-}
-
-/**
- * Convert compressed OpenAI messages back to Anthropic format.
- */
-function openAIToAnthropic(messages: OpenAIMessage[]): any[] {
- const result: any[] = [];
-
- for (const msg of messages) {
- if (msg.role === "user") {
- if (typeof msg.content === "string") {
- result.push({ role: "user", content: msg.content });
- } else if (Array.isArray(msg.content)) {
- result.push({
- role: "user",
- content: msg.content.map((p) => {
- if (p.type === "text") return { type: "text", text: p.text };
- if (p.type === "image_url") return openAIImageBlock(p.image_url.url);
- return { type: "text", text: "" };
- }),
- });
- }
- continue;
- }
-
- if (msg.role === "assistant") {
- const blocks: any[] = [];
- if (msg.content) blocks.push({ type: "text", text: msg.content });
- if (msg.tool_calls) {
- for (const tc of msg.tool_calls) {
- blocks.push({
- type: "tool_use",
- id: tc.id,
- name: tc.function.name,
- input: JSON.parse(tc.function.arguments),
- });
- }
- }
- result.push({
- role: "assistant",
- content:
- blocks.length === 1 && blocks[0].type === "text"
- ? blocks[0].text
- : blocks,
- });
- continue;
- }
-
- if (msg.role === "tool") {
- result.push({
- role: "user",
- content: [
- {
- type: "tool_result",
- tool_use_id: msg.tool_call_id,
- content: msg.content,
- },
- ],
- });
- continue;
- }
-
- if (msg.role === "system") {
- // System messages are handled separately in Anthropic (as `system` param)
- // Pass through as user message if it appears in the messages array
- result.push({ role: "user", content: msg.content });
- }
- }
-
- return result;
-}
-
/**
* Wrap an Anthropic client to auto-compress messages before each request.
*
diff --git a/sdk/typescript/test/adapters/anthropic.test.ts b/sdk/typescript/test/adapters/anthropic.test.ts
index 89de634e2..b78d530af 100644
--- a/sdk/typescript/test/adapters/anthropic.test.ts
+++ b/sdk/typescript/test/adapters/anthropic.test.ts
@@ -190,6 +190,52 @@ describe("withHeadroom (Anthropic)", () => {
expect(createArgs.messages.length).toBeGreaterThan(0);
});
+ it("flattens array-content tool_result blocks to text for the compression request", async () => {
+ mockFetch.mockResolvedValueOnce(mockCompressSuccess());
+
+ const mockCreate = vi.fn().mockResolvedValue({});
+ const fakeClient = { messages: { create: mockCreate } };
+
+ const wrapped = withHeadroom(fakeClient as any, {
+ baseUrl: "http://localhost:8787",
+ });
+
+ await wrapped.messages.create({
+ model: "claude-sonnet-4-5-20250929",
+ messages: [
+ { role: "user", content: "run the query" },
+ {
+ role: "assistant",
+ content: [
+ { type: "tool_use", id: "tu_1", name: "query", input: { sql: "select 1" } },
+ ],
+ },
+ {
+ role: "user",
+ content: [
+ {
+ type: "tool_result",
+ tool_use_id: "tu_1",
+ content: [
+ { type: "text", text: "row 1" },
+ { type: "text", text: "row 2" },
+ ],
+ },
+ ],
+ },
+ ],
+ max_tokens: 1024,
+ });
+
+ // The proxy must receive the tool output as text, not a JSON-encoded block array.
+ const body = JSON.parse(mockFetch.mock.calls[0][1].body);
+ expect(body.messages[2]).toEqual({
+ role: "tool",
+ content: "row 1\nrow 2",
+ tool_call_id: "tu_1",
+ });
+ });
+
it("preserves image blocks instead of dropping them during compression", async () => {
mockFetch.mockResolvedValueOnce(mockCompressSuccess());
diff --git a/sdk/typescript/test/utils/format.test.ts b/sdk/typescript/test/utils/format.test.ts
index e43b3c216..f6763156a 100644
--- a/sdk/typescript/test/utils/format.test.ts
+++ b/sdk/typescript/test/utils/format.test.ts
@@ -367,6 +367,27 @@ describe("anthropicToOpenAI", () => {
]);
expect(result).toEqual([]);
});
+
+ it("flattens array-content tool_result blocks to newline-joined text", () => {
+ const result = anthropicToOpenAI([
+ {
+ role: "user",
+ content: [
+ {
+ type: "tool_result",
+ tool_use_id: "tu_1",
+ content: [
+ { type: "text", text: "row 1" },
+ { type: "text", text: "row 2" },
+ ],
+ },
+ ],
+ },
+ ]);
+ expect(result).toEqual([
+ { role: "tool", content: "row 1\nrow 2", tool_call_id: "tu_1" },
+ ]);
+ });
});
describe("openAIToAnthropic", () => {