Skip to main content
Glama
NiuTrans

MCP Translation Text

by NiuTrans

translate_text

Translate text between 450+ languages using the NiuTrans API. Specify source and target languages with codes or common names to convert text accurately.

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 tool handler function for 'translate_text', decorated with @mcp.tool(). Handles input validation via Annotated types (schema), normalizes language codes, calls Niutrans API via helper, and formats the response.
    @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,
        }
  • Helper function that makes the HTTP POST request to the Niutrans API, handles errors, and returns the parsed JSON 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 language codes for source and target, using aliases, synonyms, and fuzzy matching.
    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 adds valuable behavioral context: it specifies the API provider (小牛翻译), mentions support for 450+ languages with alias handling, and details the return structure including raw API response. However, it doesn't cover potential limitations like rate limits 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 well-structured and front-loaded: it starts with the core purpose, followed by key features, then detailed parameter and return explanations. Every sentence adds value with no redundancy, making it efficient and easy to parse.

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

Completeness5/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 the presence of an output schema (detailed in the Returns section), the description is complete. It covers purpose, parameters, return values, and behavioral aspects like language support, leaving no significant gaps for the agent.

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

Parameters4/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 meaningful context by explaining that parameters accept '语言代码或常见别名' and providing concrete examples (e.g., 'zh', '中文', 'chinese'), which clarifies usage beyond the schema's basic 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 distinguishes itself by mentioning the API provider and comprehensive language support, though no siblings exist for comparison.

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 for text translation with language codes or aliases, but provides no explicit guidance on when to use this tool versus alternatives (e.g., other translation services or methods). Since no sibling tools exist, this is adequate but lacks broader context.

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/NiuTrans/MCP-TextTranslation'

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