2026-12-06 ~7 min read Node 20 · MCP · x402 · Solana RSS

Shipping Zero-Infra-Cost Agentic Tools: An 80/20 Hybrid LLM CostGuard MCP Server and a Static Solana Forensics Observatory

Architectural teardown of two zero-dependency Node 20 systems: a self-hosted 80/20 LLM CostGuard MCP + x402 container and a static CoinGecko + Solana RPC forensics observatory.

Most side-project developer tools do not die from lack of users; they die from infrastructure fatigue. You wire up a $20/month managed database, a Redis queue, a frontend bundler, and 800 transitive npm packages for a weekend idea — and three months later you spend your Saturday fixing npm audit alerts and paying cloud bills for an idle staging box.

A personal conviction I keep coming back to while tinkering with AI workflows and open-source tools is simple: technical barriers are lower than ever right now — public specs, APIs, and runtimes are sitting right in front of us, which makes it much easier to build the right small tool at the right moment without overcomplicating it.

Over the past week, alongside cutting xgbtxy/ap v2.99.0 (our zero-dependency pure-Rust coding-agent toolkit, now past 733 GitHub release binary downloads) and landing our 92nd+ upstream open-source PR in gimli-rs/object#1039, I shipped two standalone Node 20+ systems designed around a strict $0 recurring infrastructure budget and 0 runtime npm dependencies:

  1. xgbtxy/pi-solohost-costguard (live static preview, container ghcr.io/xgbtxy/pi-solohost-costguard:1.0.0) — a self-hosted 12-model LLM API cost comparator, deterministic 80/20 hybrid compute router, local monthly spend redline guard, Streamable HTTP MCP server (POST /mcp), and x402 v2 HTTP 402 compute-metering sandbox packaged for loopback execution (127.0.0.1:18080) on Pi Desktop SoloHost or any local Docker/Node host.
  2. xgbtxy/solana-longtail-observatory (live terminal, snapshot.json, daily-story.md) — a static onchain market forensics observatory combining CoinGecko API + GeckoTerminal v2 pool cohorts with batched Solana Mainnet JSON-RPC (getMultipleAccounts jsonParsed) authority audits, refreshed every 6 hours via GitHub Actions onto GitHub Pages.

Below is a practical teardown of how both systems are put together, the exact routing and forensic math inside them, and the real tradeoffs of refusing external dependencies and always-on cloud backends.

1. Two Different Domains, Same Zero-Dependency Constraints

At first glance, local LLM budget routing and Solana DEX pool forensics have nothing in common. Architecturally, though, both follow the exact same set of constraints:

Dimension xgbtxy/pi-solohost-costguard xgbtxy/solana-longtail-observatory
Runtime Node >=20.0.0 ESM (0 npm deps) Node >=20.0.0 ESM (0 npm deps)
Deployment node:20-alpine on 127.0.0.1:18080 + Pages preview Static docs/ on GitHub Pages + 6h Actions cron (17 */6 * * *)
Persistence Named volume /data/state.json (in-memory fallback) Git-versioned snapshot.json + daily-story.md
Interfaces POST /mcp (3 tools) + x402 v2 POST /api/x402/route-audit Frameless ?embed= cards, SVG/2x PNG exports & daily briefs
Secrets Zero signing keys; optional PI_API_KEY stays server-side Zero wallet keys; CoinGecko API + public Solana Mainnet RPC
Tests 20 node:test checks + live SoloHost validator (ok: true) 18 node:test checks (math, schema, secrets, SVG geometry)

Targeting Node 20+ (and Node 22 in CI) eliminates most excuses for pulling in dozens of day-one packages: native fetch + AbortController covers HTTP and JSON-RPC retries; node --test + node:assert/strict spins up ephemeral loopback servers on port 0 in milliseconds; and plain ES modules let docs/lib/analytics.mjs run identically across the Node collector (scripts/collect.mjs), test suite (tests/observatory.test.mjs), and browser UI (docs/app.js) with zero bundler.

Working on low-level Rust repositories reinforces that habit. In gimli-rs/object#1039, fixing a subtle PE import-table bug came down to checking thunk.raw() == 0 instead of thunk.address() == 0 in ImportThunkList::next so high flag bits with a zeroed low address are not misread as a null terminator. Keeping codebases small and dependency-free keeps invariants just as legible.

2. Inside pi-solohost-costguard: 80/20 Hybrid Routing, Spend Redlines, and Loopback MCP

Why LLM bills actually spike

When multi-agent loops burn through an API budget, the culprit is rarely the 15 minutes of hard architectural synthesis where you genuinely needed a flagship model. The culprit is sending thousands of routine classification, summarization, JSON-extraction, drafting, and log-triage calls to that same $3/$15 or $15/$75 per-million-token endpoint out of habit.

In src/catalog.mjs, pi-solohost-costguard encodes 12 official public API models across five providers (Mistral, OpenAI, Google, DeepSeek, Anthropic), split into three explicit tiers with uncached input, prompt-cached input (cachedInputPer1M), and output rates per 1,000,000 tokens:

  • Economy (5 models): mistral/mistral-small-3 ($0.10 / $0.30), openai/gpt-4o-mini ($0.15 / $0.60), google/gemini-2.5-flash ($0.15 / $0.60, $0.0375 cached), deepseek/deepseek-chat ($0.27 / $1.10), and openai/gpt-4.1-mini ($0.40 / $1.60).
  • Balanced (3 models): deepseek/deepseek-reasoner ($0.55 / $2.19), anthropic/claude-3-5-haiku ($0.80 / $4.00), and openai/o3-mini ($1.10 / $4.40).
  • Frontier (4 models): google/gemini-2.5-pro ($1.25 / $10.00), openai/gpt-4.1 ($2.00 / $8.00), anthropic/claude-sonnet-4 ($3.00 / $15.00, $0.30 cached), and anthropic/claude-opus-4 ($15.00 / $75.00).

Why an 80/20 split still needs a local budget redline state machine

Running optimizeHybridRoute on a realistic solo-builder agent workload — 10,000 requests/month averaging 2,500 input tokens, 900 output tokens, and a 25% prompt-cache hit rate — changes the bill significantly:

  • 100% anthropic/claude-sonnet-4 baseline: $193.13/month ($2,317.56/year).
  • hybrid_80_20 split (80% google/gemini-2.5-flash at $6.76/month + 20% anthropic/claude-sonnet-4 at $38.63/month): $45.39/month ($544.63/year) — cutting 76.5% ($147.74/month or $1,772.93/year) while keeping complex debugging, architecture, and security review on the frontier tier.

Notice what happens next, though, if the operator configured a hard $25/month spend ceiling (MONTHLY_BUDGET_USD=25): even $45.39/month is still 181.54% of budget! A static percentage split alone cannot guarantee a dollar cap when request volume spikes.

That is why checkBudgetRedline pairs hybrid routing with an explicit three-state guardrail (OK, WARNING, BREACH):

let status = "OK";
let action = "ALLOW";
if (projectedMonthlyUsd > monthlyBudgetUsd) {
  status = "BREACH";
  action = "DOWNSHIFT_TO_HYBRID";
} else if (utilizationPct >= 80) {
  status = "WARNING";
  action = "ENABLE_CACHE_AND_WATCH";
}

const fallbackPlan = optimizeHybridRoute({
  profile: status === "BREACH" ? "ultra_frugal" : defaults.routingProfile || "hybrid_80_20",
  frontierModelId:
    input.currentModelId && getModelById(input.currentModelId)
      ? input.currentModelId
      : "anthropic/claude-sonnet-4",
  economyModelId: status === "BREACH" ? "mistral/mistral-small-3" : "google/gemini-2.5-flash",
  requestsPerMonth: input.requestsPerMonth || 5000,
  avgInputTokens: input.avgInputTokens || 2500,
  avgOutputTokens: input.avgOutputTokens || 900,
});

When projected burn crosses 80% of the monthly ceiling, agents get a WARNING (ENABLE_CACHE_AND_WATCH). When it crosses 100%, BREACH computes an ultra_frugal fallback (90% mistral/mistral-small-3 + 10% frontier) and explicitly returns fitsWithinBudget (true or false) — so if even a 90/10 downshift still exceeds a tight $25 ceiling at 10,000 requests/month, the caller sees fitsWithinBudget: false instead of assuming the downshift solved the overrun.

Exposing CostGuard over Streamable HTTP MCP and x402 v2

Rather than trapping that math inside a browser calculator, src/mcp.mjs serves JSON-RPC 2.0 Streamable HTTP MCP at POST /mcp (protocolVersion: "2025-03-26"), exposing estimate_llm_cost, optimize_hybrid_route, and check_budget_redline with typed structuredContent bound to /data/state.json. Alongside /mcp, src/x402.mjs meters POST /api/x402/route-audit: unpaid calls receive HTTP 402 Payment Required with a Base64 PAYMENT-REQUIRED header (x402Version: 2, CAIP-2 eip155:84532 or eip155:8453, atomic USDC units, and CORS Access-Control-Expose-Headers), while ?sample=true returns an instant $0 HTTP 200 12-model audit preview (X-X402-Mode: free-sample).

Loopback-first container hardening for Pi SoloHost

Packaging for self-hosted desktop node operators enforces strict container hygiene checked against Pi's SoloHost staging validator (npm run validate:solohost -> ok: true). solohost/docker-compose.yml runs node:20-alpine as non-root USER node, binds strictly to loopback (127.0.0.1:${PORT:-18080}:8080), uses a named volume (costguard_data:/data) with zero privileged: or host bind mounts, and keeps optional PI_API_KEY (preserve_if_blank: true) strictly server-side — verified never to appear in /health, /api/config, or HTML by sentinel tests in tests/costguard.test.mjs.

3. Inside solana-longtail-observatory: Static Git-Backed Onchain Forensics

Why headline 24h DEX volume misleads

On long-tail Solana markets, flat token leaderboards rank pools by 24-hour USD volume. That single number routinely mixes together three completely different phenomena:

  1. Genuine two-sided liquidity with revoked token authorities.
  2. Tight wash-trading or sybil loops recycling $800K+ of volume over $1.5K of pool reserve.
  3. Post-pump LP drains where a pool racked up $25M+ in 24-hour volume before liquidity was pulled below $500, leaving stale volume sitting near the top of 24-hour charts.

Building a custom indexer with Postgres and paid WebSocket streams just to separate those cohorts would violate the $0 maintenance goal. Instead, solana-longtail-observatory turns GitHub Actions + GitHub Pages into a deterministic 6-hour forensic pipeline (.github/workflows/refresh-data.yml, cron: '17 */6 * * *').

Multi-venue cohort sampling + batched Solana Mainnet RPC

Every collection run (node scripts/collect.mjs) executes three stages without external libraries:

  1. Multi-venue pool discovery (CoinGecko API / GeckoTerminal v2): Samples trending_pools, new_pools, and six venue cohorts (pumpswap, pump-fun, raydium, raydium-clmm, meteora, orca) with 2,300ms request pacing and exponential backoff (Retry-After aware) to stay comfortably inside the 30 req/min public allowance — while automatically upgrading to CoinGecko's /onchain/networks/solana/pools/megafilter if COINGECKO_PRO_API_KEY or COINGECKO_DEMO_API_KEY is present.
  2. Batched Solana Mainnet JSON-RPC authority audits (auditMintsOnSolanaRpc): Firing 150 separate getAccountInfo calls against public https://api.mainnet-beta.solana.com asks to get rate-limited. Instead, collect.mjs filters out canonical wrapped/custodial majors (SOL, USDC, USDT, mSOL, JitoSOL, cbBTC, WETH, JLP), deduplicates the subject long-tail mints, and queries getMultipleAccounts (encoding: "jsonParsed", commitment: "confirmed") in batches of 90 pubkeys per RPC call — auditing all 111 deduplicated long-tail mints in two HTTP round-trips (up to 180 mints per pair of batches).
  3. SPL Token & Token-2022 extension parsing (parseMintAccount): Checks account ownership across both classic SPL Token (TokenkegQfeZyiNwAJbNbGKPFXCWuBvf9Ss623VQ5DA) and Token-2022 (TokenzQdBNbLqP5VEhdkAS6EPFLC1PHnBqCXEpPxuEb), verifying mintAuthority === null, freezeAuthority === null, and scanning info.extensions for active permanentDelegate, transferHook, defaultAccountState === "frozen", or non-zero transferFeeConfig basis points.

The deterministic 0–100 forensic scorer

In docs/lib/analytics.mjs, computePoolMetrics combines reserve depth (0–35 pts), onchain authority hygiene (0–30 pts, -6 if risky Token-2022 hooks/delegates are active), organic turnover sanity (0–20 pts), and FDV / Reserve backing (0–15 pts) alongside explicit anomaly flags:

const rawWashRatio = reserveUsd > 0 ? volume24hUsd / reserveUsd : 0;
const liquidityDrained = volume24hUsd >= 10_000 && reserveUsd < 500;
const washRatio = Math.min(rawWashRatio, 9999.99);
const washAnomaly = reserveUsd > 0 && rawWashRatio > THRESHOLDS.WASH_VOLUME_RATIO; // > 15x
const fdvLiquidityRatio =
  reserveUsd >= 100 && fdvUsd > 0 ? Math.min(fdvUsd / reserveUsd, 99999.99) : null;
const fragileFdv =
  fdvLiquidityRatio !== null && fdvLiquidityRatio > THRESHOLDS.FRAGILE_FDV_LIQ_RATIO; // > 50x
const txnsPerTrader = uniqueTraders24h > 0 ? txns24h / uniqueTraders24h : null;
const sybilLoopSuspect =
  washAnomaly && txnsPerTrader !== null && txnsPerTrader > THRESHOLDS.SYBIL_TXNS_PER_TRADER; // > 25

Ordering the verdict ladder so LIQUIDITY_DRAINED (reserveUsd < $500 after >=$10K 24h volume) is evaluated before generic turnover ratios prevents drained rugs from masquerading as "high-velocity breakout pools."

What the live Solana snapshot surfaced

Looking at the live 2026-12-06 snapshot committed in docs/data/daily-story.md (153 live Solana pools holding $116.93M in reserves across $567.69M in 24h volume, plus 111 RPC-audited long-tail mints and 10 CoinGecko narrative categories):

  • Exit liquidity is much thinner than volume suggests: Only 49.7% of sampled active pools held >$50K in real reserve depth (median $46.8K). Raydium AMM (86.4% >$50K) and Orca Whirlpool (85.0% >$50K) held the deepest liquidity, whereas PumpSwap sat at 37.5% >$50K ($31.9K median) and pre-graduation Pump.fun bonding-curve pools averaged $1.4K median reserve (0.0% >$10K).
  • One-third of active pools tripped the >15x wash-turnover threshold (33.3%): Meteora DLMM (59.1%) and PumpSwap (56.3%) showed the highest high-turnover concentrations — including extreme outliers above 460x Vol/Reserve and two post-volume LP drains ($34.52M and $26.03M 24h volume with $0 and $5.51 remaining reserve).
  • Token-2022 dominates new launches, while authority risk hides in larger pools: 65.8% of audited long-tail mints used Token-2022 and 87.4% (97 of 111) had revoked both mint and freeze authorities — yet 14 active pools still carried live mintAuthority or freezeAuthority on multi-million-dollar 24h volume pairs.

Because researchers and newsletter writers rarely want to screenshot a busy dashboard, the static frontend (docs/app.js) also renders frameless ?embed=survival, ?embed=narratives, and ?embed=pool&addr=<pool> cards plus pure-SVG downloads — backed by a bounding-box collision test in tests/observatory.test.mjs (test #18) that mathematically asserts zero overlapping text labels on the narrative scatter plot before any snapshot commit can push.

4. Tradeoffs: Where Zero-Infra Designs Hit Their Ceiling

Shipping with zero npm dependencies and zero recurring cloud bills keeps maintenance near zero, though it comes with deliberate boundaries worth stating plainly:

  1. CostGuard is a deterministic policy advisor and sandbox, not an inline API proxy. pi-solohost-costguard computes 12-model routing splits, enforces /data/state.json budget redlines over MCP, and demonstrates x402 v2 header negotiation (local-sandbox-receipt-check), rather than holding upstream OpenAI/Anthropic keys or settling mainnet USDC via a remote facilitator (unlike cf-x402-mcp). Keeping LLM and wallet keys out of the container limits credential exposure on home nodes, while requiring the calling agent to honor check_budget_redline's returned tier.
  2. 6-hour Git snapshots optimize for cohort forensics, not sub-second execution. solana-longtail-observatory samples page-1 venue cohorts (~153 pools/run) on a 6-hour schedule (plus an optional live browser refresh). It fits structural venue forensics and data journalism, not mempool-speed execution.
  3. Turnover heuristics differ between passive AMMs and concentrated liquidity. Concentrated-liquidity bins (Raydium CLMM, Meteora DLMM, Orca Whirlpool) naturally turn over active-tick capital faster than x*y=k pools. Separating major_pair benchmarks (SOL/USDC) from longtail tokens and pairing washRatio > 15x with txnsPerTrader > 25 and FDV / Reserve > 50x cuts false positives, though tight LP rebalancing can still look noisy without tick-level history.

The main lesson from building both back-to-back is how far standard platform primitives (node:http, node:test, fetch, getMultipleAccounts, GitHub Actions cron, and GitHub Pages) carry you before you ever need a framework or a monthly server bill. When running an experiment costs $0 to keep online next year, you get to try ten more ideas without worrying which old side project is quietly charging your card, hhh.

If you are running hybrid economy/frontier routing in your own local MCP setup — or building lightweight onchain analytics without a dedicated indexer — how are you drawing the line between staying dependency-free and reaching for heavier infrastructure?

Links

我觉得技术没有壁垒,在合适的时间做合适的事情就好,hhh