Skip to main content
Glama
tianfn

MCP Translation Text

by tianfn

translate_text

Translate text between 450+ languages using Niutrans API. Accepts language codes or common aliases and returns standardized translations with API response data.

Instructions

使用小牛翻译 API 将文本从 source 语种翻译到 target 语种。

支持 450+ 种语言代码,并可自动处理常见别名。返回结构包含译文和 API 原始响应。

Args:
    text (str): 待翻译的原文文本,可以是任意长度的字符串。
    source (str): 源语言代码或常见别名(例如 "zh"、"中文"、"chinese")。
    target (str): 目标语言代码或常见别名(例如 "en"、"英文"、"english")。

Returns:
    Dict[str, Any]: 包含以下字段的字典:
        - source: 标准化后的源语言代码
        - target: 标准化后的目标语言代码
        - original_text: 原文
        - translated_text: 译文
        - raw: 小牛翻译 API 的原始响应数据

Input Schema

TableJSON Schema
NameRequiredDescriptionDefault
textYes待翻译的原文文本,可以是任意长度的字符串。
sourceYes源语言代码或常见别名(例如 "zh"、"中文"、"chinese")。
targetYes目标语言代码或常见别名(例如 "en"、"英文"、"english")。

Output Schema

TableJSON Schema
NameRequiredDescriptionDefault
resultYes

Implementation Reference

  • The main handler function for the 'translate_text' tool. It validates input languages, constructs the API payload, calls the Niutrans translation API via _call_niutrans helper, and returns a structured response with the translation.
    @mcp.tool()
    def translate_text(
        text: Annotated[str, Field(description="待翻译的原文文本,可以是任意长度的字符串。")],
        source: Annotated[str, Field(description='源语言代码或常见别名(例如 "zh"、"中文"、"chinese")。')],
        target: Annotated[str, Field(description='目标语言代码或常见别名(例如 "en"、"英文"、"english")。')],
    ) -> Dict[str, Any]:
        """使用小牛翻译 API 将文本从 source 语种翻译到 target 语种。
    
        支持 450+ 种语言代码,并可自动处理常见别名。返回结构包含译文和 API 原始响应。
    
        Args:
            text (str): 待翻译的原文文本,可以是任意长度的字符串。
            source (str): 源语言代码或常见别名(例如 "zh"、"中文"、"chinese")。
            target (str): 目标语言代码或常见别名(例如 "en"、"英文"、"english")。
    
        Returns:
            Dict[str, Any]: 包含以下字段的字典:
                - source: 标准化后的源语言代码
                - target: 标准化后的目标语言代码
                - original_text: 原文
                - translated_text: 译文
                - raw: 小牛翻译 API 的原始响应数据
        """
        api_key = os.getenv("NIUTRANS_API_KEY")
        if not api_key:
            raise RuntimeError("缺少环境变量 NIUTRANS_API_KEY")
    
        source_code = _ensure_language_code("source", source)
        target_code = _ensure_language_code("target", target)
    
        payload: Dict[str, Any] = {
            "apikey": api_key,
            "from": source_code,
            "to": target_code,
            "src_text": text,
        }
    
        data = _call_niutrans(payload)
    
        translated = data.get("tgt_text") or data.get("target_text")
        if translated is None:
            raise RuntimeError(f"小牛翻译接口未返回译文: {data}")
    
        return {
            "source": source_code,
            "target": target_code,
            "original_text": text,
            "translated_text": translated,
            "raw": data,
        }
  • Pydantic schema for tool inputs using Annotated types and Field descriptions for text, source language, and target language.
    def translate_text(
        text: Annotated[str, Field(description="待翻译的原文文本,可以是任意长度的字符串。")],
        source: Annotated[str, Field(description='源语言代码或常见别名(例如 "zh"、"中文"、"chinese")。')],
        target: Annotated[str, Field(description='目标语言代码或常见别名(例如 "en"、"英文"、"english")。')],
    ) -> Dict[str, Any]:
  • The @mcp.tool() decorator registers the translate_text function as an MCP tool.
    @mcp.tool()
  • Helper function that makes the HTTP POST request to the Niutrans API, handles errors, and returns the parsed response.
    def _call_niutrans(payload: Dict[str, Any]) -> Dict[str, Any]:
        api_url = os.getenv("NIUTRANS_API_URL", DEFAULT_NIUTRANS_API_URL)
        try:
            response = requests.post(api_url, data=payload, timeout=10)
        except requests.RequestException as exc:
            raise RuntimeError(f"调用小牛翻译接口失败: {exc}") from exc
    
        if response.status_code != 200:
            raise RuntimeError(
                f"小牛翻译接口返回非 200 状态码 {response.status_code}: {response.text}"
            )
    
        try:
            data: Dict[str, Any] = response.json()
        except ValueError as exc:
            raise RuntimeError("小牛翻译接口返回非 JSON 内容") from exc
    
        error_code = data.get("error_code") or data.get("errorCode")
        if error_code not in (None, "0", 0):
            message = data.get("error_msg") or data.get("errorMessage") or "Unknown error"
            raise RuntimeError(f"小牛翻译接口报错 {error_code}: {message}")
    
        return data
  • Helper function to normalize and validate source/target language codes using synonyms and aliases.
    def _ensure_language_code(label: str, value: str) -> str:
        if not value:
            raise RuntimeError(f"缺少 {label} 语言代码")
    
        raw = value.strip()
        if raw in LANGUAGE_CODES:
            return raw
    
        normalized = _normalize_alias(raw)
    
        if normalized in LANGUAGE_CODES:
            return normalized
    
        alias_code = LANGUAGE_SYNONYMS.get(normalized) or LANGUAGE_SYNONYMS.get(
            normalized.replace(" ", "")
        )
        if alias_code:
            return alias_code
    
        normalized_lower = raw.lower()
        for code in LANGUAGE_CODES:
            if code.lower() == normalized_lower:
                return code
    
        raise RuntimeError(
            f"不支持的 {label} 语言代码: {value}。请参考 language-catalog 资源提供的列表后重新选择。"
        )
Behavior4/5

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

With no annotations provided, the description carries full burden and does well by disclosing key behavioral traits: it specifies the external API integration ('小牛翻译 API'), mentions support for 450+ languages with alias handling, and describes the return structure. However, it doesn't cover rate limits, authentication needs, or error handling.

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

Conciseness5/5

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

The description is efficiently structured with a clear purpose statement upfront, followed by organized parameter and return value sections. Every sentence adds value without redundancy, making it easy to parse quickly.

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

Completeness4/5

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

Given the tool's moderate complexity, 100% schema coverage, and presence of an output schema, the description is mostly complete. It covers purpose, parameters, and returns adequately, though it could benefit from mentioning authentication requirements or error scenarios for full completeness.

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

Parameters3/5

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

Schema description coverage is 100%, so the baseline is 3. The description adds minimal value beyond the schema by briefly restating parameter purposes in the Args section, but doesn't provide additional semantic context like examples beyond what's already in the schema descriptions.

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

Purpose5/5

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

The description clearly states the specific action ('使用小牛翻译 API 将文本从 source 语种翻译到 target 语种') with the resource (text) and scope (450+ languages with alias handling). It precisely defines what the tool does without being tautological or vague.

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

Usage Guidelines3/5

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

The description implies usage context through language support details and API integration, but there are no explicit guidelines on when to use this tool versus alternatives. Since no sibling tools are provided, this is adequate but lacks proactive guidance about potential edge cases or limitations.

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/tianfn/mcp-translation-text'

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