Skip to main content
Glama

find_nth_substring

Locate the starting position of the nth occurrence of a substring within text. Returns -1 if the substring does not appear the specified number of times.

Instructions

Find starting index of nth occurrence of a substring. Returns -1 if not found.

Input Schema

TableJSON Schema
NameRequiredDescriptionDefault
textYes
substringYes
nNo

Implementation Reference

  • Implements the find_nth_substring tool logic using a while loop with str.find() to locate the starting index of the nth occurrence of the substring, handling overlaps by advancing start by 1.
    def find_nth_substring(
        text: Annotated[str, "Text to search in"],
        substring: Annotated[str, "Substring to find"],
        n: Annotated[int, "Which occurrence to find (1-based)"] = 1
    ) -> int:
        """Find starting index of nth occurrence of a substring. Returns -1 if not found."""
        if not substring:
            raise ValueError("substring cannot be empty")
        if n < 1:
            raise ValueError("n must be >= 1")
        
        count = 0
        start = 0
        
        while True:
            index = text.find(substring, start)
            if index == -1:
                return -1
            
            count += 1
            if count == n:
                return index
            
            start = index + 1
  • The @mcp.tool() decorator from FastMCP registers the find_nth_substring function as an MCP tool.
    @mcp.tool()
  • The function signature with Annotated type hints defines the input schema: text (str), substring (str), n (int, default 1) and output int.
    def find_nth_substring(
        text: Annotated[str, "Text to search in"],
        substring: Annotated[str, "Substring to find"],
        n: Annotated[int, "Which occurrence to find (1-based)"] = 1
    ) -> int:

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/agent-hanju/char-index-mcp'

If you have feedback or need assistance with the MCP directory API, please join our Discord server