Extract a JSON object from an LLM response, with markdown fence handling. Returns the parsed dict, or None if no JSON object could be extracted. An empty dict ``{}`` is a valid successful parse (e.g. for no-arg tools).
(raw: str)
| 223 | |
| 224 | |
| 225 | def _parse_json(raw: str) -> dict | None: |
| 226 | """Extract a JSON object from an LLM response, with markdown fence handling. |
| 227 | |
| 228 | Returns the parsed dict, or None if no JSON object could be extracted. |
| 229 | An empty dict ``{}`` is a valid successful parse (e.g. for no-arg tools). |
| 230 | """ |
| 231 | text = raw.strip() |
| 232 | if text.startswith("```"): |
| 233 | lines = text.splitlines() |
| 234 | inner = lines[1:-1] if lines[-1].strip() == "```" else lines[1:] |
| 235 | text = "\n".join(inner).lstrip("json").strip() |
| 236 | try: |
| 237 | result = json.loads(text) |
| 238 | if isinstance(result, dict): |
| 239 | return result |
| 240 | except json.JSONDecodeError: |
| 241 | pass |
| 242 | start, end = text.find("{"), text.rfind("}") + 1 |
| 243 | if start != -1 and end > start: |
| 244 | try: |
| 245 | result = json.loads(text[start:end]) |
| 246 | if isinstance(result, dict): |
| 247 | return result |
| 248 | except json.JSONDecodeError: |
| 249 | pass |
| 250 | _log.debug("_parse_json: could not extract a JSON object from: %r…", raw[:120]) |
| 251 | return None |
| 252 | |
| 253 | |
| 254 | # ── MCP protocol helpers ────────────────────────────────────────────────────── |