Skip to content

Use Claude Code, Codex, VSCode, Pi, and OpenCode (and 6 other harnesses) for free (1.3B+ free tokens) from your terminal, app, IDE, or phone, and now from the browser with native browser sessions (multi-harness + multi-model) like OpenClaw (voice supported + ToS friendly)

Python

Fix Codex namespace Responses tools

Alishahryar1dcc4b50aae05
diff --git a/core/openai_responses/conversion.py b/core/openai_responses/conversion.py
index d9c7d656..e0d62094 100644
--- a/core/openai_responses/conversion.py
+++ b/core/openai_responses/conversion.py
@@ -2,12 +2,19 @@
from __future__ import annotations
+import hashlib
import json
+import re
import time
import uuid
from collections.abc import Mapping
from typing import Any
+_MAX_ANTHROPIC_TOOL_NAME_LEN = 64
+_NAMESPACE_TOOL_SEPARATOR = "__"
+_UNSUPPORTED_PASSIVE_TOOL_TYPES = frozenset({"web_search", "image_generation"})
+_INVALID_TOOL_NAME_CHARS = re.compile(r"[^A-Za-z0-9_-]+")
+
class ResponsesConversionError(ValueError):
"""Raised when a Responses request cannot be converted deterministically."""
@@ -71,10 +78,14 @@ def anthropic_message_response_to_openai_response(
if block_type == "text":
text_parts.append(str(block.get("text", "")))
elif block_type == "tool_use":
+ namespace, name = responses_tool_identity_from_anthropic_name(
+ request, str(block.get("name", ""))
+ )
output.append(
_function_call_item(
block_id=str(block.get("id", "") or _new_call_id()),
- name=str(block.get("name", "")),
+ name=name,
+ namespace=namespace,
arguments=json.dumps(block.get("input") or {}),
status="completed",
)
@@ -134,6 +145,8 @@ def _append_input_item(
_append_message_item(role, item.get("content", ""), messages, system_parts)
return
if item_type == "function_call":
+ namespace = _optional_str(item.get("namespace"))
+ name = _required_str(item.get("name"), "function_call.name")
messages.append(
{
"role": "assistant",
@@ -141,7 +154,9 @@ def _append_input_item(
{
"type": "tool_use",
"id": _call_id_from_item(item),
- "name": _required_str(item.get("name"), "function_call.name"),
+ "name": responses_tool_name_to_anthropic_name(
+ name, namespace=namespace
+ ),
"input": _parse_arguments(item.get("arguments")),
}
],
@@ -264,29 +279,64 @@ def _convert_tools(value: Any) -> list[dict[str, Any]] | None:
f"Unsupported Responses tool: {type(tool).__name__}"
)
tool_type = tool.get("type")
+ if tool_type == "function":
+ tools.append(_convert_function_tool(tool, namespace=None))
+ continue
+ if tool_type == "namespace":
+ tools.extend(_convert_namespace_tool(tool))
+ continue
+ if tool_type in _UNSUPPORTED_PASSIVE_TOOL_TYPES:
+ continue
if tool_type != "function":
raise ResponsesConversionError(
f"Unsupported Responses tool type: {tool_type!r}"
)
+ return tools
+
+
+def _convert_namespace_tool(tool: Mapping[str, Any]) -> list[dict[str, Any]]:
+ namespace = _required_str(tool.get("name"), "tool.namespace.name")
+ nested_tools = tool.get("tools")
+ if not isinstance(nested_tools, list):
+ raise ResponsesConversionError(
+ f"Responses namespace tool {namespace!r} tools must be a list"
+ )
- function = tool.get("function")
- source = function if isinstance(function, dict) else tool
- name = _required_str(source.get("name"), "tool.name")
- schema = source.get("parameters")
- if schema is None:
- schema = {"type": "object", "properties": {}}
- if not isinstance(schema, dict):
+ converted_tools: list[dict[str, Any]] = []
+ for nested_tool in nested_tools:
+ if not isinstance(nested_tool, dict):
raise ResponsesConversionError(
- f"Responses tool {name!r} parameters must be an object"
+ f"Unsupported Responses namespace tool: {type(nested_tool).__name__}"
)
- converted: dict[str, Any] = {
- "name": name,
- "input_schema": schema,
- }
- if description := _optional_str(source.get("description")):
- converted["description"] = description
- tools.append(converted)
- return tools
+ nested_tool_type = nested_tool.get("type")
+ if nested_tool_type != "function":
+ raise ResponsesConversionError(
+ f"Unsupported Responses namespace tool type: {nested_tool_type!r}"
+ )
+ converted_tools.append(_convert_function_tool(nested_tool, namespace=namespace))
+ return converted_tools
+
+
+def _convert_function_tool(
+ tool: Mapping[str, Any], *, namespace: str | None
+) -> dict[str, Any]:
+ function = tool.get("function")
+ source = function if isinstance(function, dict) else tool
+ name = _required_str(source.get("name"), "tool.name")
+ schema = source.get("parameters")
+ if schema is None:
+ schema = {"type": "object", "properties": {}}
+ if not isinstance(schema, dict):
+ raise ResponsesConversionError(
+ f"Responses tool {name!r} parameters must be an object"
+ )
+ converted: dict[str, Any] = {
+ "name": responses_tool_name_to_anthropic_name(name, namespace=namespace),
+ "input_schema": schema,
+ }
+ if description := _optional_str(source.get("description")):
+ converted["description"] = description
+ return converted
def _convert_tool_choice(value: Any) -> dict[str, Any] | None:
@@ -299,15 +349,84 @@ def _convert_tool_choice(value: Any) -> dict[str, Any] | None:
if isinstance(value, dict):
choice_type = value.get("type")
if choice_type == "function":
+ namespace = _optional_str(value.get("namespace"))
+ name = _required_str(value.get("name"), "tool_choice.name")
return {
"type": "tool",
- "name": _required_str(value.get("name"), "tool_choice.name"),
+ "name": responses_tool_name_to_anthropic_name(
+ name, namespace=namespace
+ ),
}
if choice_type in {"auto", "any", "tool"}:
return dict(value)
raise ResponsesConversionError(f"Unsupported Responses tool_choice: {value!r}")
+def responses_tool_name_to_anthropic_name(
+ name: str, *, namespace: str | None = None
+) -> str:
+ """Return a deterministic Anthropic tool name for a Responses tool identity."""
+
+ if not namespace:
+ return name
+ combined = (
+ f"{_tool_name_part(namespace)}"
+ f"{_NAMESPACE_TOOL_SEPARATOR}"
+ f"{_tool_name_part(name)}"
+ )
+ if len(combined) <= _MAX_ANTHROPIC_TOOL_NAME_LEN:
+ return combined
+ digest = hashlib.sha1(combined.encode("utf-8")).hexdigest()[:8]
+ prefix_len = _MAX_ANTHROPIC_TOOL_NAME_LEN - len(digest) - 1
+ return f"{combined[:prefix_len]}_{digest}"
+
+
+def responses_tool_identity_from_anthropic_name(
+ request: Mapping[str, Any], anthropic_name: str
+) -> tuple[str | None, str]:
+ """Return the Responses namespace/name represented by an Anthropic tool name."""
+
+ tools = request.get("tools")
+ if not isinstance(tools, list):
+ return None, anthropic_name
+ for tool in tools:
+ if not isinstance(tool, dict):
+ continue
+ tool_type = tool.get("type")
+ if tool_type == "function":
+ source = tool.get("function")
+ function = source if isinstance(source, dict) else tool
+ if (name := _optional_str(function.get("name"))) and (
+ responses_tool_name_to_anthropic_name(name) == anthropic_name
+ ):
+ return None, name
+ continue
+ if tool_type != "namespace":
+ continue
+ namespace = _optional_str(tool.get("name"))
+ nested_tools = tool.get("tools")
+ if not namespace or not isinstance(nested_tools, list):
+ continue
+ for nested_tool in nested_tools:
+ if not isinstance(nested_tool, dict):
+ continue
+ if nested_tool.get("type") != "function":
+ continue
+ source = nested_tool.get("function")
+ function = source if isinstance(source, dict) else nested_tool
+ if (name := _optional_str(function.get("name"))) and (
+ responses_tool_name_to_anthropic_name(name, namespace=namespace)
+ == anthropic_name
+ ):
+ return namespace, name
+ return None, anthropic_name
+
+
+def _tool_name_part(value: str) -> str:
+ normalized = _INVALID_TOOL_NAME_CHARS.sub("_", value).strip("_")
+ return normalized or "tool"
+
+
def _parse_arguments(value: Any) -> dict[str, Any]:
if value is None or value == "":
return {}
@@ -375,10 +494,11 @@ def _function_call_item(
*,
block_id: str,
name: str,
+ namespace: str | None,
arguments: str,
status: str,
) -> dict[str, Any]:
- return {
+ item = {
"id": block_id if block_id.startswith("fc_") else f"fc_{uuid.uuid4().hex[:24]}",
"type": "function_call",
"status": status,
@@ -386,6 +506,9 @@ def _function_call_item(
"name": name,
"arguments": arguments,
}
+ if namespace:
+ item["namespace"] = namespace
+ return item
def _openai_usage(value: Any) -> dict[str, int] | None:
diff --git a/core/openai_responses/sse.py b/core/openai_responses/sse.py
index 023532f3..b21a2db7 100644
--- a/core/openai_responses/sse.py
+++ b/core/openai_responses/sse.py
@@ -9,7 +9,10 @@ from collections.abc import AsyncIterable, AsyncIterator, Mapping
from dataclasses import dataclass, field
from typing import Any
-from .conversion import anthropic_message_response_to_openai_response
+from .conversion import (
+ anthropic_message_response_to_openai_response,
+ responses_tool_identity_from_anthropic_name,
+)
OPENAI_RESPONSES_SSE_HEADERS: dict[str, str] = {
"X-Accel-Buffering": "no",
@@ -146,6 +149,7 @@ class _ToolState:
item_id: str
call_id: str
name: str
+ namespace: str | None = None
argument_parts: list[str] = field(default_factory=list)
@@ -245,11 +249,15 @@ class _ResponsesStreamTransformer:
call_id = str(block.get("id", "") or _new_call_id())
item_id = f"fc_{uuid.uuid4().hex[:24]}"
output_index = len(self._output)
+ namespace, name = responses_tool_identity_from_anthropic_name(
+ self._request, str(block.get("name", ""))
+ )
state = _ToolState(
output_index=output_index,
item_id=item_id,
call_id=call_id,
- name=str(block.get("name", "")),
+ name=name,
+ namespace=namespace,
)
initial_input = block.get("input")
if isinstance(initial_input, dict) and initial_input:
@@ -411,6 +419,8 @@ class _ResponsesStreamTransformer:
"name": state.name,
"arguments": arguments,
}
+ if state.namespace:
+ item["namespace"] = state.namespace
self._output.append(item)
chunks = [
format_response_sse_event(
diff --git a/pyproject.toml b/pyproject.toml
index 9070ccee..44c64596 100644
--- a/pyproject.toml
+++ b/pyproject.toml
@@ -4,7 +4,7 @@ build-backend = "hatchling.build"
[project]
name = "free-claude-code"
-version = "2.1.0"
+version = "2.1.1"
description = "Middleware between Claude Code CLI (Anthropic API) and NVIDIA NIM"
readme = "README.md"
requires-python = ">=3.14.0"
diff --git a/tests/api/test_openai_responses.py b/tests/api/test_openai_responses.py
index 0063d830..ccdffb15 100644
--- a/tests/api/test_openai_responses.py
+++ b/tests/api/test_openai_responses.py
@@ -127,6 +127,49 @@ def test_create_response_tool_stream_emits_function_call() -> None:
assert call["arguments"] == '{"value":"FCC"}'
+def test_create_response_accepts_codex_namespace_tool_request() -> None:
+ provider = FakeProvider(_anthropic_tool_stream(tool_name="mcp__node_repl__js"))
+ app = create_app(lifespan_enabled=False)
+ with (
+ patch("api.dependencies.resolve_provider", return_value=provider),
+ TestClient(app) as client,
+ ):
+ response = client.post(
+ "/v1/responses",
+ json={
+ "model": "nvidia_nim/test-model",
+ "input": "Use JS",
+ "stream": True,
+ "tools": [
+ {"type": "web_search", "external_web_access": True},
+ {"type": "image_generation", "output_format": "png"},
+ {
+ "type": "namespace",
+ "name": "mcp__node_repl",
+ "tools": [
+ {
+ "type": "function",
+ "name": "js",
+ "parameters": {
+ "type": "object",
+ "properties": {"code": {"type": "string"}},
+ },
+ }
+ ],
+ },
+ ],
+ },
+ )
+
+ assert response.status_code == 200
+ routed = provider.requests[0]
+ assert [tool.name for tool in routed.tools] == ["mcp__node_repl__js"]
+ completed = parse_sse_text(response.text)[-1].data["response"]
+ call = completed["output"][0]
+ assert call["namespace"] == "mcp__node_repl"
+ assert call["name"] == "js"
+
+
def test_create_response_unsupported_tool_returns_openai_error(
responses_client: tuple[TestClient, FakeProvider],
) -> None:
@@ -182,7 +225,7 @@ def _anthropic_text_stream(text: str) -> list[str]:
]
-def _anthropic_tool_stream() -> list[str]:
+def _anthropic_tool_stream(tool_name: str = "echo") -> list[str]:
return [
format_sse_event("message_start", {"type": "message_start", "message": {}}),
format_sse_event(
@@ -193,7 +236,7 @@ def _anthropic_tool_stream() -> list[str]:
"content_block": {
"type": "tool_use",
"id": "toolu_1",
- "name": "echo",
+ "name": tool_name,
"input": {},
},
},
diff --git a/tests/core/openai_responses/test_conversion.py b/tests/core/openai_responses/test_conversion.py
index db47854a..10425caa 100644
--- a/tests/core/openai_responses/test_conversion.py
+++ b/tests/core/openai_responses/test_conversion.py
@@ -4,6 +4,7 @@ import pytest
from core.openai_responses import (
ResponsesConversionError,
+ anthropic_message_response_to_openai_response,
responses_request_to_anthropic_payload,
)
@@ -133,6 +134,133 @@ def test_responses_tool_choice_none_disables_forwarded_tools() -> None:
assert "tool_choice" not in payload
+def test_responses_namespace_tools_flatten_for_anthropic() -> None:
+ payload = responses_request_to_anthropic_payload(
+ {
+ "model": "nvidia_nim/test-model",
+ "input": "Use JS",
+ "tools": [
+ {
+ "type": "namespace",
+ "name": "mcp__node_repl",
+ "description": "Node tools",
+ "tools": [
+ {
+ "type": "function",
+ "name": "js",
+ "description": "Run JavaScript",
+ "parameters": {
+ "type": "object",
+ "properties": {"code": {"type": "string"}},
+ "required": ["code"],
+ },
+ }
+ ],
+ }
+ ],
+ "tool_choice": {
+ "type": "function",
+ "namespace": "mcp__node_repl",
+ "name": "js",
+ },
+ }
+ )
+
+ assert payload["tools"] == [
+ {
+ "name": "mcp__node_repl__js",
+ "description": "Run JavaScript",
+ "input_schema": {
+ "type": "object",
+ "properties": {"code": {"type": "string"}},
+ "required": ["code"],
+ },
+ }
+ ]
+ assert payload["tool_choice"] == {"type": "tool", "name": "mcp__node_repl__js"}
+
+
+def test_responses_passive_codex_built_in_tools_are_ignored() -> None:
+ payload = responses_request_to_anthropic_payload(
+ {
+ "model": "nvidia_nim/test-model",
+ "input": "Hello",
+ "tools": [
+ {"type": "web_search", "external_web_access": True},
+ {"type": "image_generation", "output_format": "png"},
+ {
+ "type": "function",
+ "name": "echo",
+ "parameters": {"type": "object", "properties": {}},
+ },
+ ],
+ }
+ )
+
+ assert payload["tools"] == [
+ {"name": "echo", "input_schema": {"type": "object", "properties": {}}}
+ ]
+
+
+def test_responses_namespaced_prior_function_call_flattens_tool_use_name() -> None:
+ payload = responses_request_to_anthropic_payload(
+ {
+ "model": "nvidia_nim/test-model",
+ "input": [
+ {
+ "type": "function_call",
+ "call_id": "call_1",
+ "namespace": "mcp__node_repl",
+ "name": "js",
+ "arguments": '{"code":"1+1"}',
+ },
+ {
+ "type": "function_call_output",
+ "call_id": "call_1",
+ "output": "2",
+ },
+ ],
+ }
+ )
+
+ assert payload["messages"][0]["content"][0]["name"] == "mcp__node_repl__js"
+
+
+def test_anthropic_namespaced_tool_response_restores_responses_namespace() -> None:
+ response = anthropic_message_response_to_openai_response(
+ {
+ "content": [
+ {
+ "type": "tool_use",
+ "id": "toolu_1",
+ "name": "mcp__node_repl__js",
+ "input": {"code": "1+1"},
+ }
+ ]
+ },
+ {
+ "model": "nvidia_nim/test-model",
+ "tools": [
+ {
+ "type": "namespace",
+ "name": "mcp__node_repl",
+ "tools": [
+ {
+ "type": "function",
+ "name": "js",
+ "parameters": {"type": "object", "properties": {}},
+ }
+ ],
+ }
+ ],
+ },
+ )
+
+ call = response["output"][0]
+ assert call["namespace"] == "mcp__node_repl"
+ assert call["name"] == "js"
+
+
def test_responses_unsupported_tool_type_is_clear() -> None:
with pytest.raises(
ResponsesConversionError, match="Unsupported Responses tool type"
diff --git a/tests/core/openai_responses/test_sse.py b/tests/core/openai_responses/test_sse.py
index 7b01f0d0..59f259d1 100644
--- a/tests/core/openai_responses/test_sse.py
+++ b/tests/core/openai_responses/test_sse.py
@@ -56,6 +56,39 @@ async def test_anthropic_tool_stream_converts_to_function_call_item() -> None:
assert function_call["arguments"] == '{"value":"FCC"}'
+async def test_namespaced_anthropic_tool_stream_restores_responses_namespace() -> None:
+ text = await _collect_sse(
+ iter_anthropic_sse_as_openai_responses(
+ _aiter(_anthropic_tool_stream(tool_name="mcp__node_repl__js")),
+ {
+ "model": "nvidia_nim/test-model",
+ "stream": True,
+ "tools": [
+ {
+ "type": "namespace",
+ "name": "mcp__node_repl",
+ "tools": [
+ {
+ "type": "function",
+ "name": "js",
+ "parameters": {"type": "object", "properties": {}},
+ }
+ ],
+ }
+ ],
+ },
+ )
+ )
+
+ events = parse_sse_text(text)
+ completed = events[-1].data["response"]
+ function_call = completed["output"][0]
+ assert function_call["type"] == "function_call"
+ assert function_call["namespace"] == "mcp__node_repl"
+ assert function_call["name"] == "js"
+
+
@pytest.mark.asyncio
async def test_anthropic_error_stream_converts_to_responses_error_event() -> None:
text = await _collect_sse(
@@ -141,7 +174,7 @@ def _anthropic_text_stream(text: str) -> list[str]:
]
-def _anthropic_tool_stream() -> list[str]:
+def _anthropic_tool_stream(tool_name: str = "echo") -> list[str]:
return [
format_sse_event("message_start", {"type": "message_start", "message": {}}),
format_sse_event(
@@ -152,7 +185,7 @@ def _anthropic_tool_stream() -> list[str]:
"content_block": {
"type": "tool_use",
"id": "toolu_1",
- "name": "echo",
+ "name": tool_name,
"input": {},
},
},
diff --git a/uv.lock b/uv.lock
index a2c6e7ea..f1ff7d3f 100644
--- a/uv.lock
+++ b/uv.lock
@@ -561,7 +561,7 @@ wheels = [
[[package]]
name = "free-claude-code"
-version = "2.1.0"
+version = "2.1.1"
source = { editable = "." }
dependencies = [
{ name = "aiohttp" },