Generator

mcp_tools.generator

Generate FastAPI endpoints from templates.

register_template(app, template, *, tool_name=None, remove_comments=True)

Register a template as a FastAPI endpoint.

Parameters:
  • app (FastAPI) –

    FastAPI application

  • template (Template) –

    Parsed template

  • tool_name (str | None, default: None ) –

    Custom endpoint name (default: derived from template name)

  • remove_comments (bool, default: True ) –

    Whether to remove HTML comments in output

Source code in mcp_tools/generator.py
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
def register_template(
    app: FastAPI,
    template: Template,
    *,
    tool_name: str | None = None,
    remove_comments: bool = True,
) -> None:
    """
    Register a template as a FastAPI endpoint.

    Args:
        app: FastAPI application
        template: Parsed template
        tool_name: Custom endpoint name (default: derived from template name)
        remove_comments: Whether to remove HTML comments in output
    """
    # Parse template if not already parsed
    if not template.variables:
        template = parse(template)

    # Generate tool name
    name = tool_name or f"create_{_slugify(template.name)}"
    description = template.about or f"Create content from {template.name} template"

    # Create input model
    InputModel = _create_input_model(name, template)

    # Capture in closure
    _template = template
    _remove_comments = remove_comments

    async def endpoint(input_data: InputModel) -> str:  # type: ignore[valid-type]
        return render(
            _template, input_data.model_dump(), remove_comments=_remove_comments
        )

    # Set metadata
    endpoint.__name__ = name
    endpoint.__doc__ = description

    # Register endpoint
    app.post(
        f"/{name}",
        name=name,
        description=description,
        summary=template.name or name,
        tags=["Template Tools"],
    )(endpoint)