MCP Autonomous Data Agent
Anthropic Claude API & MCP Autonomous Data Agent
本番稼働に対応したエンタープライズ向け金融分析システムであり、Anthropic Model Context Protocol(MCP) と 自律推論エージェント を統合しています。本システムは、標準のJSON-RPC 2.0 stdioトランスポートを介して、マルチテーブルのリレーショナル金融データウェアハウスを大規模言語モデル(LLM)に安全に公開します。
インテリジェントな5層多層防御(Defense-in-Depth)アーキテクチャ、純Python製のSQL ASTレキサー&再帰下降パーサー、EXPLAINプラン性能アナライザー、オペコード実行タイムアウトを備えたスレッドセーフなコネクションプール、そしてSQL構文エラー・ASTセキュリティ違反・デカルト積結合警告から自動復旧できる自律エージェントの自己修復ループを特徴としています。
アーキテクチャ概要
┌─────────────────────────────────────────────────────────────────────────────┐
│ Stakeholder / User Prompt │
│ ("Identify branches with elevated 60+ delinquency") │
└──────────────────────────────────────┬──────────────────────────────────────┘
│
▼
┌─────────────────────────────────────────────────────────────────────────────┐
│ Autonomous Agent Runner (agent/client_runner.py) │
│ - Multi-Turn Tool-Calling Loop (Anthropic Claude API / MockClaudeClient) │
│ - Schema-First Reflection & Planning │
│ - Closed-Loop Self-Correction & Query Repair Engine (Max Turns: 5) │
└──────────────────────────────────────┬──────────────────────────────────────┘
│ JSON-RPC 2.0 (stdio)
▼
┌─────────────────────────────────────────────────────────────────────────────┐
│ MCP Server Engine (agent/server.py) │
│ ┌───────────────────────────────────────────────────────────────────────┐ │
│ │ Methods: initialize, ping, tools/list, tools/call, resources, prompts │ │
│ └───────────────────────────────────┬───────────────────────────────────┘ │
│ │ │
│ ┌───────────────────────────────┼───────────────────────────────┐ │
│ ▼ ▼ ▼ │
│ query_database explain_query get_database_ │
│ (query_financial_lakehouse) schema │
└──────┬───────────────────────────────┬───────────────────────────────┬──────┘
│ │ │
▼ ▼ ▼
┌─────────────────────────┐ ┌─────────────────────────┐ ┌─────────────────────┐
│ Layer 1: AST Gate │ │ Layer 2: Plan Analyzer │ │ Layer 3: Connection │
│ (agent/ast_validator.py)│ │(agent/explain_analyzer) │ │ Pool & Sandboxing │
│ - Pure Python Lexer │ │ - Cost Scoring (0-100) │ │ (agent/db_engine.py)│
│ - Recursive AST Parser │ │ - Full Scan Detection │ │ - URI mode=ro │
│ - 100% Non-DQL Block │ │ - Cartesian Join Flag │ │ - sqlite authorizer │
│ - Injection Defense │ │ - Index Tuning Advice │ │ - Opcode Timeouts │
└────────────┬────────────┘ └────────────┬────────────┘ └──────────┬──────────┘
│ │ │
└───────────────────────────┼─────────────────────────┘
▼
┌───────────────────────────────────────────────┐
│ Financial Data Warehouse (data/warehouse.db) │
│ - 6 Relational Tables & Composite Indexes │
│ - branches, customers, credit_ratings, │
│ loans, repayments, audit_log │
└───────────────────────────────────────────────┘5層多層防御セキュリティモデル
本システムは、5つの独立した層にまたがって、LLMとデータベースエンジンの間に厳格なセキュリティ境界を適用します。
レイヤー | コンポーネント | セキュリティメカニズム | 軽減される脅威ベクター |
レイヤー1: 実行前ASTゲート |
| 単一ステートメントDQL( | スタック型クエリインジェクション( |
レイヤー2: 事前実行コストゲート |
| SQLiteの | デカルト積($O(N \times M)$の結合)、無制限のスキャン、一時的なBツリーによるメモリ枯渇。 |
レイヤー3: OS・エンジン読み取り専用モード |
| URI | 不正なディスク書き込みの試み、スキーマ改ざん。 |
レイヤー4: 実行時オーソライザーコールバック |
| 操作を |
|
レイヤー5: リソース・メモリガードレール |
| クエリ実行時間を監視するオペレコード進捗ハンドラー( | 暴走する再帰型CTE、CPUへのサービス拒否(DoS)、無制限の結果セットによるメモリ不足クラッシュ。 |
AST SQLセキュリティバリデータ(agent/ast_validator.py)
ASTセキュリティゲートは、デュアルモードのエンジンを実装しています。
ゼロ依存の純Pythonレキサー&再帰下降パーサー: 行・列の完全な座標追跡を備えたPython標準ライブラリのみで実装。
オプションの
sqlglotエンジン:sqlglotがインストールされている場合、自動的に有効化される言語認識パーサー。
サポートされる分析SQL文法
単一ステートメントのDQL:
SELECTおよびWITH [RECURSIVE] ... SELECT。共通CTE式(CTE): 単一および複数チェーン形式のCTE。任意のCTE定義を再帰的にトラバースし、埋め込みDMLが含まれないことを保証します。
ウィンドウ関数:
OVER (PARTITION BY ... ORDER BY ... [ROWS/RANGE ...])、ROW_NUMBER()、RANK()、SUM() OVER ()。マルチテーブル結合:
INNER JOIN、LEFT OUTER JOIN、CROSS JOIN、NATURAL JOINはONおよびUSING (...)を伴います。サブクエリ:
FROM句のサブクエリ、SELECT内のスカラサブクエリ、IN (SELECT ...)、EXISTS (SELECT ...)。複合演算:
UNION [ALL]、INTERSECT、EXCEPT。スカラ式:
CASE WHEN ... THEN ... ELSE ... END、CAST(... AS ...)、文字列連結(||)、算術演算。
禁止パターン(100%ブロック率)
DDL:
DROP、CREATE、ALTER、TRUNCATE。DML:
INSERT、UPDATE、DELETE、REPLACE、UPSERT、MERGE。管理者コマンド:
PRAGMA、ATTACH、DETACH、VACUUM、REINDEX、ANALYZE、BEGIN、COMMIT。危険関数:
load_extension、readfile、writefile、edit、fts3_tokenizer、eval、randomblob。システムテーブル:
sqlite_master、sqlite_schema、sqlite_temp_master、sqlite_temp_schema、sqlite_sequence、sqlite_stat*。インジェクションベクター: マルチステートメントのセミコロン(
;)、末尾が閉じられていないブロックコメント(/* ...)、未終了の文字列リテラル。
EXPLAINクエイプランアナライザー(agent/explain_analyzer.py)
SQLiteの EXPLAIN QUERY PLAN ツリーを、SQLite 3.24+の4カラム形式 (id, parent, notused, detail) およびレガシー形式にわたって解析します。
スコアリング計算式とペナルティ
$$\text{CostScore} = \min\left(100, ; \sum \text{Penalties}\right)$$
操作の詳細 | 分類 | 深刻度 | ペナルティ |
| インデックスなしフルテーブルスキャン | 高 | 各+25.0 |
| 一時インデックスの構築 | 高 | +20.0 |
| インデックスなしソート | 中 | +15.0 |
| 一時的な集約Bツリー | 中 | +10.0 |
| マテリアライズされたサブクエリ | 中 | 各+10.0 |
マルチテーブルのインデックス未使用スキャン | デカルト積結合 | 重大 | +30.0 |
評価カテゴリ
$0.0 - 25.0$(最適): 完全にインデックス化されたポイント・レンジ幅検索。高速実行。
$26.0 - 50.0$(許容): 軽微な一時ソート、または単一の小テーブルのスキャル。
$51.0 - 74.0$(警告): 最適ではないプラン。複数スキャルの存在。
$75.0 - 100.0$(重大): デカルト積生成もしくは大規模なインデックス未使用結合。MCP実行ゲートによってブロックされます。
金融データウェブのスキーマ(data/schema.sql)
本ウェブは、6つのリレーショナルテーブルを持つ車両資産融資ドメインをモデル化しています。
┌──────────────┐ 1:N ┌──────────────┐ 1:N ┌──────────────┐
│ branches ├────────────────►│ customers ├────────────────►│credit_ratings│
└──────┬───────┘ └──────┬───────┘ └──────────────┘
│ 1:N │ 1:N
│ ┌──────────────┐ │
└────────►│ loans │◄──────┘
└──────┬───────┘
│ 1:N
┌──────▼───────┐
│ repayments │
└──────────────┘
┌──────────────┐
│ audit_log │ (Immutable lifecycle state transition log)
└──────────────┘branches: 再帰系の親子階層(parent_branch_id)を持つ12の地域ハブと小売店舗。customers: 対数正規分布に従う所得分布、負債獲得率、SHA-256ハッシュされた個人情報を持つ300の借り手プロフィプル。credit_ratings:PRIME_PLUSからDEEP_SUBPRIMEまでの5段階のリスクにわたる、600以上の長期のクレジット機関スコアのスナップショット。loans: リスク調整後金利と月額の償還返済の額を適用した500件の車両ローン・中小企業融資契約。repayments: 元金・利息・手数料の内訳と延滞追跡を含む17,000以上の取引元帳エントリ。audit_log:DELINQUENT_90、DEFAULTED、WRITE_OFFへローン状態遷移を追跡する改変不可な監査記録。
MCPツール群とJSON-RPC 2.0プロトコルインターフェース
サーバー(agent/server.py)は、以下の4つのコアツールを公開しています。
1. query_database(エイリアス:query_financial_lakehouse)
安全な読み取り専用SQLクエリを、事前の自動AST検証、オペレコード進捗タイムアウト、行数制限付きで実行します。
入力:
query(str、必須)、max_rows(int、デフォルト:100)、timeout_seconds(float、デフォルト:5.0)。出力:
columns、rows、row_count、is_truncated、execution_time_msを含むJSONペイロード。
2. explain_query
実行プランのノードに検査し、コストスコア($0-100$)を計算、スキャンを検出し、変更を加えずにインデックス構築の推奨を行います。
入力:
query(str、必須)。出力:
cost_score、complexity_rating、scanned_tables、indexed_tables、warnings、recommendations。
3. get_database_schema
データベースカタログのメタデータ、カラム型、主キー、外部キー、インデックスを取得します。
入力:
table_name(str、任意)。出力: すべてのテーブルまたは対象テーブにフィルーされたスキーマ定義。
4. validate_sql_safety
データベースにアクセスせずに、静的ASTセキュリティ分析を実行します。
入力:
query(str、必須)。出力:
is_safe(bool)、statement_type、referenced_tables、detected_risks。
自律エージェントと自己修復ループ(agent/client_runner.py)
AutonomousDataAgent は、クローズドループでエラー修正を行う反復型のツール呼び出しループを実装しています。
┌─────────────────────────────────────┐
│ User: "Top 5 default risk branches" │
└──────────────────┬──────────────────┘
│
▼
┌─────────────────────────────────────┐
│ Turn 1: Introspect Database Schema │
└──────────────────┬──────────────────┘
│
▼
┌─────────────────────────────────────┐
│ Turn 2: Synthesize & Explain Plan │
└──────────┬──────────────────────┬───┘
│ │
Plan Warning / ▼ ▼ Pass
Cartesian Join ┌──────────────────┐ ┌──────────────────┐
│ 🔄 Repair Query │ │ Turn 3: Execute │
│ (Add JOIN ... ON)│ │ query_database │
└────────┬─────────┘ └────────┬─────────┘
│ │
▼ ▼
┌──────────────────┐ ┌──────────────────┐
│ Turn 4: Re-check │ │ Synthesize Final │
│ & Run Query │ │ Executive Report │
└──────────────────┘ └──────────────────┘サポートされている自己修正シナリオ
SQLite 構文 / スキーマエラー(例:列ヘル名のスペルミス): スキーマカタログ付きの
SYNTAX_ERROR_TEMPLATEを注入し、エージェントが列名を修正します。ASTセキュリティ拒否(例:非DQLクエリ):
AST_VIOLATION_TEMPLATEを注入し、エージェントがDQLに準拠した単一SELECT文に修正します。**高コストクエリ / デル精下联合:
PLAN_WARNING_TEMPLATEを注入し、エージェントがインデックスを追加した結合条件を付与します。決定論的オフライン実行:
MockClaudeClientにより、Anthropic APIキーなしでの100%オフラインテストが可能です。
クイックスタート&検証ガイド
1. インストールと環境設定
# Clone and navigate to repository
cd MCP_Autonomous_Agent
# Install dependencies
pip install -r requirements.txt2. シードデータウェアの生成
固定シード 42 による決定論的合成データで、data/warehouse.db を初期化します。
python data/seed_warehouse.py出力:
[SeedWarehouse] branches : 12 rows
[SeedWarehouse] customers : 300 rows
[SeedWarehouse] credit_ratings : 627 rows
[SeedWarehouse] loans : 500 rows
[SeedWarehouse] repayments : 17120 rows
[SeedWarehouse] audit_log : 44 rows
[SeedWarehouse] Database seeding successfully completed.3. 総合テストスイートの実行
AST検証、EXPLAIN解析、DBエンジンのスレッドセーフ性、MCPツール、エージェントの自己修復ループを対象とした、全66件のユニ垂直総合テストを実行します。
python -m unittest discover -s tests -v4.
自律エージェントのデモ実行
金融データウェアに対して、マルチターンの分析クエリセッションを実行します。
from agent.client_runner import AutonomousDataAgent
agent = AutonomousDataAgent()
response = agent.run("Identify the top default risk branches with delinquency counts and total exposure")
print(f"Success: {response.success}")
print(f"Turns Taken: {response.turns_taken}")
print(f"SQL Executed: {response.sql_executed}")
print(f"\n{response.final_answer}")5. StdioでのMCPサーバー起動
Anthropic Claude DesktopアプリまたはMCP Inspectorに接続する場合:
python agent/server.pyClaude Desktopの設定ファイル claude_desktop_config.json:
{
"mcpServers": {
"financial-data-agent": {
"command": "python",
"args": ["-m", "agent.server"],
"cwd": "/path/to/MCP_Autonomous_Agent"
}
}
}プロジェクト構造
MCP_Autonomous_Agent/
├── data/
│ ├── __init__.py
│ ├── schema.sql # 6-table relational financial warehouse DDL
│ ├── seed_warehouse.py # Deterministic synthetic data generator (seed 42)
│ └── warehouse.db # Generated SQLite database file
├── agent/
│ ├── __init__.py
│ ├── ast_validator.py # Pure-Python SQL Lexer & Recursive Descent AST Parser
│ ├── explain_analyzer.py # SQLite EXPLAIN QUERY PLAN analyzer & cost scorer
│ ├── db_engine.py # Thread-safe read-only connection pool & opcode timeout
│ ├── prompts.py # System prompts, tool schemas & remediation templates
│ ├── client_runner.py # Autonomous agent loop with closed-loop self-correction
│ └── server.py # MCP JSON-RPC 2.0 stdio server implementation
├── tests/
│ ├── __init__.py
│ ├── test_ast_validator.py # Unit tests for AST security and analytical DQL (29 tests)
│ ├── test_explain_analyzer.py# Unit tests for plan parsing, scans, cartesian (7 tests)
│ ├── test_db_engine.py # Unit tests for read-only pool, timeouts, threads (8 tests)
│ ├── test_mcp_tools.py # Unit tests for MCP protocol, tool calls, errors (15 tests)
│ └── test_client_runner.py # Unit tests for agent loop and self-healing (5 tests)
├── requirements.txt # Dependency specification (mcp, anthropic, sqlglot, pytest)
└── README.md # Complete architectural & technical documentationライセンス
MITライセンスです。エンタープライズ向け金融データ分析およびAIエージェントのポートフォリオデモを目的として作成されました。
This server cannot be installed
Maintenance
Resources
Unclaimed servers have limited discoverability.
Looking for Admin?
If you are the server author, to access and configure the admin panel.
Related MCP Connectors
Query PostgreSQL databases in plain English — LLM-generated, safety-validated SQL.
Ask your app anything — revenue, errors, read-cost, growth — and get rendered charts back.
Read-only bank access for your AI agent. Connects Claude, ChatGPT, Cursor, Gemini, Codex.
Latest Blog Posts
- Who's Calling? MCP Hosts Are an Identity Blind Spot (And the Spec Knows It)By Om-Shree-0709 on .mcpAgent IdentityOAuth 2.1
- Your AI Chatbot Just Exposed Your CEO's Salary to an InternBy Om-Shree-0709 on .Agent IdentityMCP SecurityOAuth Delegation
- Why MCP Servers Need Execution Sandboxing (And Why Your Current Stack Isn't Enough)By Om-Shree-0709 on .Agentic AiPrompt InjectionWebAssembly
MCP directory API
We provide all the information about MCP servers via our MCP API.
curl -X GET 'https://glama.ai/api/mcp/v1/servers/fortuneMog/MCP_Autonomous_Agent'
If you have feedback or need assistance with the MCP directory API, please join our Discord server