Skip to main content
Glama
onion-ai

onion-mcp-server

Official
by onion-ai

code_convert

Convert code between programming languages. Specify source and target languages to translate your code accurately.

Instructions

将代码从一种编程语言转换为另一种语言。

Input Schema

TableJSON Schema
NameRequiredDescriptionDefault
codeYes
from_languageYes
to_languageYes

Implementation Reference

  • Tool schema definition for 'code_convert' — defines name, description, and inputSchema with required fields: code, from_language, to_language.
    types.Tool(
        name="code_convert",
        description="将代码从一种编程语言转换为另一种语言。",
        inputSchema={
            "type": "object",
            "properties": {
                "code":          {"type": "string"},
                "from_language": {"type": "string"},
                "to_language":   {"type": "string"},
            },
            "required": ["code", "from_language", "to_language"],
        },
    ),
  • Handler logic for 'code_convert' — constructs an LLM prompt to convert code from one language to another, preserving logic and using idiomatic style.
    elif name == "code_convert":
        prompt = (
            f"请将以下 {a['from_language']} 代码转换为 {a['to_language']}。\n"
            f"要求:保持逻辑完全一致,使用目标语言的惯用写法,只输出转换后的代码。\n\n"
            f"```{a['from_language'].lower()}\n{a['code']}\n```"
        )
  • The full handle_code async function which dispatches based on tool name, including the code_convert branch (lines 145-150). Calls llm_call with the constructed prompt.
    async def handle_code(name: str, arguments: dict) -> list[types.TextContent]:
        a = arguments
    
        if name == "code_explain":
            detail_map = {"brief": "用一两句话简短", "detailed": "非常详细地", "normal": ""}
            detail_str = detail_map.get(a.get("detail", "normal"), "")
            lang       = a.get("language", "") or "(自动检测)"
            prompt = (
                f"请{detail_str}解释以下 {lang} 代码的功能和逻辑,"
                f"包括:整体作用、关键步骤、重要变量/函数的含义。\n\n"
                f"```\n{a['code']}\n```"
            )
    
        elif name == "code_review":
            focus     = a.get("focus", ["all"])
            focus_str = "所有方面(Bug、安全、性能、代码风格)" if "all" in focus else "、".join(focus)
            lang      = a.get("language", "") or ""
            prompt = (
                f"请对以下 {lang} 代码进行代码审查,重点关注:{focus_str}。\n"
                f"请按以下格式输出:\n"
                f"1. 问题列表(严重程度 + 描述 + 修复建议)\n"
                f"2. 整体评分(1-10)\n"
                f"3. 改进后的代码(如有必要)\n\n"
                f"```\n{a['code']}\n```"
            )
    
        elif name == "code_generate":
            style_map = {
                "simple":     "简洁易读",
                "production": "生产级别(含完整错误处理、日志、类型注解)",
            }
            style_str = style_map.get(a.get("style", "simple"), "简洁易读")
            lang      = a.get("language", "Python")
            prompt = (
                f"请用 {lang} 编写以下功能的代码,风格要求:{style_str}。\n"
                f"只输出代码和必要的注释,不需要额外解释。\n\n"
                f"需求:{a['description']}"
            )
    
        elif name == "code_convert":
            prompt = (
                f"请将以下 {a['from_language']} 代码转换为 {a['to_language']}。\n"
                f"要求:保持逻辑完全一致,使用目标语言的惯用写法,只输出转换后的代码。\n\n"
                f"```{a['from_language'].lower()}\n{a['code']}\n```"
            )
    
        elif name == "code_fix":
            err_part = f"\n\n错误信息:\n```\n{a['error_message']}\n```" if a.get("error_message") else ""
            lang     = a.get("language", "") or ""
            prompt = (
                f"请修复以下 {lang} 代码中的错误。\n"
                f"要求:输出修复后的完整代码,并在代码前简要说明修复了什么问题。\n\n"
                f"```\n{a['code']}\n```{err_part}"
            )
    
        elif name == "code_docstring":
            style    = a.get("style", "google")
            language = a.get("language", "Python")
            prompt = (
                f"请为以下 {language} 代码生成 {style} 风格的文档注释(docstring)。\n"
                f"要求:为每个函数/类/方法添加完整的参数说明、返回值说明、异常说明(如有)。\n"
                f"只输出添加了文档注释的完整代码。\n\n"
                f"```\n{a['code']}\n```"
            )
    
        else:
            raise ValueError(f"未知 code 工具: {name}")
    
        reply = await llm_call(prompt)
        return [types.TextContent(type="text", text=reply)]
  • Registration of code_convert tool: iterates CODE_TOOLS and maps each tool name (including 'code_convert') to the handle_code handler in the _HANDLERS routing table.
    for _t in CODE_TOOLS:   
        _HANDLERS[_t.name] = handle_code
  • The call_tool handler that looks up the tool name in _HANDLERS (which includes 'code_convert' -> handle_code) and executes it.
    @server.call_tool()
    async def call_tool(
        name: str,
        arguments: dict,
    ) -> list[types.TextContent | types.ImageContent | types.EmbeddedResource]:
        log.warning("call: %s %s", name, arguments)
        handler = _HANDLERS.get(name)
        if handler is None:
            raise ValueError(
                f"未知工具: {name}\n"
                f"可用工具: {', '.join(_HANDLERS.keys())}"
            )
        try:
            return await handler(name, arguments)
        except Exception as e:
            log.error("工具 %s 失败: %s", name, e, exc_info=True)
            return [types.TextContent(
                type="text",
Behavior2/5

Does the description disclose side effects, auth requirements, rate limits, or destructive behavior?

No annotations are present, and the description does not disclose any behavioral traits like side effects, limitations, or permissions. The agent is left to assume it is a simple transformation with no additional context.

Agents need to know what a tool does to the world before calling it. Descriptions should go beyond structured annotations to explain consequences.

Conciseness4/5

Is the description appropriately sized, front-loaded, and free of redundancy?

The description is a single, concise sentence that is front-loaded with the core purpose. No unnecessary words are present, though it could benefit from slightly more structure without losing conciseness.

Shorter descriptions cost fewer tokens and are easier for agents to parse. Every sentence should earn its place.

Completeness2/5

Given the tool's complexity, does the description cover enough for an agent to succeed on first attempt?

Given the tool has three required parameters and no output schema, the description should provide more context such as supported languages, code formatting expectations, or any limitations. It currently lacks this information, making it incomplete for effective use.

Complex tools with many parameters or behaviors need more documentation. Simple tools need less. This dimension scales expectations accordingly.

Parameters1/5

Does the description clarify parameter syntax, constraints, interactions, or defaults beyond what the schema provides?

The input schema has 0% description coverage for its three parameters (code, from_language, to_language). The description adds no meaning to these parameters, such as expected formats, valid language values, or constraints. This leaves the agent guessing about parameter details.

Input schemas describe structure but not intent. Descriptions should explain non-obvious parameter relationships and valid value ranges.

Purpose4/5

Does the description clearly state what the tool does and how it differs from similar tools?

The description clearly states the tool converts code from one language to another, which is a specific action. However, it does not explicitly differentiate this from sibling tools like code_explain or code_fix, which have distinct purposes.

Agents choose between tools based on descriptions. A clear purpose with a specific verb and resource helps agents select the right tool.

Usage Guidelines2/5

Does the description explain when to use this tool, when not to, or what alternatives exist?

The description provides no guidance on when to use this tool over alternatives such as ai_translate (for natural language) or code_generate. There are no examples, prerequisites, or context for correct use.

Agents often have multiple tools that could apply. Explicit usage guidance like "use X instead of Y when Z" prevents misuse.

Install Server

Other Tools

Latest Blog Posts

MCP directory API

We provide all the information about MCP servers via our MCP API.

curl -X GET 'https://glama.ai/api/mcp/v1/servers/onion-ai/mcp-server'

If you have feedback or need assistance with the MCP directory API, please join our Discord server