Skip to main content
Glama
onion-ai

onion-mcp-server

Official
by onion-ai

ai_chat

Engage in multi-turn conversations with AI using custom prompts and message history to maintain context.

Instructions

与 AI 进行多轮对话。支持传入历史消息以保持上下文,支持自定义 system prompt。

Input Schema

TableJSON Schema
NameRequiredDescriptionDefault
messageYes用户消息
systemNo系统提示词(设定 AI 角色和行为)
historyNo历史消息列表,格式: [{"role":"user","content":"..."},{"role":"assistant","content":"..."}]
temperatureNo温度 0.0~2.0(默认 0.7,越高越有创意)

Implementation Reference

  • The handler function for ai_chat. Receives arguments (message, system, history, temperature), constructs a messages list, and delegates to llm_chat for the LLM response.
    async def handle_ai(name: str, arguments: dict) -> list[types.TextContent]:
        a = arguments
    
        if name == "ai_chat":
            messages = []
            if a.get("system"):
                messages.append({"role": "system", "content": a["system"]})
            messages.extend(a.get("history", []))
            messages.append({"role": "user", "content": a["message"]})
            reply = await llm_chat(messages, temperature=float(a.get("temperature", 0.7)))
            return [types.TextContent(type="text", text=reply)]
  • The Tool definition (schema) for ai_chat, defining the name, description, and inputSchema with properties: message (required), system, history (array of {role, content}), and temperature.
    AI_TOOLS: list[types.Tool] = [
        types.Tool(
            name="ai_chat",
            description=(
                "与 AI 进行多轮对话。支持传入历史消息以保持上下文,"
                "支持自定义 system prompt。"
            ),
            inputSchema={
                "type": "object",
                "properties": {
                    "message": {
                        "type":        "string",
                        "description": "用户消息",
                    },
                    "system": {
                        "type":        "string",
                        "description": "系统提示词(设定 AI 角色和行为)",
                        "default":     "",
                    },
                    "history": {
                        "type":        "array",
                        "description": "历史消息列表,格式: [{\"role\":\"user\",\"content\":\"...\"},{\"role\":\"assistant\",\"content\":\"...\"}]",
                        "items": {
                            "type": "object",
                            "properties": {
                                "role":    {"type": "string", "enum": ["user", "assistant"]},
                                "content": {"type": "string"},
                            },
                        },
                        "default": [],
                    },
                    "temperature": {
                        "type":    "number",
                        "description": "温度 0.0~2.0(默认 0.7,越高越有创意)",
                        "default": 0.7,
                    },
                },
                "required": ["message"],
            },
        ),
  • Registration of ai_chat into the handler routing table: iterates AI_TOOLS and maps each tool name (including 'ai_chat') to handle_ai.
    _HANDLERS: dict = {}
    for _t in AI_TOOLS:     
        _HANDLERS[_t.name] = handle_ai
  • The llm_chat helper function that performs the actual LLM multi-turn chat call. Handles config, API key validation, OpenAI client creation, and error handling.
    async def llm_chat(
        messages: list,
        temperature: float = 0.7,
    ) -> str:
        """多轮调用"""
        cfg = _get_config()
    
        if not cfg["api_key"]:
            return _no_key_message()
    
        try:
            from openai import AsyncOpenAI
        except ImportError:
            return (
                "❌ 需要安装 openai 依赖:\n\n"
                "```bash\n"
                "pip install openai\n"
                "# 或\n"
                "uvx onion-mcp-server  # 自动安装\n"
                "```"
            )
    
        client = AsyncOpenAI(
            api_key=cfg["api_key"],
            base_url=cfg["base_url"],
        )
    
        try:
            resp = await client.chat.completions.create(
                model=cfg["model"],
                messages=messages,
                temperature=temperature,
                max_tokens=cfg["max_tokens"],
            )
            return resp.choices[0].message.content or ""
        except Exception as e:
            err = str(e)
            # 友好错误提示
            if "401" in err or "authentication" in err.lower():
                return f"❌ API Key 无效或已过期\n\n当前配置:\n  base_url: {cfg['base_url']}\n  model: {cfg['model']}\n\n错误: {e}"
            if "404" in err or "model" in err.lower():
                return f"❌ 模型不存在: {cfg['model']}\n\n请设置 ONION_MCP_MODEL 为正确的模型名\n\n错误: {e}"
            if "429" in err:
                return f"❌ API 请求频率超限,请稍后重试\n\n错误: {e}"
            return f"❌ LLM 调用失败\n\n错误: {e}"
  • Re-exports AI_TOOLS and handle_ai from the ai module so they can be imported by server.py.
    from onion_mcp_server.tools.ai     import AI_TOOLS,     handle_ai
Behavior3/5

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

Without annotations, the description carries the transparency burden. It discloses multi-turn capability and custom prompts but omits potential limitations (e.g., model, token limits, response format). Adequate but not detailed.

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?

Two concise sentences front-loading the core purpose and key features (multi-turn, history, system prompt). No unnecessary words.

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 no output schema and no annotations, the description covers the main behavior and differentiators. It doesn't explain return value, but for a chat tool, a response is expected. Slightly incomplete but sufficient.

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 coverage is 100%, so the baseline is 3. The description adds little beyond the schema: it reaffirms the multi-turn context and system prompt purpose but no additional semantic nuance.

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 it's for multi-turn conversations with AI, highlighting support for history context and custom system prompts, which distinguishes it from siblings like ai_summarize or ai_translate.

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

Usage Guidelines4/5

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

The description implies use for general dialogue, not specific transformations, and the sibling list makes the distinction clear. However, it lacks explicit 'when to use vs alternatives' guidance.

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