mcpField
S
semantic-frame

semantic-frame

ローカル
github.com/Anarkitty1データ・分析146 週間前に更新

semantic-frame について

semantic-frame は数値系列や表を分析し、LLM アプリケーション向けの簡潔な文章や構造化データに変換します。傾向や異常などを決定的に計算してからエージェントへ渡したい開発者やデータチーム向けです。

主な機能

  1. 01傾向・変動・異常の分析
  2. 02季節性と分布の分析
  3. 03ステップ変化とデータ品質の検出
  4. 04文章・JSON・詳細結果の出力
  5. 05バッチおよび DataFrame の分析

活用シーン

  1. 01CPU とメモリの監視データの要約
  2. 02売上や市場の時系列データの記述
  3. 03エージェント用の簡潔なデータコンテキスト作成

MCP 対応

MCP サーバーは MCP クライアントに `describe_data` とバッチ分析ツールを公開します。利用可能なツールには `describe_batch` と `describe_json` があります。

設定

ローカルサーバーの設定はどのクライアントでも共通です。コピーしてクライアントの MCP 設定ファイルに貼り付けてください。

mcp.json · 共通設定
{
"mcpServers": {
"anarkitty1-semantic-frame": {
"command": "uvx",
"args": [
"semantic-frame"
]
}
}
}
起動コマンドuvx semantic-frame

ローカルサーバーにはマシン上の実行環境(Node.js 18 以上など)が必要です。設定ファイルの場所はクライアントごとに異なります。

パッケージ
pypisemantic-frame0.2.1

ツール

ツール一覧はまだ取得されていません

ローカルサーバーのツールはマシン上で起動して初めて取得できます。メンテナーはまだツール一覧を提供していません。

詳細

Semantic Frame

MCP Registry PyPI version License: MIT

数値データをトークン効率よく意味圧縮します。

Semantic Frame は、生の数値データ(NumPy、Pandas、Polars)を、LLM が扱いやすい自然言語の説明に変換します。何千ものデータポイントを AI エージェントに送る代わりに、50 語の意味的な要約を送信できます。

問題点

LLM は算術処理が苦手です。[100, 102, 99, 101, 500, 100, 98] のような生データを GPT-4 や Claude に送信すると、次のような問題が発生します。

  • トークンの浪費:1000 個のデータポイントで約 2000 トークンを消費します
  • ハルシネーションのリスク:LLM は傾向を計算する代わりに推測します
  • コンテキストの超過:大規模なデータセットがコンテキストウィンドウを埋め尽くします

解決策

Semantic Frame は NumPy を使って決定論的な分析を行い、結果をトークン効率のよい説明文に変換します。

from semantic_frame import describe_series
import pandas as pd

data = pd.Series([100, 102, 99, 101, 500, 100, 98])
print(describe_series(data, context="Server Latency (ms)"))

出力:

The Server Latency (ms) data shows a flat/stationary pattern with stable
variability. 1 anomaly detected at index 4 (value: 500.00).
Baseline: 100.00 (range: 98.00-500.00).

結果:トークンを 95% 以上削減し、ハルシネーションのリスクをゼロにします。

インストール

pip install semantic-frame

または uv を使用します。

uv add semantic-frame

🤖 Claude との連携(MCP)

Semantic Frame は公式 MCP Registryで利用でき、Claude と直接連携できます。

Claude Code CLI:

claude mcp add semantic-frame

Claude Desktop - claude_desktop_config.json に追加します。

macOS:~/Library/Application Support/Claude/claude_desktop_config.json Windows:%APPDATA%\Claude\claude_desktop_config.json

{
  "mcpServers": {
    "semantic-frame": {
      "command": "uvx",
      "args": ["--from", "semantic-frame[mcp]", "semantic-frame-mcp"]
    }
  }
}

設定が完了すると、Claude は次のツールを使用できます。

  • describe_data - 単一のデータ系列を分析します
  • describe_batch - 複数の系列を一度に分析します
  • describe_json - 構造化された JSON 出力を取得します

クイックスタート

系列を分析する
from semantic_frame import describe_series
import numpy as np

# Works with NumPy arrays
data = np.array([10, 20, 30, 40, 50, 60, 70, 80, 90, 100])
result = describe_series(data, context="Daily Sales")
print(result)
# "The Daily Sales data shows a rapidly rising pattern with moderate variability..."
DataFrame を分析する
from semantic_frame import describe_dataframe
import pandas as pd

df = pd.DataFrame({
    'cpu': [40, 42, 41, 95, 40, 41],
    'memory': [60, 61, 60, 60, 61, 60],
})

results = describe_dataframe(df, context="Server Metrics")
print(results['cpu'].narrative)
# "The Server Metrics - cpu data shows a flat/stationary pattern..."
構造化された出力を取得する
result = describe_series(data, output="full")

print(result.trend)          # TrendState.RISING_SHARP
print(result.volatility)     # VolatilityState.MODERATE
print(result.anomalies)      # [AnomalyInfo(index=4, value=500.0, z_score=4.2)]
print(result.compression_ratio)  # 0.95
API 用の JSON 出力
result = describe_series(data, output="json")
# Returns dict ready for JSON serialization

対応データ型

  • NumPy:np.ndarray
  • Pandas:pd.Series、pd.DataFrame
  • Polars:pl.Series、pl.DataFrame
  • Python:list

分析機能

機能手法出力
傾向線形回帰の傾きRISING_SHARP、RISING_STEADY、FLAT、FALLING_STEADY、FALLING_SHARP
変動性変動係数COMPRESSED、STABLE、MODERATE、EXPANDING、EXTREME
異常値Z スコア/IQR 適応型各外れ値のインデックス、値、Z スコア
季節性自己相関NONE、WEAK、MODERATE、STRONG
分布歪度+尖度NORMAL、LEFT_SKEWED、RIGHT_SKEWED、BIMODAL、UNIFORM
ステップ変化ベースラインのシフト検出NONE、STEP_UP、STEP_DOWN
データ品質欠損値の割合PRISTINE、GOOD、SPARSE、FRAGMENTED

LLM との連携

システムプロンプトへの挿入
from semantic_frame.interfaces import format_for_system_prompt

result = describe_series(data, output="full")
prompt = format_for_system_prompt(result)
# Returns formatted context block for system prompts
LangChain ツールの出力
from semantic_frame.interfaces import format_for_langchain

output = format_for_langchain(result)
# {"output": "narrative...", "metadata": {...}}
複数列のエージェントコンテキスト
from semantic_frame.interfaces import create_agent_context

results = describe_dataframe(df)
context = create_agent_context(results)
# Combined narrative for all columns with attention flags

フレームワークとの連携

Anthropic Claude(ネイティブなツール使用)
pip install semantic-frame[anthropic]
import anthropic
from semantic_frame.integrations.anthropic import get_anthropic_tool, handle_tool_call

client = anthropic.Anthropic()
tool = get_anthropic_tool()

response = client.messages.create(
    model="claude-sonnet-4-20250514",
    max_tokens=1024,
    tools=[tool],
    messages=[{"role": "user", "content": "Analyze this sales data: [100, 120, 115, 500, 118]"}]
)

# Handle tool use in response
for block in response.content:
    if block.type == "tool_use" and block.name == "semantic_analysis":
        result = handle_tool_call(block.input)
        print(result)
LangChain
pip install semantic-frame[langchain]
from semantic_frame.integrations.langchain import get_semantic_tool

tool = get_semantic_tool()
# Use as a LangChain BaseTool in your agent
CrewAI
pip install semantic-frame[crewai]
from semantic_frame.integrations.crewai import get_crewai_tool

tool = get_crewai_tool()
# Use with CrewAI agents
MCP(Model Context Protocol)
pip install semantic-frame[mcp]

MCP サーバーを起動します。

mcp run semantic_frame.integrations.mcp:mcp

describe_data ツールを公開し、次のような MCP クライアントから利用できます。

  • ElizaOS:TypeScript ベースのエージェントフレームワーク
  • Claude Desktop:Anthropic のデスクトップアプリ
  • Claude Code:Claude 用の Anthropic の CLI
  • その他すべての MCP 対応クライアント
Claude Code

Claude Code に Semantic Frame をネイティブツールとして追加します。

# Install MCP dependencies
pip install semantic-frame[mcp]

# Add MCP server to Claude Code
claude mcp add semantic-frame -- uv run --project /path/to/semantic-frame mcp run /path/to/semantic-frame/semantic_frame/integrations/mcp.py

# Restart Claude Code, then verify connection
claude mcp list
# semantic-frame: ... - ✓ Connected

設定が完了すると、Claude にデータ分析を依頼した際に describe_data ツールが自動的に使用されます。

高度なツール使用(ベータ版)

Semantic Frame は、複雑なエージェントのワークフローで効率的にツールをオーケストレーションするため、Anthropic の Advanced Tool Use 機能に対応しています。

機能
機能メリットAPI
入力例パラメーターの精度が+18%向上デフォルトで含まれます
ツール検索コンテキストを肥大化させずに1000以上のツールを利用defer_loading=True
プログラムによる呼び出しコード実行によるバッチ分析allowed_callers=["code_execution"]
クイックスタート(上級者向け)
import anthropic
from semantic_frame.integrations.anthropic import get_advanced_tool, handle_tool_call

client = anthropic.Anthropic()
tool = get_advanced_tool()  # All advanced features enabled

response = client.beta.messages.create(
    betas=["advanced-tool-use-2025-11-20"],
    model="claude-sonnet-4-5-20250929",
    max_tokens=4096,
    tools=[
        {"type": "tool_search_tool_regex_20251119", "name": "tool_search"},
        {"type": "code_execution_20250825", "name": "code_execution"},
        tool,
    ],
    messages=[{"role": "user", "content": "Analyze all columns in this dataset..."}]
)
設定オプション
from semantic_frame.integrations.anthropic import (
    get_anthropic_tool,          # Standard (includes examples)
    get_tool_for_discovery,      # For Tool Search
    get_tool_for_batch_processing,  # For code execution
    get_advanced_tool,           # All features enabled
)
MCP バッチ分析
from semantic_frame.integrations.mcp import describe_batch

# Analyze multiple series in one call
result = describe_batch(
    datasets='{"cpu": [45, 47, 95, 44], "memory": [60, 61, 60, 61]}',
)

詳しいドキュメントについては、docs/advanced-tool-use.mdをご覧ください。

ユースケース

暗号資産取引
btc_prices = pd.Series(hourly_btc_prices)
insight = describe_series(btc_prices, context="BTC/USD Hourly")
# "The BTC/USD Hourly data shows a rapidly rising pattern with extreme variability.
#  Step up detected at index 142. 2 anomalies detected at indices 89, 203."
DevOps のモニタリング
cpu_data = pd.Series(cpu_readings)
insight = describe_series(cpu_data, context="CPU Usage %")
# "The CPU Usage % data shows a flat/stationary pattern with stable variability
#  until index 850, where a critical anomaly was detected..."
営業分析
sales = pd.Series(daily_sales)
insight = describe_series(sales, context="Daily Revenue")
# "The Daily Revenue data shows a steadily rising pattern with weak cyclic pattern
#  detected. Baseline: $12,450 (range: $8,200-$18,900)."
IoT センサーデータ
temps = pl.Series("temperature", sensor_readings)
insight = describe_series(temps, context="Machine Temperature (C)")
# "The Machine Temperature (C) data is expanding with extreme outliers.
#  3 anomalies detected at indices 142, 156, 161."

📈 取引モジュール(v0.4.0)

取引エージェント、ポートフォリオマネージャー、金融アプリケーション向けの、専門的なセマンティック分析機能です。

取引ツール
ツール説明
describe_drawdownドローダウンの深刻度を含むエクイティカーブ分析
describe_trading_performance勝率、シャープレシオ、プロフィットファクターの指標
describe_rankings複数のエージェント/戦略の比較
describe_anomalies損益情報を加味した高度な異常検知
describe_windows複数の時間枠におけるトレンドの一致度
describe_regime市場レジームの検知(強気/弱気/横ばい)
describe_allocationポートフォリオ配分の提案 ⚠️
使用例
from semantic_frame.trading import (
    describe_trading_performance,
    describe_drawdown,
    describe_regime,
    describe_allocation,
)

# Trading Performance
pnl = [100, -50, 75, -25, 150, -30, 80]
result = describe_trading_performance(pnl, context="My Bot")
print(result.narrative)
# "My Bot shows good performance with 57.1% win rate. Profit factor: 2.53..."

# Drawdown Analysis
equity = [10000, 10500, 10200, 9800, 9500, 10100]
result = describe_drawdown(equity, context="Strategy")
print(result.narrative)
# "Strategy max drawdown: 9.5% (moderate). Currently recovering..."

# Market Regime
returns = [0.01, 0.015, 0.02, -0.01, 0.025, 0.018]  # Daily returns
result = describe_regime(returns, context="BTC")
print(result.narrative)
# "BTC is in a strong bullish regime. Conditions favor trend-following..."

# Portfolio Allocation (⚠️ Educational only, not financial advice)
assets = {"BTC": [40000, 42000, 44000], "ETH": [2500, 2650, 2800]}
result = describe_allocation(assets, method="risk_parity")
print(result.narrative)
# "Suggested allocation: BTC (55%), ETH (45%). Risk: high..."
MCP 統合

すべての取引ツールをMCP経由で利用できます。

semantic-frame-mcp

ツール:describe_drawdown、describe_trading_performance、describe_rankings、describe_anomalies、describe_windows、describe_regime、describe_allocation

📖 取引に関する全ドキュメント | クイックリファレンス

API リファレンス

describe_series(data, context=None, output="text")

単一のデータ系列を分析します。

パラメーター:

  • data:入力データ(NumPy 配列、Pandas Series、Polars Series、またはリスト)
  • context:データの任意のラベル(説明文に表示されます)
  • output:形式。"text"(文字列)、"json"(dict)、または"full"(SemanticResult)

戻り値: 指定された形式のセマンティックな説明。

describe_dataframe(df, context=None)

DataFrame内のすべての数値列を分析します。

パラメーター:

  • df:Pandas または Polars の DataFrame
  • context:列のコンテキストラベルに付加する任意の接頭辞

戻り値: 列名をSemanticResultオブジェクトに対応付けるdict。

SemanticResult

次の情報を含む完全な分析結果:

  • narrative:人が読みやすいテキスト形式の説明
  • trend:TrendState enum
  • volatility:VolatilityState enum
  • data_quality:DataQuality enum
  • anomaly_state:AnomalyState enum
  • anomalies:AnomalyInfoオブジェクトのリスト
  • seasonality:任意のSeasonalityState
  • distribution:任意のDistributionShape
  • step_change:任意のStructuralChange(STEP_UP、STEP_DOWN、NONE)
  • step_change_index:任意のint(ステップ変化が発生したインデックス)
  • profile:統計情報を含むSeriesProfile
  • compression_ratio:トークン削減率

開発

# Clone and install
git clone https://github.com/yourusername/semantic-frame
cd semantic-frame
uv sync

# Run tests
uv run pytest

# Run with coverage
uv run pytest --cov=semantic_frame

ライセンス

MIT License。LICENSEファイルをご覧ください。

コメント

MCP は初めてですか?

プロトコルの概要から最初のサーバーの導入まで、よくある疑問にまとめて答えます。

AI アプリケーションが外部のツールやデータソースに統一的な方法で接続するためのオープンなプロトコルです。クライアントはモデルとの対話を担い、MCP サーバーはツール・リソース・プロンプトテンプレートを提供します。標準メッセージでやり取りするため、1 つのサーバーを複数のクライアントで再利用できます。