in gemini/mcp/mcp_orchestration_app/src/gemini_client.py [0:0]
def extract_tool_call_json(text: str) -> Optional[Dict[str, Any]]:
"""
Extracts a JSON object formatted for tool
calls from markdown code blocks.
Specifically looks for ```json { "tool": ..., "arguments": ... } ```
Args:
text: The input string potentially containing
the JSON tool call.
Returns:
The loaded Python dictionary representing the tool call,
or None if extraction/parsing fails or
if it's not a valid tool call structure.
"""
# Regex to find ```json ... ``` block
# Using non-greedy matching .*? for the content
match = re.search(r"```json\s*(\{.*?\})\s*```", text, re.DOTALL | re.IGNORECASE)
json_string = None
if match:
json_string = match.group(1).strip()
logging.debug(
"Extracted JSON string " f"from ```json block:\n{json_string}"
)
else:
# Fallback: If no ```json block, maybe the entire text is the JSON?
# Be cautious with this, might parse unintended text.
# Let's only consider it if it looks like a JSON object.
text_stripped = text.strip()
if text_stripped.startswith("{") and text_stripped.endswith("}"):
json_string = text_stripped
logging.debug(
"No ```json block found, attempting to "
"parse entire stripped text as JSON."
)
if not json_string:
# If after trying both, we have nothing, return None
# This also catches the case where the original
# text was empty or whitespace
if text.strip(): # Only log if there was actual text content
logging.debug(
"Could not extract a JSON string from "
f"the LLM response: >>>{text}<<<"
)
return None
# Load the extracted string into a Python JSON object
try:
loaded_json = json.loads(json_string)
# Validate if it looks like a tool call
if (
isinstance(loaded_json, dict)
and "tool" in loaded_json
and "arguments" in loaded_json
):
logging.debug("Successfully validated JSON ")
return loaded_json
logging.debug(
"Parsed JSON but it does not " + "match expected tool call structure."
)
return None # Not a valid tool call structure
except json.JSONDecodeError as e:
logging.warning(
f"Error decoding JSON: {e}. String was: >>>{json_string}<<<"
)
return None