{
  "markdown": "# Semantic Frame\n\n<!-- mcp-name: io.github.Anarkitty1/semantic-frame -->\n\n[![MCP Registry](https://img.shields.io/badge/MCP-Registry-blue)](https://registry.modelcontextprotocol.io/v0/servers?search=semantic-frame)\n[![PyPI version](https://img.shields.io/pypi/v/semantic-frame.svg)](https://pypi.org/project/semantic-frame/)\n[![License: MIT](https://img.shields.io/badge/License-MIT-yellow.svg)](https://opensource.org/licenses/MIT)\n\n**Token-efficient semantic compression for numerical data.**\n\nSemantic Frame converts raw numerical data (NumPy, Pandas, Polars) into natural language descriptions optimized for LLM consumption. Instead of sending thousands of data points to an AI agent, send a 50-word semantic summary.\n\n## The Problem\n\nLLMs are terrible at arithmetic. When you send raw data like `[100, 102, 99, 101, 500, 100, 98]` to GPT-4 or Claude:\n- **Token waste**: 1000 data points = ~2000 tokens\n- **Hallucination risk**: LLMs guess trends instead of calculating them\n- **Context overflow**: Large datasets fill the context window\n\n## The Solution\n\nSemantic Frame provides **deterministic analysis** using NumPy, then translates results into **token-efficient narratives**:\n\n```python\nfrom semantic_frame import describe_series\nimport pandas as pd\n\ndata = pd.Series([100, 102, 99, 101, 500, 100, 98])\nprint(describe_series(data, context=\"Server Latency (ms)\"))\n```\n\nOutput:\n```\nThe Server Latency (ms) data shows a flat/stationary pattern with stable\nvariability. 1 anomaly detected at index 4 (value: 500.00).\nBaseline: 100.00 (range: 98.00-500.00).\n```\n\n**Result**: 95%+ token reduction, zero hallucination risk.\n\n## Installation\n\n```bash\npip install semantic-frame\n```\n\nOr with uv:\n```bash\nuv add semantic-frame\n```\n\n## 🤖 Claude Integration (MCP)\n\nSemantic Frame is available on the [official MCP Registry](https://registry.modelcontextprotocol.io/v0/servers?search=semantic-frame), enabling direct integration with Claude.\n\n**Claude Code CLI:**\n```bash\nclaude mcp add semantic-frame\n```\n\n**Claude Desktop** - Add to your `claude_desktop_config.json`:\n\nmacOS: `~/Library/Application Support/Claude/claude_desktop_config.json`\nWindows: `%APPDATA%\\Claude\\claude_desktop_config.json`\n\n```json\n{\n  \"mcpServers\": {\n    \"semantic-frame\": {\n      \"command\": \"uvx\",\n      \"args\": [\"--from\", \"semantic-frame[mcp]\", \"semantic-frame-mcp\"]\n    }\n  }\n}\n```\n\nOnce configured, Claude can use these tools:\n- `describe_data` - Analyze a single data series\n- `describe_batch` - Analyze multiple series at once\n- `describe_json` - Get structured JSON output\n\n## Quick Start\n\n### Analyze a Series\n\n```python\nfrom semantic_frame import describe_series\nimport numpy as np\n\n# Works with NumPy arrays\ndata = np.array([10, 20, 30, 40, 50, 60, 70, 80, 90, 100])\nresult = describe_series(data, context=\"Daily Sales\")\nprint(result)\n# \"The Daily Sales data shows a rapidly rising pattern with moderate variability...\"\n```\n\n### Analyze a DataFrame\n\n```python\nfrom semantic_frame import describe_dataframe\nimport pandas as pd\n\ndf = pd.DataFrame({\n    'cpu': [40, 42, 41, 95, 40, 41],\n    'memory': [60, 61, 60, 60, 61, 60],\n})\n\nresults = describe_dataframe(df, context=\"Server Metrics\")\nprint(results['cpu'].narrative)\n# \"The Server Metrics - cpu data shows a flat/stationary pattern...\"\n```\n\n### Get Structured Output\n\n```python\nresult = describe_series(data, output=\"full\")\n\nprint(result.trend)          # TrendState.RISING_SHARP\nprint(result.volatility)     # VolatilityState.MODERATE\nprint(result.anomalies)      # [AnomalyInfo(index=4, value=500.0, z_score=4.2)]\nprint(result.compression_ratio)  # 0.95\n```\n\n### JSON Output for APIs\n\n```python\nresult = describe_series(data, output=\"json\")\n# Returns dict ready for JSON serialization\n```\n\n## Supported Data Types\n\n- **NumPy**: `np.ndarray`\n- **Pandas**: `pd.Series`, `pd.DataFrame`\n- **Polars**: `pl.Series`, `pl.DataFrame`\n- **Python**: `list`\n\n## Analysis Features\n\n| Feature | Method | Output |\n|---------|--------|--------|\n| **Trend** | Linear regression slope | RISING_SHARP, RISING_STEADY, FLAT, FALLING_STEADY, FALLING_SHARP |\n| **Volatility** | Coefficient of variation | COMPRESSED, STABLE, MODERATE, EXPANDING, EXTREME |\n| **Anomalies** | Z-score / IQR adaptive | Index, value, z-score for each outlier |\n| **Seasonality** | Autocorrelation | NONE, WEAK, MODERATE, STRONG |\n| **Distribution** | Skewness + Kurtosis | NORMAL, LEFT_SKEWED, RIGHT_SKEWED, BIMODAL, UNIFORM |\n| **Step Change** | Baseline shift detection | NONE, STEP_UP, STEP_DOWN |\n| **Data Quality** | Missing value % | PRISTINE, GOOD, SPARSE, FRAGMENTED |\n\n## LLM Integration\n\n### System Prompt Injection\n\n```python\nfrom semantic_frame.interfaces import format_for_system_prompt\n\nresult = describe_series(data, output=\"full\")\nprompt = format_for_system_prompt(result)\n# Returns formatted context block for system prompts\n```\n\n### LangChain Tool Output\n\n```python\nfrom semantic_frame.interfaces import format_for_langchain\n\noutput = format_for_langchain(result)\n# {\"output\": \"narrative...\", \"metadata\": {...}}\n```\n\n### Multi-Column Agent Context\n\n```python\nfrom semantic_frame.interfaces import create_agent_context\n\nresults = describe_dataframe(df)\ncontext = create_agent_context(results)\n# Combined narrative for all columns with attention flags\n```\n\n## Framework Integrations\n\n### Anthropic Claude (Native Tool Use)\n\n```bash\npip install semantic-frame[anthropic]\n```\n\n```python\nimport anthropic\nfrom semantic_frame.integrations.anthropic import get_anthropic_tool, handle_tool_call\n\nclient = anthropic.Anthropic()\ntool = get_anthropic_tool()\n\nresponse = client.messages.create(\n    model=\"claude-sonnet-4-20250514\",\n    max_tokens=1024,\n    tools=[tool],\n    messages=[{\"role\": \"user\", \"content\": \"Analyze this sales data: [100, 120, 115, 500, 118]\"}]\n)\n\n# Handle tool use in response\nfor block in response.content:\n    if block.type == \"tool_use\" and block.name == \"semantic_analysis\":\n        result = handle_tool_call(block.input)\n        print(result)\n```\n\n### LangChain\n\n```bash\npip install semantic-frame[langchain]\n```\n\n```python\nfrom semantic_frame.integrations.langchain import get_semantic_tool\n\ntool = get_semantic_tool()\n# Use as a LangChain BaseTool in your agent\n```\n\n### CrewAI\n\n```bash\npip install semantic-frame[crewai]\n```\n\n```python\nfrom semantic_frame.integrations.crewai import get_crewai_tool\n\ntool = get_crewai_tool()\n# Use with CrewAI agents\n```\n\n### MCP (Model Context Protocol)\n\n```bash\npip install semantic-frame[mcp]\n```\n\nRun the MCP server:\n```bash\nmcp run semantic_frame.integrations.mcp:mcp\n```\n\nExposes `describe_data` tool for MCP clients like:\n- **ElizaOS**: TypeScript-based agent framework\n- **Claude Desktop**: Anthropic's desktop app\n- **Claude Code**: Anthropic's CLI for Claude\n- Any MCP-compatible client\n\n### Claude Code\n\nAdd Semantic Frame as a native tool in [Claude Code](https://claude.ai/code):\n\n```bash\n# Install MCP dependencies\npip install semantic-frame[mcp]\n\n# Add MCP server to Claude Code\nclaude mcp add semantic-frame -- uv run --project /path/to/semantic-frame mcp run /path/to/semantic-frame/semantic_frame/integrations/mcp.py\n\n# Restart Claude Code, then verify connection\nclaude mcp list\n# semantic-frame: ... - ✓ Connected\n```\n\nOnce configured, ask Claude to analyze data and it will use the `describe_data` tool automatically.\n\n## Advanced Tool Use (Beta)\n\nSemantic Frame supports [Anthropic's Advanced Tool Use features](https://www.anthropic.com/engineering/advanced-tool-use) for efficient tool orchestration in complex agent workflows.\n\n### Features\n\n| Feature | Benefit | API |\n|---------|---------|-----|\n| **Input Examples** | +18% parameter accuracy | Included by default |\n| **Tool Search** | 1000+ tools without context bloat | `defer_loading=True` |\n| **Programmatic Calling** | Batch analysis via code execution | `allowed_callers=[\"code_execution\"]` |\n\n### Quick Start (Advanced)\n\n```python\nimport anthropic\nfrom semantic_frame.integrations.anthropic import get_advanced_tool, handle_tool_call\n\nclient = anthropic.Anthropic()\ntool = get_advanced_tool()  # All advanced features enabled\n\nresponse = client.beta.messages.create(\n    betas=[\"advanced-tool-use-2025-11-20\"],\n    model=\"claude-sonnet-4-5-20250929\",\n    max_tokens=4096,\n    tools=[\n        {\"type\": \"tool_search_tool_regex_20251119\", \"name\": \"tool_search\"},\n        {\"type\": \"code_execution_20250825\", \"name\": \"code_execution\"},\n        tool,\n    ],\n    messages=[{\"role\": \"user\", \"content\": \"Analyze all columns in this dataset...\"}]\n)\n```\n\n### Configuration Options\n\n```python\nfrom semantic_frame.integrations.anthropic import (\n    get_anthropic_tool,          # Standard (includes examples)\n    get_tool_for_discovery,      # For Tool Search\n    get_tool_for_batch_processing,  # For code execution\n    get_advanced_tool,           # All features enabled\n)\n```\n\n### MCP Batch Analysis\n\n```python\nfrom semantic_frame.integrations.mcp import describe_batch\n\n# Analyze multiple series in one call\nresult = describe_batch(\n    datasets='{\"cpu\": [45, 47, 95, 44], \"memory\": [60, 61, 60, 61]}',\n)\n```\n\nSee [docs/advanced-tool-use.md](docs/advanced-tool-use.md) for complete documentation.\n\n## Use Cases\n\n### Crypto Trading\n```python\nbtc_prices = pd.Series(hourly_btc_prices)\ninsight = describe_series(btc_prices, context=\"BTC/USD Hourly\")\n# \"The BTC/USD Hourly data shows a rapidly rising pattern with extreme variability.\n#  Step up detected at index 142. 2 anomalies detected at indices 89, 203.\"\n```\n\n### DevOps Monitoring\n```python\ncpu_data = pd.Series(cpu_readings)\ninsight = describe_series(cpu_data, context=\"CPU Usage %\")\n# \"The CPU Usage % data shows a flat/stationary pattern with stable variability\n#  until index 850, where a critical anomaly was detected...\"\n```\n\n### Sales Analytics\n```python\nsales = pd.Series(daily_sales)\ninsight = describe_series(sales, context=\"Daily Revenue\")\n# \"The Daily Revenue data shows a steadily rising pattern with weak cyclic pattern\n#  detected. Baseline: $12,450 (range: $8,200-$18,900).\"\n```\n\n### IoT Sensor Data\n```python\ntemps = pl.Series(\"temperature\", sensor_readings)\ninsight = describe_series(temps, context=\"Machine Temperature (C)\")\n# \"The Machine Temperature (C) data is expanding with extreme outliers.\n#  3 anomalies detected at indices 142, 156, 161.\"\n```\n\n## 📈 Trading Module (v0.4.0)\n\nSpecialized semantic analysis for trading agents, portfolio managers, and financial applications.\n\n### Trading Tools\n\n| Tool | Description |\n|------|-------------|\n| `describe_drawdown` | Equity curve drawdown analysis with severity |\n| `describe_trading_performance` | Win rate, Sharpe, profit factor metrics |\n| `describe_rankings` | Multi-agent/strategy comparison |\n| `describe_anomalies` | Enhanced anomaly detection with PnL context |\n| `describe_windows` | Multi-timeframe trend alignment |\n| `describe_regime` | Market regime detection (bull/bear/sideways) |\n| `describe_allocation` | Portfolio allocation suggestions ⚠️ |\n\n### Quick Examples\n\n```python\nfrom semantic_frame.trading import (\n    describe_trading_performance,\n    describe_drawdown,\n    describe_regime,\n    describe_allocation,\n)\n\n# Trading Performance\npnl = [100, -50, 75, -25, 150, -30, 80]\nresult = describe_trading_performance(pnl, context=\"My Bot\")\nprint(result.narrative)\n# \"My Bot shows good performance with 57.1% win rate. Profit factor: 2.53...\"\n\n# Drawdown Analysis\nequity = [10000, 10500, 10200, 9800, 9500, 10100]\nresult = describe_drawdown(equity, context=\"Strategy\")\nprint(result.narrative)\n# \"Strategy max drawdown: 9.5% (moderate). Currently recovering...\"\n\n# Market Regime\nreturns = [0.01, 0.015, 0.02, -0.01, 0.025, 0.018]  # Daily returns\nresult = describe_regime(returns, context=\"BTC\")\nprint(result.narrative)\n# \"BTC is in a strong bullish regime. Conditions favor trend-following...\"\n\n# Portfolio Allocation (⚠️ Educational only, not financial advice)\nassets = {\"BTC\": [40000, 42000, 44000], \"ETH\": [2500, 2650, 2800]}\nresult = describe_allocation(assets, method=\"risk_parity\")\nprint(result.narrative)\n# \"Suggested allocation: BTC (55%), ETH (45%). Risk: high...\"\n```\n\n### MCP Integration\n\nAll trading tools are available via MCP:\n\n```bash\nsemantic-frame-mcp\n```\n\nTools: `describe_drawdown`, `describe_trading_performance`, `describe_rankings`, `describe_anomalies`, `describe_windows`, `describe_regime`, `describe_allocation`\n\n📖 **[Full Trading Documentation](docs/trading-module.md)** | **[Quick Reference](docs/trading-cheatsheet.md)**\n\n## API Reference\n\n### `describe_series(data, context=None, output=\"text\")`\n\nAnalyze a single data series.\n\n**Parameters:**\n- `data`: Input data (NumPy array, Pandas Series, Polars Series, or list)\n- `context`: Optional label for the data (appears in narrative)\n- `output`: Format - `\"text\"` (string), `\"json\"` (dict), or `\"full\"` (SemanticResult)\n\n**Returns:** Semantic description in requested format.\n\n### `describe_dataframe(df, context=None)`\n\nAnalyze all numeric columns in a DataFrame.\n\n**Parameters:**\n- `df`: Pandas or Polars DataFrame\n- `context`: Optional prefix for column context labels\n\n**Returns:** Dict mapping column names to SemanticResult objects.\n\n### `SemanticResult`\n\nFull analysis result with:\n- `narrative`: Human-readable text description\n- `trend`: TrendState enum\n- `volatility`: VolatilityState enum\n- `data_quality`: DataQuality enum\n- `anomaly_state`: AnomalyState enum\n- `anomalies`: List of AnomalyInfo objects\n- `seasonality`: Optional SeasonalityState\n- `distribution`: Optional DistributionShape\n- `step_change`: Optional StructuralChange (STEP_UP, STEP_DOWN, NONE)\n- `step_change_index`: Optional int (index where step change occurred)\n- `profile`: SeriesProfile with statistics\n- `compression_ratio`: Token reduction ratio\n\n## Development\n\n```bash\n# Clone and install\ngit clone https://github.com/yourusername/semantic-frame\ncd semantic-frame\nuv sync\n\n# Run tests\nuv run pytest\n\n# Run with coverage\nuv run pytest --cov=semantic_frame\n```\n\n## License\n\nMIT License - see LICENSE file.\n",
  "bytes": 13957,
  "sha": "c2040869d7c6097cb23820e1501fa09031187c588fa255e371005725b9ded353",
  "repo_slug": "anarkitty1/semantic-frame",
  "fonte": "repo",
  "truncated": false,
  "api": "https://agentalog.com/api/listings/mcp_io_github_anarkitty1_semantic_frame_aaf77ba1/readme"
}