text_template
Renders text templates by replacing {variable} placeholders with provided values. Supports optional strict mode to error on missing variables.
Instructions
简单模板渲染,将 {变量名} 替换为对应值。
Input Schema
| Name | Required | Description | Default |
|---|---|---|---|
| template | Yes | 模板文本,用 {变量名} 标记变量 | |
| variables | Yes | 变量键值对,如 {"name": "Alice", "age": "30"} | |
| strict | No | 严格模式:缺少变量时报错(默认 false,保留原占位符) |
Implementation Reference
- The _text_template function that executes the template rendering logic: replaces {variable} placeholders using format_map, with optional strict mode to error on missing variables.
def _text_template(args: dict) -> list[types.TextContent]: template = args["template"] variables = args.get("variables", {}) strict = bool(args.get("strict", False)) # 找出所有占位符 placeholders = set(re.findall(r"\{(\w+)\}", template)) missing = placeholders - set(variables.keys()) if strict and missing: return [types.TextContent(type="text", text=( f"❌ 严格模式:缺少变量 {', '.join(sorted(missing))}\n" f"需要变量: {', '.join(sorted(placeholders))}" ))] try: result = template.format_map({ k: variables.get(k, f"{{{k}}}") for k in placeholders }) except Exception as e: return [types.TextContent(type="text", text=f"❌ 模板渲染失败: {e}")] return [types.TextContent(type="text", text=result)] - The Tool definition for 'text_template' including inputSchema (template, variables, strict) and description.
types.Tool( name="text_template", description="简单模板渲染,将 {变量名} 替换为对应值。", inputSchema={ "type": "object", "properties": { "template": {"type": "string", "description": "模板文本,用 {变量名} 标记变量"}, "variables": { "type": "object", "description": "变量键值对,如 {\"name\": \"Alice\", \"age\": \"30\"}", }, "strict": { "type": "boolean", "description": "严格模式:缺少变量时报错(默认 false,保留原占位符)", "default": False, }, }, "required": ["template", "variables"], }, ), - src/onion_mcp_server/tools/text.py:117-128 (registration)The handle_text dispatch function that routes the 'text_template' name to the _text_template handler.
async def handle_text(name: str, arguments: dict) -> list[types.TextContent]: handlers = { "text_format": _text_format, "text_diff": _text_diff, "text_template": _text_template, "text_count": _text_count, "text_clean": _text_clean, } fn = handlers.get(name) if fn is None: raise ValueError(f"未知 text 工具: {name}") return fn(arguments) - src/onion_mcp_server/server.py:48-61 (registration)Server-level registration: maps all TEXT_TOOLS (including 'text_template') to handle_text in the _HANDLERS routing table.
# ── 路由表 ──────────────────────────────────────────────────── _HANDLERS: dict = {} for _t in AI_TOOLS: _HANDLERS[_t.name] = handle_ai for _t in CODE_TOOLS: _HANDLERS[_t.name] = handle_code for _t in TEXT_TOOLS: _HANDLERS[_t.name] = handle_text for _t in DATA_TOOLS: _HANDLERS[_t.name] = handle_data for _t in WEB_TOOLS: _HANDLERS[_t.name] = handle_web for _t in SYSTEM_TOOLS: _HANDLERS[_t.name] = handle_system