Skip to content

feat(util): add Claude tool id and tool_use mapping helpers#1927

Open
shenshuoyaoyouguang wants to merge 1 commit intorouter-for-me:mainfrom
shenshuoyaoyouguang:pr/claude-tool-id-sanitize
Open

feat(util): add Claude tool id and tool_use mapping helpers#1927
shenshuoyaoyouguang wants to merge 1 commit intorouter-for-me:mainfrom
shenshuoyaoyouguang:pr/claude-tool-id-sanitize

Conversation

@shenshuoyaoyouguang
Copy link
Contributor

@shenshuoyaoyouguang shenshuoyaoyouguang commented Mar 7, 2026

Summary

  • add a reusable helper to sanitize Claude-facing tool ids into ^[a-zA-Z0-9_-]+$
  • add a helper to recover ool_use.id -> tool_use.name mappings from Claude request payloads
  • add focused util-level regression coverage for both helpers

Why this PR was narrowed

The repository path guard rejects pull requests that modify internal/translator/.
To keep business value moving without fighting repository policy, this PR now contains only reusable helper functions under internal/util/
.

The translator-specific follow-up has been moved to issue #1930 for the maintenance team.

Business value

  • gives downstream translator and adapter code a shared, tested primitive for Claude tool id compliance
  • preserves the original feature intent in a form that can be reused internally by the maintenance team
  • unblocks CI for this public PR instead of leaving it permanently red on a path policy failure

Tests

  • go test ./internal/util

@gemini-code-assist
Copy link
Contributor

Summary of Changes

Hello, I'm Gemini Code Assist1! I'm currently reviewing this pull request and will post my feedback shortly. In the meantime, here's a summary to help you and other reviewers quickly get up to speed!

This pull request significantly improves the robustness and compatibility of the Claude translator by addressing two key areas: ensuring tool IDs meet strict formatting requirements and maintaining accurate tool name mappings throughout the translation process. These changes prevent errors in tool-using conversations and provide a more consistent experience when interacting with various AI providers through the Claude interface.

Highlights

  • Claude Tool ID Sanitization: Implemented a new utility to sanitize Claude tool IDs, ensuring they conform to stricter provider requirements and prevent downstream request failures.
  • Tool Mapping Preservation: Enhanced translator logic across various providers (Antigravity, Gemini-CLI, Gemini, Codex, OpenAI) to preserve the original tool names when converting Claude requests and responses, addressing issues with broken tool call mapping.
  • Expanded Test Coverage: Added focused regression tests for the updated translator flows, specifically covering Antigravity, Gemini-CLI, Gemini, Codex, and OpenAI, to ensure the new sanitization and mapping logic works as expected.

🧠 New Feature in Public Preview: You can now enable Memory to help Gemini Code Assist learn from your team's feedback. This makes future code reviews more consistent and personalized to your project's style. Click here to enable Memory in your admin console.

Changelog
  • internal/translator/antigravity/claude/antigravity_claude_request.go
    • Updated ConvertClaudeRequestToAntigravity to use a tool name map for recovering original tool names in tool_result content.
  • internal/translator/antigravity/claude/antigravity_claude_request_test.go
    • Added a test case to verify that tool_result correctly uses the original tool name from the message.
  • internal/translator/antigravity/claude/antigravity_claude_response.go
    • Imported the util package.
    • Applied util.SanitizeClaudeToolID to tool IDs during response generation.
  • internal/translator/antigravity/claude/antigravity_claude_response_test.go
    • Imported regexp and gjson packages.
    • Added a test case to ensure streaming Claude tool use IDs are properly sanitized.
  • internal/translator/codex/claude/codex_claude_response.go
    • Imported the util package.
    • Applied util.SanitizeClaudeToolID to tool IDs in both streaming and non-streaming Codex to Claude response conversions.
  • internal/translator/codex/claude/codex_claude_response_test.go
    • Added a new test file.
    • Included tests for sanitizing streaming and non-streaming Claude tool use IDs in Codex responses.
  • internal/translator/gemini-cli/claude/gemini-cli_claude_request.go
    • Imported the util package.
    • Updated ConvertClaudeRequestToCLI to use a tool name map for recovering original tool names in tool_result content.
  • internal/translator/gemini-cli/claude/gemini-cli_claude_request_test.go
    • Added a test case to verify that tool_result correctly uses the original tool name from the message.
  • internal/translator/gemini-cli/claude/gemini-cli_claude_response.go
    • Imported the util package.
    • Applied util.SanitizeClaudeToolID to tool IDs during response generation.
  • internal/translator/gemini-cli/claude/gemini-cli_claude_response_test.go
    • Added a new test file.
    • Included a test for sanitizing Claude tool use IDs in Gemini-CLI responses.
  • internal/translator/gemini/claude/gemini_claude_request.go
    • Imported the util package.
    • Updated ConvertClaudeRequestToGemini to use a tool name map for recovering original tool names in tool_use and tool_result content.
  • internal/translator/gemini/claude/gemini_claude_request_test.go
    • Added a test case to verify that tool_result correctly uses the original tool name from the message.
  • internal/translator/gemini/claude/gemini_claude_response.go
    • Applied util.SanitizeClaudeToolID to tool IDs in both streaming and non-streaming Gemini to Claude response conversions.
  • internal/translator/gemini/claude/gemini_claude_response_test.go
    • Added a new test file.
    • Included tests for sanitizing streaming and non-streaming Claude tool use IDs in Gemini responses.
  • internal/translator/openai/claude/openai_claude_response.go
    • Applied util.SanitizeClaudeToolID to tool IDs in both streaming and non-streaming OpenAI to Claude response conversions.
  • internal/translator/openai/claude/openai_claude_response_test.go
    • Added a new test file.
    • Included tests for sanitizing streaming and non-streaming Claude tool use IDs in OpenAI responses.
  • internal/util/claude_tool_id.go
    • Added a new utility file.
    • Defined SanitizeClaudeToolID function to ensure tool IDs conform to Claude's regex requirements.
  • internal/util/claude_tool_id_test.go
    • Added a new test file.
    • Included tests for the SanitizeClaudeToolID function, covering invalid characters and empty results.
  • internal/util/translator.go
    • Added ToolUseNameMapFromClaudeRequest function to extract tool ID to tool name mappings from Claude requests.
Activity
  • The author, shenshuoyaoyouguang, has run go test ./internal/util ./internal/translator/... to validate the changes.
Using Gemini Code Assist

The full guide for Gemini Code Assist can be found on our documentation page, here are some quick tips.

Invoking Gemini

You can request assistance from Gemini at any point by creating a comment using either /gemini <command> or @gemini-code-assist <command>. Below is a summary of the supported commands on the current page.

Feature Command Description
Code Review /gemini review Performs a code review for the current pull request in its current state.
Pull Request Summary /gemini summary Provides a summary of the current pull request in its current state.
Comment @gemini-code-assist Responds in comments when explicitly tagged, both in pull request comments and review comments.
Help /gemini help Displays a list of available commands.

Customization

To customize Gemini Code Assist for GitHub experience, repository maintainers can create a configuration file and/or provide a custom code review style guide (such as PEP-8 for Python) by creating and adding files to a .gemini/ folder in the base of the repository. Detailed instructions can be found here.

Limitations & Feedback

Gemini Code Assist may make mistakes. Please leave feedback on any instances where its feedback is incorrect or counter productive. You can react with 👍 and 👎 on @gemini-code-assist comments. If you're interested in giving your feedback about your experience with Gemini Code Assist for Github and other Google products, sign up here.

You can also get AI-powered code generation, chat, as well as code reviews directly in the IDE at no cost with the Gemini Code Assist IDE Extension.

Footnotes

  1. Review the Privacy Notices, Generative AI Prohibited Use Policy, Terms of Service, and learn how to configure Gemini Code Assist in GitHub here. Gemini can make mistakes, so double check it and use code with caution.

Copy link
Contributor

@gemini-code-assist gemini-code-assist bot left a comment

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Code Review

This pull request introduces important fixes for handling Claude tool IDs by sanitizing them and preserving tool name mappings across different translators. The changes are well-supported by new regression tests.

My review identified a recurring issue where a utility function, util.MapToolName, is used incorrectly. While it doesn't seem to cause a bug at the moment due to how the function behaves on lookup failure, it makes the code confusing and fragile. I've left comments with suggestions to simplify and correct this usage for better clarity and robustness.

@shenshuoyaoyouguang shenshuoyaoyouguang marked this pull request as ready for review March 7, 2026 09:33
Copy link

@chatgpt-codex-connector chatgpt-codex-connector bot left a comment

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

💡 Codex Review

Here are some automated review suggestions for this pull request.

Reviewed commit: 0d0ccd04f3

ℹ️ About Codex in GitHub

Your team has set up Codex to review pull requests in this repo. Reviews are triggered when you

  • Open a pull request for review
  • Mark a draft as ready
  • Comment "@codex review".

If Codex has suggestions, it will comment; otherwise it will react with 👍.

Codex can also answer questions or update the PR. Try commenting "@codex address that feedback".

@shenshuoyaoyouguang shenshuoyaoyouguang force-pushed the pr/claude-tool-id-sanitize branch from 0d0ccd0 to cc418bb Compare March 7, 2026 10:06
@shenshuoyaoyouguang shenshuoyaoyouguang changed the title fix(translator): sanitize claude tool ids and preserve tool mappings feat(util): add Claude tool id and tool_use mapping helpers Mar 7, 2026
@shenshuoyaoyouguang
Copy link
Contributor Author

Narrowed this PR to internal/util/** only so it complies with ranslator-path-guard. The translator-specific follow-up is tracked in #1930.

@shenshuoyaoyouguang
Copy link
Contributor Author

/gemini review

Copy link
Contributor

@gemini-code-assist gemini-code-assist bot left a comment

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Code Review

This pull request introduces two useful helper functions for handling Claude-specific tool IDs and mappings, along with corresponding tests. The SanitizeClaudeToolID function correctly sanitizes tool IDs, and ToolUseNameMapFromClaudeRequest effectively extracts tool use mappings from request payloads. The changes are well-implemented and tested. I have one suggestion to simplify the implementation of ToolUseNameMapFromClaudeRequest by leveraging more of gjson's pathing capabilities.

Comment on lines +268 to +306
if len(rawJSON) == 0 || !gjson.ValidBytes(rawJSON) {
return nil
}

messages := gjson.GetBytes(rawJSON, "messages")
if !messages.Exists() || !messages.IsArray() {
return nil
}

out := map[string]string{}
messages.ForEach(func(_, message gjson.Result) bool {
contents := message.Get("content")
if !contents.IsArray() {
return true
}

contents.ForEach(func(_, content gjson.Result) bool {
if content.Get("type").String() != "tool_use" {
return true
}

toolUseID := strings.TrimSpace(content.Get("id").String())
toolName := strings.TrimSpace(content.Get("name").String())
if toolUseID == "" || toolName == "" {
return true
}

if _, exists := out[toolUseID]; !exists {
out[toolUseID] = toolName
}
return true
})
return true
})

if len(out) == 0 {
return nil
}
return out
Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

medium

This function can be simplified by using a gjson path query to directly select the tool_use objects. This avoids nested loops and several checks, making the code more concise and potentially more performant.

    if !gjson.ValidBytes(rawJSON) {
        return nil
    }

    out := map[string]string{}
    gjson.GetBytes(rawJSON, `messages.#.content.#[type=="tool_use"]`).ForEach(func(_, content gjson.Result) bool {
        toolUseID := strings.TrimSpace(content.Get("id").String())
        toolName := strings.TrimSpace(content.Get("name").String())
        if toolUseID == "" || toolName == "" {
            return true
        }

        if _, exists := out[toolUseID]; !exists {
            out[toolUseID] = toolName
        }
        return true
    })

    if len(out) == 0 {
        return nil
    }
    return out

@shenshuoyaoyouguang
Copy link
Contributor Author

/gemini review

Copy link
Contributor

@gemini-code-assist gemini-code-assist bot left a comment

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Code Review

This pull request introduces two useful helper functions for handling Claude tool IDs and tool use mappings, along with corresponding tests. The implementation is solid. I've provided a couple of suggestions to refactor the code to be more idiomatic and to improve the test coverage and maintainability.

Comment on lines +8 to +23
func TestSanitizeClaudeToolID_ReplacesInvalidCharacters(t *testing.T) {
got := SanitizeClaudeToolID("fs.readFile:temp@1")
if got != "fs_readFile_temp_1" {
t.Fatalf("SanitizeClaudeToolID returned %q", got)
}
}

func TestSanitizeClaudeToolID_GeneratesFallbackForEmptyResult(t *testing.T) {
got := SanitizeClaudeToolID("!!!")
if got == "" {
t.Fatal("expected non-empty fallback id")
}
if !regexp.MustCompile(`^[a-zA-Z0-9_-]+$`).MatchString(got) {
t.Fatalf("fallback id %q does not match Claude regex", got)
}
}
Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

medium

The tests are good, but they could be improved by using a single table-driven test. This would make it easier to add more test cases in the future, would cover more edge cases (like empty input or already-valid IDs), and would avoid recompiling the regex in a loop.

func TestSanitizeClaudeToolID(t *testing.T) {
	claudeToolIDRegex := regexp.MustCompile(`^[a-zA-Z0-9_-]+$`)

	tests := []struct {
		name             string
		input            string
		expected         string
		fallbackExpected bool
	}{
		{"replaces invalid characters", "fs.readFile:temp@1", "fs_readFile_temp_1", false},
		{"valid id is unchanged", "valid-id_123", "valid-id_123", false},
		{"generates fallback for all-invalid input", "!!!", "", true},
		{"generates fallback for empty input", "", "", true},
	}

	for _, tt := range tests {
		t.Run(tt.name, func(t *testing.T) {
			got := SanitizeClaudeToolID(tt.input)

			if tt.fallbackExpected {
				if got == "" {
					t.Error("expected fallback ID, but got empty string")
				}
			} else {
				if got != tt.expected {
					t.Errorf("got %q, want %q", got, tt.expected)
				}
			}

			if !claudeToolIDRegex.MatchString(got) {
				t.Errorf("output %q does not match Claude tool ID regex", got)
			}
		})
	}
}

Comment on lines +272 to +301
messages := gjson.GetBytes(rawJSON, "messages")
if !messages.Exists() || !messages.IsArray() {
return nil
}

out := map[string]string{}
messages.ForEach(func(_, message gjson.Result) bool {
contents := message.Get("content")
if !contents.IsArray() {
return true
}

contents.ForEach(func(_, content gjson.Result) bool {
if content.Get("type").String() != "tool_use" {
return true
}

toolUseID := strings.TrimSpace(content.Get("id").String())
toolName := strings.TrimSpace(content.Get("name").String())
if toolUseID == "" || toolName == "" {
return true
}

if _, exists := out[toolUseID]; !exists {
out[toolUseID] = toolName
}
return true
})
return true
})
Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

medium

The current implementation with nested ForEach loops can be simplified by using a gjson path query to directly select all tool_use content parts. This makes the code more concise and idiomatic when using the gjson library.

	out := map[string]string{}
	gjson.GetBytes(rawJSON, `messages.#.content.#[type=="tool_use"]`).ForEach(func(_, toolUse gjson.Result) bool {
		toolUseID := strings.TrimSpace(toolUse.Get("id").String())
		toolName := strings.TrimSpace(toolUse.Get("name").String())
		if toolUseID == "" || toolName == "" {
			return true
		}

		if _, exists := out[toolUseID]; !exists {
			out[toolUseID] = toolName
		}
		return true
	})

@shenshuoyaoyouguang
Copy link
Contributor Author

Update Note: This PR is now a deliberately scoped-down util-only version, keeping only reusable, testable helper changes under internal/util/. The translator-side wiring modifications mentioned in previous reviews are reasonable directions, but due to repo rules .github/workflows/pr-path-guard.yml directly blocking public PR changes to internal/translator/, that portion has been split out to issue #1930 for follow-up by the maintenance team. Current PR business goal: deliver general helpers in a mergeable, reusable form first, avoiding continued policy gate blocks.

Review Navigation: Current PR is the deliberately scoped-down util-only version, keeping only reusable helpers under internal/util/**; old translator-side comments mostly correspond to subsequent work already split to issue #1930, no longer applicable to current diff. Current CI has passed.

luispater

This comment was marked as duplicate.

@luispater luispater self-requested a review March 9, 2026 01:50
Copy link
Collaborator

@luispater luispater left a comment

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Summary: Thanks for narrowing this down. The util-level additions look reasonable, but the branch is currently not mergeable against main.

Blocking:

This PR still adds internal/util/claude_tool_id.go, but main already contains SanitizeClaudeToolID. Rebasing onto current main reproduces an add/add conflict in that file, so the PR cannot be merged as-is.
Please rebase and drop or resolve that duplicated file so the remaining diff is only the new tests plus ToolUseNameMapFromClaudeRequest.
Test plan:

go test ./internal/util
Attempted merge of main into the PR branch and reproduced the conflict in internal/util/claude_tool_id.go.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

2 participants