Name | tracelight JSON |
Version |
0.1.3
JSON |
| download |
home_page | None |
Summary | Reveal hidden state in Python exceptions with automatic variable tracing |
upload_time | 2025-08-04 18:46:19 |
maintainer | None |
docs_url | None |
author | None |
requires_python | >=3.7 |
license | MIT |
keywords |
debugging
exceptions
logging
tracing
agents
|
VCS |
 |
bugtrack_url |
|
requirements |
No requirements were recorded.
|
Travis-CI |
No Travis.
|
coveralls test coverage |
No coveralls.
|
# Tracelight
> Reveal hidden state in Python exceptions with automatic variable tracing
Tracelight exposes the hidden state of your application by automatically logging all local variables in each frame of an exception's traceback. This gives you instant insight into what went wrong without having to add print statements or run in debug mode.
## ✨ Special Features
🔧 **Pydantic Integration**: Automatically detects and serializes Pydantic models (both v1 and v2) in exception traces, showing model data instead of object representations.
🤖 **Agent-First Design**: Built specifically for agent systems and MCP servers with structured error responses that never crash your workflows.
📊 **Smart Variable Handling**: Intelligently formats complex data structures, truncates large values, and excludes sensitive information.
## Installation
```bash
pip install tracelight
```
## Quick Start
```python
import logging
from tracelight import log_exception_state
# Configure your logger however you like
logging.basicConfig(level=logging.DEBUG)
logger = logging.getLogger("exception_logger")
def some_function(x):
a = x + 1
b = a * 2
return b / 0 # Deliberate error
try:
some_function(5)
except Exception as e:
# Log all local variables from each frame
log_exception_state(e, logger)
# Re-raise if needed
raise
```
## Key Features
### Function Decorator
Automate error handling with the `@traced` decorator:
```python
from tracelight import traced
@traced()
def risky_function(x, y):
complicated_result = process(x)
return complicated_result[y] # Might raise KeyError
# All exceptions automatically logged with full variable context!
risky_function("input", "missing_key")
```
### Agent Tool Decorator
Specifically designed for agent systems and MCP servers:
```python
from tracelight.agent_utils import traced_tool
@traced_tool()
def weather_tool(location="New York"):
# Complex implementation with HTTP calls etc.
return get_weather_data(location)
# If anything fails, returns a structured error dict:
# {"status": "error", "error_type": "...", ...}
```
### Context Manager
Easily wrap specific blocks of code:
```python
from tracelight import TracedError
# Automatically logs and preserves original exception
with TracedError(logger=my_logger):
risky_operation()
```
### 🔧 Pydantic Model Support
Tracelight automatically detects and properly serializes Pydantic models in exception traces:
```python
from pydantic import BaseModel
from tracelight import log_exception_state
class UserModel(BaseModel):
name: str
age: int
email: str
def process_user(user_data):
user = UserModel(**user_data) # Pydantic model
# ... processing that might fail
return user.name.upper().split()[10] # IndexError!
try:
process_user({"name": "Alice Smith", "age": 30, "email": "alice@example.com"})
except Exception as e:
# Tracelight will show the full Pydantic model data:
# user = {'name': 'Alice Smith', 'age': 30, 'email': 'alice@example.com'}
log_exception_state(e, logger)
```
## Use Cases
Tracelight is particularly useful for:
### 1. Data‐Pipeline Breakdowns
**Context**: Multi-stage ETL jobs where a mysterious `KeyError` pops up.
**With Tracelight**: Your logs show the full contents of the record and every local variable—no need to sprinkle `print` calls or guess which field is missing.
### 2. Async Callback Chaos
**Context**: In an `asyncio`-driven system, tasks fire off callbacks and one raises an exception deep inside a helper function.
**With Tracelight**: You get the full context of all local variables in that callback frame—instantly pinpointing the cause.
### 3. Agent-Based Workflows
**Context**: Your LLM‐driven agent orchestrates several tools; one tool call fails with a parsing error.
**With Tracelight**: You immediately see all variables in context, including the raw responses and state data—so you can adjust your tool chain.
## Integration with Agent Systems
Tracelight is designed to work seamlessly with agent-based systems and Model Context Protocol (MCP) servers. It can be integrated as a drop-in error handler to provide rich debugging information when tool calls or agent workflows fail unexpectedly.
```python
from tracelight import log_exception_state
from tracelight.agent_utils import traced_tool
# Method 1: Wrap entire tool with decorator
@traced_tool()
def agent_tool(params):
# Complex implementation...
return process_complex_workflow(params)
# Method 2: Manual integration
def another_tool(params):
try:
# Complex tool implementation
result = process_complex_workflow(params)
return {"status": "success", "data": result}
except Exception as e:
# Log all variables in each frame of the exception
log_exception_state(e, logger)
# Return a graceful error response with helpful context
return {
"status": "error",
"error": str(e),
"error_type": type(e).__name__
}
```
## FastMCP Integration Example
Tracelight integrates seamlessly with FastMCP servers for rich error handling in MCP tools:
```python
from mcp.server.fastmcp import FastMCP, Context
from pydantic import BaseModel, Field
from tracelight.agent_utils import traced_tool
import logging
# Setup logging
logger = logging.getLogger("mcp-server")
# Create FastMCP server
mcp = FastMCP("TracelightExample")
# Define request model
class WeatherRequest(BaseModel):
city: str = Field(..., description="City to get weather for")
country_code: str = Field(None, description="Optional 2-letter country code")
# Define response models
class WeatherResponse(BaseModel):
temperature: float
condition: str
humidity: int
class ErrorResponse(BaseModel):
status: str = "error"
error_type: str
error: str
context: dict = None
# Create traced tool with automatic error handling
@mcp.tool()
@traced_tool(logger=logger)
async def get_weather(request: WeatherRequest, ctx: Context):
"""Get current weather with automatic error tracing."""
# This will automatically log all variables if an exception occurs
# and return a properly formatted error response
if request.city.lower() == "atlantis":
raise ValueError("City not found: Atlantis is a fictional city")
# Simulate API call
weather_data = await fetch_weather_api(request.city) # Would raise on failure
# The decorator automatically handles any exceptions and returns
# a structured error response that works with FastMCP
return WeatherResponse(
temperature=23.5,
condition="sunny",
humidity=65
)
```
When the tool fails, Tracelight logs the complete variable state and returns a structured error response that works perfectly with FastMCP's tool response format, making it easy for agents to handle errors gracefully.
## Advanced Usage
```python
from tracelight import log_exception_state
from tracelight.agent_utils import format_for_agent
# Exclude sensitive variables
log_exception_state(e, logger, exclude_vars=["password", "api_key"])
# Custom formatting for agent consumption
log_exception_state(e, logger, format_var=format_for_agent)
# Customize log level and variable length
log_exception_state(e, logger,
level=logging.ERROR, # Log level
max_var_length=2000) # Allow longer variable values
```
## License
MIT
Raw data
{
"_id": null,
"home_page": null,
"name": "tracelight",
"maintainer": null,
"docs_url": null,
"requires_python": ">=3.7",
"maintainer_email": null,
"keywords": "debugging, exceptions, logging, tracing, agents",
"author": null,
"author_email": "Your Actual Name <your.actual@email.com>",
"download_url": "https://files.pythonhosted.org/packages/c2/49/054e54e78699387e9de05c3204201da02663af70b4ab3ccbb42629d05459/tracelight-0.1.3.tar.gz",
"platform": null,
"description": "# Tracelight\n\n> Reveal hidden state in Python exceptions with automatic variable tracing\n\nTracelight exposes the hidden state of your application by automatically logging all local variables in each frame of an exception's traceback. This gives you instant insight into what went wrong without having to add print statements or run in debug mode.\n\n## \u2728 Special Features\n\n\ud83d\udd27 **Pydantic Integration**: Automatically detects and serializes Pydantic models (both v1 and v2) in exception traces, showing model data instead of object representations.\n\n\ud83e\udd16 **Agent-First Design**: Built specifically for agent systems and MCP servers with structured error responses that never crash your workflows.\n\n\ud83d\udcca **Smart Variable Handling**: Intelligently formats complex data structures, truncates large values, and excludes sensitive information.\n\n## Installation\n\n```bash\npip install tracelight\n```\n\n## Quick Start\n\n```python\nimport logging\nfrom tracelight import log_exception_state\n\n# Configure your logger however you like\nlogging.basicConfig(level=logging.DEBUG)\nlogger = logging.getLogger(\"exception_logger\")\n\ndef some_function(x):\n a = x + 1\n b = a * 2\n return b / 0 # Deliberate error\n\ntry:\n some_function(5)\nexcept Exception as e:\n # Log all local variables from each frame\n log_exception_state(e, logger)\n # Re-raise if needed\n raise\n```\n\n## Key Features\n\n### Function Decorator\n\nAutomate error handling with the `@traced` decorator:\n\n```python\nfrom tracelight import traced\n\n@traced()\ndef risky_function(x, y):\n complicated_result = process(x)\n return complicated_result[y] # Might raise KeyError\n\n# All exceptions automatically logged with full variable context!\nrisky_function(\"input\", \"missing_key\")\n```\n\n### Agent Tool Decorator\n\nSpecifically designed for agent systems and MCP servers:\n\n```python\nfrom tracelight.agent_utils import traced_tool\n\n@traced_tool()\ndef weather_tool(location=\"New York\"):\n # Complex implementation with HTTP calls etc.\n return get_weather_data(location) \n\n# If anything fails, returns a structured error dict:\n# {\"status\": \"error\", \"error_type\": \"...\", ...}\n```\n\n### Context Manager\n\nEasily wrap specific blocks of code:\n\n```python\nfrom tracelight import TracedError\n\n# Automatically logs and preserves original exception\nwith TracedError(logger=my_logger):\n risky_operation()\n```\n\n### \ud83d\udd27 Pydantic Model Support\n\nTracelight automatically detects and properly serializes Pydantic models in exception traces:\n\n```python\nfrom pydantic import BaseModel\nfrom tracelight import log_exception_state\n\nclass UserModel(BaseModel):\n name: str\n age: int\n email: str\n\ndef process_user(user_data):\n user = UserModel(**user_data) # Pydantic model\n # ... processing that might fail\n return user.name.upper().split()[10] # IndexError!\n\ntry:\n process_user({\"name\": \"Alice Smith\", \"age\": 30, \"email\": \"alice@example.com\"})\nexcept Exception as e:\n # Tracelight will show the full Pydantic model data:\n # user = {'name': 'Alice Smith', 'age': 30, 'email': 'alice@example.com'}\n log_exception_state(e, logger)\n```\n\n## Use Cases\n\nTracelight is particularly useful for:\n\n### 1. Data\u2010Pipeline Breakdowns\n\n**Context**: Multi-stage ETL jobs where a mysterious `KeyError` pops up.\n\n**With Tracelight**: Your logs show the full contents of the record and every local variable\u2014no need to sprinkle `print` calls or guess which field is missing.\n\n### 2. Async Callback Chaos\n\n**Context**: In an `asyncio`-driven system, tasks fire off callbacks and one raises an exception deep inside a helper function.\n\n**With Tracelight**: You get the full context of all local variables in that callback frame\u2014instantly pinpointing the cause.\n\n### 3. Agent-Based Workflows\n\n**Context**: Your LLM\u2010driven agent orchestrates several tools; one tool call fails with a parsing error.\n\n**With Tracelight**: You immediately see all variables in context, including the raw responses and state data\u2014so you can adjust your tool chain.\n\n## Integration with Agent Systems\n\nTracelight is designed to work seamlessly with agent-based systems and Model Context Protocol (MCP) servers. It can be integrated as a drop-in error handler to provide rich debugging information when tool calls or agent workflows fail unexpectedly.\n\n```python\nfrom tracelight import log_exception_state\nfrom tracelight.agent_utils import traced_tool\n\n# Method 1: Wrap entire tool with decorator\n@traced_tool()\ndef agent_tool(params):\n # Complex implementation...\n return process_complex_workflow(params)\n\n# Method 2: Manual integration\ndef another_tool(params):\n try:\n # Complex tool implementation\n result = process_complex_workflow(params)\n return {\"status\": \"success\", \"data\": result}\n except Exception as e:\n # Log all variables in each frame of the exception\n log_exception_state(e, logger)\n # Return a graceful error response with helpful context\n return {\n \"status\": \"error\",\n \"error\": str(e),\n \"error_type\": type(e).__name__\n }\n```\n\n## FastMCP Integration Example\n\nTracelight integrates seamlessly with FastMCP servers for rich error handling in MCP tools:\n\n```python\nfrom mcp.server.fastmcp import FastMCP, Context\nfrom pydantic import BaseModel, Field\nfrom tracelight.agent_utils import traced_tool\nimport logging\n\n# Setup logging\nlogger = logging.getLogger(\"mcp-server\")\n\n# Create FastMCP server\nmcp = FastMCP(\"TracelightExample\")\n\n# Define request model\nclass WeatherRequest(BaseModel):\n city: str = Field(..., description=\"City to get weather for\")\n country_code: str = Field(None, description=\"Optional 2-letter country code\")\n\n# Define response models\nclass WeatherResponse(BaseModel):\n temperature: float\n condition: str\n humidity: int\n\nclass ErrorResponse(BaseModel):\n status: str = \"error\"\n error_type: str\n error: str\n context: dict = None\n\n# Create traced tool with automatic error handling\n@mcp.tool()\n@traced_tool(logger=logger)\nasync def get_weather(request: WeatherRequest, ctx: Context):\n \"\"\"Get current weather with automatic error tracing.\"\"\"\n # This will automatically log all variables if an exception occurs\n # and return a properly formatted error response\n \n if request.city.lower() == \"atlantis\":\n raise ValueError(\"City not found: Atlantis is a fictional city\") \n \n # Simulate API call\n weather_data = await fetch_weather_api(request.city) # Would raise on failure\n \n # The decorator automatically handles any exceptions and returns\n # a structured error response that works with FastMCP\n return WeatherResponse(\n temperature=23.5,\n condition=\"sunny\",\n humidity=65\n )\n```\n\nWhen the tool fails, Tracelight logs the complete variable state and returns a structured error response that works perfectly with FastMCP's tool response format, making it easy for agents to handle errors gracefully.\n\n## Advanced Usage\n\n```python\nfrom tracelight import log_exception_state\nfrom tracelight.agent_utils import format_for_agent\n\n# Exclude sensitive variables\nlog_exception_state(e, logger, exclude_vars=[\"password\", \"api_key\"])\n\n# Custom formatting for agent consumption\nlog_exception_state(e, logger, format_var=format_for_agent)\n\n# Customize log level and variable length\nlog_exception_state(e, logger, \n level=logging.ERROR, # Log level\n max_var_length=2000) # Allow longer variable values\n```\n\n## License\n\nMIT\n",
"bugtrack_url": null,
"license": "MIT",
"summary": "Reveal hidden state in Python exceptions with automatic variable tracing",
"version": "0.1.3",
"project_urls": {
"Bug Tracker": "https://github.com/newsbubbles/tracelight/issues",
"Documentation": "https://github.com/newsbubbles/tracelight#readme",
"Homepage": "https://github.com/newsbubbles/tracelight"
},
"split_keywords": [
"debugging",
" exceptions",
" logging",
" tracing",
" agents"
],
"urls": [
{
"comment_text": null,
"digests": {
"blake2b_256": "dc57bd698651ccec0012801be9fc8cc94995d1bc062f348fe7b9f68c25c6d978",
"md5": "7b453827874c5a28876f4c30c8ed6568",
"sha256": "b7cf4329332f72e2e1f3ec76f75c44ec13db4e6324b56371ad43a2b73b58dbec"
},
"downloads": -1,
"filename": "tracelight-0.1.3-py3-none-any.whl",
"has_sig": false,
"md5_digest": "7b453827874c5a28876f4c30c8ed6568",
"packagetype": "bdist_wheel",
"python_version": "py3",
"requires_python": ">=3.7",
"size": 10282,
"upload_time": "2025-08-04T18:46:18",
"upload_time_iso_8601": "2025-08-04T18:46:18.195539Z",
"url": "https://files.pythonhosted.org/packages/dc/57/bd698651ccec0012801be9fc8cc94995d1bc062f348fe7b9f68c25c6d978/tracelight-0.1.3-py3-none-any.whl",
"yanked": false,
"yanked_reason": null
},
{
"comment_text": null,
"digests": {
"blake2b_256": "c249054e54e78699387e9de05c3204201da02663af70b4ab3ccbb42629d05459",
"md5": "ce645a964c3a77af1e538493a92788e2",
"sha256": "dfbd6b3d2f2e075e18b7265307d428776151f17426a528b4eccf93d2e53198e1"
},
"downloads": -1,
"filename": "tracelight-0.1.3.tar.gz",
"has_sig": false,
"md5_digest": "ce645a964c3a77af1e538493a92788e2",
"packagetype": "sdist",
"python_version": "source",
"requires_python": ">=3.7",
"size": 15552,
"upload_time": "2025-08-04T18:46:19",
"upload_time_iso_8601": "2025-08-04T18:46:19.150343Z",
"url": "https://files.pythonhosted.org/packages/c2/49/054e54e78699387e9de05c3204201da02663af70b4ab3ccbb42629d05459/tracelight-0.1.3.tar.gz",
"yanked": false,
"yanked_reason": null
}
],
"upload_time": "2025-08-04 18:46:19",
"github": true,
"gitlab": false,
"bitbucket": false,
"codeberg": false,
"github_user": "newsbubbles",
"github_project": "tracelight",
"travis_ci": false,
"coveralls": false,
"github_actions": true,
"lcname": "tracelight"
}