Skip to content

ToolsetCodeGenerator

🛈 DocStrings

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()
'''

:fa-brands-github: Show source on GitHub