web3-systemic-agent 1.0.2__py3-none-any.whl
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.
- scripts/active_contract_hunter.py +262 -0
- scripts/block_contract_scanner.py +887 -0
- scripts/client_agent_x402.py +584 -0
- scripts/dex_pool_monitor.py +1418 -0
- scripts/governance_daemon.py +683 -0
- scripts/governance_listener.py +201 -0
- scripts/register_erc8004_agent.py +297 -0
- scripts/setup_buyer_wallet.py +193 -0
- src/api.py +5094 -0
- src/chain_inspector.py +256 -0
- src/discovery_hunter.py +1000 -0
- src/engine.py +281 -0
- src/governance_connector.py +548 -0
- src/mcp_server.py +2048 -0
- src/preflight_firewall.py +603 -0
- src/report.py +142 -0
- src/schemas.py +330 -0
- src/semantic_evaluator.py +981 -0
- src/source_resolver.py +792 -0
- src/storage.py +863 -0
- src/task_worker.py +325 -0
- src/test_cache_and_telemetry.py +488 -0
- src/x402_payment.py +1540 -0
- web3_systemic_agent-1.0.2.dist-info/METADATA +511 -0
- web3_systemic_agent-1.0.2.dist-info/RECORD +29 -0
- web3_systemic_agent-1.0.2.dist-info/WHEEL +5 -0
- web3_systemic_agent-1.0.2.dist-info/entry_points.txt +3 -0
- web3_systemic_agent-1.0.2.dist-info/licenses/LICENSE +201 -0
- web3_systemic_agent-1.0.2.dist-info/top_level.txt +2 -0
src/mcp_server.py
ADDED
|
@@ -0,0 +1,2048 @@
|
|
|
1
|
+
"""
|
|
2
|
+
Model Context Protocol (MCP) Server for Web3 Condition-Action Trigger Agent.
|
|
3
|
+
|
|
4
|
+
Provides 5 Free Stage 1 Deterministic Inspection Tools:
|
|
5
|
+
1. scan_contract_selectors: Discovers 4-byte EVM function selectors and flags administrative backdoors.
|
|
6
|
+
2. check_token_honeypot: Static bytecode analysis for DEX honeypots, transfer taxes, and blacklist traps.
|
|
7
|
+
3. scan_dao_proposals: Ingests and summarizes recent Snapshot DAO governance proposals with on-chain execution payloads.
|
|
8
|
+
4. preflight_tx_firewall: Pre-sign security firewall for calldata, approvals, Permit2, EIP-712, prompt injection, and eth_call simulation.
|
|
9
|
+
5. inspect_proxy_and_source: Resolves EIP-1967/Beacon proxy implementations, admin/owner/paused state, and verified Solidity source.
|
|
10
|
+
|
|
11
|
+
Provides 1 Paid Stage 2 Deep Semantic LLM Audit Tool:
|
|
12
|
+
6. deep_semantic_audit: Two-stage on-chain gatekeeping + structured Google Gemini LLM security evaluation ($0.015 USDC standard / $0.25 USDC deep proxy + verified source x402 micropayment on Base Mainnet).
|
|
13
|
+
|
|
14
|
+
Usage:
|
|
15
|
+
# 1. Run MCP Server in stdio mode (Claude Desktop / Cursor / Smithery / Glama):
|
|
16
|
+
python -m src.mcp_server
|
|
17
|
+
|
|
18
|
+
# 2. Offline verification and self-test:
|
|
19
|
+
python src/mcp_server.py --dry-run
|
|
20
|
+
"""
|
|
21
|
+
|
|
22
|
+
import argparse
|
|
23
|
+
import asyncio
|
|
24
|
+
import json
|
|
25
|
+
import logging
|
|
26
|
+
import os
|
|
27
|
+
import sys
|
|
28
|
+
import time
|
|
29
|
+
from datetime import datetime, timezone
|
|
30
|
+
from typing import Dict, Any, Optional, List, Union
|
|
31
|
+
|
|
32
|
+
import httpx
|
|
33
|
+
from eth_account import Account
|
|
34
|
+
from web3 import Web3
|
|
35
|
+
|
|
36
|
+
# Ensure module search paths support running directly or as a package
|
|
37
|
+
_CURRENT_DIR = os.path.dirname(os.path.abspath(__file__))
|
|
38
|
+
_ROOT_DIR = os.path.abspath(os.path.join(_CURRENT_DIR, "..")) if os.path.basename(_CURRENT_DIR) == "src" else _CURRENT_DIR
|
|
39
|
+
_SRC_DIR = os.path.join(_ROOT_DIR, "src")
|
|
40
|
+
_SCRIPTS_DIR = os.path.join(_ROOT_DIR, "scripts")
|
|
41
|
+
for _p in (_ROOT_DIR, _SRC_DIR, _SCRIPTS_DIR):
|
|
42
|
+
if _p not in sys.path:
|
|
43
|
+
sys.path.insert(0, _p)
|
|
44
|
+
|
|
45
|
+
try:
|
|
46
|
+
from src.schemas import (
|
|
47
|
+
ChainId,
|
|
48
|
+
ConditionRulePayload,
|
|
49
|
+
DeterministicCondition,
|
|
50
|
+
SemanticCondition,
|
|
51
|
+
FinalAgentResponse,
|
|
52
|
+
PaymentReceipt,
|
|
53
|
+
PreflightRequest,
|
|
54
|
+
PreflightVerdict,
|
|
55
|
+
)
|
|
56
|
+
from src.preflight_firewall import PreflightFirewall
|
|
57
|
+
from src.source_resolver import ContractSourceResolver
|
|
58
|
+
from src.engine import ConditionAgentEngine
|
|
59
|
+
from src.chain_inspector import ChainInspector
|
|
60
|
+
from src.governance_connector import (
|
|
61
|
+
SnapshotGovernanceConnector,
|
|
62
|
+
get_curated_dao_proposals,
|
|
63
|
+
)
|
|
64
|
+
from src.x402_payment import (
|
|
65
|
+
X402Config,
|
|
66
|
+
parse_x402_header,
|
|
67
|
+
create_eip3009_payment_header,
|
|
68
|
+
get_x402_facilitator,
|
|
69
|
+
usdc_to_atomic,
|
|
70
|
+
DEFAULT_PAY_TO_ADDRESS,
|
|
71
|
+
)
|
|
72
|
+
from scripts.block_contract_scanner import (
|
|
73
|
+
extract_selectors_from_bytecode,
|
|
74
|
+
is_high_risk_signature,
|
|
75
|
+
KNOWN_SELECTORS as SCANNER_KNOWN_SELECTORS,
|
|
76
|
+
HIGH_RISK_KEYWORDS,
|
|
77
|
+
)
|
|
78
|
+
from scripts.dex_pool_monitor import (
|
|
79
|
+
analyze_bytecode_honeypot,
|
|
80
|
+
HONEYPOT_SELECTORS,
|
|
81
|
+
)
|
|
82
|
+
except ImportError:
|
|
83
|
+
from schemas import (
|
|
84
|
+
ChainId,
|
|
85
|
+
ConditionRulePayload,
|
|
86
|
+
DeterministicCondition,
|
|
87
|
+
SemanticCondition,
|
|
88
|
+
FinalAgentResponse,
|
|
89
|
+
PaymentReceipt,
|
|
90
|
+
PreflightRequest,
|
|
91
|
+
PreflightVerdict,
|
|
92
|
+
)
|
|
93
|
+
from preflight_firewall import PreflightFirewall
|
|
94
|
+
from source_resolver import ContractSourceResolver
|
|
95
|
+
from engine import ConditionAgentEngine
|
|
96
|
+
from chain_inspector import ChainInspector
|
|
97
|
+
from governance_connector import (
|
|
98
|
+
SnapshotGovernanceConnector,
|
|
99
|
+
get_curated_dao_proposals,
|
|
100
|
+
)
|
|
101
|
+
from x402_payment import (
|
|
102
|
+
X402Config,
|
|
103
|
+
parse_x402_header,
|
|
104
|
+
create_eip3009_payment_header,
|
|
105
|
+
get_x402_facilitator,
|
|
106
|
+
usdc_to_atomic,
|
|
107
|
+
DEFAULT_PAY_TO_ADDRESS,
|
|
108
|
+
)
|
|
109
|
+
from block_contract_scanner import (
|
|
110
|
+
extract_selectors_from_bytecode,
|
|
111
|
+
is_high_risk_signature,
|
|
112
|
+
KNOWN_SELECTORS as SCANNER_KNOWN_SELECTORS,
|
|
113
|
+
HIGH_RISK_KEYWORDS,
|
|
114
|
+
)
|
|
115
|
+
from dex_pool_monitor import (
|
|
116
|
+
analyze_bytecode_honeypot,
|
|
117
|
+
HONEYPOT_SELECTORS,
|
|
118
|
+
)
|
|
119
|
+
|
|
120
|
+
logger = logging.getLogger("mcp_server")
|
|
121
|
+
|
|
122
|
+
MCP_PROTOCOL_VERSION = "2024-11-05"
|
|
123
|
+
SUPPORTED_MCP_VERSIONS = ("2024-11-05", "2025-03-26", "2025-06-18")
|
|
124
|
+
MCP_SERVER_NAME = "web3-systemic-agent"
|
|
125
|
+
MCP_SERVER_VERSION = "1.0.2"
|
|
126
|
+
|
|
127
|
+
|
|
128
|
+
def _validate_checksum_address(address: str) -> str:
|
|
129
|
+
"""Validates an EVM hex address and returns its canonical EIP-55 checksum string."""
|
|
130
|
+
if not address or not isinstance(address, str) or not Web3.is_address(address):
|
|
131
|
+
raise ValueError(f"Invalid Ethereum address: {address}")
|
|
132
|
+
return Web3.to_checksum_address(address)
|
|
133
|
+
|
|
134
|
+
|
|
135
|
+
async def _resolve_contract_bytecode(
|
|
136
|
+
checksum_addr: str,
|
|
137
|
+
chain_id: int,
|
|
138
|
+
bytecode_override: Optional[str] = None,
|
|
139
|
+
) -> bytes:
|
|
140
|
+
"""
|
|
141
|
+
Resolves contract runtime bytecode with priority:
|
|
142
|
+
1. Explicit bytecode_override (offline analysis / test fixture)
|
|
143
|
+
2. ChainInspector FIFO memory cache
|
|
144
|
+
3. On-chain EVM RPC query via ChainInspector
|
|
145
|
+
"""
|
|
146
|
+
if bytecode_override is not None:
|
|
147
|
+
raw = bytecode_override.strip()
|
|
148
|
+
if raw.startswith("0x") or raw.startswith("0X"):
|
|
149
|
+
raw = raw[2:]
|
|
150
|
+
if not raw:
|
|
151
|
+
return b""
|
|
152
|
+
try:
|
|
153
|
+
return bytes.fromhex(raw)
|
|
154
|
+
except ValueError as exc:
|
|
155
|
+
raise ValueError(f"Invalid bytecode_override hex string: {exc}")
|
|
156
|
+
|
|
157
|
+
cache_key = f"{chain_id}:{checksum_addr}"
|
|
158
|
+
cached = getattr(ChainInspector, "_bytecode_cache", {}).get(cache_key)
|
|
159
|
+
if cached is not None:
|
|
160
|
+
return cached
|
|
161
|
+
|
|
162
|
+
try:
|
|
163
|
+
inspector = ChainInspector(chain_id=chain_id)
|
|
164
|
+
code = await inspector.w3.eth.get_code(checksum_addr)
|
|
165
|
+
if isinstance(code, str):
|
|
166
|
+
code_hex = code[2:] if code.startswith("0x") else code
|
|
167
|
+
code_bytes = bytes.fromhex(code_hex) if code_hex else b""
|
|
168
|
+
else:
|
|
169
|
+
code_bytes = bytes(code) if code else b""
|
|
170
|
+
ChainInspector._set_bytecode_cache(cache_key, code_bytes)
|
|
171
|
+
return code_bytes
|
|
172
|
+
except Exception as exc:
|
|
173
|
+
logger.warning(f"Failed to fetch bytecode for {checksum_addr} on chain {chain_id}: {exc}")
|
|
174
|
+
return b""
|
|
175
|
+
|
|
176
|
+
|
|
177
|
+
class Web3SystemicMCPServer:
|
|
178
|
+
"""
|
|
179
|
+
Model Context Protocol (MCP) Server exposing Web3 Condition-Action Trigger Agent capabilities.
|
|
180
|
+
Serves 5 Free Stage 1 Deterministic Inspection Tools and 1 Paid Stage 2 Semantic Audit Tool,
|
|
181
|
+
plus MCP Resources and Prompts.
|
|
182
|
+
"""
|
|
183
|
+
|
|
184
|
+
def __init__(
|
|
185
|
+
self,
|
|
186
|
+
engine: Optional[ConditionAgentEngine] = None,
|
|
187
|
+
agent_url: Optional[str] = None,
|
|
188
|
+
buyer_private_key: Optional[str] = None,
|
|
189
|
+
require_x402_for_deep_audit: bool = True,
|
|
190
|
+
x402_config: Optional[Any] = None,
|
|
191
|
+
facilitator: Optional[Any] = None,
|
|
192
|
+
storage: Optional[Any] = None,
|
|
193
|
+
remote_mode: Optional[bool] = None,
|
|
194
|
+
http_client: Optional[Any] = None,
|
|
195
|
+
):
|
|
196
|
+
self.engine = engine
|
|
197
|
+
self.agent_url = (
|
|
198
|
+
agent_url
|
|
199
|
+
or os.getenv("WEB3_AGENT_URL")
|
|
200
|
+
or os.getenv("PUBLIC_API_URL")
|
|
201
|
+
or "https://web3-systemic-agent.onrender.com"
|
|
202
|
+
).rstrip("/")
|
|
203
|
+
self.buyer_private_key = buyer_private_key or os.getenv("X402_BUYER_PRIVATE_KEY")
|
|
204
|
+
self.require_x402_for_deep_audit = require_x402_for_deep_audit
|
|
205
|
+
self.x402_config = x402_config
|
|
206
|
+
self.facilitator = facilitator
|
|
207
|
+
self.storage = storage
|
|
208
|
+
self.remote_mode = remote_mode
|
|
209
|
+
self.http_client = http_client
|
|
210
|
+
|
|
211
|
+
def _should_use_remote_api(self) -> bool:
|
|
212
|
+
"""Determines whether paid deep_semantic_audit calls should proxy to the remote HTTP API."""
|
|
213
|
+
if self.remote_mode is not None:
|
|
214
|
+
return bool(self.remote_mode)
|
|
215
|
+
mode_env = os.getenv("MCP_EXECUTION_MODE", "").strip().lower()
|
|
216
|
+
if mode_env == "remote":
|
|
217
|
+
return True
|
|
218
|
+
if mode_env == "local":
|
|
219
|
+
return False
|
|
220
|
+
if self.engine is not None or self.facilitator is not None or "pytest" in sys.modules:
|
|
221
|
+
return False
|
|
222
|
+
has_llm_key = bool(
|
|
223
|
+
os.getenv("GEMINI_API_KEY")
|
|
224
|
+
or os.getenv("GOOGLE_API_KEY")
|
|
225
|
+
or os.getenv("OPENAI_API_KEY")
|
|
226
|
+
)
|
|
227
|
+
return not has_llm_key
|
|
228
|
+
|
|
229
|
+
def get_tools_manifest(self, include_extended: bool = True) -> List[Dict[str, Any]]:
|
|
230
|
+
"""Returns the canonical MCP tools manifest defining all available tools and their schemas."""
|
|
231
|
+
tools = [
|
|
232
|
+
{
|
|
233
|
+
"name": "scan_contract_selectors",
|
|
234
|
+
"description": (
|
|
235
|
+
"Stage 1 Free ($0.00) deterministic EVM bytecode inspector that extracts 4-byte function "
|
|
236
|
+
"selectors and flags privileged backdoors (transferOwnership, upgradeTo, mint, selfdestruct). "
|
|
237
|
+
"Queries live RPC for chain_id (8453 Base, 84532 Base Sepolia, 42161 Arbitrum) unless "
|
|
238
|
+
"bytecode_override (0x hex) is supplied for offline analysis; falls back to empty bytecode on RPC error. "
|
|
239
|
+
"Returns JSON with is_contract, bytecode_size_bytes, selectors_found, high_risk_selectors, "
|
|
240
|
+
"risk_level (HIGH, LOW, EOA), and recommendation."
|
|
241
|
+
),
|
|
242
|
+
"annotations": {
|
|
243
|
+
"title": "Scan Smart Contract Bytecode & Selectors",
|
|
244
|
+
"readOnlyHint": True,
|
|
245
|
+
"destructiveHint": False,
|
|
246
|
+
"idempotentHint": True,
|
|
247
|
+
"openWorldHint": True,
|
|
248
|
+
},
|
|
249
|
+
"inputSchema": {
|
|
250
|
+
"type": "object",
|
|
251
|
+
"properties": {
|
|
252
|
+
"target_address": {
|
|
253
|
+
"type": "string",
|
|
254
|
+
"description": "Hex EVM address of smart contract to inspect (e.g. '0x4200000000000000000000000000000000000006')",
|
|
255
|
+
},
|
|
256
|
+
"chain_id": {
|
|
257
|
+
"type": "integer",
|
|
258
|
+
"default": 8453,
|
|
259
|
+
"description": "EVM Chain ID (8453 for Base Mainnet, 84532 for Base Sepolia, 42161 for Arbitrum One)",
|
|
260
|
+
},
|
|
261
|
+
"bytecode_override": {
|
|
262
|
+
"type": "string",
|
|
263
|
+
"description": "Optional raw contract runtime bytecode hex string (0x...) for offline analysis without RPC calls",
|
|
264
|
+
},
|
|
265
|
+
},
|
|
266
|
+
"required": ["target_address"],
|
|
267
|
+
},
|
|
268
|
+
"outputSchema": {
|
|
269
|
+
"type": "object",
|
|
270
|
+
"properties": {
|
|
271
|
+
"tool": {"type": "string"},
|
|
272
|
+
"stage": {"type": "integer"},
|
|
273
|
+
"cost_usd": {"type": "number"},
|
|
274
|
+
"target_address": {"type": "string"},
|
|
275
|
+
"chain_id": {"type": "integer"},
|
|
276
|
+
"is_contract": {"type": "boolean"},
|
|
277
|
+
"bytecode_size_bytes": {"type": "integer"},
|
|
278
|
+
"selectors_found": {"type": "array", "items": {"type": "object"}},
|
|
279
|
+
"high_risk_selectors": {"type": "array", "items": {"type": "string"}},
|
|
280
|
+
"high_risk_signatures": {"type": "array", "items": {"type": "string"}},
|
|
281
|
+
"risk_level": {"type": "string", "enum": ["HIGH", "LOW", "EOA"]},
|
|
282
|
+
"recommendation": {"type": "string"},
|
|
283
|
+
"upsell_recommendation": {"type": ["string", "null"]},
|
|
284
|
+
"llm_invoked": {"type": "boolean"},
|
|
285
|
+
},
|
|
286
|
+
"required": ["target_address", "is_contract", "selectors_found", "high_risk_selectors", "risk_level"],
|
|
287
|
+
},
|
|
288
|
+
},
|
|
289
|
+
{
|
|
290
|
+
"name": "check_token_honeypot",
|
|
291
|
+
"description": (
|
|
292
|
+
"Stage 1 Free ($0.00) static DEX token bytecode scanner that detects blacklist traps "
|
|
293
|
+
"(isBlacklisted, setBlacklist), 100% sell-tax modifiers (setTax, setFee), trading freezes (pause), "
|
|
294
|
+
"and SELFDESTRUCT opcodes. Fetches live token_address bytecode on chain_id unless bytecode_override "
|
|
295
|
+
"(0x hex) is provided for offline execution; returns safe EOA status if bytecode is empty. "
|
|
296
|
+
"Returns JSON with is_contract, is_honeypot_suspect (bool), risk_score (0.0-10.0), "
|
|
297
|
+
"threat_categories, risk_flags, and recommendation."
|
|
298
|
+
),
|
|
299
|
+
"annotations": {
|
|
300
|
+
"title": "Check Token Honeypot & Tax Traps",
|
|
301
|
+
"readOnlyHint": True,
|
|
302
|
+
"destructiveHint": False,
|
|
303
|
+
"idempotentHint": True,
|
|
304
|
+
"openWorldHint": True,
|
|
305
|
+
},
|
|
306
|
+
"inputSchema": {
|
|
307
|
+
"type": "object",
|
|
308
|
+
"properties": {
|
|
309
|
+
"token_address": {
|
|
310
|
+
"type": "string",
|
|
311
|
+
"description": "Hex EVM address of token contract to inspect for honeypot traps",
|
|
312
|
+
},
|
|
313
|
+
"chain_id": {
|
|
314
|
+
"type": "integer",
|
|
315
|
+
"default": 8453,
|
|
316
|
+
"description": "EVM Chain ID (8453 for Base Mainnet)",
|
|
317
|
+
},
|
|
318
|
+
"bytecode_override": {
|
|
319
|
+
"type": "string",
|
|
320
|
+
"description": "Optional raw token runtime bytecode hex string (0x...) for offline analysis",
|
|
321
|
+
},
|
|
322
|
+
},
|
|
323
|
+
"required": ["token_address"],
|
|
324
|
+
},
|
|
325
|
+
"outputSchema": {
|
|
326
|
+
"type": "object",
|
|
327
|
+
"properties": {
|
|
328
|
+
"tool": {"type": "string"},
|
|
329
|
+
"stage": {"type": "integer"},
|
|
330
|
+
"cost_usd": {"type": "number"},
|
|
331
|
+
"token_address": {"type": "string"},
|
|
332
|
+
"chain_id": {"type": "integer"},
|
|
333
|
+
"is_contract": {"type": "boolean"},
|
|
334
|
+
"bytecode_size_bytes": {"type": "integer"},
|
|
335
|
+
"is_honeypot_suspect": {"type": "boolean"},
|
|
336
|
+
"risk_score": {"type": "number"},
|
|
337
|
+
"threat_categories": {"type": "array", "items": {"type": "string"}},
|
|
338
|
+
"categories_detected": {"type": "array", "items": {"type": "string"}},
|
|
339
|
+
"risk_flags": {"type": "array", "items": {"type": "string"}},
|
|
340
|
+
"recommendation": {"type": "string"},
|
|
341
|
+
"upsell_recommendation": {"type": ["string", "null"]},
|
|
342
|
+
"llm_invoked": {"type": "boolean"},
|
|
343
|
+
},
|
|
344
|
+
"required": ["token_address", "is_honeypot_suspect", "risk_score", "threat_categories", "risk_flags"],
|
|
345
|
+
},
|
|
346
|
+
},
|
|
347
|
+
{
|
|
348
|
+
"name": "scan_dao_proposals",
|
|
349
|
+
"description": (
|
|
350
|
+
"Stage 1 Free ($0.00) governance scanner that fetches up to limit (1-20) recent Snapshot DAO "
|
|
351
|
+
"proposals for space_id (e.g. arbitrumfoundation.eth, aavedao.eth, ens.eth) and extracts on-chain "
|
|
352
|
+
"target addresses and calldata to spot hostile takeover payloads. Queries Snapshot GraphQL API "
|
|
353
|
+
"by default, or falls back to deterministic offline fixtures when use_curated_offline=true or "
|
|
354
|
+
"network fails. Returns JSON with space_id, proposals_count, proposals (id, title, target_address, "
|
|
355
|
+
"calldata, value_wei, state), and recommendation."
|
|
356
|
+
),
|
|
357
|
+
"annotations": {
|
|
358
|
+
"title": "Scan Snapshot DAO Governance Proposals",
|
|
359
|
+
"readOnlyHint": True,
|
|
360
|
+
"destructiveHint": False,
|
|
361
|
+
"idempotentHint": True,
|
|
362
|
+
"openWorldHint": True,
|
|
363
|
+
},
|
|
364
|
+
"inputSchema": {
|
|
365
|
+
"type": "object",
|
|
366
|
+
"properties": {
|
|
367
|
+
"space_id": {
|
|
368
|
+
"type": "string",
|
|
369
|
+
"default": "arbitrumfoundation.eth",
|
|
370
|
+
"description": "Snapshot DAO space ENS identifier (e.g., 'arbitrumfoundation.eth', 'aavedao.eth', 'ens.eth')",
|
|
371
|
+
},
|
|
372
|
+
"limit": {
|
|
373
|
+
"type": "integer",
|
|
374
|
+
"default": 3,
|
|
375
|
+
"description": "Maximum number of proposals to fetch (default: 3)",
|
|
376
|
+
},
|
|
377
|
+
"use_curated_offline": {
|
|
378
|
+
"type": "boolean",
|
|
379
|
+
"default": False,
|
|
380
|
+
"description": "If true, returns verified realistic offline curated proposals without outbound network calls",
|
|
381
|
+
},
|
|
382
|
+
},
|
|
383
|
+
},
|
|
384
|
+
"outputSchema": {
|
|
385
|
+
"type": "object",
|
|
386
|
+
"properties": {
|
|
387
|
+
"tool": {"type": "string"},
|
|
388
|
+
"stage": {"type": "integer"},
|
|
389
|
+
"cost_usd": {"type": "number"},
|
|
390
|
+
"space_id": {"type": "string"},
|
|
391
|
+
"proposals_count": {"type": "integer"},
|
|
392
|
+
"proposals": {"type": "array", "items": {"type": "object"}},
|
|
393
|
+
"recommendation": {"type": "string"},
|
|
394
|
+
"upsell_recommendation": {"type": ["string", "null"]},
|
|
395
|
+
"llm_invoked": {"type": "boolean"},
|
|
396
|
+
},
|
|
397
|
+
"required": ["space_id", "proposals_count", "proposals"],
|
|
398
|
+
},
|
|
399
|
+
},
|
|
400
|
+
{
|
|
401
|
+
"name": "deep_semantic_audit",
|
|
402
|
+
"description": (
|
|
403
|
+
"Stage 2 Paid ($0.015 USDC standard / $0.25 USDC deep proxy + verified source via x402 on Base Mainnet) "
|
|
404
|
+
"hybrid audit combining Stage 1 on-chain gatekeeping with Stage 2 Gemini LLM evaluation to verify "
|
|
405
|
+
"proposal_description claims against target_address bytecode and calldata under policy_prompt. "
|
|
406
|
+
"Non-idempotent due to LLM evaluation and single-use EIP-3009 x402_payment_header nonce; omitting "
|
|
407
|
+
"x402_payment_header safely returns an HTTP 402 payment challenge without charging. Breaching "
|
|
408
|
+
"risk_threshold (0.0-10.0) escalates decision to REJECT. Returns JSON with status, decision "
|
|
409
|
+
"(APPROVE, MANUAL_REVIEW, REJECT), risk_score, reasoning, and flagged_issues."
|
|
410
|
+
),
|
|
411
|
+
"annotations": {
|
|
412
|
+
"title": "Deep Semantic LLM Governance & Contract Audit (x402)",
|
|
413
|
+
"readOnlyHint": True,
|
|
414
|
+
"destructiveHint": False,
|
|
415
|
+
"idempotentHint": False,
|
|
416
|
+
"openWorldHint": True,
|
|
417
|
+
},
|
|
418
|
+
"inputSchema": {
|
|
419
|
+
"type": "object",
|
|
420
|
+
"properties": {
|
|
421
|
+
"target_address": {
|
|
422
|
+
"type": "string",
|
|
423
|
+
"description": "Hex EVM address of smart contract under evaluation",
|
|
424
|
+
},
|
|
425
|
+
"proposal_description": {
|
|
426
|
+
"type": "string",
|
|
427
|
+
"description": "Natural language claim or governance proposal description explaining the intent of the transaction",
|
|
428
|
+
},
|
|
429
|
+
"policy_prompt": {
|
|
430
|
+
"type": "string",
|
|
431
|
+
"default": (
|
|
432
|
+
"Audit contract and proposal for unauthorized privilege escalation, "
|
|
433
|
+
"proxy upgrades, honeypot traps, or treasury drainage."
|
|
434
|
+
),
|
|
435
|
+
"description": "Security policy or governance criteria to audit against",
|
|
436
|
+
},
|
|
437
|
+
"calldata": {
|
|
438
|
+
"type": "string",
|
|
439
|
+
"default": "0x",
|
|
440
|
+
"description": "Transaction hex calldata or function selector being executed",
|
|
441
|
+
},
|
|
442
|
+
"chain_id": {
|
|
443
|
+
"type": "integer",
|
|
444
|
+
"default": 8453,
|
|
445
|
+
"description": "EVM Chain ID (default: 8453 for Base Mainnet)",
|
|
446
|
+
},
|
|
447
|
+
"risk_threshold": {
|
|
448
|
+
"type": "number",
|
|
449
|
+
"default": 7.0,
|
|
450
|
+
"description": "Risk score threshold (0.0 to 10.0) above which the audit triggers rejection or alert",
|
|
451
|
+
},
|
|
452
|
+
"x402_payment_header": {
|
|
453
|
+
"type": "string",
|
|
454
|
+
"description": "Optional Base64-encoded EIP-3009 transferWithAuthorization payment header satisfying $0.015 USDC (standard) or $0.25 USDC (deep proxy + verified source) requirement",
|
|
455
|
+
},
|
|
456
|
+
"resolve_proxy": {
|
|
457
|
+
"type": "boolean",
|
|
458
|
+
"default": False,
|
|
459
|
+
"description": "If true, resolves EIP-1967/1822 proxy implementation contract and inspects implementation state",
|
|
460
|
+
},
|
|
461
|
+
"fetch_verified_source": {
|
|
462
|
+
"type": "boolean",
|
|
463
|
+
"default": False,
|
|
464
|
+
"description": "If true, fetches verified Solidity source code from block explorers (Etherscan, Basescan, Sourcify)",
|
|
465
|
+
},
|
|
466
|
+
},
|
|
467
|
+
"required": ["target_address", "proposal_description"],
|
|
468
|
+
},
|
|
469
|
+
"outputSchema": {
|
|
470
|
+
"type": "object",
|
|
471
|
+
"properties": {
|
|
472
|
+
"tool": {"type": "string"},
|
|
473
|
+
"stage": {"type": "integer"},
|
|
474
|
+
"status": {"type": "string", "enum": ["completed", "payment_required"]},
|
|
475
|
+
"status_code": {"type": "integer"},
|
|
476
|
+
"decision": {"type": "string"},
|
|
477
|
+
"risk_score": {"type": "number"},
|
|
478
|
+
"reasoning": {"type": "string"},
|
|
479
|
+
"flagged_issues": {"type": "array", "items": {"type": "string"}},
|
|
480
|
+
"llm_invoked": {"type": "boolean"},
|
|
481
|
+
},
|
|
482
|
+
"required": ["tool", "stage", "status"],
|
|
483
|
+
},
|
|
484
|
+
},
|
|
485
|
+
]
|
|
486
|
+
|
|
487
|
+
if include_extended:
|
|
488
|
+
tools.append({
|
|
489
|
+
"name": "preflight_tx_firewall",
|
|
490
|
+
"description": (
|
|
491
|
+
"Stage 1 Free ($0.00) pre-sign security firewall evaluating EVM transaction risks, "
|
|
492
|
+
"calldata decoding, unlimited token approvals, Permit2 signatures, EIP-712 typed data phishing, "
|
|
493
|
+
"Indirect Prompt Injections in untrusted calldata/descriptions, and simulated state changes via eth_call. "
|
|
494
|
+
"Returns JSON with verdict (ALLOW, BLOCK, MANUAL_REVIEW), risk_score (0.0-10.0), reasons, and simulation details."
|
|
495
|
+
),
|
|
496
|
+
"annotations": {
|
|
497
|
+
"title": "Preflight Transaction Security Firewall",
|
|
498
|
+
"readOnlyHint": True,
|
|
499
|
+
"destructiveHint": False,
|
|
500
|
+
"idempotentHint": True,
|
|
501
|
+
"openWorldHint": True,
|
|
502
|
+
},
|
|
503
|
+
"inputSchema": {
|
|
504
|
+
"type": "object",
|
|
505
|
+
"properties": {
|
|
506
|
+
"to_address": {
|
|
507
|
+
"type": "string",
|
|
508
|
+
"description": "Target contract or recipient EVM address",
|
|
509
|
+
},
|
|
510
|
+
"target_address": {
|
|
511
|
+
"type": "string",
|
|
512
|
+
"description": "Alias for to_address",
|
|
513
|
+
},
|
|
514
|
+
"from_address": {
|
|
515
|
+
"type": "string",
|
|
516
|
+
"description": "Optional sender EVM address",
|
|
517
|
+
},
|
|
518
|
+
"calldata": {
|
|
519
|
+
"type": "string",
|
|
520
|
+
"default": "0x",
|
|
521
|
+
"description": "Hex transaction calldata",
|
|
522
|
+
},
|
|
523
|
+
"value_wei": {
|
|
524
|
+
"type": "integer",
|
|
525
|
+
"default": 0,
|
|
526
|
+
"description": "Transaction value in Wei",
|
|
527
|
+
},
|
|
528
|
+
"chain_id": {
|
|
529
|
+
"type": "integer",
|
|
530
|
+
"default": 8453,
|
|
531
|
+
"description": "EVM Chain ID (default: 8453 for Base Mainnet)",
|
|
532
|
+
},
|
|
533
|
+
"eip712_typed_data": {
|
|
534
|
+
"type": "object",
|
|
535
|
+
"description": "Optional EIP-712 typed data dictionary to inspect before signing",
|
|
536
|
+
},
|
|
537
|
+
"untrusted_text": {
|
|
538
|
+
"type": "string",
|
|
539
|
+
"description": "Optional untrusted text or proposal description to scan for prompt injection",
|
|
540
|
+
},
|
|
541
|
+
"run_simulation": {
|
|
542
|
+
"type": "boolean",
|
|
543
|
+
"default": True,
|
|
544
|
+
"description": "Whether to run eth_call simulation on chain",
|
|
545
|
+
},
|
|
546
|
+
},
|
|
547
|
+
},
|
|
548
|
+
"outputSchema": {
|
|
549
|
+
"type": "object",
|
|
550
|
+
"properties": {
|
|
551
|
+
"tool": {"type": "string"},
|
|
552
|
+
"stage": {"type": "integer"},
|
|
553
|
+
"cost_usd": {"type": "number"},
|
|
554
|
+
"verdict": {"type": "string", "enum": ["ALLOW", "BLOCK", "MANUAL_REVIEW"]},
|
|
555
|
+
"risk_score": {"type": "number"},
|
|
556
|
+
"flagged_issues": {"type": "array", "items": {"type": "string"}},
|
|
557
|
+
"approval_risks": {"type": "array", "items": {"type": "string"}},
|
|
558
|
+
"eip712_findings": {"type": "array", "items": {"type": "string"}},
|
|
559
|
+
"prompt_injection_detected": {"type": "boolean"},
|
|
560
|
+
"reasons": {"type": "array", "items": {"type": "string"}},
|
|
561
|
+
"summary": {"type": "string"},
|
|
562
|
+
"llm_invoked": {"type": "boolean"},
|
|
563
|
+
},
|
|
564
|
+
"required": ["tool", "stage", "verdict", "risk_score", "flagged_issues", "reasons"],
|
|
565
|
+
},
|
|
566
|
+
})
|
|
567
|
+
tools.append({
|
|
568
|
+
"name": "inspect_proxy_and_source",
|
|
569
|
+
"description": (
|
|
570
|
+
"Stage 1 Free ($0.00) EIP-1967/Beacon proxy slot inspector and verified Solidity source resolver. "
|
|
571
|
+
"Probes on-chain implementation, admin, beacon, owner(), and paused() states via AsyncWeb3 and "
|
|
572
|
+
"retrieves verified source metadata from Sourcify/Etherscan v2 without invoking any LLM. "
|
|
573
|
+
"Supports offline_mode=True for deterministic dry-run or network-free verification."
|
|
574
|
+
),
|
|
575
|
+
"annotations": {
|
|
576
|
+
"title": "Inspect EIP-1967 Proxy & Verified Source",
|
|
577
|
+
"readOnlyHint": True,
|
|
578
|
+
"destructiveHint": False,
|
|
579
|
+
"idempotentHint": True,
|
|
580
|
+
"openWorldHint": True,
|
|
581
|
+
},
|
|
582
|
+
"inputSchema": {
|
|
583
|
+
"type": "object",
|
|
584
|
+
"properties": {
|
|
585
|
+
"target_address": {
|
|
586
|
+
"type": "string",
|
|
587
|
+
"description": "Hex EVM address of smart contract or proxy to inspect",
|
|
588
|
+
},
|
|
589
|
+
"chain_id": {
|
|
590
|
+
"type": "integer",
|
|
591
|
+
"default": 8453,
|
|
592
|
+
"description": "EVM Chain ID (8453 for Base Mainnet, 84532 for Base Sepolia, 42161 for Arbitrum One)",
|
|
593
|
+
},
|
|
594
|
+
"fetch_verified_source": {
|
|
595
|
+
"type": "boolean",
|
|
596
|
+
"default": True,
|
|
597
|
+
"description": "Whether to query Sourcify/Etherscan v2 for verified Solidity source metadata",
|
|
598
|
+
},
|
|
599
|
+
"offline_mode": {
|
|
600
|
+
"type": "boolean",
|
|
601
|
+
"default": False,
|
|
602
|
+
"description": "If true, returns a deterministic clean offline structure without making RPC or HTTP calls",
|
|
603
|
+
},
|
|
604
|
+
},
|
|
605
|
+
"required": ["target_address"],
|
|
606
|
+
},
|
|
607
|
+
"outputSchema": {
|
|
608
|
+
"type": "object",
|
|
609
|
+
"properties": {
|
|
610
|
+
"tool": {"type": "string"},
|
|
611
|
+
"stage": {"type": "integer"},
|
|
612
|
+
"cost_usd": {"type": "number"},
|
|
613
|
+
"llm_invoked": {"type": "boolean"},
|
|
614
|
+
"target_address": {"type": "string"},
|
|
615
|
+
"chain_id": {"type": "integer"},
|
|
616
|
+
"effective_audit_address": {"type": "string"},
|
|
617
|
+
"is_proxy": {"type": "boolean"},
|
|
618
|
+
"implementation_address": {"type": ["string", "null"]},
|
|
619
|
+
"admin_address": {"type": ["string", "null"]},
|
|
620
|
+
"beacon_address": {"type": ["string", "null"]},
|
|
621
|
+
"owner_address": {"type": ["string", "null"]},
|
|
622
|
+
"is_paused": {"type": ["boolean", "null"]},
|
|
623
|
+
"source_verified": {"type": "boolean"},
|
|
624
|
+
"source_provider": {"type": ["string", "null"]},
|
|
625
|
+
"contract_names": {"type": "array", "items": {"type": "string"}},
|
|
626
|
+
"security_warnings": {"type": "array", "items": {"type": "string"}},
|
|
627
|
+
"recommendation": {"type": "string"},
|
|
628
|
+
"upsell_recommendation": {"type": ["string", "null"]},
|
|
629
|
+
},
|
|
630
|
+
"required": [
|
|
631
|
+
"tool",
|
|
632
|
+
"stage",
|
|
633
|
+
"cost_usd",
|
|
634
|
+
"llm_invoked",
|
|
635
|
+
"target_address",
|
|
636
|
+
"is_proxy",
|
|
637
|
+
"source_verified",
|
|
638
|
+
],
|
|
639
|
+
},
|
|
640
|
+
})
|
|
641
|
+
|
|
642
|
+
return tools
|
|
643
|
+
|
|
644
|
+
async def scan_contract_selectors(
|
|
645
|
+
self,
|
|
646
|
+
target_address: str,
|
|
647
|
+
chain_id: int = 8453,
|
|
648
|
+
bytecode_override: Optional[str] = None,
|
|
649
|
+
) -> Dict[str, Any]:
|
|
650
|
+
"""Tool 1: Discovers 4-byte EVM function selectors and flags high-risk administrative capabilities."""
|
|
651
|
+
checksum_addr = _validate_checksum_address(target_address)
|
|
652
|
+
code_bytes = await _resolve_contract_bytecode(checksum_addr, chain_id, bytecode_override)
|
|
653
|
+
|
|
654
|
+
is_contract = bool(code_bytes and code_bytes not in (b"", b"\x00"))
|
|
655
|
+
bytecode_size = len(code_bytes) if is_contract else 0
|
|
656
|
+
|
|
657
|
+
if is_contract:
|
|
658
|
+
selectors = extract_selectors_from_bytecode(code_bytes)
|
|
659
|
+
high_risk = [
|
|
660
|
+
s["signature"]
|
|
661
|
+
for s in selectors
|
|
662
|
+
if is_high_risk_signature(s.get("signature", ""))
|
|
663
|
+
]
|
|
664
|
+
risk_level = "HIGH" if high_risk else "LOW"
|
|
665
|
+
upsell = (
|
|
666
|
+
"High-risk administrative capabilities detected. "
|
|
667
|
+
"Run 'deep_semantic_audit' for comprehensive Gemini LLM security evaluation."
|
|
668
|
+
if high_risk
|
|
669
|
+
else None
|
|
670
|
+
)
|
|
671
|
+
else:
|
|
672
|
+
selectors = []
|
|
673
|
+
high_risk = []
|
|
674
|
+
risk_level = "EOA"
|
|
675
|
+
upsell = None
|
|
676
|
+
|
|
677
|
+
return {
|
|
678
|
+
"tool": "scan_contract_selectors",
|
|
679
|
+
"stage": 1,
|
|
680
|
+
"target_address": checksum_addr,
|
|
681
|
+
"chain_id": chain_id,
|
|
682
|
+
"is_contract": is_contract,
|
|
683
|
+
"bytecode_size_bytes": bytecode_size,
|
|
684
|
+
"selectors_found": selectors,
|
|
685
|
+
"high_risk_selectors": high_risk,
|
|
686
|
+
"high_risk_signatures": high_risk,
|
|
687
|
+
"risk_level": risk_level,
|
|
688
|
+
"recommendation": upsell or "No high-risk administrative selectors detected.",
|
|
689
|
+
"llm_invoked": False,
|
|
690
|
+
"cost_usd": 0.0,
|
|
691
|
+
"upsell_recommendation": upsell,
|
|
692
|
+
}
|
|
693
|
+
|
|
694
|
+
async def check_token_honeypot(
|
|
695
|
+
self,
|
|
696
|
+
token_address: str,
|
|
697
|
+
chain_id: int = 8453,
|
|
698
|
+
bytecode_override: Optional[str] = None,
|
|
699
|
+
) -> Dict[str, Any]:
|
|
700
|
+
"""Tool 2: Static bytecode analysis for DEX honeypots, transfer taxes, and blacklist traps."""
|
|
701
|
+
checksum_addr = _validate_checksum_address(token_address)
|
|
702
|
+
code_bytes = await _resolve_contract_bytecode(checksum_addr, chain_id, bytecode_override)
|
|
703
|
+
|
|
704
|
+
if not code_bytes or code_bytes in (b"", b"\x00"):
|
|
705
|
+
return {
|
|
706
|
+
"tool": "check_token_honeypot",
|
|
707
|
+
"stage": 1,
|
|
708
|
+
"token_address": checksum_addr,
|
|
709
|
+
"chain_id": chain_id,
|
|
710
|
+
"is_contract": False,
|
|
711
|
+
"bytecode_size_bytes": 0,
|
|
712
|
+
"is_honeypot_suspect": False,
|
|
713
|
+
"risk_score": 0.0,
|
|
714
|
+
"threat_categories": [],
|
|
715
|
+
"risk_flags": [],
|
|
716
|
+
"categories_detected": [],
|
|
717
|
+
"recommendation": "No static honeypot indicators detected.",
|
|
718
|
+
"llm_invoked": False,
|
|
719
|
+
"cost_usd": 0.0,
|
|
720
|
+
"upsell_recommendation": None,
|
|
721
|
+
}
|
|
722
|
+
|
|
723
|
+
analysis = analyze_bytecode_honeypot(code_bytes)
|
|
724
|
+
is_honeypot = bool(analysis.get("is_honeypot", False))
|
|
725
|
+
categories = analysis.get("categories", {})
|
|
726
|
+
active_cats = [k for k, v in categories.items() if v]
|
|
727
|
+
severity = analysis.get("severity", "CLEAN")
|
|
728
|
+
|
|
729
|
+
risk_score = (
|
|
730
|
+
9.5
|
|
731
|
+
if severity == "CRITICAL"
|
|
732
|
+
else (7.5 if severity == "HIGH" else (5.0 if severity == "MEDIUM" else 1.0))
|
|
733
|
+
)
|
|
734
|
+
upsell = (
|
|
735
|
+
"Critical honeypot indicators detected! Recommend executing 'deep_semantic_audit' before interacting."
|
|
736
|
+
if is_honeypot
|
|
737
|
+
else None
|
|
738
|
+
)
|
|
739
|
+
|
|
740
|
+
return {
|
|
741
|
+
"tool": "check_token_honeypot",
|
|
742
|
+
"stage": 1,
|
|
743
|
+
"token_address": checksum_addr,
|
|
744
|
+
"chain_id": chain_id,
|
|
745
|
+
"is_contract": bool(code_bytes and code_bytes not in (b"", b"\x00")),
|
|
746
|
+
"bytecode_size_bytes": len(code_bytes) if code_bytes and code_bytes not in (b"", b"\x00") else 0,
|
|
747
|
+
"is_honeypot_suspect": is_honeypot,
|
|
748
|
+
"risk_score": risk_score,
|
|
749
|
+
"threat_categories": active_cats,
|
|
750
|
+
"risk_flags": analysis.get("honeypot_flags", []),
|
|
751
|
+
"categories_detected": active_cats,
|
|
752
|
+
"recommendation": upsell or "No static honeypot indicators detected.",
|
|
753
|
+
"llm_invoked": False,
|
|
754
|
+
"cost_usd": 0.0,
|
|
755
|
+
"upsell_recommendation": upsell,
|
|
756
|
+
}
|
|
757
|
+
|
|
758
|
+
async def scan_dao_proposals(
|
|
759
|
+
self,
|
|
760
|
+
space_id: str = "arbitrumfoundation.eth",
|
|
761
|
+
limit: int = 3,
|
|
762
|
+
use_curated_offline: bool = False,
|
|
763
|
+
) -> Dict[str, Any]:
|
|
764
|
+
"""Tool 3: Ingests and summarizes recent Snapshot DAO governance proposals with on-chain execution payloads."""
|
|
765
|
+
proposals = []
|
|
766
|
+
if use_curated_offline:
|
|
767
|
+
all_curated = get_curated_dao_proposals(limit=10)
|
|
768
|
+
matched = [p for p in all_curated if p.space_id == space_id]
|
|
769
|
+
proposals = (matched if matched else all_curated)[:limit]
|
|
770
|
+
else:
|
|
771
|
+
try:
|
|
772
|
+
connector = SnapshotGovernanceConnector()
|
|
773
|
+
proposals = await connector.fetch_proposals(spaces=[space_id], limit=limit)
|
|
774
|
+
except Exception as exc:
|
|
775
|
+
logger.warning(f"Snapshot query failed ({exc}), falling back to curated proposals.")
|
|
776
|
+
all_curated = get_curated_dao_proposals(limit=10)
|
|
777
|
+
matched = [p for p in all_curated if p.space_id == space_id]
|
|
778
|
+
proposals = (matched if matched else all_curated)[:limit]
|
|
779
|
+
|
|
780
|
+
formatted = [
|
|
781
|
+
{
|
|
782
|
+
"proposal_id": p.proposal_id,
|
|
783
|
+
"title": p.title,
|
|
784
|
+
"state": p.state,
|
|
785
|
+
"target_address": p.target_address,
|
|
786
|
+
"calldata": p.calldata,
|
|
787
|
+
"onchain_hints": {
|
|
788
|
+
"tx_value_wei": p.tx_value_wei,
|
|
789
|
+
"chain_id": int(p.chain_id),
|
|
790
|
+
},
|
|
791
|
+
}
|
|
792
|
+
for p in proposals
|
|
793
|
+
]
|
|
794
|
+
|
|
795
|
+
return {
|
|
796
|
+
"tool": "scan_dao_proposals",
|
|
797
|
+
"stage": 1,
|
|
798
|
+
"space_id": space_id,
|
|
799
|
+
"proposals_count": len(formatted),
|
|
800
|
+
"proposals": formatted,
|
|
801
|
+
"recommendation": "Use 'deep_semantic_audit' on any proposal with suspicious calldata or target contract.",
|
|
802
|
+
"llm_invoked": False,
|
|
803
|
+
"cost_usd": 0.0,
|
|
804
|
+
"upsell_recommendation": "Use 'deep_semantic_audit' on any proposal with suspicious calldata or target contract.",
|
|
805
|
+
}
|
|
806
|
+
|
|
807
|
+
def _build_mcp_402_dict(
|
|
808
|
+
self,
|
|
809
|
+
payload: ConditionRulePayload,
|
|
810
|
+
reason: Optional[str] = None,
|
|
811
|
+
cfg: Optional[Any] = None,
|
|
812
|
+
is_deep_tier: bool = False,
|
|
813
|
+
) -> Dict[str, Any]:
|
|
814
|
+
net = cfg.network if cfg and getattr(cfg, "network", None) else "eip155:8453"
|
|
815
|
+
if is_deep_tier:
|
|
816
|
+
raw_price = getattr(cfg, "price_per_deep_audit_usdc", None) if cfg else None
|
|
817
|
+
price = float(
|
|
818
|
+
raw_price
|
|
819
|
+
if raw_price is not None
|
|
820
|
+
else os.getenv("X402_PRICE_DEEP_AUDIT", "0.25")
|
|
821
|
+
)
|
|
822
|
+
evaluate_endpoint = f"{self.agent_url}/audit/deep"
|
|
823
|
+
else:
|
|
824
|
+
raw_price = getattr(cfg, "price_per_eval_usdc", None) if cfg else None
|
|
825
|
+
price = float(
|
|
826
|
+
raw_price
|
|
827
|
+
if raw_price is not None
|
|
828
|
+
else os.getenv("X402_PRICE_EVALUATE", "0.015")
|
|
829
|
+
)
|
|
830
|
+
evaluate_endpoint = f"{self.agent_url}/evaluate"
|
|
831
|
+
|
|
832
|
+
pay_to = (
|
|
833
|
+
cfg.pay_to_address
|
|
834
|
+
if cfg and getattr(cfg, "pay_to_address", None) and cfg.pay_to_address != DEFAULT_PAY_TO_ADDRESS
|
|
835
|
+
else os.getenv("PAY_TO_ADDRESS", "0x2b7F1fd931f7f28f89e0f688Dd5Bb7a620c24b63")
|
|
836
|
+
)
|
|
837
|
+
price_label = f"${price:.3f}".rstrip("0").rstrip(".")
|
|
838
|
+
return {
|
|
839
|
+
"tool": "deep_semantic_audit",
|
|
840
|
+
"stage": 2,
|
|
841
|
+
"status": "payment_required",
|
|
842
|
+
"status_code": 402,
|
|
843
|
+
"protocol": "x402",
|
|
844
|
+
"network": net,
|
|
845
|
+
"price_usdc": price,
|
|
846
|
+
"pay_to_address": pay_to,
|
|
847
|
+
"evaluate_endpoint": evaluate_endpoint,
|
|
848
|
+
"message": reason or f"Stage 2 Deep Semantic LLM Audit requires a {price_label} USDC x402 micropayment on Base Mainnet.",
|
|
849
|
+
"reason": reason or "Payment Required",
|
|
850
|
+
"instructions": "Provide 'x402_payment_header' (Base64 EIP-3009 authorization) or configure X402_BUYER_PRIVATE_KEY in the MCP environment.",
|
|
851
|
+
"rule_payload": payload.model_dump(mode="json"),
|
|
852
|
+
}
|
|
853
|
+
|
|
854
|
+
async def preflight_tx_firewall(
|
|
855
|
+
self,
|
|
856
|
+
to_address: Optional[str] = None,
|
|
857
|
+
target_address: Optional[str] = None,
|
|
858
|
+
from_address: Optional[str] = None,
|
|
859
|
+
calldata: str = "0x",
|
|
860
|
+
value_wei: int = 0,
|
|
861
|
+
chain_id: int = 8453,
|
|
862
|
+
eip712_typed_data: Optional[Dict[str, Any]] = None,
|
|
863
|
+
untrusted_text: Optional[str] = None,
|
|
864
|
+
run_simulation: bool = True,
|
|
865
|
+
) -> Dict[str, Any]:
|
|
866
|
+
"""Tool 5: Stage 1 Free pre-sign security firewall evaluating EVM tx risks, calldata, Permit2, EIP-712, prompt injection, and simulations."""
|
|
867
|
+
try:
|
|
868
|
+
cid = ChainId(chain_id)
|
|
869
|
+
except ValueError:
|
|
870
|
+
cid = ChainId.BASE_MAINNET
|
|
871
|
+
|
|
872
|
+
req = PreflightRequest(
|
|
873
|
+
chain_id=cid,
|
|
874
|
+
to_address=to_address,
|
|
875
|
+
target_address=target_address,
|
|
876
|
+
from_address=from_address,
|
|
877
|
+
calldata=calldata,
|
|
878
|
+
value_wei=value_wei,
|
|
879
|
+
eip712_typed_data=eip712_typed_data,
|
|
880
|
+
untrusted_text=untrusted_text,
|
|
881
|
+
run_simulation=run_simulation,
|
|
882
|
+
)
|
|
883
|
+
firewall = getattr(self, "preflight_firewall", None) or PreflightFirewall()
|
|
884
|
+
verdict = await firewall.evaluate(req)
|
|
885
|
+
dumped = verdict.model_dump(mode="json")
|
|
886
|
+
dumped["tool"] = "preflight_tx_firewall"
|
|
887
|
+
dumped["stage"] = 1
|
|
888
|
+
dumped["cost_usd"] = 0.0
|
|
889
|
+
dumped["reasons"] = list(dumped.get("flagged_issues", []))
|
|
890
|
+
return dumped
|
|
891
|
+
|
|
892
|
+
async def inspect_proxy_and_source(
|
|
893
|
+
self,
|
|
894
|
+
target_address: str,
|
|
895
|
+
chain_id: int = 8453,
|
|
896
|
+
fetch_verified_source: bool = True,
|
|
897
|
+
offline_mode: bool = False,
|
|
898
|
+
) -> Dict[str, Any]:
|
|
899
|
+
"""Tool 6: Stage 1 Free EIP-1967/Beacon proxy slot inspector and verified Solidity source resolver."""
|
|
900
|
+
checksum_addr = _validate_checksum_address(target_address)
|
|
901
|
+
|
|
902
|
+
if offline_mode:
|
|
903
|
+
return {
|
|
904
|
+
"tool": "inspect_proxy_and_source",
|
|
905
|
+
"stage": 1,
|
|
906
|
+
"cost_usd": 0.0,
|
|
907
|
+
"llm_invoked": False,
|
|
908
|
+
"target_address": checksum_addr,
|
|
909
|
+
"chain_id": chain_id,
|
|
910
|
+
"effective_audit_address": checksum_addr,
|
|
911
|
+
"is_proxy": False,
|
|
912
|
+
"implementation_address": None,
|
|
913
|
+
"admin_address": None,
|
|
914
|
+
"beacon_address": None,
|
|
915
|
+
"owner_address": None,
|
|
916
|
+
"is_paused": None,
|
|
917
|
+
"source_verified": False,
|
|
918
|
+
"source_provider": None,
|
|
919
|
+
"contract_names": [],
|
|
920
|
+
"security_warnings": [],
|
|
921
|
+
"recommendation": "Offline mode: skipped on-chain proxy and block explorer source resolution.",
|
|
922
|
+
"upsell_recommendation": None,
|
|
923
|
+
}
|
|
924
|
+
|
|
925
|
+
resolver = getattr(self, "source_resolver", None) or ContractSourceResolver()
|
|
926
|
+
audit_ctx = await resolver.resolve_full_audit_context(
|
|
927
|
+
chain_id=chain_id,
|
|
928
|
+
target_address=checksum_addr,
|
|
929
|
+
resolve_proxy=True,
|
|
930
|
+
fetch_source=fetch_verified_source,
|
|
931
|
+
)
|
|
932
|
+
proxy_info = audit_ctx.get("proxy_info", {}) or {}
|
|
933
|
+
source_info = audit_ctx.get("source_info", {}) or {}
|
|
934
|
+
effective_audit_address = (
|
|
935
|
+
audit_ctx.get("effective_audit_address")
|
|
936
|
+
or proxy_info.get("effective_audit_address")
|
|
937
|
+
or checksum_addr
|
|
938
|
+
)
|
|
939
|
+
is_proxy = bool(proxy_info.get("is_proxy", False))
|
|
940
|
+
source_verified = bool(source_info.get("verified"))
|
|
941
|
+
security_warnings = list(audit_ctx.get("security_warnings", []))
|
|
942
|
+
|
|
943
|
+
if is_proxy or security_warnings or source_verified:
|
|
944
|
+
upsell: Optional[str] = (
|
|
945
|
+
"Proxy, verified source, or security warnings detected. Run 'deep_semantic_audit' "
|
|
946
|
+
"with resolve_proxy=True and fetch_verified_source=True ($0.25 USDC via x402) for "
|
|
947
|
+
"full implementation and Solidity LLM evaluation."
|
|
948
|
+
)
|
|
949
|
+
recommendation = upsell
|
|
950
|
+
else:
|
|
951
|
+
upsell = None
|
|
952
|
+
recommendation = (
|
|
953
|
+
"No EIP-1967 proxy slots or verified source detected. Run 'scan_contract_selectors' "
|
|
954
|
+
"for static bytecode inspection."
|
|
955
|
+
)
|
|
956
|
+
|
|
957
|
+
return {
|
|
958
|
+
"tool": "inspect_proxy_and_source",
|
|
959
|
+
"stage": 1,
|
|
960
|
+
"cost_usd": 0.0,
|
|
961
|
+
"llm_invoked": False,
|
|
962
|
+
"target_address": checksum_addr,
|
|
963
|
+
"chain_id": chain_id,
|
|
964
|
+
"effective_audit_address": effective_audit_address,
|
|
965
|
+
"is_proxy": is_proxy,
|
|
966
|
+
"implementation_address": proxy_info.get("implementation_address"),
|
|
967
|
+
"admin_address": proxy_info.get("admin_address"),
|
|
968
|
+
"beacon_address": proxy_info.get("beacon_address"),
|
|
969
|
+
"owner_address": proxy_info.get("owner_address"),
|
|
970
|
+
"is_paused": proxy_info.get("is_paused"),
|
|
971
|
+
"source_verified": source_verified,
|
|
972
|
+
"source_provider": source_info.get("provider"),
|
|
973
|
+
"contract_names": list(source_info.get("contract_names", [])),
|
|
974
|
+
"security_warnings": security_warnings,
|
|
975
|
+
"recommendation": recommendation,
|
|
976
|
+
"upsell_recommendation": upsell,
|
|
977
|
+
}
|
|
978
|
+
|
|
979
|
+
async def _execute_remote_deep_audit(
|
|
980
|
+
self,
|
|
981
|
+
payload: ConditionRulePayload,
|
|
982
|
+
checksum_addr: str,
|
|
983
|
+
cid: ChainId,
|
|
984
|
+
proposal_description: str,
|
|
985
|
+
policy_prompt: str,
|
|
986
|
+
calldata: str,
|
|
987
|
+
risk_threshold: float,
|
|
988
|
+
x402_payment_header: Optional[str],
|
|
989
|
+
resolve_proxy: bool,
|
|
990
|
+
fetch_verified_source: bool,
|
|
991
|
+
is_deep: bool,
|
|
992
|
+
) -> Dict[str, Any]:
|
|
993
|
+
"""Delegates deep_semantic_audit execution to the remote HTTP API using x402."""
|
|
994
|
+
cid_int = int(cid.value if hasattr(cid, "value") else cid)
|
|
995
|
+
endpoint_path = "/audit/deep" if is_deep else "/audit"
|
|
996
|
+
target_url = f"{self.agent_url}{endpoint_path}"
|
|
997
|
+
|
|
998
|
+
if self.require_x402_for_deep_audit and not x402_payment_header and not self.buyer_private_key:
|
|
999
|
+
return self._build_mcp_402_dict(payload, cfg=self.x402_config, is_deep_tier=is_deep)
|
|
1000
|
+
|
|
1001
|
+
body: Dict[str, Any] = {
|
|
1002
|
+
"target_address": checksum_addr,
|
|
1003
|
+
"chain_id": cid_int,
|
|
1004
|
+
"proposal_description": proposal_description,
|
|
1005
|
+
"policy_prompt": policy_prompt,
|
|
1006
|
+
"calldata": calldata,
|
|
1007
|
+
"risk_threshold": risk_threshold,
|
|
1008
|
+
}
|
|
1009
|
+
if is_deep:
|
|
1010
|
+
body["resolve_proxy"] = resolve_proxy
|
|
1011
|
+
body["fetch_verified_source"] = fetch_verified_source
|
|
1012
|
+
|
|
1013
|
+
cfg = self.x402_config or X402Config(
|
|
1014
|
+
enabled=True,
|
|
1015
|
+
network=os.getenv("X402_NETWORK", "eip155:8453"),
|
|
1016
|
+
price_per_eval_usdc=float(os.getenv("X402_PRICE_EVALUATE", "0.015")),
|
|
1017
|
+
price_per_deep_audit_usdc=float(os.getenv("X402_PRICE_DEEP_AUDIT", "0.25")),
|
|
1018
|
+
pay_to_address=os.getenv("PAY_TO_ADDRESS", "0x2b7F1fd931f7f28f89e0f688Dd5Bb7a620c24b63"),
|
|
1019
|
+
)
|
|
1020
|
+
|
|
1021
|
+
async def _run_with_client(client: Any) -> Dict[str, Any]:
|
|
1022
|
+
payment_hdr = x402_payment_header
|
|
1023
|
+
if not payment_hdr and self.buyer_private_key:
|
|
1024
|
+
fallback_price = (
|
|
1025
|
+
float(getattr(cfg, "price_per_deep_audit_usdc", 0.25))
|
|
1026
|
+
if is_deep
|
|
1027
|
+
else float(getattr(cfg, "price_per_eval_usdc", 0.015))
|
|
1028
|
+
)
|
|
1029
|
+
pay_to = (
|
|
1030
|
+
cfg.pay_to_address
|
|
1031
|
+
if getattr(cfg, "pay_to_address", None) and cfg.pay_to_address != DEFAULT_PAY_TO_ADDRESS
|
|
1032
|
+
else os.getenv("PAY_TO_ADDRESS", "0x2b7F1fd931f7f28f89e0f688Dd5Bb7a620c24b63")
|
|
1033
|
+
)
|
|
1034
|
+
amount_atomic = usdc_to_atomic(fallback_price)
|
|
1035
|
+
network = getattr(cfg, "network", None) or "eip155:8453"
|
|
1036
|
+
usdc_address: Optional[str] = None
|
|
1037
|
+
|
|
1038
|
+
try:
|
|
1039
|
+
probe_resp = await client.get(target_url)
|
|
1040
|
+
if probe_resp.status_code == 402:
|
|
1041
|
+
probe_json = probe_resp.json()
|
|
1042
|
+
accepts = probe_json.get("accepts", [])
|
|
1043
|
+
if isinstance(accepts, list) and accepts:
|
|
1044
|
+
acc = accepts[0]
|
|
1045
|
+
pay_to = acc.get("payTo") or pay_to
|
|
1046
|
+
raw_amt = acc.get("amount") or acc.get("maxAmountRequired")
|
|
1047
|
+
if raw_amt is not None:
|
|
1048
|
+
amount_atomic = int(raw_amt)
|
|
1049
|
+
network = acc.get("network") or network
|
|
1050
|
+
usdc_address = acc.get("asset") or acc.get("usdcAddress") or usdc_address
|
|
1051
|
+
except Exception as exc:
|
|
1052
|
+
logger.debug("Remote 402 challenge probe failed, using X402Config fallback: %s", exc)
|
|
1053
|
+
|
|
1054
|
+
try:
|
|
1055
|
+
account = Account.from_key(self.buyer_private_key)
|
|
1056
|
+
payment_hdr = create_eip3009_payment_header(
|
|
1057
|
+
account=account,
|
|
1058
|
+
pay_to_address=pay_to,
|
|
1059
|
+
amount_atomic=amount_atomic,
|
|
1060
|
+
network=network,
|
|
1061
|
+
usdc_address=usdc_address,
|
|
1062
|
+
as_base64=True,
|
|
1063
|
+
)
|
|
1064
|
+
except Exception as exc:
|
|
1065
|
+
return self._build_mcp_402_dict(
|
|
1066
|
+
payload,
|
|
1067
|
+
reason=f"Invalid buyer private key or signing failure: {exc}",
|
|
1068
|
+
cfg=cfg,
|
|
1069
|
+
is_deep_tier=is_deep,
|
|
1070
|
+
)
|
|
1071
|
+
|
|
1072
|
+
req_headers = {"PAYMENT-SIGNATURE": payment_hdr} if payment_hdr else {}
|
|
1073
|
+
try:
|
|
1074
|
+
post_resp = await client.post(target_url, json=body, headers=req_headers)
|
|
1075
|
+
except Exception as exc:
|
|
1076
|
+
return {
|
|
1077
|
+
"tool": "deep_semantic_audit",
|
|
1078
|
+
"stage": 2,
|
|
1079
|
+
"status": "error",
|
|
1080
|
+
"status_code": 503,
|
|
1081
|
+
"payment_settled": False,
|
|
1082
|
+
"error": f"Remote API request failed: {exc}",
|
|
1083
|
+
"remote_endpoint": target_url,
|
|
1084
|
+
}
|
|
1085
|
+
|
|
1086
|
+
if post_resp.status_code == 200:
|
|
1087
|
+
remote_data = post_resp.json()
|
|
1088
|
+
sem = remote_data.get("semantic_Evaluation") or remote_data.get("semantic_evaluation") or {}
|
|
1089
|
+
det = remote_data.get("deterministic_check") or {}
|
|
1090
|
+
decision = (
|
|
1091
|
+
sem.get("recommended_action")
|
|
1092
|
+
if sem
|
|
1093
|
+
else ("APPROVE" if det.get("passed") else "REJECT")
|
|
1094
|
+
)
|
|
1095
|
+
risk_score = sem.get("risk_score", 0.0) if sem else 0.0
|
|
1096
|
+
reasoning = sem.get("summary") if sem else det.get("reason", "")
|
|
1097
|
+
flagged_issues = sem.get("flagged_issues", []) if sem else []
|
|
1098
|
+
|
|
1099
|
+
result = dict(remote_data)
|
|
1100
|
+
result["tool"] = "deep_semantic_audit"
|
|
1101
|
+
result["stage"] = 2
|
|
1102
|
+
result["status"] = "completed"
|
|
1103
|
+
result["status_code"] = 200
|
|
1104
|
+
result["decision"] = decision
|
|
1105
|
+
result["risk_score"] = risk_score
|
|
1106
|
+
result["reasoning"] = reasoning
|
|
1107
|
+
result["flagged_issues"] = flagged_issues
|
|
1108
|
+
result["remote_endpoint"] = target_url
|
|
1109
|
+
return result
|
|
1110
|
+
|
|
1111
|
+
if post_resp.status_code == 402:
|
|
1112
|
+
reason = "Payment Required"
|
|
1113
|
+
remote_402: Dict[str, Any] = {}
|
|
1114
|
+
try:
|
|
1115
|
+
remote_402 = post_resp.json()
|
|
1116
|
+
reason = remote_402.get("message") or remote_402.get("error") or reason
|
|
1117
|
+
except Exception:
|
|
1118
|
+
pass
|
|
1119
|
+
out_402 = self._build_mcp_402_dict(payload, reason=reason, cfg=cfg, is_deep_tier=is_deep)
|
|
1120
|
+
accepts = remote_402.get("accepts", [])
|
|
1121
|
+
if isinstance(accepts, list) and accepts:
|
|
1122
|
+
acc = accepts[0]
|
|
1123
|
+
if acc.get("payTo"):
|
|
1124
|
+
out_402["pay_to_address"] = acc["payTo"]
|
|
1125
|
+
if acc.get("network"):
|
|
1126
|
+
out_402["network"] = acc["network"]
|
|
1127
|
+
if acc.get("amount_usdc") is not None:
|
|
1128
|
+
out_402["price_usdc"] = acc["amount_usdc"]
|
|
1129
|
+
return out_402
|
|
1130
|
+
|
|
1131
|
+
err_detail = post_resp.text
|
|
1132
|
+
try:
|
|
1133
|
+
err_json = post_resp.json()
|
|
1134
|
+
err_detail = err_json.get("message") or err_json.get("error") or err_json.get("detail") or err_detail
|
|
1135
|
+
except Exception:
|
|
1136
|
+
pass
|
|
1137
|
+
return {
|
|
1138
|
+
"tool": "deep_semantic_audit",
|
|
1139
|
+
"stage": 2,
|
|
1140
|
+
"status": "error",
|
|
1141
|
+
"status_code": post_resp.status_code,
|
|
1142
|
+
"payment_settled": False,
|
|
1143
|
+
"error": str(err_detail),
|
|
1144
|
+
"remote_endpoint": target_url,
|
|
1145
|
+
}
|
|
1146
|
+
|
|
1147
|
+
if self.http_client is not None:
|
|
1148
|
+
return await _run_with_client(self.http_client)
|
|
1149
|
+
async with httpx.AsyncClient(timeout=45.0) as client:
|
|
1150
|
+
return await _run_with_client(client)
|
|
1151
|
+
|
|
1152
|
+
async def deep_semantic_audit(
|
|
1153
|
+
self,
|
|
1154
|
+
target_address: str,
|
|
1155
|
+
proposal_description: str,
|
|
1156
|
+
policy_prompt: str = (
|
|
1157
|
+
"Audit contract and proposal for unauthorized privilege escalation, "
|
|
1158
|
+
"proxy upgrades, honeypot traps, or treasury drainage."
|
|
1159
|
+
),
|
|
1160
|
+
calldata: str = "0x",
|
|
1161
|
+
chain_id: int = 8453,
|
|
1162
|
+
risk_threshold: float = 7.0,
|
|
1163
|
+
x402_payment_header: Optional[str] = None,
|
|
1164
|
+
resolve_proxy: bool = False,
|
|
1165
|
+
fetch_verified_source: bool = False,
|
|
1166
|
+
) -> Dict[str, Any]:
|
|
1167
|
+
"""Tool 4: Two-stage on-chain gatekeeping + structured Gemini LLM security audit ($0.015 USDC standard / $0.25 USDC deep proxy + verified source x402 payment)."""
|
|
1168
|
+
checksum_addr = _validate_checksum_address(target_address)
|
|
1169
|
+
try:
|
|
1170
|
+
cid = ChainId(chain_id)
|
|
1171
|
+
except ValueError:
|
|
1172
|
+
cid = ChainId.BASE_MAINNET
|
|
1173
|
+
|
|
1174
|
+
is_deep = bool(resolve_proxy or fetch_verified_source)
|
|
1175
|
+
selector = (
|
|
1176
|
+
calldata[:10].lower()
|
|
1177
|
+
if calldata and calldata != "0x" and len(calldata) >= 10
|
|
1178
|
+
else "0x"
|
|
1179
|
+
)
|
|
1180
|
+
payload = ConditionRulePayload(
|
|
1181
|
+
rule_id=f"mcp-audit-{checksum_addr.lower()[:8]}-{int(time.time())}",
|
|
1182
|
+
chain_id=cid,
|
|
1183
|
+
deterministic=DeterministicCondition(
|
|
1184
|
+
target_address=checksum_addr,
|
|
1185
|
+
min_value_wei=0,
|
|
1186
|
+
required_function_selectors=None,
|
|
1187
|
+
check_native_balance=False,
|
|
1188
|
+
),
|
|
1189
|
+
semantic=SemanticCondition(
|
|
1190
|
+
enabled=True,
|
|
1191
|
+
policy_prompt=policy_prompt,
|
|
1192
|
+
risk_threshold=risk_threshold,
|
|
1193
|
+
),
|
|
1194
|
+
context_metadata={
|
|
1195
|
+
"contract_address": checksum_addr,
|
|
1196
|
+
"proposal_description": proposal_description,
|
|
1197
|
+
"calldata": calldata,
|
|
1198
|
+
"calldata_analysis": {
|
|
1199
|
+
"selector": selector,
|
|
1200
|
+
"signature": ChainInspector.KNOWN_SELECTORS.get(
|
|
1201
|
+
selector, "unknown_selector"
|
|
1202
|
+
),
|
|
1203
|
+
},
|
|
1204
|
+
"source": "mcp_server",
|
|
1205
|
+
},
|
|
1206
|
+
)
|
|
1207
|
+
|
|
1208
|
+
if self._should_use_remote_api():
|
|
1209
|
+
return await self._execute_remote_deep_audit(
|
|
1210
|
+
payload=payload,
|
|
1211
|
+
checksum_addr=checksum_addr,
|
|
1212
|
+
cid=cid,
|
|
1213
|
+
proposal_description=proposal_description,
|
|
1214
|
+
policy_prompt=policy_prompt,
|
|
1215
|
+
calldata=calldata,
|
|
1216
|
+
risk_threshold=risk_threshold,
|
|
1217
|
+
x402_payment_header=x402_payment_header,
|
|
1218
|
+
resolve_proxy=resolve_proxy,
|
|
1219
|
+
fetch_verified_source=fetch_verified_source,
|
|
1220
|
+
is_deep=is_deep,
|
|
1221
|
+
)
|
|
1222
|
+
|
|
1223
|
+
async def _enrich_audit_context():
|
|
1224
|
+
if resolve_proxy or fetch_verified_source:
|
|
1225
|
+
resolver = getattr(self, "source_resolver", None) or ContractSourceResolver()
|
|
1226
|
+
cid_int = int(cid.value if hasattr(cid, "value") else cid)
|
|
1227
|
+
audit_ctx = await resolver.resolve_full_audit_context(
|
|
1228
|
+
chain_id=cid_int,
|
|
1229
|
+
target_address=checksum_addr,
|
|
1230
|
+
resolve_proxy=resolve_proxy,
|
|
1231
|
+
fetch_source=fetch_verified_source,
|
|
1232
|
+
)
|
|
1233
|
+
effective_addr = (
|
|
1234
|
+
audit_ctx.get("effective_audit_address")
|
|
1235
|
+
or audit_ctx.get("proxy_info", {}).get("effective_audit_address")
|
|
1236
|
+
)
|
|
1237
|
+
if effective_addr:
|
|
1238
|
+
payload.deterministic.target_address = effective_addr
|
|
1239
|
+
payload.context_metadata["effective_audit_address"] = effective_addr or checksum_addr
|
|
1240
|
+
payload.context_metadata["proxy_info"] = audit_ctx.get("proxy_info", {})
|
|
1241
|
+
payload.context_metadata["source_info"] = audit_ctx.get("source_info", {})
|
|
1242
|
+
payload.context_metadata["effective_selectors"] = audit_ctx.get("effective_selectors", [])
|
|
1243
|
+
payload.context_metadata["security_warnings"] = audit_ctx.get("security_warnings", [])
|
|
1244
|
+
|
|
1245
|
+
if self.require_x402_for_deep_audit:
|
|
1246
|
+
if not x402_payment_header and not self.buyer_private_key:
|
|
1247
|
+
return self._build_mcp_402_dict(payload, cfg=self.x402_config, is_deep_tier=is_deep)
|
|
1248
|
+
|
|
1249
|
+
cfg = self.x402_config or X402Config(
|
|
1250
|
+
enabled=True,
|
|
1251
|
+
network=os.getenv("X402_NETWORK", "eip155:8453"),
|
|
1252
|
+
price_per_eval_usdc=float(os.getenv("X402_PRICE_EVALUATE", "0.015")),
|
|
1253
|
+
price_per_deep_audit_usdc=float(os.getenv("X402_PRICE_DEEP_AUDIT", "0.25")),
|
|
1254
|
+
pay_to_address=os.getenv("PAY_TO_ADDRESS", "0x2b7F1fd931f7f28f89e0f688Dd5Bb7a620c24b63"),
|
|
1255
|
+
)
|
|
1256
|
+
|
|
1257
|
+
required_usdc = (
|
|
1258
|
+
float(getattr(cfg, "price_per_deep_audit_usdc", 0.25))
|
|
1259
|
+
if is_deep
|
|
1260
|
+
else float(getattr(cfg, "price_per_eval_usdc", 0.015))
|
|
1261
|
+
)
|
|
1262
|
+
endpoint_path = "/audit/deep" if is_deep else "/evaluate"
|
|
1263
|
+
|
|
1264
|
+
if not x402_payment_header and self.buyer_private_key:
|
|
1265
|
+
try:
|
|
1266
|
+
account = Account.from_key(self.buyer_private_key)
|
|
1267
|
+
req_atomic = usdc_to_atomic(required_usdc)
|
|
1268
|
+
x402_payment_header = create_eip3009_payment_header(
|
|
1269
|
+
account=account,
|
|
1270
|
+
pay_to_address=cfg.pay_to_address,
|
|
1271
|
+
amount_atomic=req_atomic,
|
|
1272
|
+
network=cfg.network,
|
|
1273
|
+
as_base64=True,
|
|
1274
|
+
)
|
|
1275
|
+
except Exception as exc:
|
|
1276
|
+
return self._build_mcp_402_dict(
|
|
1277
|
+
payload,
|
|
1278
|
+
reason=f"Invalid buyer private key or signing failure: {exc}",
|
|
1279
|
+
cfg=cfg,
|
|
1280
|
+
is_deep_tier=is_deep,
|
|
1281
|
+
)
|
|
1282
|
+
|
|
1283
|
+
try:
|
|
1284
|
+
payment_data = parse_x402_header(x402_payment_header, default_network=cfg.network)
|
|
1285
|
+
except ValueError as exc:
|
|
1286
|
+
return self._build_mcp_402_dict(
|
|
1287
|
+
payload,
|
|
1288
|
+
reason=f"Malformed payment header: {exc}",
|
|
1289
|
+
cfg=cfg,
|
|
1290
|
+
is_deep_tier=is_deep,
|
|
1291
|
+
)
|
|
1292
|
+
|
|
1293
|
+
payment_data["endpoint"] = endpoint_path
|
|
1294
|
+
|
|
1295
|
+
if self.storage is not None and await self.storage.is_payment_settled(payment_data["payment_id"]):
|
|
1296
|
+
return self._build_mcp_402_dict(
|
|
1297
|
+
payload,
|
|
1298
|
+
reason="Payment already settled (replay detected)",
|
|
1299
|
+
cfg=cfg,
|
|
1300
|
+
is_deep_tier=is_deep,
|
|
1301
|
+
)
|
|
1302
|
+
|
|
1303
|
+
facilitator = self.facilitator or get_x402_facilitator(cfg)
|
|
1304
|
+
required_atomic = usdc_to_atomic(required_usdc)
|
|
1305
|
+
|
|
1306
|
+
ver = await facilitator.verify(payment_data, required_atomic, cfg)
|
|
1307
|
+
if not ver.valid:
|
|
1308
|
+
return self._build_mcp_402_dict(
|
|
1309
|
+
payload,
|
|
1310
|
+
reason=ver.reason or "Payment verification failed",
|
|
1311
|
+
cfg=cfg,
|
|
1312
|
+
is_deep_tier=is_deep,
|
|
1313
|
+
)
|
|
1314
|
+
|
|
1315
|
+
if self.engine is None:
|
|
1316
|
+
self.engine = ConditionAgentEngine()
|
|
1317
|
+
|
|
1318
|
+
if resolve_proxy or fetch_verified_source:
|
|
1319
|
+
await _enrich_audit_context()
|
|
1320
|
+
|
|
1321
|
+
res = await self.engine.process_rule(payload, source="mcp_server")
|
|
1322
|
+
|
|
1323
|
+
if res.deterministic_check.error is not None:
|
|
1324
|
+
return {
|
|
1325
|
+
"tool": "deep_semantic_audit",
|
|
1326
|
+
"stage": 2,
|
|
1327
|
+
"status": "error",
|
|
1328
|
+
"status_code": 503,
|
|
1329
|
+
"payment_settled": False,
|
|
1330
|
+
"error": res.deterministic_check.error,
|
|
1331
|
+
}
|
|
1332
|
+
|
|
1333
|
+
settlement = await facilitator.settle(payment_data, required_atomic, cfg)
|
|
1334
|
+
if not settlement.settled:
|
|
1335
|
+
return self._build_mcp_402_dict(
|
|
1336
|
+
payload,
|
|
1337
|
+
reason=settlement.error or "Payment settlement failed",
|
|
1338
|
+
cfg=cfg,
|
|
1339
|
+
is_deep_tier=is_deep,
|
|
1340
|
+
)
|
|
1341
|
+
|
|
1342
|
+
receipt = PaymentReceipt(
|
|
1343
|
+
payment_id=payment_data["payment_id"],
|
|
1344
|
+
payer_address=payment_data["payer_address"],
|
|
1345
|
+
pay_to_address=cfg.pay_to_address,
|
|
1346
|
+
amount_usdc=round(required_usdc, 6),
|
|
1347
|
+
amount_atomic=required_atomic,
|
|
1348
|
+
network=payment_data.get("network") or cfg.network,
|
|
1349
|
+
asset=cfg.asset,
|
|
1350
|
+
tx_hash=settlement.tx_hash or "",
|
|
1351
|
+
endpoint=endpoint_path,
|
|
1352
|
+
settled_at=datetime.now(timezone.utc).isoformat(),
|
|
1353
|
+
)
|
|
1354
|
+
res.payment = receipt
|
|
1355
|
+
if self.storage is not None:
|
|
1356
|
+
await self.storage.record_payment(receipt, rule_id=payload.rule_id)
|
|
1357
|
+
else:
|
|
1358
|
+
if self.engine is None:
|
|
1359
|
+
self.engine = ConditionAgentEngine()
|
|
1360
|
+
|
|
1361
|
+
if resolve_proxy or fetch_verified_source:
|
|
1362
|
+
await _enrich_audit_context()
|
|
1363
|
+
|
|
1364
|
+
res = await self.engine.process_rule(payload, source="mcp_server")
|
|
1365
|
+
|
|
1366
|
+
sem = getattr(res, "semantic_Evaluation", None) or getattr(res, "semantic_evaluation", None)
|
|
1367
|
+
dumped = res.model_dump(mode="json")
|
|
1368
|
+
dumped["tool"] = "deep_semantic_audit"
|
|
1369
|
+
dumped["stage"] = 2
|
|
1370
|
+
dumped["status"] = "completed"
|
|
1371
|
+
dumped["status_code"] = 200
|
|
1372
|
+
dumped["decision"] = sem.recommended_action if sem else ("APPROVE" if res.deterministic_check.passed else "REJECT")
|
|
1373
|
+
dumped["risk_score"] = sem.risk_score if sem else 0.0
|
|
1374
|
+
dumped["reasoning"] = sem.summary if sem else res.deterministic_check.reason
|
|
1375
|
+
dumped["flagged_issues"] = sem.flagged_issues if sem else []
|
|
1376
|
+
return dumped
|
|
1377
|
+
|
|
1378
|
+
def get_resources_manifest(self) -> List[Dict[str, Any]]:
|
|
1379
|
+
"""Returns the canonical MCP resources manifest defining all readable agent resources."""
|
|
1380
|
+
return [
|
|
1381
|
+
{
|
|
1382
|
+
"uri": "web3://x402/pricing",
|
|
1383
|
+
"name": "x402 Micropayment Pricing & Tiers",
|
|
1384
|
+
"mimeType": "application/json",
|
|
1385
|
+
"description": (
|
|
1386
|
+
"Current x402 USDC micropayment pricing tiers, supported EVM network profiles "
|
|
1387
|
+
"(Base Mainnet, Base Sepolia, Arbitrum One), and free vs paid tool mapping."
|
|
1388
|
+
),
|
|
1389
|
+
},
|
|
1390
|
+
{
|
|
1391
|
+
"uri": "web3://security/selectors-catalog",
|
|
1392
|
+
"name": "Known EVM Selectors & Honeypot Traps",
|
|
1393
|
+
"mimeType": "application/json",
|
|
1394
|
+
"description": (
|
|
1395
|
+
"Static catalog of known 4-byte EVM administrative selectors, high-risk keywords, "
|
|
1396
|
+
"and DEX honeypot/rugpull signatures."
|
|
1397
|
+
),
|
|
1398
|
+
},
|
|
1399
|
+
{
|
|
1400
|
+
"uri": "web3://feed/dao-curated-proposals",
|
|
1401
|
+
"name": "Curated Snapshot DAO Governance Proposals",
|
|
1402
|
+
"mimeType": "application/json",
|
|
1403
|
+
"description": (
|
|
1404
|
+
"Deterministic curated dataset of Snapshot DAO governance proposals with extracted "
|
|
1405
|
+
"on-chain target contracts and execution calldata."
|
|
1406
|
+
),
|
|
1407
|
+
},
|
|
1408
|
+
{
|
|
1409
|
+
"uri": "web3://feed/recent-audits",
|
|
1410
|
+
"name": "Recent Autonomous Security Audits Feed",
|
|
1411
|
+
"mimeType": "application/json",
|
|
1412
|
+
"description": (
|
|
1413
|
+
"Most recent autonomous contract and governance security evaluations recorded in "
|
|
1414
|
+
"AgentStorage."
|
|
1415
|
+
),
|
|
1416
|
+
},
|
|
1417
|
+
]
|
|
1418
|
+
|
|
1419
|
+
async def read_resource(self, uri: str) -> Dict[str, Any]:
|
|
1420
|
+
"""Reads and returns the JSON payload for a known MCP resource URI."""
|
|
1421
|
+
if uri == "web3://x402/pricing":
|
|
1422
|
+
cfg = self.x402_config or X402Config(
|
|
1423
|
+
enabled=True,
|
|
1424
|
+
network=os.getenv("X402_NETWORK", "eip155:8453"),
|
|
1425
|
+
price_per_token_check_usdc=float(os.getenv("X402_PRICE_TOKEN_CHECK", "0.005")),
|
|
1426
|
+
price_per_preflight_usdc=float(os.getenv("X402_PRICE_PREFLIGHT", "0.01")),
|
|
1427
|
+
price_per_eval_usdc=float(os.getenv("X402_PRICE_EVALUATE", "0.015")),
|
|
1428
|
+
price_per_deep_audit_usdc=float(os.getenv("X402_PRICE_DEEP_AUDIT", "0.25")),
|
|
1429
|
+
pay_to_address=os.getenv("PAY_TO_ADDRESS", "0x2b7F1fd931f7f28f89e0f688Dd5Bb7a620c24b63"),
|
|
1430
|
+
)
|
|
1431
|
+
pay_to = (
|
|
1432
|
+
cfg.pay_to_address
|
|
1433
|
+
if getattr(cfg, "pay_to_address", None) and cfg.pay_to_address != DEFAULT_PAY_TO_ADDRESS
|
|
1434
|
+
else os.getenv("PAY_TO_ADDRESS", "0x2b7F1fd931f7f28f89e0f688Dd5Bb7a620c24b63")
|
|
1435
|
+
)
|
|
1436
|
+
return {
|
|
1437
|
+
"protocol": "x402",
|
|
1438
|
+
"asset": getattr(cfg, "asset", "USDC"),
|
|
1439
|
+
"network": getattr(cfg, "network", "eip155:8453"),
|
|
1440
|
+
"pay_to_address": pay_to,
|
|
1441
|
+
"stage_1_free_mcp_tools": [
|
|
1442
|
+
"scan_contract_selectors",
|
|
1443
|
+
"check_token_honeypot",
|
|
1444
|
+
"scan_dao_proposals",
|
|
1445
|
+
"preflight_tx_firewall",
|
|
1446
|
+
"inspect_proxy_and_source",
|
|
1447
|
+
],
|
|
1448
|
+
"tiers": {
|
|
1449
|
+
"token_check": {
|
|
1450
|
+
"endpoint": "/token/check",
|
|
1451
|
+
"price_usdc": float(getattr(cfg, "price_per_token_check_usdc", 0.005)),
|
|
1452
|
+
},
|
|
1453
|
+
"preflight": {
|
|
1454
|
+
"endpoint": "/preflight",
|
|
1455
|
+
"price_usdc": float(getattr(cfg, "price_per_preflight_usdc", 0.01)),
|
|
1456
|
+
},
|
|
1457
|
+
"standard_audit": {
|
|
1458
|
+
"endpoint": "/audit",
|
|
1459
|
+
"mcp_tool": "deep_semantic_audit",
|
|
1460
|
+
"price_usdc": float(getattr(cfg, "price_per_eval_usdc", 0.015)),
|
|
1461
|
+
},
|
|
1462
|
+
"deep_audit": {
|
|
1463
|
+
"endpoint": "/audit/deep",
|
|
1464
|
+
"mcp_tool": "deep_semantic_audit (resolve_proxy=True or fetch_verified_source=True)",
|
|
1465
|
+
"price_usdc": float(getattr(cfg, "price_per_deep_audit_usdc", 0.25)),
|
|
1466
|
+
},
|
|
1467
|
+
},
|
|
1468
|
+
}
|
|
1469
|
+
|
|
1470
|
+
if uri == "web3://security/selectors-catalog":
|
|
1471
|
+
return {
|
|
1472
|
+
"known_selectors": dict(SCANNER_KNOWN_SELECTORS),
|
|
1473
|
+
"high_risk_keywords": list(HIGH_RISK_KEYWORDS),
|
|
1474
|
+
"honeypot_selectors": dict(HONEYPOT_SELECTORS),
|
|
1475
|
+
}
|
|
1476
|
+
|
|
1477
|
+
if uri == "web3://feed/dao-curated-proposals":
|
|
1478
|
+
proposals = get_curated_dao_proposals(limit=10)
|
|
1479
|
+
return {
|
|
1480
|
+
"count": len(proposals),
|
|
1481
|
+
"proposals": [p.model_dump(mode="json") for p in proposals],
|
|
1482
|
+
}
|
|
1483
|
+
|
|
1484
|
+
if uri == "web3://feed/recent-audits":
|
|
1485
|
+
evaluations: List[Dict[str, Any]] = []
|
|
1486
|
+
if self.storage is not None and hasattr(self.storage, "get_recent_feed_evaluations"):
|
|
1487
|
+
rows = await self.storage.get_recent_feed_evaluations(limit=10)
|
|
1488
|
+
if isinstance(rows, list):
|
|
1489
|
+
evaluations = rows
|
|
1490
|
+
return {
|
|
1491
|
+
"count": len(evaluations),
|
|
1492
|
+
"evaluations": evaluations,
|
|
1493
|
+
}
|
|
1494
|
+
|
|
1495
|
+
raise ValueError(f"Resource not found: {uri}")
|
|
1496
|
+
|
|
1497
|
+
def get_prompts_manifest(self) -> List[Dict[str, Any]]:
|
|
1498
|
+
"""Returns the canonical MCP prompts manifest defining all reusable security audit workflows."""
|
|
1499
|
+
return [
|
|
1500
|
+
{
|
|
1501
|
+
"name": "audit-token-before-swap",
|
|
1502
|
+
"description": (
|
|
1503
|
+
"Guided pre-swap security workflow for evaluating an ERC-20 token for honeypot traps, "
|
|
1504
|
+
"privileged selectors, proxy upgradability, and optional deep LLM source audit."
|
|
1505
|
+
),
|
|
1506
|
+
"arguments": [
|
|
1507
|
+
{
|
|
1508
|
+
"name": "token_address",
|
|
1509
|
+
"description": "Hex EVM address of the token contract to audit before swapping",
|
|
1510
|
+
"required": True,
|
|
1511
|
+
},
|
|
1512
|
+
{
|
|
1513
|
+
"name": "chain_id",
|
|
1514
|
+
"description": "EVM Chain ID (default: 8453 for Base Mainnet)",
|
|
1515
|
+
"required": False,
|
|
1516
|
+
},
|
|
1517
|
+
],
|
|
1518
|
+
},
|
|
1519
|
+
{
|
|
1520
|
+
"name": "pre-sign-transaction-firewall",
|
|
1521
|
+
"description": (
|
|
1522
|
+
"Pre-sign transaction security firewall workflow inspecting calldata, unlimited approvals, "
|
|
1523
|
+
"Permit2, EIP-712 typed data phishing, prompt injections, and eth_call simulation."
|
|
1524
|
+
),
|
|
1525
|
+
"arguments": [
|
|
1526
|
+
{
|
|
1527
|
+
"name": "to_address",
|
|
1528
|
+
"description": "Target contract or recipient EVM hex address",
|
|
1529
|
+
"required": True,
|
|
1530
|
+
},
|
|
1531
|
+
{
|
|
1532
|
+
"name": "calldata",
|
|
1533
|
+
"description": "Hex transaction calldata (default: 0x)",
|
|
1534
|
+
"required": False,
|
|
1535
|
+
},
|
|
1536
|
+
],
|
|
1537
|
+
},
|
|
1538
|
+
{
|
|
1539
|
+
"name": "audit-dao-governance-space",
|
|
1540
|
+
"description": (
|
|
1541
|
+
"Governance security workflow scanning recent Snapshot DAO proposals for hostile takeover "
|
|
1542
|
+
"payloads and escalating suspicious execution calldata."
|
|
1543
|
+
),
|
|
1544
|
+
"arguments": [
|
|
1545
|
+
{
|
|
1546
|
+
"name": "space_id",
|
|
1547
|
+
"description": "Snapshot DAO space ENS identifier (default: arbitrumfoundation.eth)",
|
|
1548
|
+
"required": False,
|
|
1549
|
+
},
|
|
1550
|
+
],
|
|
1551
|
+
},
|
|
1552
|
+
]
|
|
1553
|
+
|
|
1554
|
+
def get_prompt(
|
|
1555
|
+
self, name: str, arguments: Optional[Dict[str, Any]] = None
|
|
1556
|
+
) -> Dict[str, Any]:
|
|
1557
|
+
"""Renders a named MCP prompt template with validated arguments."""
|
|
1558
|
+
args = arguments if isinstance(arguments, dict) else {}
|
|
1559
|
+
|
|
1560
|
+
if name == "audit-token-before-swap":
|
|
1561
|
+
token_address = str(args.get("token_address") or "").strip()
|
|
1562
|
+
if not token_address:
|
|
1563
|
+
raise ValueError("Missing required prompt argument: 'token_address'")
|
|
1564
|
+
chain_id = args.get("chain_id", 8453)
|
|
1565
|
+
prompt_text = (
|
|
1566
|
+
f"Perform a pre-swap security audit for token `{token_address}` on chain_id={chain_id}:\n"
|
|
1567
|
+
f"1. Call `check_token_honeypot(token_address='{token_address}', chain_id={chain_id})` (Free Stage 1).\n"
|
|
1568
|
+
f"2. Call `scan_contract_selectors(target_address='{token_address}', chain_id={chain_id})` (Free Stage 1).\n"
|
|
1569
|
+
f"3. Call `inspect_proxy_and_source(target_address='{token_address}', chain_id={chain_id})` (Free Stage 1).\n"
|
|
1570
|
+
"4. If honeypot traps, privileged backdoors (mint/setTax/upgradeTo), or unverified proxy risks are flagged, "
|
|
1571
|
+
"escalate to `deep_semantic_audit` with `resolve_proxy=True` and `fetch_verified_source=True` before swapping."
|
|
1572
|
+
)
|
|
1573
|
+
return {
|
|
1574
|
+
"description": "Pre-swap ERC-20 token security audit workflow",
|
|
1575
|
+
"messages": [
|
|
1576
|
+
{
|
|
1577
|
+
"role": "user",
|
|
1578
|
+
"content": {"type": "text", "text": prompt_text},
|
|
1579
|
+
}
|
|
1580
|
+
],
|
|
1581
|
+
}
|
|
1582
|
+
|
|
1583
|
+
if name == "pre-sign-transaction-firewall":
|
|
1584
|
+
to_address = str(args.get("to_address") or "").strip()
|
|
1585
|
+
if not to_address:
|
|
1586
|
+
raise ValueError("Missing required prompt argument: 'to_address'")
|
|
1587
|
+
calldata = str(args.get("calldata") or "0x").strip()
|
|
1588
|
+
prompt_text = (
|
|
1589
|
+
f"Run a pre-sign firewall check before signing a transaction to `{to_address}` with calldata `{calldata}`:\n"
|
|
1590
|
+
f"1. Call `preflight_tx_firewall(to_address='{to_address}', calldata='{calldata}', run_simulation=True)` (Free Stage 1).\n"
|
|
1591
|
+
f"2. Call `inspect_proxy_and_source(target_address='{to_address}')` to verify whether the destination is an upgradeable proxy.\n"
|
|
1592
|
+
"3. Block execution immediately if `verdict == 'BLOCK'`, unlimited approval risks, EIP-712 phishing, or prompt injection are detected."
|
|
1593
|
+
)
|
|
1594
|
+
return {
|
|
1595
|
+
"description": "Pre-sign transaction security firewall inspection",
|
|
1596
|
+
"messages": [
|
|
1597
|
+
{
|
|
1598
|
+
"role": "user",
|
|
1599
|
+
"content": {"type": "text", "text": prompt_text},
|
|
1600
|
+
}
|
|
1601
|
+
],
|
|
1602
|
+
}
|
|
1603
|
+
|
|
1604
|
+
if name == "audit-dao-governance-space":
|
|
1605
|
+
space_id = str(args.get("space_id") or "arbitrumfoundation.eth").strip()
|
|
1606
|
+
prompt_text = (
|
|
1607
|
+
f"Audit recent governance proposals for Snapshot DAO space `{space_id}`:\n"
|
|
1608
|
+
f"1. Call `scan_dao_proposals(space_id='{space_id}', limit=5)` (Free Stage 1).\n"
|
|
1609
|
+
"2. For any proposal containing an on-chain `target_address` and non-empty `calldata`, run "
|
|
1610
|
+
"`preflight_tx_firewall` and `inspect_proxy_and_source`.\n"
|
|
1611
|
+
"3. Escalate suspicious or high-impact treasury/upgrade payloads to `deep_semantic_audit`."
|
|
1612
|
+
)
|
|
1613
|
+
return {
|
|
1614
|
+
"description": "Snapshot DAO governance security audit workflow",
|
|
1615
|
+
"messages": [
|
|
1616
|
+
{
|
|
1617
|
+
"role": "user",
|
|
1618
|
+
"content": {"type": "text", "text": prompt_text},
|
|
1619
|
+
}
|
|
1620
|
+
],
|
|
1621
|
+
}
|
|
1622
|
+
|
|
1623
|
+
raise ValueError(f"Prompt not found: {name}")
|
|
1624
|
+
|
|
1625
|
+
async def handle_jsonrpc(
|
|
1626
|
+
self, request_data: Dict[str, Any]
|
|
1627
|
+
) -> Optional[Dict[str, Any]]:
|
|
1628
|
+
"""Handles a single JSON-RPC 2.0 request or notification according to MCP specifications."""
|
|
1629
|
+
if not isinstance(request_data, dict):
|
|
1630
|
+
return {
|
|
1631
|
+
"jsonrpc": "2.0",
|
|
1632
|
+
"id": None,
|
|
1633
|
+
"error": {
|
|
1634
|
+
"code": -32600,
|
|
1635
|
+
"message": "Invalid Request: expected JSON object",
|
|
1636
|
+
},
|
|
1637
|
+
}
|
|
1638
|
+
|
|
1639
|
+
req_id = request_data.get("id")
|
|
1640
|
+
method = request_data.get("method")
|
|
1641
|
+
|
|
1642
|
+
# 1. initialize
|
|
1643
|
+
if method == "initialize":
|
|
1644
|
+
params = request_data.get("params")
|
|
1645
|
+
if not isinstance(params, dict):
|
|
1646
|
+
params = {}
|
|
1647
|
+
requested_ver = params.get("protocolVersion")
|
|
1648
|
+
negotiated_ver = (
|
|
1649
|
+
requested_ver
|
|
1650
|
+
if requested_ver in SUPPORTED_MCP_VERSIONS
|
|
1651
|
+
else MCP_PROTOCOL_VERSION
|
|
1652
|
+
)
|
|
1653
|
+
return {
|
|
1654
|
+
"jsonrpc": "2.0",
|
|
1655
|
+
"id": req_id,
|
|
1656
|
+
"result": {
|
|
1657
|
+
"protocolVersion": negotiated_ver,
|
|
1658
|
+
"capabilities": {
|
|
1659
|
+
"tools": {"listChanged": False},
|
|
1660
|
+
"resources": {"subscribe": False, "listChanged": False},
|
|
1661
|
+
"prompts": {"listChanged": False},
|
|
1662
|
+
},
|
|
1663
|
+
"serverInfo": {
|
|
1664
|
+
"name": MCP_SERVER_NAME,
|
|
1665
|
+
"version": MCP_SERVER_VERSION,
|
|
1666
|
+
},
|
|
1667
|
+
"instructions": (
|
|
1668
|
+
"Use the five free Stage 1 tools (scan_contract_selectors, check_token_honeypot, "
|
|
1669
|
+
"scan_dao_proposals, preflight_tx_firewall, inspect_proxy_and_source) first for "
|
|
1670
|
+
"zero-cost deterministic screening. Escalate to the paid Stage 2 tool "
|
|
1671
|
+
"(deep_semantic_audit, $0.015 USDC standard / $0.25 USDC deep proxy + verified source "
|
|
1672
|
+
"via x402 on Base) only when high-risk selectors, honeypot traps, upgradeable proxies, "
|
|
1673
|
+
"or suspicious governance calldata are detected."
|
|
1674
|
+
),
|
|
1675
|
+
},
|
|
1676
|
+
}
|
|
1677
|
+
|
|
1678
|
+
# 2. notifications/initialized (notification - no response)
|
|
1679
|
+
if method == "notifications/initialized":
|
|
1680
|
+
return None
|
|
1681
|
+
|
|
1682
|
+
# 3. ping
|
|
1683
|
+
if method == "ping":
|
|
1684
|
+
return {
|
|
1685
|
+
"jsonrpc": "2.0",
|
|
1686
|
+
"id": req_id,
|
|
1687
|
+
"result": {},
|
|
1688
|
+
}
|
|
1689
|
+
|
|
1690
|
+
# 3b. server/discover & rpc.discover
|
|
1691
|
+
if method in ("server/discover", "rpc.discover"):
|
|
1692
|
+
return {
|
|
1693
|
+
"jsonrpc": "2.0",
|
|
1694
|
+
"id": req_id,
|
|
1695
|
+
"result": {
|
|
1696
|
+
"name": MCP_SERVER_NAME,
|
|
1697
|
+
"version": MCP_SERVER_VERSION,
|
|
1698
|
+
"protocolVersion": MCP_PROTOCOL_VERSION,
|
|
1699
|
+
"tools": self.get_tools_manifest(),
|
|
1700
|
+
},
|
|
1701
|
+
}
|
|
1702
|
+
|
|
1703
|
+
# 3c. logging/setLevel
|
|
1704
|
+
if method == "logging/setLevel":
|
|
1705
|
+
return {
|
|
1706
|
+
"jsonrpc": "2.0",
|
|
1707
|
+
"id": req_id,
|
|
1708
|
+
"result": {},
|
|
1709
|
+
}
|
|
1710
|
+
|
|
1711
|
+
# 4. tools/list
|
|
1712
|
+
if method == "tools/list":
|
|
1713
|
+
return {
|
|
1714
|
+
"jsonrpc": "2.0",
|
|
1715
|
+
"id": req_id,
|
|
1716
|
+
"result": {
|
|
1717
|
+
"tools": self.get_tools_manifest(),
|
|
1718
|
+
},
|
|
1719
|
+
}
|
|
1720
|
+
|
|
1721
|
+
# 5. resources/list
|
|
1722
|
+
if method == "resources/list":
|
|
1723
|
+
return {
|
|
1724
|
+
"jsonrpc": "2.0",
|
|
1725
|
+
"id": req_id,
|
|
1726
|
+
"result": {
|
|
1727
|
+
"resources": self.get_resources_manifest(),
|
|
1728
|
+
},
|
|
1729
|
+
}
|
|
1730
|
+
|
|
1731
|
+
# 5b. resources/read
|
|
1732
|
+
if method == "resources/read":
|
|
1733
|
+
params = request_data.get("params")
|
|
1734
|
+
uri = params.get("uri") if isinstance(params, dict) else None
|
|
1735
|
+
if not uri or not isinstance(uri, str):
|
|
1736
|
+
return {
|
|
1737
|
+
"jsonrpc": "2.0",
|
|
1738
|
+
"id": req_id,
|
|
1739
|
+
"error": {
|
|
1740
|
+
"code": -32602,
|
|
1741
|
+
"message": "Invalid params: 'uri' string is required",
|
|
1742
|
+
},
|
|
1743
|
+
}
|
|
1744
|
+
try:
|
|
1745
|
+
data = await self.read_resource(uri)
|
|
1746
|
+
except ValueError as exc:
|
|
1747
|
+
return {
|
|
1748
|
+
"jsonrpc": "2.0",
|
|
1749
|
+
"id": req_id,
|
|
1750
|
+
"error": {
|
|
1751
|
+
"code": -32602,
|
|
1752
|
+
"message": str(exc),
|
|
1753
|
+
},
|
|
1754
|
+
}
|
|
1755
|
+
return {
|
|
1756
|
+
"jsonrpc": "2.0",
|
|
1757
|
+
"id": req_id,
|
|
1758
|
+
"result": {
|
|
1759
|
+
"contents": [
|
|
1760
|
+
{
|
|
1761
|
+
"uri": uri,
|
|
1762
|
+
"mimeType": "application/json",
|
|
1763
|
+
"text": json.dumps(data, indent=2, default=str),
|
|
1764
|
+
}
|
|
1765
|
+
]
|
|
1766
|
+
},
|
|
1767
|
+
}
|
|
1768
|
+
|
|
1769
|
+
# 6. prompts/list
|
|
1770
|
+
if method == "prompts/list":
|
|
1771
|
+
return {
|
|
1772
|
+
"jsonrpc": "2.0",
|
|
1773
|
+
"id": req_id,
|
|
1774
|
+
"result": {
|
|
1775
|
+
"prompts": self.get_prompts_manifest(),
|
|
1776
|
+
},
|
|
1777
|
+
}
|
|
1778
|
+
|
|
1779
|
+
# 6b. prompts/get
|
|
1780
|
+
if method == "prompts/get":
|
|
1781
|
+
params = request_data.get("params")
|
|
1782
|
+
name = params.get("name") if isinstance(params, dict) else None
|
|
1783
|
+
arguments = params.get("arguments") if isinstance(params, dict) else None
|
|
1784
|
+
if not name or not isinstance(name, str):
|
|
1785
|
+
return {
|
|
1786
|
+
"jsonrpc": "2.0",
|
|
1787
|
+
"id": req_id,
|
|
1788
|
+
"error": {
|
|
1789
|
+
"code": -32602,
|
|
1790
|
+
"message": "Invalid params: 'name' string is required",
|
|
1791
|
+
},
|
|
1792
|
+
}
|
|
1793
|
+
try:
|
|
1794
|
+
prompt_result = self.get_prompt(name, arguments)
|
|
1795
|
+
except ValueError as exc:
|
|
1796
|
+
return {
|
|
1797
|
+
"jsonrpc": "2.0",
|
|
1798
|
+
"id": req_id,
|
|
1799
|
+
"error": {
|
|
1800
|
+
"code": -32602,
|
|
1801
|
+
"message": str(exc),
|
|
1802
|
+
},
|
|
1803
|
+
}
|
|
1804
|
+
return {
|
|
1805
|
+
"jsonrpc": "2.0",
|
|
1806
|
+
"id": req_id,
|
|
1807
|
+
"result": prompt_result,
|
|
1808
|
+
}
|
|
1809
|
+
|
|
1810
|
+
# 7. tools/call
|
|
1811
|
+
if method == "tools/call":
|
|
1812
|
+
params = request_data.get("params", {})
|
|
1813
|
+
tool_name = params.get("name")
|
|
1814
|
+
arguments = params.get("arguments", {})
|
|
1815
|
+
|
|
1816
|
+
known_tools = {
|
|
1817
|
+
"scan_contract_selectors": self.scan_contract_selectors,
|
|
1818
|
+
"check_token_honeypot": self.check_token_honeypot,
|
|
1819
|
+
"scan_dao_proposals": self.scan_dao_proposals,
|
|
1820
|
+
"deep_semantic_audit": self.deep_semantic_audit,
|
|
1821
|
+
"preflight_tx_firewall": self.preflight_tx_firewall,
|
|
1822
|
+
"inspect_proxy_and_source": self.inspect_proxy_and_source,
|
|
1823
|
+
}
|
|
1824
|
+
|
|
1825
|
+
if tool_name not in known_tools:
|
|
1826
|
+
return {
|
|
1827
|
+
"jsonrpc": "2.0",
|
|
1828
|
+
"id": req_id,
|
|
1829
|
+
"error": {
|
|
1830
|
+
"code": -32601,
|
|
1831
|
+
"message": f"Tool '{tool_name}' not found",
|
|
1832
|
+
},
|
|
1833
|
+
}
|
|
1834
|
+
|
|
1835
|
+
try:
|
|
1836
|
+
fn = known_tools[tool_name]
|
|
1837
|
+
out = await fn(**arguments)
|
|
1838
|
+
return {
|
|
1839
|
+
"jsonrpc": "2.0",
|
|
1840
|
+
"id": req_id,
|
|
1841
|
+
"result": {
|
|
1842
|
+
"content": [
|
|
1843
|
+
{
|
|
1844
|
+
"type": "text",
|
|
1845
|
+
"text": json.dumps(out, indent=2, default=str),
|
|
1846
|
+
}
|
|
1847
|
+
],
|
|
1848
|
+
"structuredContent": out,
|
|
1849
|
+
"isError": False,
|
|
1850
|
+
},
|
|
1851
|
+
}
|
|
1852
|
+
except Exception as exc:
|
|
1853
|
+
return {
|
|
1854
|
+
"jsonrpc": "2.0",
|
|
1855
|
+
"id": req_id,
|
|
1856
|
+
"result": {
|
|
1857
|
+
"content": [
|
|
1858
|
+
{
|
|
1859
|
+
"type": "text",
|
|
1860
|
+
"text": json.dumps({"error": str(exc)}),
|
|
1861
|
+
}
|
|
1862
|
+
],
|
|
1863
|
+
"isError": True,
|
|
1864
|
+
},
|
|
1865
|
+
}
|
|
1866
|
+
|
|
1867
|
+
# Unrecognized method
|
|
1868
|
+
return {
|
|
1869
|
+
"jsonrpc": "2.0",
|
|
1870
|
+
"id": req_id,
|
|
1871
|
+
"error": {
|
|
1872
|
+
"code": -32601,
|
|
1873
|
+
"message": f"Method '{method}' not found",
|
|
1874
|
+
},
|
|
1875
|
+
}
|
|
1876
|
+
|
|
1877
|
+
|
|
1878
|
+
async def run_stdio_server(server: Web3SystemicMCPServer) -> None:
|
|
1879
|
+
"""Runs the MCP server over standard I/O (JSON-RPC 2.0)."""
|
|
1880
|
+
loop = asyncio.get_running_loop()
|
|
1881
|
+
while True:
|
|
1882
|
+
line = await loop.run_in_executor(None, sys.stdin.readline)
|
|
1883
|
+
if not line:
|
|
1884
|
+
break
|
|
1885
|
+
raw_text = line.strip()
|
|
1886
|
+
if not raw_text:
|
|
1887
|
+
continue
|
|
1888
|
+
try:
|
|
1889
|
+
req_data = json.loads(raw_text)
|
|
1890
|
+
except json.JSONDecodeError as exc:
|
|
1891
|
+
err_resp = {
|
|
1892
|
+
"jsonrpc": "2.0",
|
|
1893
|
+
"id": None,
|
|
1894
|
+
"error": {"code": -32700, "message": f"Parse error: {exc}"},
|
|
1895
|
+
}
|
|
1896
|
+
sys.stdout.write(json.dumps(err_resp) + "\n")
|
|
1897
|
+
sys.stdout.flush()
|
|
1898
|
+
continue
|
|
1899
|
+
|
|
1900
|
+
resp = await server.handle_jsonrpc(req_data)
|
|
1901
|
+
if resp is not None:
|
|
1902
|
+
sys.stdout.write(json.dumps(resp) + "\n")
|
|
1903
|
+
sys.stdout.flush()
|
|
1904
|
+
|
|
1905
|
+
|
|
1906
|
+
async def run_dry_run() -> int:
|
|
1907
|
+
"""Executes an offline self-test verifying all 6 MCP tools, resources, prompts, and protocol conformance."""
|
|
1908
|
+
print("=== Web3 Systemic Agent MCP Server Self-Test ===")
|
|
1909
|
+
server = Web3SystemicMCPServer(require_x402_for_deep_audit=True)
|
|
1910
|
+
manifest = server.get_tools_manifest()
|
|
1911
|
+
tool_names = [t["name"] for t in manifest]
|
|
1912
|
+
print(f"[1/9] Registered {len(manifest)} MCP tools: {', '.join(tool_names)}")
|
|
1913
|
+
assert len(manifest) == 6, f"Expected 6 tools, got {len(manifest)}"
|
|
1914
|
+
|
|
1915
|
+
# 1. scan_contract_selectors
|
|
1916
|
+
benign_bytecode = "0x608060405234801561001057600080fd5b508063a9059cbb14"
|
|
1917
|
+
r1 = await server.scan_contract_selectors(
|
|
1918
|
+
target_address="0x3333333333333333333333333333333333333333",
|
|
1919
|
+
bytecode_override=benign_bytecode,
|
|
1920
|
+
)
|
|
1921
|
+
print(
|
|
1922
|
+
f"[2/9] Tool 'scan_contract_selectors' OK: risk_level={r1['risk_level']}, "
|
|
1923
|
+
f"selectors={len(r1['selectors_found'])}, cost=${r1['cost_usd']:.2f}"
|
|
1924
|
+
)
|
|
1925
|
+
assert r1["is_contract"] is True
|
|
1926
|
+
assert r1["cost_usd"] == 0.0
|
|
1927
|
+
|
|
1928
|
+
# 2. check_token_honeypot
|
|
1929
|
+
honeypot_bytecode = "0x6080604052631e3dd19f14" # setTax(uint256)
|
|
1930
|
+
r2 = await server.check_token_honeypot(
|
|
1931
|
+
token_address="0x4444444444444444444444444444444444444444",
|
|
1932
|
+
bytecode_override=honeypot_bytecode,
|
|
1933
|
+
)
|
|
1934
|
+
print(
|
|
1935
|
+
f"[3/9] Tool 'check_token_honeypot' OK: is_honeypot={r2['is_honeypot_suspect']}, "
|
|
1936
|
+
f"score={r2['risk_score']}, cost=${r2['cost_usd']:.2f}"
|
|
1937
|
+
)
|
|
1938
|
+
assert r2["cost_usd"] == 0.0
|
|
1939
|
+
|
|
1940
|
+
# 3. scan_dao_proposals
|
|
1941
|
+
r3 = await server.scan_dao_proposals(use_curated_offline=True, limit=2)
|
|
1942
|
+
print(
|
|
1943
|
+
f"[4/9] Tool 'scan_dao_proposals' OK: count={r3['proposals_count']}, "
|
|
1944
|
+
f"cost=${r3['cost_usd']:.2f}"
|
|
1945
|
+
)
|
|
1946
|
+
assert r3["proposals_count"] >= 1
|
|
1947
|
+
assert r3["cost_usd"] == 0.0
|
|
1948
|
+
|
|
1949
|
+
# 4. preflight_tx_firewall (offline without eth_call)
|
|
1950
|
+
r4_pf = await server.preflight_tx_firewall(
|
|
1951
|
+
to_address="0x4200000000000000000000000000000000000006",
|
|
1952
|
+
calldata="0x095ea7b30000000000000000000000001111111111111111111111111111111111111111ffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffff",
|
|
1953
|
+
run_simulation=False,
|
|
1954
|
+
)
|
|
1955
|
+
print(
|
|
1956
|
+
f"[5/9] Tool 'preflight_tx_firewall' OK: verdict={r4_pf['verdict']}, "
|
|
1957
|
+
f"risk_score={r4_pf['risk_score']}, cost=${r4_pf['cost_usd']:.2f}"
|
|
1958
|
+
)
|
|
1959
|
+
assert r4_pf["verdict"] in ("BLOCK", "MANUAL_REVIEW")
|
|
1960
|
+
assert r4_pf["risk_score"] >= 7.0
|
|
1961
|
+
assert r4_pf["reasons"] == r4_pf["flagged_issues"]
|
|
1962
|
+
assert r4_pf["cost_usd"] == 0.0
|
|
1963
|
+
|
|
1964
|
+
# 5. inspect_proxy_and_source (offline_mode=True)
|
|
1965
|
+
r5_proxy = await server.inspect_proxy_and_source(
|
|
1966
|
+
target_address="0x4200000000000000000000000000000000000006",
|
|
1967
|
+
offline_mode=True,
|
|
1968
|
+
)
|
|
1969
|
+
print(
|
|
1970
|
+
f"[6/9] Tool 'inspect_proxy_and_source' OK: is_proxy={r5_proxy['is_proxy']}, "
|
|
1971
|
+
f"source_verified={r5_proxy['source_verified']}, cost=${r5_proxy['cost_usd']:.2f}"
|
|
1972
|
+
)
|
|
1973
|
+
assert r5_proxy["tool"] == "inspect_proxy_and_source"
|
|
1974
|
+
assert r5_proxy["is_proxy"] is False
|
|
1975
|
+
assert r5_proxy["source_verified"] is False
|
|
1976
|
+
assert r5_proxy["cost_usd"] == 0.0
|
|
1977
|
+
assert r5_proxy["llm_invoked"] is False
|
|
1978
|
+
|
|
1979
|
+
# 6. deep_semantic_audit (expecting 402 payment required)
|
|
1980
|
+
r6 = await server.deep_semantic_audit(
|
|
1981
|
+
target_address="0x4200000000000000000000000000000000000006",
|
|
1982
|
+
proposal_description="Test proposal",
|
|
1983
|
+
)
|
|
1984
|
+
print(
|
|
1985
|
+
f"[7/9] Tool 'deep_semantic_audit' OK: status={r6.get('status')}, "
|
|
1986
|
+
f"status_code={r6.get('status_code')}, price_usdc={r6.get('price_usdc')}"
|
|
1987
|
+
)
|
|
1988
|
+
assert r6.get("status") == "payment_required"
|
|
1989
|
+
assert r6.get("status_code") == 402
|
|
1990
|
+
|
|
1991
|
+
# 7. MCP resources/list & resources/read
|
|
1992
|
+
res_list = await server.handle_jsonrpc({"jsonrpc": "2.0", "id": "res-list", "method": "resources/list"})
|
|
1993
|
+
resources = res_list["result"]["resources"]
|
|
1994
|
+
assert len(resources) == 4, f"Expected 4 resources, got {len(resources)}"
|
|
1995
|
+
for res_item in resources:
|
|
1996
|
+
res_read = await server.handle_jsonrpc({
|
|
1997
|
+
"jsonrpc": "2.0",
|
|
1998
|
+
"id": f"read-{res_item['uri']}",
|
|
1999
|
+
"method": "resources/read",
|
|
2000
|
+
"params": {"uri": res_item["uri"]},
|
|
2001
|
+
})
|
|
2002
|
+
assert "result" in res_read and len(res_read["result"]["contents"]) == 1
|
|
2003
|
+
parsed = json.loads(res_read["result"]["contents"][0]["text"])
|
|
2004
|
+
assert isinstance(parsed, dict)
|
|
2005
|
+
print(f"[8/9] MCP resources/list & resources/read OK: {len(resources)} resources verified")
|
|
2006
|
+
|
|
2007
|
+
# 8. MCP prompts/list & prompts/get
|
|
2008
|
+
prm_list = await server.handle_jsonrpc({"jsonrpc": "2.0", "id": "prm-list", "method": "prompts/list"})
|
|
2009
|
+
prompts = prm_list["result"]["prompts"]
|
|
2010
|
+
assert len(prompts) == 3, f"Expected 3 prompts, got {len(prompts)}"
|
|
2011
|
+
sample_args = {
|
|
2012
|
+
"audit-token-before-swap": {"token_address": "0x4200000000000000000000000000000000000006"},
|
|
2013
|
+
"pre-sign-transaction-firewall": {"to_address": "0x4200000000000000000000000000000000000006", "calldata": "0x"},
|
|
2014
|
+
"audit-dao-governance-space": {"space_id": "arbitrumfoundation.eth"},
|
|
2015
|
+
}
|
|
2016
|
+
for prm_item in prompts:
|
|
2017
|
+
prm_get = await server.handle_jsonrpc({
|
|
2018
|
+
"jsonrpc": "2.0",
|
|
2019
|
+
"id": f"get-{prm_item['name']}",
|
|
2020
|
+
"method": "prompts/get",
|
|
2021
|
+
"params": {"name": prm_item["name"], "arguments": sample_args[prm_item["name"]]},
|
|
2022
|
+
})
|
|
2023
|
+
assert "result" in prm_get and len(prm_get["result"]["messages"]) >= 1
|
|
2024
|
+
print(f"[9/9] MCP prompts/list & prompts/get OK: {len(prompts)} prompts verified")
|
|
2025
|
+
|
|
2026
|
+
print("=== All MCP self-tests PASSED successfully ===")
|
|
2027
|
+
return 0
|
|
2028
|
+
|
|
2029
|
+
|
|
2030
|
+
def main() -> None:
|
|
2031
|
+
parser = argparse.ArgumentParser(description="Web3 Systemic Agent MCP Server")
|
|
2032
|
+
parser.add_argument(
|
|
2033
|
+
"--dry-run",
|
|
2034
|
+
action="store_true",
|
|
2035
|
+
help="Run offline self-test verification without starting stdio loop",
|
|
2036
|
+
)
|
|
2037
|
+
args = parser.parse_args()
|
|
2038
|
+
|
|
2039
|
+
if args.dry_run:
|
|
2040
|
+
exit_code = asyncio.run(run_dry_run())
|
|
2041
|
+
sys.exit(exit_code)
|
|
2042
|
+
else:
|
|
2043
|
+
server = Web3SystemicMCPServer()
|
|
2044
|
+
asyncio.run(run_stdio_server(server))
|
|
2045
|
+
|
|
2046
|
+
|
|
2047
|
+
if __name__ == "__main__":
|
|
2048
|
+
main()
|