Normalize Cursor Anthropic tool blocks on OpenAI /v1/chat/completions endpoint
Summary
Cursor in agent / tool mode sends Anthropic-native content blocks to the OpenAI /v1/chat/completions endpoint instead of OpenAI-format tool messages. ConvertOpenAIRequestToClaude assumes valid OpenAI shapes, so these payloads are dropped, producing invalid Claude requests and broken tool calling. Same root cause as #1165.
I opened PR #3804 with a tested fix, but it's blocked by the translator-path-guard CI gate (changes under internal/translator/** are not allowed in PRs). Per that policy, I'm filing this issue so the maintenance team can apply the change. PR #3804 contains ready-to-merge, tested reference code.
Repro
- Point Cursor (agent mode, OpenAI-compatible endpoint) at CLIProxyAPI's
/v1/chat/completionsbacked by Claude over OAuth. - Trigger a tool call (e.g. file read/edit in agent mode).
- Cursor sends:
user.contentarrays containing{ "type": "tool_result", "tool_use_id": ..., "content": ... }assistant.contentarrays containing{ "type": "tool_use", "id": ..., "name": ..., "input": {...} }- bare tool definitions
{ "name", "description", "input_schema" }(notype: "function"wrapper)
- Result: errors like
messages.N: user messages must have non-empty contentor silently broken tool calling.
Also reported on the Cursor forum: "Wrong tools handling on OpenAI compatible endpoint".
Proposed fix
Add normalizeAnthropicRequestBlocks, a pre-processing pass at the top of ConvertOpenAIRequestToClaude (in internal/translator/claude/openai/chat-completions/claude_openai_request.go) that rewrites Anthropic-native shapes into standard OpenAI shapes before the existing translation runs:
usercontenttool_resultblocks → standalonerole:"tool"messages (tool_call_id,content); sibling text preserved as a trailingusermessage.assistantcontenttool_useblocks →assistant.tool_calls[].function(text blocks merged intocontent).- bare
{ name, description, input_schema }tools →{ type:"function", function:{ name, description, parameters } }.
Standard OpenAI payloads are detected via anthropicBlocksPresent and pass through untouched (no behavior change for existing clients). Typed Anthropic server tools (e.g. web_search_20250305) are left untouched by the normalizer.
Why this matters
Without this, Cursor users must run an external request-rewriting proxy/shim in front of CLIProxyAPI to use agent mode with Claude over OAuth. This fix makes the OpenAI endpoint accept Cursor's payloads natively.
Tests (in PR #3804)
claude_openai_normalize_test.go:
TestConvertOpenAIRequestToClaude_CursorToolResultBlockTestConvertOpenAIRequestToClaude_CursorToolResultWithTextTestConvertOpenAIRequestToClaude_BareAnthropicToolsTestConvertOpenAIRequestToClaude_StandardOpenAIUnchangedTestNormalizeAnthropicRequestBlocks_TypedToolNotWrapped
go test ./internal/translator/claude/openai/chat-completions/...
go build ./internal/translator/...
go vet ./internal/translator/claude/openai/chat-completions/...
Full proposed diff (also in PR #3804)
diff --git a/internal/translator/claude/openai/chat-completions/claude_openai_normalize_test.go b/internal/translator/claude/openai/chat-completions/claude_openai_normalize_test.go
new file mode 100644
index 0000000000..7d0993c74a
--- /dev/null
+++ b/internal/translator/claude/openai/chat-completions/claude_openai_normalize_test.go
@@ -0,0 +1,227 @@
+package chat_completions
+
+import (
+ "testing"
+
+ "github.com/tidwall/gjson"
+)
+
+// Cursor agent mode sends Anthropic-native tool_use / tool_result blocks and
+// bare tool definitions to the OpenAI Chat Completions endpoint. These tests
+// verify normalizeAnthropicRequestBlocks rewrites them into standard OpenAI
+// shapes so the existing translation produces a valid Claude request.
+
+func TestConvertOpenAIRequestToClaude_CursorToolResultBlock(t *testing.T) {
+ inputJSON := `{
+ "model": "claude-sonnet-4-5",
+ "messages": [
+ {"role": "user", "content": "list files"},
+ {
+ "role": "assistant",
+ "content": [
+ {"type": "text", "text": "Let me check."},
+ {"type": "tool_use", "id": "toolu_1", "name": "list_dir", "input": {"path": "."}}
+ ]
+ },
+ {
+ "role": "user",
+ "content": [
+ {"type": "tool_result", "tool_use_id": "toolu_1", "content": "a.txt\nb.txt"}
+ ]
+ }
+ ]
+ }`
+
+ result := ConvertOpenAIRequestToClaude("claude-sonnet-4-5", []byte(inputJSON), false)
+ resultJSON := gjson.ParseBytes(result)
+ messages := resultJSON.Get("messages").Array()
+
+ if len(messages) != 3 {
+ t.Fatalf("Expected 3 messages, got %d. Messages: %s", len(messages), resultJSON.Get("messages").Raw)
+ }
+
+ // assistant message must carry a tool_use block
+ asst := messages[1]
+ if got := asst.Get("role").String(); got != "assistant" {
+ t.Fatalf("Expected messages[1].role assistant, got %q", got)
+ }
+ toolUse := asst.Get("content.#(type==tool_use)")
+ if !toolUse.Exists() {
+ t.Fatalf("Expected a tool_use block in assistant message, got: %s", asst.Raw)
+ }
+ if got := toolUse.Get("id").String(); got != "toolu_1" {
+ t.Fatalf("Expected tool_use id toolu_1, got %q", got)
+ }
+ if got := toolUse.Get("name").String(); got != "list_dir" {
+ t.Fatalf("Expected tool_use name list_dir, got %q", got)
+ }
+ if got := toolUse.Get("input.path").String(); got != "." {
+ t.Fatalf("Expected tool_use input.path '.', got %q", got)
+ }
+
+ // the tool_result must become a user message with a tool_result block
+ toolResultMsg := messages[2]
+ if got := toolResultMsg.Get("role").String(); got != "user" {
+ t.Fatalf("Expected messages[2].role user, got %q", got)
+ }
+ tr := toolResultMsg.Get("content.0")
+ if got := tr.Get("type").String(); got != "tool_result" {
+ t.Fatalf("Expected tool_result block, got %q (%s)", got, toolResultMsg.Raw)
+ }
+ if got := tr.Get("tool_use_id").String(); got != "toolu_1" {
+ t.Fatalf("Expected tool_use_id toolu_1, got %q", got)
+ }
+ if got := tr.Get("content").String(); got != "a.txt\nb.txt" {
+ t.Fatalf("Expected tool_result content, got %q", got)
+ }
+}
+
+func TestConvertOpenAIRequestToClaude_CursorToolResultWithText(t *testing.T) {
+ // A user turn that mixes a tool_result with a follow-up text instruction.
+ inputJSON := `{
+ "model": "claude-sonnet-4-5",
+ "messages": [
+ {
+ "role": "user",
+ "content": [
+ {"type": "tool_result", "tool_use_id": "toolu_9", "content": "done"},
+ {"type": "text", "text": "now summarize"}
+ ]
+ }
+ ]
+ }`
+
+ result := ConvertOpenAIRequestToClaude("claude-sonnet-4-5", []byte(inputJSON), false)
+ resultJSON := gjson.ParseBytes(result)
+ messages := resultJSON.Get("messages").Array()
+
+ if len(messages) != 2 {
+ t.Fatalf("Expected 2 messages (tool_result + user text), got %d: %s", len(messages), resultJSON.Get("messages").Raw)
+ }
+
+ if got := messages[0].Get("content.0.type").String(); got != "tool_result" {
+ t.Fatalf("Expected first message tool_result, got %q", got)
+ }
+ if got := messages[1].Get("content.0.text").String(); got != "now summarize" {
+ t.Fatalf("Expected trailing user text 'now summarize', got %q", got)
+ }
+}
+
+func TestConvertOpenAIRequestToClaude_BareAnthropicTools(t *testing.T) {
+ inputJSON := `{
+ "model": "claude-sonnet-4-5",
+ "messages": [{"role": "user", "content": "hi"}],
+ "tools": [
+ {
+ "name": "read_file",
+ "description": "Read a file",
+ "input_schema": {"type": "object", "properties": {"path": {"type": "string"}}}
+ }
+ ]
+ }`
+
+ result := ConvertOpenAIRequestToClaude("claude-sonnet-4-5", []byte(inputJSON), false)
+ resultJSON := gjson.ParseBytes(result)
+ tools := resultJSON.Get("tools").Array()
+
+ if len(tools) != 1 {
+ t.Fatalf("Expected 1 tool, got %d: %s", len(tools), resultJSON.Get("tools").Raw)
+ }
+ tool := tools[0]
+ if got := tool.Get("name").String(); got != "read_file" {
+ t.Fatalf("Expected tool name read_file, got %q", got)
+ }
+ if got := tool.Get("description").String(); got != "Read a file" {
+ t.Fatalf("Expected tool description, got %q", got)
+ }
+ if got := tool.Get("input_schema.properties.path.type").String(); got != "string" {
+ t.Fatalf("Expected input_schema preserved, got: %s", tool.Raw)
+ }
+}
+
+func TestNormalizeAnthropicRequestBlocks_TypedToolNotWrapped(t *testing.T) {
+ // Typed Anthropic server tools (type present, not "function") must NOT be
+ // rewritten into OpenAI function tools by the normalizer; only bare tools
+ // (no "type") are wrapped. This guards against corrupting server tools like
+ // web_search_20250305 into a wrong custom tool with no schema.
+ inputJSON := `{
+ "model": "claude-sonnet-4-5",
+ "messages": [{"role": "user", "content": "search"}],
+ "tools": [
+ {"type": "web_search_20250305", "name": "web_search", "max_uses": 5},
+ {"name": "read_file", "description": "Read a file", "input_schema": {"type": "object"}}
+ ]
+ }`
+
+ normalized := normalizeAnthropicRequestBlocks([]byte(inputJSON))
+ normJSON := gjson.ParseBytes(normalized)
+ tools := normJSON.Get("tools").Array()
+
+ if len(tools) != 2 {
+ t.Fatalf("Expected 2 tools after normalize, got %d: %s", len(tools), normJSON.Get("tools").Raw)
+ }
+
+ // Typed server tool kept verbatim (still its original type, not "function").
+ typed := normJSON.Get(`tools.#(name=="web_search")`)
+ if !typed.Exists() {
+ t.Fatalf("Expected web_search tool preserved, got: %s", normJSON.Get("tools").Raw)
+ }
+ if got := typed.Get("type").String(); got != "web_search_20250305" {
+ t.Fatalf("Expected typed tool type preserved as web_search_20250305, got %q (%s)", got, typed.Raw)
+ }
+ if got := typed.Get("max_uses").Int(); got != 5 {
+ t.Fatalf("Expected typed tool fields preserved (max_uses=5), got %d", got)
+ }
+
+ // Bare tool wrapped into OpenAI function shape.
+ bare := normJSON.Get(`tools.#(function.name=="read_file")`)
+ if !bare.Exists() {
+ t.Fatalf("Expected read_file wrapped into function tool, got: %s", normJSON.Get("tools").Raw)
+ }
+ if got := bare.Get("type").String(); got != "function" {
+ t.Fatalf("Expected wrapped tool type function, got %q", got)
+ }
+ if !bare.Get("function.parameters").Exists() {
+ t.Fatalf("Expected wrapped tool parameters, got: %s", bare.Raw)
+ }
+}
+
+func TestConvertOpenAIRequestToClaude_StandardOpenAIUnchanged(t *testing.T) {
+ // A normal OpenAI payload must pass through normalization untouched.
+ inputJSON := `{
+ "model": "claude-sonnet-4-5",
+ "messages": [
+ {
+ "role": "assistant",
+ "content": "",
+ "tool_calls": [
+ {"id": "call_1", "type": "function", "function": {"name": "do_work", "arguments": "{\"a\":1}"}}
+ ]
+ },
+ {"role": "tool", "tool_call_id": "call_1", "content": "ok"}
+ ],
+ "tools": [
+ {"type": "function", "function": {"name": "do_work", "description": "d", "parameters": {"type": "object"}}}
+ ]
+ }`
+
+ result := ConvertOpenAIRequestToClaude("claude-sonnet-4-5", []byte(inputJSON), false)
+ resultJSON := gjson.ParseBytes(result)
+ messages := resultJSON.Get("messages").Array()
+
+ if len(messages) != 2 {
+ t.Fatalf("Expected 2 messages, got %d: %s", len(messages), resultJSON.Get("messages").Raw)
+ }
+ if got := messages[0].Get("content.0.type").String(); got != "tool_use" {
+ t.Fatalf("Expected assistant tool_use, got %q", got)
+ }
+ if got := messages[0].Get("content.0.id").String(); got != "call_1" {
+ t.Fatalf("Expected tool_use id call_1, got %q", got)
+ }
+ if got := messages[1].Get("content.0.type").String(); got != "tool_result" {
+ t.Fatalf("Expected tool_result, got %q", got)
+ }
+ if got := resultJSON.Get("tools.0.name").String(); got != "do_work" {
+ t.Fatalf("Expected tool do_work, got %q", got)
+ }
+}
diff --git a/internal/translator/claude/openai/chat-completions/claude_openai_request.go b/internal/translator/claude/openai/chat-completions/claude_openai_request.go
index bad56d1273..d3a9ef0955 100644
--- a/internal/translator/claude/openai/chat-completions/claude_openai_request.go
+++ b/internal/translator/claude/openai/chat-completions/claude_openai_request.go
@@ -44,7 +44,12 @@ var (
// Returns:
// - []byte: The transformed request data in Claude Code API format
func ConvertOpenAIRequestToClaude(modelName string, inputRawJSON []byte, stream bool) []byte {
- rawJSON := inputRawJSON
+ // Some OpenAI-compatible clients (notably Cursor in agent/tool mode) send
+ // Anthropic-native content blocks (tool_use / tool_result) and bare tool
+ // definitions to the OpenAI Chat Completions endpoint. Those payloads are not
+ // valid OpenAI format, so normalize them to standard OpenAI shape before the
+ // regular translation below runs.
+ rawJSON := normalizeAnthropicRequestBlocks(inputRawJSON)
if account == "" {
u, _ := uuid.NewRandom()
@@ -330,6 +335,227 @@ func ConvertOpenAIRequestToClaude(modelName string, inputRawJSON []byte, stream
return out
}
+// normalizeAnthropicRequestBlocks rewrites Anthropic-native message and tool
+// shapes into standard OpenAI Chat Completions shapes. It is a no-op for
+// already-valid OpenAI payloads.
+//
+// Conversions:
+// 1. user message content with tool_result blocks -> separate role:"tool"
+// messages ({tool_call_id, content}). Any sibling text blocks are kept as a
+// trailing role:"user" message.
+// 2. assistant message content with tool_use blocks -> assistant message with
+// tool_calls[].function (and text blocks merged into content).
+// 3. bare tool definitions ({name, description, input_schema}) -> wrapped
+// {type:"function", function:{name, description, parameters}}.
+func normalizeAnthropicRequestBlocks(rawJSON []byte) []byte {
+ root := gjson.ParseBytes(rawJSON)
+
+ if !anthropicBlocksPresent(root) {
+ return rawJSON
+ }
+
+ out := rawJSON
+
+ // Rebuild messages array if any message carries Anthropic content blocks.
+ if messages := root.Get("messages"); messages.Exists() && messages.IsArray() {
+ newMessages := "[]"
+ messages.ForEach(func(_, message gjson.Result) bool {
+ role := message.Get("role").String()
+ content := message.Get("content")
+
+ if !content.IsArray() || !messageHasAnthropicBlocks(content) {
+ newMessages, _ = sjson.SetRaw(newMessages, "-1", message.Raw)
+ return true
+ }
+
+ switch role {
+ case "user":
+ textParts := make([]string, 0)
+ toolResults := make([]gjson.Result, 0)
+ passthrough := make([]gjson.Result, 0)
+ content.ForEach(func(_, block gjson.Result) bool {
+ switch block.Get("type").String() {
+ case "tool_result":
+ toolResults = append(toolResults, block)
+ case "text":
+ if t := block.Get("text").String(); t != "" {
+ textParts = append(textParts, t)
+ }
+ default:
+ passthrough = append(passthrough, block)
+ }
+ return true
+ })
+
+ // tool_result blocks become standalone role:"tool" messages so
+ // the downstream translator pairs them with the prior tool_calls.
+ for _, tr := range toolResults {
+ toolMsg := `{"role":"tool","tool_call_id":"","content":""}`
+ toolMsg, _ = sjson.Set(toolMsg, "tool_call_id", tr.Get("tool_use_id").String())
+ trContent := tr.Get("content")
+ if trContent.IsArray() {
+ toolMsg, _ = sjson.SetRaw(toolMsg, "content", trContent.Raw)
+ } else {
+ toolMsg, _ = sjson.Set(toolMsg, "content", flattenAnthropicToolResultText(trContent))
+ }
+ newMessages, _ = sjson.SetRaw(newMessages, "-1", toolMsg)
+ }
+
+ // Remaining text / passthrough parts stay as a user message.
+ if len(textParts) > 0 || len(passthrough) > 0 {
+ userMsg := `{"role":"user","content":[]}`
+ for _, t := range textParts {
+ textPart := `{"type":"text","text":""}`
+ textPart, _ = sjson.Set(textPart, "text", t)
+ userMsg, _ = sjson.SetRaw(userMsg, "content.-1", textPart)
+ }
+ for _, p := range passthrough {
+ userMsg, _ = sjson.SetRaw(userMsg, "content.-1", p.Raw)
+ }
+ newMessages, _ = sjson.SetRaw(newMessages, "-1", userMsg)
+ }
+
+ case "assistant":
+ textParts := make([]string, 0)
+ toolUses := make([]gjson.Result, 0)
+ content.ForEach(func(_, block gjson.Result) bool {
+ switch block.Get("type").String() {
+ case "tool_use":
+ toolUses = append(toolUses, block)
+ case "text":
+ if t := block.Get("text").String(); t != "" {
+ textParts = append(textParts, t)
+ }
+ }
+ return true
+ })
+
+ asstMsg := `{"role":"assistant","content":""}`
+ asstMsg, _ = sjson.Set(asstMsg, "content", strings.Join(textParts, ""))
+ if len(toolUses) > 0 {
+ asstMsg, _ = sjson.SetRaw(asstMsg, "tool_calls", "[]")
+ for _, tu := range toolUses {
+ toolCall := `{"id":"","type":"function","function":{"name":"","arguments":"{}"}}`
+ toolCall, _ = sjson.Set(toolCall, "id", tu.Get("id").String())
+ toolCall, _ = sjson.Set(toolCall, "function.name", tu.Get("name").String())
+ if input := tu.Get("input"); input.Exists() && input.IsObject() {
+ toolCall, _ = sjson.Set(toolCall, "function.arguments", input.Raw)
+ }
+ asstMsg, _ = sjson.SetRaw(asstMsg, "tool_calls.-1", toolCall)
+ }
+ }
+ newMessages, _ = sjson.SetRaw(newMessages, "-1", asstMsg)
+
+ default:
+ newMessages, _ = sjson.SetRaw(newMessages, "-1", message.Raw)
+ }
+ return true
+ })
+ out, _ = sjson.SetRawBytes(out, "messages", []byte(newMessages))
+ }
+
+ // Wrap bare Anthropic tool definitions into OpenAI function tools.
+ // Only tools with NO "type" field are treated as bare custom tools. Typed
+ // Anthropic server tools (e.g. {"type":"web_search_20250305","name":...})
+ // are left untouched so the downstream mapper can handle them correctly.
+ if tools := root.Get("tools"); tools.Exists() && tools.IsArray() && len(tools.Array()) > 0 {
+ needsWrap := false
+ tools.ForEach(func(_, tool gjson.Result) bool {
+ if !tool.Get("type").Exists() && tool.Get("name").Exists() {
+ needsWrap = true
+ return false
+ }
+ return true
+ })
+
+ if needsWrap {
+ newTools := "[]"
+ tools.ForEach(func(_, tool gjson.Result) bool {
+ // Pass through anything that already has a type (OpenAI function
+ // tools and typed Anthropic server tools) unchanged.
+ if tool.Get("type").Exists() {
+ newTools, _ = sjson.SetRaw(newTools, "-1", tool.Raw)
+ return true
+ }
+ wrapped := `{"type":"function","function":{"name":"","description":""}}`
+ wrapped, _ = sjson.Set(wrapped, "function.name", tool.Get("name").String())
+ wrapped, _ = sjson.Set(wrapped, "function.description", tool.Get("description").String())
+ if schema := tool.Get("input_schema"); schema.Exists() {
+ wrapped, _ = sjson.SetRaw(wrapped, "function.parameters", schema.Raw)
+ } else if schema := tool.Get("parameters"); schema.Exists() {
+ wrapped, _ = sjson.SetRaw(wrapped, "function.parameters", schema.Raw)
+ }
+ newTools, _ = sjson.SetRaw(newTools, "-1", wrapped)
+ return true
+ })
+ out, _ = sjson.SetRawBytes(out, "tools", []byte(newTools))
+ }
+ }
+
+ return out
+}
+
+// anthropicBlocksPresent reports whether the request carries any Anthropic-native
+// message content blocks or bare tool definitions.
+func anthropicBlocksPresent(root gjson.Result) bool {
+ if messages := root.Get("messages"); messages.Exists() && messages.IsArray() {
+ found := false
+ messages.ForEach(func(_, message gjson.Result) bool {
+ if messageHasAnthropicBlocks(message.Get("content")) {
+ found = true
+ return false
+ }
+ return true
+ })
+ if found {
+ return true
+ }
+ }
+
+ if tools := root.Get("tools"); tools.Exists() && tools.IsArray() {
+ found := false
+ tools.ForEach(func(_, tool gjson.Result) bool {
+ if !tool.Get("type").Exists() && tool.Get("name").Exists() {
+ found = true
+ return false
+ }
+ return true
+ })
+ if found {
+ return true
+ }
+ }
+
+ return false
+}
+
+// messageHasAnthropicBlocks reports whether a message content array contains
+// tool_use or tool_result blocks.
+func messageHasAnthropicBlocks(content gjson.Result) bool {
+ if !content.IsArray() {
+ return false
+ }
+ found := false
+ content.ForEach(func(_, block gjson.Result) bool {
+ switch block.Get("type").String() {
+ case "tool_use", "tool_result":
+ found = true
+ return false
+ }
+ return true
+ })
+ return found
+}
+
+// flattenAnthropicToolResultText reduces a tool_result content value to a plain
+// string for the non-array case.
+func flattenAnthropicToolResultText(content gjson.Result) string {
+ if content.Type == gjson.String {
+ return content.String()
+ }
+ return content.Raw
+}
+
func convertOpenAIContentPartToClaudePart(part gjson.Result) string {
switch part.Get("type").String() {
case "text":
Refs #1165 · PR #3804
Update (typed server tools now fully handled): The downstream tool mapper in ConvertOpenAIRequestToClaude previously emitted only type=="function" tools, silently dropping typed Anthropic server tools (e.g. web_search_20250305) from the final Claude request. PR #3804 now passes typed server tools through verbatim into the Claude tools array, with an end-to-end test (TestConvertOpenAIRequestToClaude_TypedServerToolPreserved) asserting they survive the full conversion. So this issue's proposed change covers both the normalization step and the final mapping.
Thanks for the detailed report and reference implementation.
Sending Anthropic-native content blocks to the OpenAI Chat Completions endpoint is a client-side protocol error. CLIProxyAPI will not rewrite or correct that invalid client behavior on this endpoint.
Please report this to Cursor so they can send a valid OpenAI Chat Completions payload when using an OpenAI-compatible endpoint.
Community feedback also suggests a possible workaround: alias claude-sonnet-4-5 as 5-4-tennos-edualc. With that alias, Cursor may send the correct OpenAI Chat Completions protocol.