debug-agent-py 0.3.0__tar.gz → 0.4.0__tar.gz

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (43) hide show
  1. {debug_agent_py-0.3.0 → debug_agent_py-0.4.0}/PKG-INFO +50 -6
  2. {debug_agent_py-0.3.0 → debug_agent_py-0.4.0}/README.md +49 -5
  3. {debug_agent_py-0.3.0 → debug_agent_py-0.4.0}/pyproject.toml +1 -1
  4. {debug_agent_py-0.3.0 → debug_agent_py-0.4.0}/src/debug_agent/inspectors/__init__.py +7 -0
  5. debug_agent_py-0.4.0/src/debug_agent/inspectors/cache_inspector.py +224 -0
  6. debug_agent_py-0.4.0/src/debug_agent/inspectors/fastapi_ext.py +226 -0
  7. debug_agent_py-0.4.0/src/debug_agent/inspectors/fd_inspector.py +150 -0
  8. debug_agent_py-0.4.0/src/debug_agent/inspectors/http_client_inspector.py +230 -0
  9. debug_agent_py-0.4.0/src/debug_agent/inspectors/logging_inspector.py +194 -0
  10. debug_agent_py-0.4.0/src/debug_agent/inspectors/metrics_inspector.py +102 -0
  11. debug_agent_py-0.4.0/src/debug_agent/inspectors/warnings_inspector.py +85 -0
  12. {debug_agent_py-0.3.0 → debug_agent_py-0.4.0}/src/debug_agent_py.egg-info/PKG-INFO +50 -6
  13. {debug_agent_py-0.3.0 → debug_agent_py-0.4.0}/src/debug_agent_py.egg-info/SOURCES.txt +7 -0
  14. {debug_agent_py-0.3.0 → debug_agent_py-0.4.0}/setup.cfg +0 -0
  15. {debug_agent_py-0.3.0 → debug_agent_py-0.4.0}/src/debug_agent/__init__.py +0 -0
  16. {debug_agent_py-0.3.0 → debug_agent_py-0.4.0}/src/debug_agent/chat_session.py +0 -0
  17. {debug_agent_py-0.3.0 → debug_agent_py-0.4.0}/src/debug_agent/config.py +0 -0
  18. {debug_agent_py-0.3.0 → debug_agent_py-0.4.0}/src/debug_agent/context_compressor.py +0 -0
  19. {debug_agent_py-0.3.0 → debug_agent_py-0.4.0}/src/debug_agent/engine.py +0 -0
  20. {debug_agent_py-0.3.0 → debug_agent_py-0.4.0}/src/debug_agent/inspectors/async_tasks.py +0 -0
  21. {debug_agent_py-0.3.0 → debug_agent_py-0.4.0}/src/debug_agent/inspectors/celery.py +0 -0
  22. {debug_agent_py-0.3.0 → debug_agent_py-0.4.0}/src/debug_agent/inspectors/database.py +0 -0
  23. {debug_agent_py-0.3.0 → debug_agent_py-0.4.0}/src/debug_agent/inspectors/django.py +0 -0
  24. {debug_agent_py-0.3.0 → debug_agent_py-0.4.0}/src/debug_agent/inspectors/flask_ext.py +0 -0
  25. {debug_agent_py-0.3.0 → debug_agent_py-0.4.0}/src/debug_agent/inspectors/framework.py +0 -0
  26. {debug_agent_py-0.3.0 → debug_agent_py-0.4.0}/src/debug_agent/inspectors/http_tracker.py +0 -0
  27. {debug_agent_py-0.3.0 → debug_agent_py-0.4.0}/src/debug_agent/inspectors/jinja2.py +0 -0
  28. {debug_agent_py-0.3.0 → debug_agent_py-0.4.0}/src/debug_agent/inspectors/memory.py +0 -0
  29. {debug_agent_py-0.3.0 → debug_agent_py-0.4.0}/src/debug_agent/inspectors/modules.py +0 -0
  30. {debug_agent_py-0.3.0 → debug_agent_py-0.4.0}/src/debug_agent/inspectors/redis.py +0 -0
  31. {debug_agent_py-0.3.0 → debug_agent_py-0.4.0}/src/debug_agent/inspectors/runtime.py +0 -0
  32. {debug_agent_py-0.3.0 → debug_agent_py-0.4.0}/src/debug_agent/inspectors/signals.py +0 -0
  33. {debug_agent_py-0.3.0 → debug_agent_py-0.4.0}/src/debug_agent/inspectors/system.py +0 -0
  34. {debug_agent_py-0.3.0 → debug_agent_py-0.4.0}/src/debug_agent/inspectors/threads.py +0 -0
  35. {debug_agent_py-0.3.0 → debug_agent_py-0.4.0}/src/debug_agent/llm_client.py +0 -0
  36. {debug_agent_py-0.3.0 → debug_agent_py-0.4.0}/src/debug_agent/middleware.py +0 -0
  37. {debug_agent_py-0.3.0 → debug_agent_py-0.4.0}/src/debug_agent/system_prompt_builder.py +0 -0
  38. {debug_agent_py-0.3.0 → debug_agent_py-0.4.0}/src/debug_agent/tool_registry.py +0 -0
  39. {debug_agent_py-0.3.0 → debug_agent_py-0.4.0}/src/debug_agent/web/__init__.py +0 -0
  40. {debug_agent_py-0.3.0 → debug_agent_py-0.4.0}/src/debug_agent/web/chat_page.py +0 -0
  41. {debug_agent_py-0.3.0 → debug_agent_py-0.4.0}/src/debug_agent_py.egg-info/dependency_links.txt +0 -0
  42. {debug_agent_py-0.3.0 → debug_agent_py-0.4.0}/src/debug_agent_py.egg-info/requires.txt +0 -0
  43. {debug_agent_py-0.3.0 → debug_agent_py-0.4.0}/src/debug_agent_py.egg-info/top_level.txt +0 -0
@@ -1,6 +1,6 @@
1
1
  Metadata-Version: 2.4
2
2
  Name: debug-agent-py
3
- Version: 0.3.0
3
+ Version: 0.4.0
4
4
  Summary: AI-powered runtime debugging agent for Python web applications
5
5
  Author-email: ggcode <noreply@ggcode.dev>
6
6
  License: MIT
@@ -52,10 +52,10 @@ Requires-Dist: pytest; extra == "dev"
52
52
  # Python Debug Agent
53
53
 
54
54
  [![debug-agent-py](https://img.shields.io/pypi/v/debug-agent-py.svg)](https://pypi.org/project/debug-agent-py/)
55
- ![Tools](https://img.shields.io/badge/tools-51-blue)
56
- ![Inspectors](https://img.shields.io/badge/inspectors-16-green)
55
+ ![Tools](https://img.shields.io/badge/tools-68-blue)
56
+ ![Inspectors](https://img.shields.io/badge/inspectors-24-green)
57
57
 
58
- An AI-powered runtime debugging agent that embeds directly into your Python web application. Add one dependency, configure an LLM key, and chat with your live app at `/agent` to inspect memory, threads, GC, modules, database connections, Redis, Django models/URLs, Celery tasks, Flask extensions, Jinja2 templates, signals, routes, HTTP requests, and more — **51 diagnostic tools across 16 inspectors**.
58
+ An AI-powered runtime debugging agent that embeds directly into your Python web application. Add one dependency, configure an LLM key, and chat with your live app at `/agent` to inspect memory, threads, GC, modules, database connections, Redis, Django models/URLs, Celery tasks, Flask extensions, Jinja2 templates, signals, routes, HTTP requests, and more — **68 diagnostic tools across 24 inspectors**.
59
59
 
60
60
  ## Quick Start
61
61
 
@@ -99,11 +99,11 @@ http://localhost:8000/agent
99
99
  - **Context compression** — automatically summarizes old conversation when token limit is approached
100
100
  - **Dark-themed chat UI** with full markdown rendering (tables, code blocks, lists)
101
101
  - **Max tool rounds** (25) with forced final summary when limit is reached
102
- - **51 diagnostic tools** across **16 inspectors**
102
+ - **68 diagnostic tools** across **24 inspectors**
103
103
  - Works with Flask, FastAPI, and Django
104
104
  - Zero external dependencies (no Datadog, no Grafana, no APM)
105
105
 
106
- ## Inspectors & Tools (51)
106
+ ## Inspectors & Tools (68)
107
107
 
108
108
  ### Memory Inspector
109
109
  | Tool | Description |
@@ -220,6 +220,50 @@ http://localhost:8000/agent
220
220
  | `get_wsgi_info` | WSGI server details (Gunicorn/uWSGI workers, config) |
221
221
  | `get_asgi_apps` | List ASGI application scope and middleware chain |
222
222
 
223
+ ### Logging Inspector
224
+ | Tool | Description |
225
+ |------|-------------|
226
+ | `get_logging_tree` | Python logging module logger hierarchy and levels |
227
+ | `get_recent_logs` | Recent log entries from the built-in ring buffer |
228
+ | `get_logging_config` | Current logging configuration (handlers, formatters, levels) |
229
+ | `set_log_level` | Dynamically set the log level for a named logger |
230
+
231
+ ### Cache Inspector
232
+ | Tool | Description |
233
+ |------|-------------|
234
+ | `get_cache_info` | Stats for registered caches (hit rate, miss count, key count) |
235
+ | `get_cache_keys` | List keys from a registered cache with optional prefix filter |
236
+ | `clear_cache` | Clear all entries from a registered cache |
237
+
238
+ ### Outbound HTTP Inspector
239
+ | Tool | Description |
240
+ |------|-------------|
241
+ | `get_http_pool_stats` | HTTP client connection pool stats (connections, keepalive, timeouts) |
242
+ | `get_outbound_summary` | Aggregated outbound HTTP call stats (total, avg latency, error rate) |
243
+
244
+ ### File Descriptor Inspector
245
+ | Tool | Description |
246
+ |------|-------------|
247
+ | `get_fd_count` | Current number of open file descriptors |
248
+ | `get_fd_limit` | File descriptor soft and hard limits (RLIMIT_NOFILE) |
249
+ | `get_fd_list` | List open file descriptors with type and details |
250
+
251
+ ### Metrics Inspector
252
+ | Tool | Description |
253
+ |------|-------------|
254
+ | `get_registered_metrics` | List all registered metrics from prometheus_client |
255
+ | `get_metric_value` | Get current value of a specific metric by name |
256
+
257
+ ### FastAPI Inspector
258
+ | Tool | Description |
259
+ |------|-------------|
260
+ | `get_fastapi_openapi` | List FastAPI routes, schemas, and OpenAPI spec details |
261
+
262
+ ### Warnings Inspector
263
+ | Tool | Description |
264
+ |------|-------------|
265
+ | `get_warnings` | List captured Python warnings with category, message, and location |
266
+
223
267
  ## Custom Tools
224
268
 
225
269
  ```python
@@ -1,10 +1,10 @@
1
1
  # Python Debug Agent
2
2
 
3
3
  [![debug-agent-py](https://img.shields.io/pypi/v/debug-agent-py.svg)](https://pypi.org/project/debug-agent-py/)
4
- ![Tools](https://img.shields.io/badge/tools-51-blue)
5
- ![Inspectors](https://img.shields.io/badge/inspectors-16-green)
4
+ ![Tools](https://img.shields.io/badge/tools-68-blue)
5
+ ![Inspectors](https://img.shields.io/badge/inspectors-24-green)
6
6
 
7
- An AI-powered runtime debugging agent that embeds directly into your Python web application. Add one dependency, configure an LLM key, and chat with your live app at `/agent` to inspect memory, threads, GC, modules, database connections, Redis, Django models/URLs, Celery tasks, Flask extensions, Jinja2 templates, signals, routes, HTTP requests, and more — **51 diagnostic tools across 16 inspectors**.
7
+ An AI-powered runtime debugging agent that embeds directly into your Python web application. Add one dependency, configure an LLM key, and chat with your live app at `/agent` to inspect memory, threads, GC, modules, database connections, Redis, Django models/URLs, Celery tasks, Flask extensions, Jinja2 templates, signals, routes, HTTP requests, and more — **68 diagnostic tools across 24 inspectors**.
8
8
 
9
9
  ## Quick Start
10
10
 
@@ -48,11 +48,11 @@ http://localhost:8000/agent
48
48
  - **Context compression** — automatically summarizes old conversation when token limit is approached
49
49
  - **Dark-themed chat UI** with full markdown rendering (tables, code blocks, lists)
50
50
  - **Max tool rounds** (25) with forced final summary when limit is reached
51
- - **51 diagnostic tools** across **16 inspectors**
51
+ - **68 diagnostic tools** across **24 inspectors**
52
52
  - Works with Flask, FastAPI, and Django
53
53
  - Zero external dependencies (no Datadog, no Grafana, no APM)
54
54
 
55
- ## Inspectors & Tools (51)
55
+ ## Inspectors & Tools (68)
56
56
 
57
57
  ### Memory Inspector
58
58
  | Tool | Description |
@@ -169,6 +169,50 @@ http://localhost:8000/agent
169
169
  | `get_wsgi_info` | WSGI server details (Gunicorn/uWSGI workers, config) |
170
170
  | `get_asgi_apps` | List ASGI application scope and middleware chain |
171
171
 
172
+ ### Logging Inspector
173
+ | Tool | Description |
174
+ |------|-------------|
175
+ | `get_logging_tree` | Python logging module logger hierarchy and levels |
176
+ | `get_recent_logs` | Recent log entries from the built-in ring buffer |
177
+ | `get_logging_config` | Current logging configuration (handlers, formatters, levels) |
178
+ | `set_log_level` | Dynamically set the log level for a named logger |
179
+
180
+ ### Cache Inspector
181
+ | Tool | Description |
182
+ |------|-------------|
183
+ | `get_cache_info` | Stats for registered caches (hit rate, miss count, key count) |
184
+ | `get_cache_keys` | List keys from a registered cache with optional prefix filter |
185
+ | `clear_cache` | Clear all entries from a registered cache |
186
+
187
+ ### Outbound HTTP Inspector
188
+ | Tool | Description |
189
+ |------|-------------|
190
+ | `get_http_pool_stats` | HTTP client connection pool stats (connections, keepalive, timeouts) |
191
+ | `get_outbound_summary` | Aggregated outbound HTTP call stats (total, avg latency, error rate) |
192
+
193
+ ### File Descriptor Inspector
194
+ | Tool | Description |
195
+ |------|-------------|
196
+ | `get_fd_count` | Current number of open file descriptors |
197
+ | `get_fd_limit` | File descriptor soft and hard limits (RLIMIT_NOFILE) |
198
+ | `get_fd_list` | List open file descriptors with type and details |
199
+
200
+ ### Metrics Inspector
201
+ | Tool | Description |
202
+ |------|-------------|
203
+ | `get_registered_metrics` | List all registered metrics from prometheus_client |
204
+ | `get_metric_value` | Get current value of a specific metric by name |
205
+
206
+ ### FastAPI Inspector
207
+ | Tool | Description |
208
+ |------|-------------|
209
+ | `get_fastapi_openapi` | List FastAPI routes, schemas, and OpenAPI spec details |
210
+
211
+ ### Warnings Inspector
212
+ | Tool | Description |
213
+ |------|-------------|
214
+ | `get_warnings` | List captured Python warnings with category, message, and location |
215
+
172
216
  ## Custom Tools
173
217
 
174
218
  ```python
@@ -4,7 +4,7 @@ build-backend = "setuptools.build_meta"
4
4
 
5
5
  [project]
6
6
  name = "debug-agent-py"
7
- version = "0.3.0"
7
+ version = "0.4.0"
8
8
  description = "AI-powered runtime debugging agent for Python web applications"
9
9
  readme = "README.md"
10
10
  license = {text = "MIT"}
@@ -2,18 +2,25 @@
2
2
 
3
3
  from debug_agent.inspectors import ( # noqa: F401
4
4
  async_tasks,
5
+ cache_inspector,
5
6
  celery,
6
7
  database,
7
8
  django,
9
+ fastapi_ext,
10
+ fd_inspector,
8
11
  flask_ext,
9
12
  framework,
13
+ http_client_inspector,
10
14
  http_tracker,
11
15
  jinja2,
16
+ logging_inspector,
12
17
  memory,
18
+ metrics_inspector,
13
19
  modules,
14
20
  redis,
15
21
  runtime,
16
22
  signals,
17
23
  system,
18
24
  threads,
25
+ warnings_inspector,
19
26
  )
@@ -0,0 +1,224 @@
1
+ """Cache inspector: stats and management for registered caches.
2
+
3
+ Register a cache at runtime so the inspector can reach it:
4
+
5
+ from debug_agent.inspectors.cache_inspector import register_cache
6
+ register_cache("my_cache", my_cache_obj)
7
+
8
+ Supports functools.lru_cache, cachetools caches, Django cache backends,
9
+ and custom cache objects.
10
+ """
11
+
12
+ from __future__ import annotations
13
+
14
+ from typing import Any
15
+
16
+ from debug_agent.tool_registry import debug_tool, ToolParam
17
+
18
+
19
+ # ─── Registration ────────────────────────────────────────────────────────────
20
+
21
+ _registered_caches: dict[str, Any] = {}
22
+
23
+
24
+ def register_cache(name: str, cache_obj: Any) -> None:
25
+ """Register a cache object under a name so the inspectors can find it."""
26
+ _registered_caches[name] = cache_obj
27
+
28
+
29
+ # ─── Cache type detection ────────────────────────────────────────────────────
30
+
31
+
32
+ def _detect_type(cache_obj: Any) -> str:
33
+ """Return a label describing the cache implementation."""
34
+ # functools.lru_cache / functools.cache wrappers expose cache_info()
35
+ if hasattr(cache_obj, "cache_info") and hasattr(cache_obj, "cache_clear"):
36
+ return "lru_cache"
37
+
38
+ # cachetools caches have __contains__ and __len__
39
+ cls_name = type(cache_obj).__module__ + "." + type(cache_obj).__qualname__
40
+ if "cachetools" in type(cache_obj).__module__:
41
+ return "cachetools"
42
+
43
+ # Django cache backends expose _cache attribute
44
+ if hasattr(cache_obj, "_cache"):
45
+ return "django"
46
+
47
+ # Generic mapping-like caches
48
+ if hasattr(cache_obj, "__contains__") and hasattr(cache_obj, "__len__"):
49
+ return "mapping"
50
+
51
+ # Custom caches with stats()/info() methods
52
+ if hasattr(cache_obj, "stats") or hasattr(cache_obj, "info"):
53
+ return "custom"
54
+
55
+ return "unknown"
56
+
57
+
58
+ # ─── Tools ───────────────────────────────────────────────────────────────────
59
+
60
+
61
+ @debug_tool(
62
+ "get_cache_info",
63
+ "Get stats for registered caches (lru_cache, cachetools, django, custom)",
64
+ )
65
+ def get_cache_info(
66
+ name: str = ToolParam("Cache name (omit for all registered caches)", required=False),
67
+ ) -> dict:
68
+ if name:
69
+ cache_obj = _registered_caches.get(name)
70
+ if cache_obj is None:
71
+ return {"error": f"No cache registered with name '{name}'"}
72
+ return _inspect_cache(name, cache_obj)
73
+
74
+ if not _registered_caches:
75
+ return {
76
+ "message": "No caches registered. Call register_cache(name, cache_obj) to register one.",
77
+ "registered_count": 0,
78
+ }
79
+
80
+ result = []
81
+ for cache_name, cache_obj in _registered_caches.items():
82
+ try:
83
+ result.append(_inspect_cache(cache_name, cache_obj))
84
+ except Exception as exc:
85
+ result.append({"name": cache_name, "error": str(exc)})
86
+
87
+ return {"registered_count": len(result), "caches": result}
88
+
89
+
90
+ def _inspect_cache(name: str, cache_obj: Any) -> dict[str, Any]:
91
+ cache_type = _detect_type(cache_obj)
92
+ info: dict[str, Any] = {"name": name, "type": cache_type}
93
+
94
+ # functools.lru_cache
95
+ if cache_type == "lru_cache":
96
+ try:
97
+ ci = cache_obj.cache_info()
98
+ info.update(
99
+ {
100
+ "hits": getattr(ci, "hits", None),
101
+ "misses": getattr(ci, "misses", None),
102
+ "maxsize": getattr(ci, "maxsize", None),
103
+ "current_size": getattr(ci, "currsize", None),
104
+ }
105
+ )
106
+ return info
107
+ except Exception as exc:
108
+ info["error"] = str(exc)
109
+ return info
110
+
111
+ # cachetools / generic mapping
112
+ if cache_type in ("cachetools", "mapping"):
113
+ try:
114
+ info["size"] = len(cache_obj)
115
+ except Exception:
116
+ info["size"] = None
117
+ info["maxsize"] = getattr(cache_obj, "maxsize", None)
118
+ return info
119
+
120
+ # django cache
121
+ if cache_type == "django":
122
+ try:
123
+ inner = getattr(cache_obj, "_cache", None)
124
+ if inner is not None and hasattr(inner, "__len__"):
125
+ info["size"] = len(inner)
126
+ else:
127
+ info["size"] = None
128
+ except Exception:
129
+ info["size"] = None
130
+ info["backend"] = type(cache_obj).__name__
131
+ return info
132
+
133
+ # custom: try stats(), info(), size
134
+ if cache_type == "custom":
135
+ for method in ("stats", "info"):
136
+ if hasattr(cache_obj, method):
137
+ try:
138
+ val = getattr(cache_obj, method)()
139
+ if isinstance(val, dict):
140
+ info.update(val)
141
+ else:
142
+ info[method] = val
143
+ except Exception:
144
+ pass
145
+ size = getattr(cache_obj, "size", None)
146
+ if size is not None:
147
+ info["size"] = size() if callable(size) else size
148
+ return info
149
+
150
+ return info
151
+
152
+
153
+ @debug_tool(
154
+ "get_cache_keys",
155
+ "List keys in a registered cache with optional prefix filter",
156
+ )
157
+ def get_cache_keys(
158
+ name: str = ToolParam("Cache name"),
159
+ prefix: str = ToolParam("Optional key prefix to filter by", required=False),
160
+ ) -> dict:
161
+ cache_obj = _registered_caches.get(name)
162
+ if cache_obj is None:
163
+ return {"error": f"No cache registered with name '{name}'"}
164
+
165
+ cache_type = _detect_type(cache_obj)
166
+ keys: list[Any] = []
167
+
168
+ try:
169
+ if cache_type == "lru_cache":
170
+ return {
171
+ "name": name,
172
+ "type": cache_type,
173
+ "message": "lru_cache does not expose its keys",
174
+ }
175
+
176
+ # Django locmem / cachetools / generic mapping
177
+ inner = cache_obj
178
+ if cache_type == "django":
179
+ inner = getattr(cache_obj, "_cache", cache_obj)
180
+
181
+ if hasattr(inner, "keys"):
182
+ keys = list(inner.keys())
183
+ elif hasattr(inner, "__iter__"):
184
+ keys = [k for k in inner]
185
+ except Exception as exc:
186
+ return {"error": f"Could not enumerate keys: {exc}"}
187
+
188
+ if prefix:
189
+ keys = [k for k in keys if str(k).startswith(prefix)]
190
+
191
+ return {
192
+ "name": name,
193
+ "type": cache_type,
194
+ "total": len(keys),
195
+ "keys": keys[:500], # cap to avoid huge responses
196
+ }
197
+
198
+
199
+ @debug_tool(
200
+ "clear_cache",
201
+ "Clear a registered cache (lru_cache: cache_clear, cachetools/django: clear)",
202
+ )
203
+ def clear_cache(
204
+ name: str = ToolParam("Cache name"),
205
+ ) -> dict:
206
+ cache_obj = _registered_caches.get(name)
207
+ if cache_obj is None:
208
+ return {"error": f"No cache registered with name '{name}'"}
209
+
210
+ cache_type = _detect_type(cache_obj)
211
+
212
+ try:
213
+ if cache_type == "lru_cache":
214
+ cache_obj.cache_clear()
215
+ elif hasattr(cache_obj, "clear"):
216
+ cache_obj.clear()
217
+ else:
218
+ return {
219
+ "error": f"Cache '{name}' (type: {cache_type}) does not support clearing",
220
+ }
221
+ except Exception as exc:
222
+ return {"error": f"Failed to clear cache '{name}': {exc}"}
223
+
224
+ return {"name": name, "type": cache_type, "cleared": True}
@@ -0,0 +1,226 @@
1
+ """FastAPI inspector: OpenAPI schema and Pydantic model introspection.
2
+
3
+ Register a FastAPI app at runtime so the inspector can reach it:
4
+
5
+ from debug_agent.inspectors.fastapi_ext import register_fastapi_app
6
+ register_fastapi_app("my_app", app)
7
+ """
8
+
9
+ from __future__ import annotations
10
+
11
+ import sys
12
+ from typing import Any
13
+
14
+ from debug_agent.tool_registry import debug_tool, ToolParam
15
+
16
+
17
+ # ─── Registration ────────────────────────────────────────────────────────────
18
+
19
+ _registered_apps: dict[str, Any] = {}
20
+
21
+
22
+ def register_fastapi_app(name: str, app: Any) -> None:
23
+ """Register a FastAPI app instance under a name."""
24
+ _registered_apps[name] = app
25
+
26
+
27
+ def _fastapi_available() -> bool:
28
+ try:
29
+ import fastapi # noqa: F401
30
+ return True
31
+ except ImportError:
32
+ return False
33
+
34
+
35
+ def _find_fastapi_apps() -> dict[str, Any]:
36
+ """Return registered apps plus any discovered in loaded modules."""
37
+ apps = dict(_registered_apps)
38
+
39
+ try:
40
+ import fastapi
41
+ except ImportError:
42
+ return apps
43
+
44
+ for mod in list(sys.modules.values()):
45
+ if mod is None or mod.__name__.startswith("debug_agent"):
46
+ continue
47
+ for attr_name in dir(mod):
48
+ if attr_name.startswith("_"):
49
+ continue
50
+ try:
51
+ obj = getattr(mod, attr_name)
52
+ if isinstance(obj, fastapi.FastAPI):
53
+ key = f"{mod.__name__}.{attr_name}"
54
+ if key not in apps:
55
+ apps[key] = obj
56
+ except Exception:
57
+ continue
58
+ return apps
59
+
60
+
61
+ # ─── Pydantic helpers ────────────────────────────────────────────────────────
62
+
63
+
64
+ def _describe_pydantic_model(model_cls: Any) -> dict[str, Any]:
65
+ """Return field metadata for a Pydantic v2 (or v1) model class."""
66
+ fields: dict[str, Any] = {}
67
+
68
+ # Pydantic v2: model_fields
69
+ model_fields = getattr(model_cls, "model_fields", None)
70
+ if model_fields:
71
+ for fname, finfo in model_fields.items():
72
+ entry: dict[str, Any] = {}
73
+ annotation = getattr(finfo, "annotation", None)
74
+ entry["type"] = str(annotation) if annotation is not None else None
75
+ entry["default"] = repr(getattr(finfo, "default", None))
76
+ entry["required"] = getattr(finfo, "is_required", lambda: True)()
77
+ fields[fname] = entry
78
+ return {"name": model_cls.__name__, "pydantic": "v2", "fields": fields}
79
+
80
+ # Pydantic v1: __fields__
81
+ v1_fields = getattr(model_cls, "__fields__", None)
82
+ if v1_fields:
83
+ for fname, finfo in v1_fields.items():
84
+ entry = {
85
+ "type": str(finfo.outer_type_) if hasattr(finfo, "outer_type_") else None,
86
+ "required": bool(getattr(finfo, "required", True)),
87
+ }
88
+ default = getattr(finfo, "default", None)
89
+ entry["default"] = repr(default)
90
+ fields[fname] = entry
91
+ return {"name": model_cls.__name__, "pydantic": "v1", "fields": fields}
92
+
93
+ return {"name": getattr(model_cls, "__name__", str(model_cls)), "fields": {}}
94
+
95
+
96
+ # ─── Tools ───────────────────────────────────────────────────────────────────
97
+
98
+
99
+ @debug_tool(
100
+ "get_fastapi_openapi",
101
+ "Get FastAPI OpenAPI schema and Pydantic models with field types from registered apps",
102
+ )
103
+ def get_fastapi_openapi(
104
+ name: str = ToolParam("App name (omit to list all registered apps)", required=False),
105
+ ) -> dict:
106
+ if not _fastapi_available():
107
+ return {"error": "FastAPI is not installed"}
108
+
109
+ apps = _find_fastapi_apps()
110
+ if not apps:
111
+ return {
112
+ "message": "No FastAPI apps registered. Call register_fastapi_app(name, app) to register one.",
113
+ "registered_count": 0,
114
+ }
115
+
116
+ if name:
117
+ app = apps.get(name)
118
+ if app is None:
119
+ return {
120
+ "error": f"No FastAPI app found with name '{name}'",
121
+ "available": list(apps.keys()),
122
+ }
123
+ return _inspect_app(name, app)
124
+
125
+ if len(apps) == 1:
126
+ n, a = next(iter(apps.items()))
127
+ return _inspect_app(n, a)
128
+
129
+ return {
130
+ "registered_count": len(apps),
131
+ "apps": list(apps.keys()),
132
+ "message": "Multiple apps found. Specify 'name' to inspect one.",
133
+ }
134
+
135
+
136
+ def _inspect_app(name: str, app: Any) -> dict[str, Any]:
137
+ result: dict[str, Any] = {"app": name}
138
+
139
+ # OpenAPI schema
140
+ try:
141
+ result["openapi_version"] = getattr(app, "openapi_version", None)
142
+ result["title"] = getattr(app, "title", None)
143
+ result["version"] = getattr(app, "version", None)
144
+
145
+ get_schema = getattr(app, "openapi", None)
146
+ if callable(get_schema):
147
+ schema = get_schema()
148
+ result["path_count"] = len(schema.get("paths", {})) if isinstance(schema, dict) else 0
149
+ result["openapi_schema"] = schema
150
+ except Exception as exc:
151
+ result["openapi_error"] = str(exc)
152
+
153
+ # Routes summary (lighter than full schema)
154
+ try:
155
+ routes = []
156
+ for route in app.routes:
157
+ methods = getattr(route, "methods", None) or set()
158
+ routes.append(
159
+ {
160
+ "path": getattr(route, "path", None),
161
+ "methods": sorted(methods) if methods else [],
162
+ "name": getattr(route, "name", None),
163
+ "endpoint": getattr(getattr(route, "endpoint", None), "__name__", None),
164
+ }
165
+ )
166
+ result["routes"] = routes
167
+ result["route_count"] = len(routes)
168
+ except Exception as exc:
169
+ result["routes_error"] = str(exc)
170
+
171
+ # Pydantic models referenced by the app
172
+ try:
173
+ models = []
174
+ for route in app.routes:
175
+ endpoint = getattr(route, "endpoint", None)
176
+ if endpoint is None:
177
+ continue
178
+ # Inspect body param type hints for BaseModel subclasses
179
+ try:
180
+ import typing
181
+
182
+ hints = typing.get_type_hints(endpoint)
183
+ except Exception:
184
+ hints = {}
185
+
186
+ import inspect as pyinspect
187
+
188
+ sig = pyinspect.signature(endpoint)
189
+ for pname, param in sig.parameters.items():
190
+ if pname in ("self", "request", "response"):
191
+ continue
192
+ ann = hints.get(pname, None)
193
+ model_cls = _resolve_model_class(ann)
194
+ if model_cls is not None and model_cls not in [m.get("_cls") for m in models]:
195
+ models.append({**_describe_pydantic_model(model_cls), "_cls": model_cls})
196
+
197
+ # Strip the internal _cls key
198
+ for m in models:
199
+ m.pop("_cls", None)
200
+ result["pydantic_models"] = models
201
+ result["model_count"] = len(models)
202
+ except Exception as exc:
203
+ result["models_error"] = str(exc)
204
+
205
+ return result
206
+
207
+
208
+ def _resolve_model_class(ann: Any) -> Any:
209
+ """Return a Pydantic BaseModel subclass from an annotation, or None."""
210
+ try:
211
+ from pydantic import BaseModel
212
+ except ImportError:
213
+ return None
214
+
215
+ if ann is None:
216
+ return None
217
+ if isinstance(ann, type) and issubclass(ann, BaseModel):
218
+ return ann
219
+
220
+ # Handle typing constructs like Optional[Model], Body(...)
221
+ args = getattr(ann, "__args__", None)
222
+ if args:
223
+ for arg in args:
224
+ if isinstance(arg, type) and issubclass(arg, BaseModel):
225
+ return arg
226
+ return None