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
| Name | Required | Description | Default |
|---|---|---|---|
| text | Yes | ||
| substring | Yes | ||
| n | No |
Implementation Reference
- char_index_mcp/server.py:65-89 (handler)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
- char_index_mcp/server.py:64-64 (registration)The @mcp.tool() decorator from FastMCP registers the find_nth_substring function as an MCP tool.@mcp.tool()
- char_index_mcp/server.py:65-69 (schema)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: