Skip to content

code_generation

Class info

Re-exported classes

Class Module Description
ToolCodeGenerator schemez.code_generation.tool_code_generator Generates code artifacts for a single tool.
ToolsetCodeGenerator schemez.code_generation.toolset_code_generator Generates code artifacts for multiple tools.

🛈 DocStrings

Meta-resource provider that exposes tools through Python execution.

ToolCodeGenerator dataclass

Generates code artifacts for a single tool.

Source code in src/schemez/code_generation/tool_code_generator.py
@dataclass
class ToolCodeGenerator:
    """Generates code artifacts for a single tool."""

    schema: FunctionSchema
    """Schema of the tool (primary source of truth)."""

    callable: Callable[..., Any] | None = None
    """Optional callable for actual execution. Required only for FastAPI route generation
    and Python namespace execution. All other operations (client code generation,
    signatures, models) work purely from the schema."""

    name_override: str | None = None
    """Name override for the function to generate code for."""

    @classmethod
    def from_callable(
        cls,
        fn: Callable[..., Any],
        exclude_types: list[type] | None = None,
        schema_type: SchemaType = "simple",
    ) -> ToolCodeGenerator:
        """Create a ToolCodeGenerator from a callable."""
        schema = create_schema(fn, exclude_types=exclude_types, mode=schema_type)
        return cls(schema=schema, callable=fn)

    @classmethod
    def from_schema(
        cls,
        schema: FunctionSchema,
        name_override: str | None = None,
    ) -> ToolCodeGenerator:
        """Create a ToolCodeGenerator from a schema only (no execution capability)."""
        return cls(schema=schema, callable=None, name_override=name_override)

    @property
    def name(self) -> str:
        """Name of the tool."""
        if self.name_override:
            return self.name_override
        if self.callable:
            return get_object_name(self.callable, "unknown")
        return self.schema.name

    def get_function_signature(self) -> str:
        """Assembles a signature for given generator, excluding (async) def."""
        return f"{self.name}{self.schema.to_python_signature()}"

    def get_function_definition(self, include_docstrings: bool = True) -> str:
        """Extract function definition using FunctionSchema."""
        parts = []
        parts.append(f"async def {self.get_function_signature()}")
        if include_docstrings and self.schema.description:
            lines = self.schema.description.split("\n")
            parts.extend(f"    {i.strip()}" for i in lines if i.strip())
        return "\n".join(parts)

    def generate_return_model(self) -> str | None:
        """Generate Pydantic model code for the tool's return type."""
        try:
            if self.schema.returns.get("type") not in {"object", "array"}:
                return None

            class_name = f"{self.name.title()}Response"
            model_code = self.schema.to_return_model_code(class_name=class_name)
            return model_code.strip() or None

        except Exception:  # noqa: BLE001
            return None

    def generate_parameter_model(self) -> str | None:
        """Generate Pydantic model code for the tool's parameters."""
        try:
            if not self.schema.parameters.get("properties"):
                return None

            class_name = f"{self.name.title()}Params"
            model_code = self.schema.to_parameter_model_code(class_name=class_name)
            return model_code.strip() or None

        except Exception:  # noqa: BLE001
            return None

    def generate_route_handler(self) -> Callable[..., Awaitable[dict[str, Any]]]:
        """Generate FastAPI route handler for this tool.

        Returns:
            Async route handler function

        Raises:
            ValueError: If callable is not provided
        """
        if self.callable is None:
            msg = f"Callable required for route generation for tool '{self.name}'"
            raise ValueError(msg)
        param_cls = create_param_model(dict(self.schema.parameters))
        return create_route_handler(self.callable, param_cls)

    def add_route_to_app(self, app: FastAPI, path_prefix: str = "/tools") -> None:
        """Add this tool's route to FastAPI app.

        Args:
            app: FastAPI application instance
            path_prefix: Path prefix for the route

        Raises:
            ValueError: If callable is not provided
        """
        if self.callable is None:
            msg = f"Callable required for route generation for tool '{self.name}'"
            raise ValueError(msg)
        param_cls = create_param_model(dict(self.schema.parameters))
        route_handler = self.generate_route_handler()
        # Set up the route with proper parameter annotations for FastAPI
        if param_cls:
            func_code = generate_func_code(param_cls.model_fields)
            namespace: dict[str, Any] = {"route_handler": route_handler, "Any": Any}
            exec(func_code, namespace)  # Execute the dynamic function creation
            dynamic_handler: Callable[..., Any] = namespace["dynamic_handler"]
        else:

            async def dynamic_handler() -> dict[str, Any]:
                return await route_handler()

        app.get(f"{path_prefix}/{self.name}")(dynamic_handler)  # Add route to FastAPI app

callable class-attribute instance-attribute

callable: Callable[..., Any] | None = None

Optional callable for actual execution. Required only for FastAPI route generation and Python namespace execution. All other operations (client code generation, signatures, models) work purely from the schema.

name property

name: str

Name of the tool.

name_override class-attribute instance-attribute

name_override: str | None = None

Name override for the function to generate code for.

schema instance-attribute

Schema of the tool (primary source of truth).

add_route_to_app

add_route_to_app(app: FastAPI, path_prefix: str = '/tools') -> None

Add this tool's route to FastAPI app.

Parameters:

Name Type Description Default
app FastAPI

FastAPI application instance

required
path_prefix str

Path prefix for the route

'/tools'

Raises:

Type Description
ValueError

If callable is not provided

Source code in src/schemez/code_generation/tool_code_generator.py
def add_route_to_app(self, app: FastAPI, path_prefix: str = "/tools") -> None:
    """Add this tool's route to FastAPI app.

    Args:
        app: FastAPI application instance
        path_prefix: Path prefix for the route

    Raises:
        ValueError: If callable is not provided
    """
    if self.callable is None:
        msg = f"Callable required for route generation for tool '{self.name}'"
        raise ValueError(msg)
    param_cls = create_param_model(dict(self.schema.parameters))
    route_handler = self.generate_route_handler()
    # Set up the route with proper parameter annotations for FastAPI
    if param_cls:
        func_code = generate_func_code(param_cls.model_fields)
        namespace: dict[str, Any] = {"route_handler": route_handler, "Any": Any}
        exec(func_code, namespace)  # Execute the dynamic function creation
        dynamic_handler: Callable[..., Any] = namespace["dynamic_handler"]
    else:

        async def dynamic_handler() -> dict[str, Any]:
            return await route_handler()

    app.get(f"{path_prefix}/{self.name}")(dynamic_handler)  # Add route to FastAPI app

from_callable classmethod

from_callable(
    fn: Callable[..., Any],
    exclude_types: list[type] | None = None,
    schema_type: SchemaType = "simple",
) -> ToolCodeGenerator

Create a ToolCodeGenerator from a callable.

Source code in src/schemez/code_generation/tool_code_generator.py
@classmethod
def from_callable(
    cls,
    fn: Callable[..., Any],
    exclude_types: list[type] | None = None,
    schema_type: SchemaType = "simple",
) -> ToolCodeGenerator:
    """Create a ToolCodeGenerator from a callable."""
    schema = create_schema(fn, exclude_types=exclude_types, mode=schema_type)
    return cls(schema=schema, callable=fn)

from_schema classmethod

from_schema(schema: FunctionSchema, name_override: str | None = None) -> ToolCodeGenerator

Create a ToolCodeGenerator from a schema only (no execution capability).

Source code in src/schemez/code_generation/tool_code_generator.py
@classmethod
def from_schema(
    cls,
    schema: FunctionSchema,
    name_override: str | None = None,
) -> ToolCodeGenerator:
    """Create a ToolCodeGenerator from a schema only (no execution capability)."""
    return cls(schema=schema, callable=None, name_override=name_override)

generate_parameter_model

generate_parameter_model() -> str | None

Generate Pydantic model code for the tool's parameters.

Source code in src/schemez/code_generation/tool_code_generator.py
def generate_parameter_model(self) -> str | None:
    """Generate Pydantic model code for the tool's parameters."""
    try:
        if not self.schema.parameters.get("properties"):
            return None

        class_name = f"{self.name.title()}Params"
        model_code = self.schema.to_parameter_model_code(class_name=class_name)
        return model_code.strip() or None

    except Exception:  # noqa: BLE001
        return None

generate_return_model

generate_return_model() -> str | None

Generate Pydantic model code for the tool's return type.

Source code in src/schemez/code_generation/tool_code_generator.py
def generate_return_model(self) -> str | None:
    """Generate Pydantic model code for the tool's return type."""
    try:
        if self.schema.returns.get("type") not in {"object", "array"}:
            return None

        class_name = f"{self.name.title()}Response"
        model_code = self.schema.to_return_model_code(class_name=class_name)
        return model_code.strip() or None

    except Exception:  # noqa: BLE001
        return None

generate_route_handler

generate_route_handler() -> Callable[..., Awaitable[dict[str, Any]]]

Generate FastAPI route handler for this tool.

Returns:

Type Description
Callable[..., Awaitable[dict[str, Any]]]

Async route handler function

Raises:

Type Description
ValueError

If callable is not provided

Source code in src/schemez/code_generation/tool_code_generator.py
def generate_route_handler(self) -> Callable[..., Awaitable[dict[str, Any]]]:
    """Generate FastAPI route handler for this tool.

    Returns:
        Async route handler function

    Raises:
        ValueError: If callable is not provided
    """
    if self.callable is None:
        msg = f"Callable required for route generation for tool '{self.name}'"
        raise ValueError(msg)
    param_cls = create_param_model(dict(self.schema.parameters))
    return create_route_handler(self.callable, param_cls)

get_function_definition

get_function_definition(include_docstrings: bool = True) -> str

Extract function definition using FunctionSchema.

Source code in src/schemez/code_generation/tool_code_generator.py
def get_function_definition(self, include_docstrings: bool = True) -> str:
    """Extract function definition using FunctionSchema."""
    parts = []
    parts.append(f"async def {self.get_function_signature()}")
    if include_docstrings and self.schema.description:
        lines = self.schema.description.split("\n")
        parts.extend(f"    {i.strip()}" for i in lines if i.strip())
    return "\n".join(parts)

get_function_signature

get_function_signature() -> str

Assembles a signature for given generator, excluding (async) def.

Source code in src/schemez/code_generation/tool_code_generator.py
def get_function_signature(self) -> str:
    """Assembles a signature for given generator, excluding (async) def."""
    return f"{self.name}{self.schema.to_python_signature()}"

ToolsetCodeGenerator dataclass

Generates code artifacts for multiple tools.

Source code in src/schemez/code_generation/toolset_code_generator.py
@dataclass
class ToolsetCodeGenerator:
    """Generates code artifacts for multiple tools."""

    generators: Sequence[ToolCodeGenerator]
    """ToolCodeGenerator instances for each tool."""

    include_docstrings: bool = True
    """Include function docstrings in documentation."""

    @classmethod
    def from_callables(
        cls,
        callables: Sequence[Callable[..., Any]],
        include_docstrings: bool = True,
        exclude_types: list[type] | None = None,
    ) -> ToolsetCodeGenerator:
        """Create a ToolsetCodeGenerator from a sequence of callables."""
        gens = [ToolCodeGenerator.from_callable(i, exclude_types=exclude_types) for i in callables]
        return cls(gens, include_docstrings)

    @classmethod
    def from_schemas(
        cls,
        schemas: Sequence[FunctionSchema],
        include_docstrings: bool = True,
    ) -> ToolsetCodeGenerator:
        """Create a ToolsetCodeGenerator from schemas only (no execution capability)."""
        generators = [ToolCodeGenerator.from_schema(schema) for schema in schemas]
        return cls(generators, include_docstrings)

    def generate_tool_description(self) -> str:
        """Generate comprehensive tool description with available functions."""
        if not self.generators:
            return "Execute Python code (no tools available)"

        parts = ["Available functions:"]
        for generator in self.generators:
            desc = generator.get_function_definition(self.include_docstrings)
            parts.append(desc)
        return "\n".join(parts)

    def generate_execution_namespace(self) -> dict[str, Any]:
        """Build Python namespace with tool functions and generated models.

        Raises:
            ValueError: If any generator lacks a callable
        """
        namespace: dict[str, Any] = {"__builtins__": __builtins__, "_result": None}
        # Add tool functions - all generators must have callables for execution
        for generator in self.generators:
            namespace[generator.name] = NamespaceCallable.from_generator(generator)
        # Add generated model classes to namespace
        if models_code := self.generate_return_models():
            with contextlib.suppress(Exception):
                exec(models_code, namespace)
        return namespace

    def generate_return_models(self) -> str:
        """Generate Pydantic models for tool return types."""
        model_parts = [c for g in self.generators if (c := g.generate_return_model())]
        return "\n\n".join(model_parts) if model_parts else ""

    def get_fastmcp_client_code(self, server_configs: dict[str, str]) -> str:
        """Generate FastMCP client code with connection management.

        Args:
            server_configs: Dict mapping server names to their transport URLs
                          e.g., {"github": "sse://localhost:8080/github"}

        Returns:
            FastMCP client code as string
        """
        server_config_code = "SERVERS = " + repr(server_configs)
        return f'''{server_config_code}

# Connection management
_clients: dict[str, Client] = {{}}

async def get_mcp_client(server_name: str) -> Client:
    """Get or create FastMCP client for server."""
    if server_name not in _clients:
        if server_name not in SERVERS:
            raise ValueError(f"Unknown MCP server: {{server_name}}")

        transport_url = SERVERS[server_name]
        client = Client(transport_url)
        _clients[server_name] = client

    return _clients[server_name]

async def call_mcp_tool(
    server_name: str, tool_name: str, arguments: dict[str, Any]
) -> Any:
    """Call a FastMCP tool and return the result."""
    client = await get_mcp_client(server_name)

    async with client:
        result = await client.call_tool(tool_name, arguments)

        # FastMCP returns CallToolResult with structured content handling
        if result.data is not None:
            return result.data  # Parsed structured content
        elif result.content:
            # Extract text from content blocks
            text_parts = []
            for content_block in result.content:
                if hasattr(content_block, 'text'):
                    text_parts.append(content_block.text)
            return "\\n".join(text_parts) if text_parts else ""

        return ""

async def close_all_mcp_connections():
    """Close all MCP client connections."""
    for server_name, client in _clients.items():
        try:
            await client.close()
        except Exception as e:
            print(f"Error closing connection to {{server_name}}: {{e}}")
    _clients.clear()
'''

    def generate_structured_code(
        self,
        base_url: str = "http://localhost:8000",
        path_prefix: str = "/tools",
        client_type: ClientType = "http",
    ) -> GeneratedCode:
        """Generate structured code with all components.

        Args:
            base_url: Base URL of the tool server (HTTP) or server name (FastMCP)
            path_prefix: Path prefix for routes (HTTP only)
            client_type: Type of client to generate ("http" or "fastmcp")

        Returns:
            GeneratedCode with all components separated
        """
        start_time = time.time()
        logger.info("Starting structured code generation")

        models_parts: list[str] = []
        http_methods_parts: list[str] = []
        clean_methods_parts: list[str] = []
        model_stubs_parts: list[str] = []
        explicit_stubs_parts: list[str] = []

        for generator in self.generators:
            # Generate input model from schema parameters
            input_class_name = None
            try:
                params = generator.schema.parameters
                if params.get("properties"):
                    words = [word.title() for word in generator.name.split("_")]
                    input_class_name = f"{''.join(words)}Input"
                    if model_code := model_to_python_code(params, class_name=input_class_name):
                        cleaned_model = clean_generated_code(model_code)
                        models_parts.append(cleaned_model)
            except ValueError, TypeError, AttributeError:
                input_class_name = None

            # Generate client method with model
            if input_class_name:
                if client_type == "fastmcp":
                    http_method = f'''
async def {generator.name}(input: {input_class_name}) -> Any:
    """{generator.schema.description or f"Call {generator.name} tool"}

    Args:
        input: Function parameters

    Returns:
        Result from the MCP server
    """
    result = await call_mcp_tool("{base_url}", "{generator.name}", input.model_dump())
    return result
'''
                else:
                    http_method = f'''
async def {generator.name}(input: {input_class_name}) -> str:
    """{generator.schema.description or f"Call {generator.name} tool"}

    Args:
        input: Function parameters

    Returns:
        String response from the tool server
    """
    async with httpx2.AsyncClient() as client:
        response = await client.get(
            "{base_url}{path_prefix}/{generator.name}",
            params=input.model_dump() if hasattr(input, 'model_dump') else {{}},
            timeout=30.0
        )
        response.raise_for_status()
        return response.text
'''
            elif client_type == "fastmcp":
                http_method = f'''
async def {generator.name}() -> Any:
    """{generator.schema.description or f"Call {generator.name} tool"}

    Returns:
        Result from the MCP server
    """
    result = await call_mcp_tool("{base_url}", "{generator.name}", {{}})
    return result
'''
            else:
                http_method = f'''
async def {generator.name}() -> str:
    """{generator.schema.description or f"Call {generator.name} tool"}

    Returns:
        String response from the tool server
    """
    async with httpx2.AsyncClient() as client:
        response = await client.get(
            "{base_url}{path_prefix}/{generator.name}",
            timeout=30.0
        )
        response.raise_for_status()
        return response.text
'''
            http_methods_parts.append(http_method)
            # Generate clean method with natural signature
            signature_str = generator.get_function_signature()
            params = generator.schema.parameters
            param_names = list(params.get("properties", {}).keys())
            if client_type == "fastmcp":
                clean_method = f'''
async def {signature_str}:
    """{generator.schema.description or f"Call {generator.name} tool"}"""
    # Build parameters dict
    params = {{{", ".join(f'"{name}": {name}' for name in param_names)}}}
    # Remove None values
    clean_params = {{k: v for k, v in params.items() if v is not None}}

    result = await call_mcp_tool("{base_url}", "{generator.name}", clean_params)
    return result
'''
            else:
                clean_method = f'''
async def {signature_str}:
    """{generator.schema.description or f"Call {generator.name} tool"}"""
    # Build parameters dict
    params = {{{", ".join(f'"{name}": {name}' for name in param_names)}}}
    # Remove None values
    clean_params = {{k: v for k, v in params.items() if v is not None}}

    async with httpx2.AsyncClient() as client:
        response = await client.get(
            "{base_url}{path_prefix}/{generator.name}",
            params=clean_params,
            timeout=30.0
        )
        response.raise_for_status()
        # Parse JSON response and return the result
        result = response.json()
        return result.get("result", response.text)
'''
            clean_methods_parts.append(clean_method)
            # Generate model-based stub
            if input_class_name:
                model_stub = f'''
async def {generator.name}(input: {input_class_name}) -> Any:
    """{generator.schema.description or f"Call {generator.name} tool"}

    Args:
        input: Function parameters

    Returns:
        Function result
    """
    ...
'''
                model_stubs_parts.append(model_stub)

            # Generate explicit signature stub
            explicit_stub = f'''
async def {signature_str}:
    """{generator.schema.description or f"Call {generator.name} tool"}"""
    ...
'''
            explicit_stubs_parts.append(explicit_stub)

        # Choose appropriate imports based on client type
        imports = FASTMCP_IMPORTS if client_type == "fastmcp" else HTTP_IMPORTS
        elapsed = time.time() - start_time
        logger.info("Structured code generation completed in %.2fs", elapsed)
        return GeneratedCode(
            models="\n".join(models_parts),
            http_methods="\n".join(http_methods_parts),
            clean_methods="\n".join(clean_methods_parts),
            model_stubs="\n".join(model_stubs_parts),
            explicit_stubs="\n".join(explicit_stubs_parts),
            imports=imports,
        )

    def generate_code(
        self,
        base_url: str = "http://localhost:8000",
        path_prefix: str = "/tools",
        args_format: ArgsFormat = "explicit",
        output_type: OutputType = "implementation",
    ) -> str:
        """Generate HTTP client code with specified format and type.

        Args:
            base_url: Base URL of the tool server
            path_prefix: Path prefix for routes
            args_format: Format for function arguments
            output_type: Type of output to generate

        Returns:
            Generated client code
        """
        structured_code = self.generate_structured_code(base_url, path_prefix)
        return structured_code.get_client_code(args_format, output_type)

    def generate_mcp_code(
        self,
        server_configs: dict[str, str],
        args_format: ArgsFormat = "explicit",
        output_type: OutputType = "implementation",
    ) -> str:
        """Generate complete FastMCP client code with tools.

        Args:
            server_configs: FastMCP server configurations mapping server names to
                           transport URLs
                           e.g., {"github": "sse://localhost:8080/github"}
            args_format: Format for function arguments
            output_type: Type of output to generate

        Returns:
            Complete FastMCP client code
        """
        # Generate structured code with FastMCP client type
        structured = self.generate_structured_code(client_type="fastmcp")
        # Get FastMCP client code
        mcp_client_code = self.get_fastmcp_client_code(server_configs)
        # Get the appropriate client code based on format/type
        tools_code = structured.get_client_code(args_format, output_type, client_type="fastmcp")
        # Combine client and tools code
        return f"""{FASTMCP_IMPORTS}
{mcp_client_code}

{tools_code}"""

    def add_all_routes(self, app: FastAPI, path_prefix: str = "/tools") -> None:
        """Add FastAPI routes for all tools."""
        for generator in self.generators:
            generator.add_route_to_app(app, path_prefix)

generators instance-attribute

generators: Sequence[ToolCodeGenerator]

ToolCodeGenerator instances for each tool.

include_docstrings class-attribute instance-attribute

include_docstrings: bool = True

Include function docstrings in documentation.

add_all_routes

add_all_routes(app: FastAPI, path_prefix: str = '/tools') -> None

Add FastAPI routes for all tools.

Source code in src/schemez/code_generation/toolset_code_generator.py
def add_all_routes(self, app: FastAPI, path_prefix: str = "/tools") -> None:
    """Add FastAPI routes for all tools."""
    for generator in self.generators:
        generator.add_route_to_app(app, path_prefix)

from_callables classmethod

from_callables(
    callables: Sequence[Callable[..., Any]],
    include_docstrings: bool = True,
    exclude_types: list[type] | None = None,
) -> ToolsetCodeGenerator

Create a ToolsetCodeGenerator from a sequence of callables.

Source code in src/schemez/code_generation/toolset_code_generator.py
@classmethod
def from_callables(
    cls,
    callables: Sequence[Callable[..., Any]],
    include_docstrings: bool = True,
    exclude_types: list[type] | None = None,
) -> ToolsetCodeGenerator:
    """Create a ToolsetCodeGenerator from a sequence of callables."""
    gens = [ToolCodeGenerator.from_callable(i, exclude_types=exclude_types) for i in callables]
    return cls(gens, include_docstrings)

from_schemas classmethod

from_schemas(
    schemas: Sequence[FunctionSchema], include_docstrings: bool = True
) -> ToolsetCodeGenerator

Create a ToolsetCodeGenerator from schemas only (no execution capability).

Source code in src/schemez/code_generation/toolset_code_generator.py
@classmethod
def from_schemas(
    cls,
    schemas: Sequence[FunctionSchema],
    include_docstrings: bool = True,
) -> ToolsetCodeGenerator:
    """Create a ToolsetCodeGenerator from schemas only (no execution capability)."""
    generators = [ToolCodeGenerator.from_schema(schema) for schema in schemas]
    return cls(generators, include_docstrings)

generate_code

generate_code(
    base_url: str = "http://localhost:8000",
    path_prefix: str = "/tools",
    args_format: ArgsFormat = "explicit",
    output_type: OutputType = "implementation",
) -> str

Generate HTTP client code with specified format and type.

Parameters:

Name Type Description Default
base_url str

Base URL of the tool server

'http://localhost:8000'
path_prefix str

Path prefix for routes

'/tools'
args_format ArgsFormat

Format for function arguments

'explicit'
output_type OutputType

Type of output to generate

'implementation'

Returns:

Type Description
str

Generated client code

Source code in src/schemez/code_generation/toolset_code_generator.py
def generate_code(
    self,
    base_url: str = "http://localhost:8000",
    path_prefix: str = "/tools",
    args_format: ArgsFormat = "explicit",
    output_type: OutputType = "implementation",
) -> str:
    """Generate HTTP client code with specified format and type.

    Args:
        base_url: Base URL of the tool server
        path_prefix: Path prefix for routes
        args_format: Format for function arguments
        output_type: Type of output to generate

    Returns:
        Generated client code
    """
    structured_code = self.generate_structured_code(base_url, path_prefix)
    return structured_code.get_client_code(args_format, output_type)

generate_execution_namespace

generate_execution_namespace() -> dict[str, Any]

Build Python namespace with tool functions and generated models.

Raises:

Type Description
ValueError

If any generator lacks a callable

Source code in src/schemez/code_generation/toolset_code_generator.py
def generate_execution_namespace(self) -> dict[str, Any]:
    """Build Python namespace with tool functions and generated models.

    Raises:
        ValueError: If any generator lacks a callable
    """
    namespace: dict[str, Any] = {"__builtins__": __builtins__, "_result": None}
    # Add tool functions - all generators must have callables for execution
    for generator in self.generators:
        namespace[generator.name] = NamespaceCallable.from_generator(generator)
    # Add generated model classes to namespace
    if models_code := self.generate_return_models():
        with contextlib.suppress(Exception):
            exec(models_code, namespace)
    return namespace

generate_mcp_code

generate_mcp_code(
    server_configs: dict[str, str],
    args_format: ArgsFormat = "explicit",
    output_type: OutputType = "implementation",
) -> str

Generate complete FastMCP client code with tools.

Parameters:

Name Type Description Default
server_configs dict[str, str]

FastMCP server configurations mapping server names to transport URLs e.g., {"github": "sse://localhost:8080/github"}

required
args_format ArgsFormat

Format for function arguments

'explicit'
output_type OutputType

Type of output to generate

'implementation'

Returns:

Type Description
str

Complete FastMCP client code

Source code in src/schemez/code_generation/toolset_code_generator.py
    def generate_mcp_code(
        self,
        server_configs: dict[str, str],
        args_format: ArgsFormat = "explicit",
        output_type: OutputType = "implementation",
    ) -> str:
        """Generate complete FastMCP client code with tools.

        Args:
            server_configs: FastMCP server configurations mapping server names to
                           transport URLs
                           e.g., {"github": "sse://localhost:8080/github"}
            args_format: Format for function arguments
            output_type: Type of output to generate

        Returns:
            Complete FastMCP client code
        """
        # Generate structured code with FastMCP client type
        structured = self.generate_structured_code(client_type="fastmcp")
        # Get FastMCP client code
        mcp_client_code = self.get_fastmcp_client_code(server_configs)
        # Get the appropriate client code based on format/type
        tools_code = structured.get_client_code(args_format, output_type, client_type="fastmcp")
        # Combine client and tools code
        return f"""{FASTMCP_IMPORTS}
{mcp_client_code}

{tools_code}"""

generate_return_models

generate_return_models() -> str

Generate Pydantic models for tool return types.

Source code in src/schemez/code_generation/toolset_code_generator.py
def generate_return_models(self) -> str:
    """Generate Pydantic models for tool return types."""
    model_parts = [c for g in self.generators if (c := g.generate_return_model())]
    return "\n\n".join(model_parts) if model_parts else ""

generate_structured_code

generate_structured_code(
    base_url: str = "http://localhost:8000",
    path_prefix: str = "/tools",
    client_type: ClientType = "http",
) -> GeneratedCode

Generate structured code with all components.

Parameters:

Name Type Description Default
base_url str

Base URL of the tool server (HTTP) or server name (FastMCP)

'http://localhost:8000'
path_prefix str

Path prefix for routes (HTTP only)

'/tools'
client_type ClientType

Type of client to generate ("http" or "fastmcp")

'http'

Returns:

Type Description
GeneratedCode

GeneratedCode with all components separated

Source code in src/schemez/code_generation/toolset_code_generator.py
    def generate_structured_code(
        self,
        base_url: str = "http://localhost:8000",
        path_prefix: str = "/tools",
        client_type: ClientType = "http",
    ) -> GeneratedCode:
        """Generate structured code with all components.

        Args:
            base_url: Base URL of the tool server (HTTP) or server name (FastMCP)
            path_prefix: Path prefix for routes (HTTP only)
            client_type: Type of client to generate ("http" or "fastmcp")

        Returns:
            GeneratedCode with all components separated
        """
        start_time = time.time()
        logger.info("Starting structured code generation")

        models_parts: list[str] = []
        http_methods_parts: list[str] = []
        clean_methods_parts: list[str] = []
        model_stubs_parts: list[str] = []
        explicit_stubs_parts: list[str] = []

        for generator in self.generators:
            # Generate input model from schema parameters
            input_class_name = None
            try:
                params = generator.schema.parameters
                if params.get("properties"):
                    words = [word.title() for word in generator.name.split("_")]
                    input_class_name = f"{''.join(words)}Input"
                    if model_code := model_to_python_code(params, class_name=input_class_name):
                        cleaned_model = clean_generated_code(model_code)
                        models_parts.append(cleaned_model)
            except ValueError, TypeError, AttributeError:
                input_class_name = None

            # Generate client method with model
            if input_class_name:
                if client_type == "fastmcp":
                    http_method = f'''
async def {generator.name}(input: {input_class_name}) -> Any:
    """{generator.schema.description or f"Call {generator.name} tool"}

    Args:
        input: Function parameters

    Returns:
        Result from the MCP server
    """
    result = await call_mcp_tool("{base_url}", "{generator.name}", input.model_dump())
    return result
'''
                else:
                    http_method = f'''
async def {generator.name}(input: {input_class_name}) -> str:
    """{generator.schema.description or f"Call {generator.name} tool"}

    Args:
        input: Function parameters

    Returns:
        String response from the tool server
    """
    async with httpx2.AsyncClient() as client:
        response = await client.get(
            "{base_url}{path_prefix}/{generator.name}",
            params=input.model_dump() if hasattr(input, 'model_dump') else {{}},
            timeout=30.0
        )
        response.raise_for_status()
        return response.text
'''
            elif client_type == "fastmcp":
                http_method = f'''
async def {generator.name}() -> Any:
    """{generator.schema.description or f"Call {generator.name} tool"}

    Returns:
        Result from the MCP server
    """
    result = await call_mcp_tool("{base_url}", "{generator.name}", {{}})
    return result
'''
            else:
                http_method = f'''
async def {generator.name}() -> str:
    """{generator.schema.description or f"Call {generator.name} tool"}

    Returns:
        String response from the tool server
    """
    async with httpx2.AsyncClient() as client:
        response = await client.get(
            "{base_url}{path_prefix}/{generator.name}",
            timeout=30.0
        )
        response.raise_for_status()
        return response.text
'''
            http_methods_parts.append(http_method)
            # Generate clean method with natural signature
            signature_str = generator.get_function_signature()
            params = generator.schema.parameters
            param_names = list(params.get("properties", {}).keys())
            if client_type == "fastmcp":
                clean_method = f'''
async def {signature_str}:
    """{generator.schema.description or f"Call {generator.name} tool"}"""
    # Build parameters dict
    params = {{{", ".join(f'"{name}": {name}' for name in param_names)}}}
    # Remove None values
    clean_params = {{k: v for k, v in params.items() if v is not None}}

    result = await call_mcp_tool("{base_url}", "{generator.name}", clean_params)
    return result
'''
            else:
                clean_method = f'''
async def {signature_str}:
    """{generator.schema.description or f"Call {generator.name} tool"}"""
    # Build parameters dict
    params = {{{", ".join(f'"{name}": {name}' for name in param_names)}}}
    # Remove None values
    clean_params = {{k: v for k, v in params.items() if v is not None}}

    async with httpx2.AsyncClient() as client:
        response = await client.get(
            "{base_url}{path_prefix}/{generator.name}",
            params=clean_params,
            timeout=30.0
        )
        response.raise_for_status()
        # Parse JSON response and return the result
        result = response.json()
        return result.get("result", response.text)
'''
            clean_methods_parts.append(clean_method)
            # Generate model-based stub
            if input_class_name:
                model_stub = f'''
async def {generator.name}(input: {input_class_name}) -> Any:
    """{generator.schema.description or f"Call {generator.name} tool"}

    Args:
        input: Function parameters

    Returns:
        Function result
    """
    ...
'''
                model_stubs_parts.append(model_stub)

            # Generate explicit signature stub
            explicit_stub = f'''
async def {signature_str}:
    """{generator.schema.description or f"Call {generator.name} tool"}"""
    ...
'''
            explicit_stubs_parts.append(explicit_stub)

        # Choose appropriate imports based on client type
        imports = FASTMCP_IMPORTS if client_type == "fastmcp" else HTTP_IMPORTS
        elapsed = time.time() - start_time
        logger.info("Structured code generation completed in %.2fs", elapsed)
        return GeneratedCode(
            models="\n".join(models_parts),
            http_methods="\n".join(http_methods_parts),
            clean_methods="\n".join(clean_methods_parts),
            model_stubs="\n".join(model_stubs_parts),
            explicit_stubs="\n".join(explicit_stubs_parts),
            imports=imports,
        )

generate_tool_description

generate_tool_description() -> str

Generate comprehensive tool description with available functions.

Source code in src/schemez/code_generation/toolset_code_generator.py
def generate_tool_description(self) -> str:
    """Generate comprehensive tool description with available functions."""
    if not self.generators:
        return "Execute Python code (no tools available)"

    parts = ["Available functions:"]
    for generator in self.generators:
        desc = generator.get_function_definition(self.include_docstrings)
        parts.append(desc)
    return "\n".join(parts)

get_fastmcp_client_code

get_fastmcp_client_code(server_configs: dict[str, str]) -> str

Generate FastMCP client code with connection management.

Parameters:

Name Type Description Default
server_configs dict[str, str]

Dict mapping server names to their transport URLs e.g., {"github": "sse://localhost:8080/github"}

required

Returns:

Type Description
str

FastMCP client code as string

Source code in src/schemez/code_generation/toolset_code_generator.py
    def get_fastmcp_client_code(self, server_configs: dict[str, str]) -> str:
        """Generate FastMCP client code with connection management.

        Args:
            server_configs: Dict mapping server names to their transport URLs
                          e.g., {"github": "sse://localhost:8080/github"}

        Returns:
            FastMCP client code as string
        """
        server_config_code = "SERVERS = " + repr(server_configs)
        return f'''{server_config_code}

# Connection management
_clients: dict[str, Client] = {{}}

async def get_mcp_client(server_name: str) -> Client:
    """Get or create FastMCP client for server."""
    if server_name not in _clients:
        if server_name not in SERVERS:
            raise ValueError(f"Unknown MCP server: {{server_name}}")

        transport_url = SERVERS[server_name]
        client = Client(transport_url)
        _clients[server_name] = client

    return _clients[server_name]

async def call_mcp_tool(
    server_name: str, tool_name: str, arguments: dict[str, Any]
) -> Any:
    """Call a FastMCP tool and return the result."""
    client = await get_mcp_client(server_name)

    async with client:
        result = await client.call_tool(tool_name, arguments)

        # FastMCP returns CallToolResult with structured content handling
        if result.data is not None:
            return result.data  # Parsed structured content
        elif result.content:
            # Extract text from content blocks
            text_parts = []
            for content_block in result.content:
                if hasattr(content_block, 'text'):
                    text_parts.append(content_block.text)
            return "\\n".join(text_parts) if text_parts else ""

        return ""

async def close_all_mcp_connections():
    """Close all MCP client connections."""
    for server_name, client in _clients.items():
        try:
            await client.close()
        except Exception as e:
            print(f"Error closing connection to {{server_name}}: {{e}}")
    _clients.clear()
'''