Token Metrics

Token Metrics

Token Metrics is a cryptocurrency investment research firm that uses AI and Machine learning along with set of data scientists, quant traders, and crypto native research analysts to provide timely insights on more than 6,000 crypto and NFT projects.

Website


My Role:

Tech Lead.

Glimpse of my Contributions:


1. Token Metrics MCP Server — AI‑Native Crypto Analytics Gateway

Github Repo

  • Role: Tech Lead (built from scratch for Token Metrics)
  • Impact: Shipped a production‑grade MCP server that made our API plug‑and‑play for AI assistants; helped onboard new customers and drove adoption through hosted access and marketplace listings.

What this is

  • Purpose: A Model Context Protocol (MCP) server that exposes Token Metrics’ crypto data, analytics, and research as first‑class AI tools via function calling and streaming HTTP.
  • Who it’s for: AI apps, agents, and LLMs (Claude, Cursor, OpenAI MCP) needing real‑time market data, signals, and research without implementing dozens of bespoke endpoints.

Problems it solves

  • Unified AI interface: Consolidates 20+ analytics endpoints into typed tools that LLMs can discover and call.
  • Frictionless onboarding: Hosted HTTP transport with simple x-api-key removes local setup.
  • Agent‑friendly: Includes a query DSL tool so agents can select the right endpoint and parameters reliably.
  • Production‑ready surface: Sessionful streaming transport, CORS and DNS‑rebinding protections, TLS ingress, non‑root containers, and GitOps deployment.

Core features

  • Real‑time data & analytics
    • Prices, OHLCV (hourly/daily), sentiment, market metrics, scenario analysis, correlation
  • Signals & grading
    • AI trading signals (daily + hourly), TM Grade, Trader/Investor grades, Technology grade
  • Indices & research
    • Indices, performance and holdings; AI‑generated token reports; top tokens; investor data
  • Search DSL for LLMs
    • Natural, compact endpoint:<key> field:value ... syntax; parser turns it into API calls
  • Hosted + local
    • Hosted HTTP transport https://mcp.tokenmetrics.com and local npx CLI/stdio server

Architecture highlights

  • MCP servers
    • src/index.ts: stdio server for desktop LLM clients (Claude/Cursor)
    • src/http.ts: streamable HTTP JSON‑RPC transport with session management and SSE fallback
    • src/http-openai.ts: OpenAI‑focused transport exposing a curated tool subset
  • Tooling framework
    • BaseApiTool in src/tools/base-api-tool.ts:
      • Centralizes API key handling, axios requests, headers, timeouts, error normalization
      • Consistent ToolResponse formatting for LLM consumption
    • 20+ concrete tools in src/tools/* (price, ohlcv, signals, grades, indices, research, etc.)
  • LLM Search DSL
    • src/utils/search.ts + src/tools/search.ts: endpoint catalog, examples, and robust token parser
    • Guides agents to fetch token_id first, then compose precise follow‑up calls
  • Session & streaming
    • Session IDs via mcp-session-id with StreamableHTTPServerTransport, SSE pings, and message routing
  • Security
    • DNS‑rebinding checks (Host vs Origin), explicit CORS allowlist headers, XSS/XFO headers
    • API key required for tools/call, no sensitive logs, non‑root Docker user

Tool catalog (selected)

  • Token & pricing: get_tokens_data, get_tokens_price, get_tokens_hourly_ohlcv, get_tokens_daily_ohlcv
  • Signals & grades: get_tokens_trading_signal, get_tokens_hourly_trading_signals, get_token_tm_grade, get_tokens_investor_grade, get_token_technology_grade
  • Market intel: get_market_metrics, get_sentiment, get_tokens_quant_metrics, get_tokens_scenario_analysis, get_tokens_correlation
  • Research & indices: get_tokens_ai_report, get_crypto_investors, get_top_tokens_by_market_cap, get_indices, get_indices_performance, get_indices_holdings
  • Agent utilities: search (DSL) and fetch (raw endpoint accessor)

Why this is complex/interesting

  • Bridges two worlds: Converts REST crypto analytics into stateful, streamed JSON‑RPC for LLMs
  • Ergonomics for agents: Purpose‑built DSL and typed schemas minimize tool‑use failures
  • Multi‑transport: Stdio for desktop LLMs; streamable HTTP/SSE for web/backends; OpenAI‑compatible subset
  • Production hardening: Non‑root runtime, ingress TLS, DNS‑rebinding defenses, and GitOps flow

Tech stack

  • Runtime: Node.js 18, TypeScript
  • Protocols: MCP SDK (@modelcontextprotocol/sdk), JSON‑RPC, HTTP/SSE
  • Web: Express, CORS
  • HTTP client: Axios
  • Tooling: ESLint, Prettier, Nodemon, rimraf, ts-node, tsc
  • Infra: Docker, Kubernetes, NGINX Ingress, ArgoCD (GitOps), Azure Container Registry
  • Listings: Smithery, Glama, MCP.so, Awesome MCP Servers

Results & impact

  • Adoption: Enabled AI clients to integrate Token Metrics in minutes, not weeks
  • Growth: The hosted transport plus marketplace visibility brought new customers to our API
  • Leadership: Drove architecture, implementation, and production rollout as Tech Lead

How to use

  • Hosted (recommended):
    • Point MCP client to https://mcp.tokenmetrics.com with x-api-key: <your-key>
  • Local (stdio):
    • export TOKEN_METRICS_API_KEY=your_key && npx -y @token-metrics-ai/mcp@latest
  • Inspector:
    • npm run build && npx @modelcontextprotocol/inspector node build/src/cli.js

Notable files

  • src/http.ts: Streamable HTTP JSON‑RPC server, sessions, CORS, DNS‑rebinding checks
  • src/index.ts + src/cli.ts: Stdio server and CLI entrypoint
  • src/tools/base-api-tool.ts: Shared HTTP client, error handling, and response shaping
  • src/tools/*: Concrete tools for prices, signals, grades, indices, research
  • src/utils/search.ts: Endpoint catalog + examples for the LLM search DSL
  • k8s-manifests/*, argocd/argocd-application.yaml: Kubernetes/ArgoCD deployment

2. Multi‑Channel Crypto Alerts & Workflow Orchestrator

A production-grade Node.js/TypeScript service I built from scratch as the Tech Lead at Token Metrics. It orchestrates data-driven, multi-channel alerting and scheduled workflows that helped drive user growth and conversions through timely, accurate notifications.

What this solves

  • Real-time engagement: Delivers timely crypto alerts (token signals, grades, indices) across email, SMS, Telegram, Slack, and Discord.
  • Operational automation: Automates billing syncs, usage resets, data syncs, and system health checks to reduce manual effort and errors.
  • Reliability at scale: Built with retries and concurrency controls.

My role & impact

  • Tech Lead, greenfield owner: Designed and implemented the architecture, data integrations, orchestration, and deployment end-to-end.
  • Business impact: Helped bring many customers to our app thanks to timely alerts and multi-channel reach that increased engagement and conversions.

Tech stack

  • Languages/Runtime: Node.js, TypeScript
  • Orchestration: Trigger.dev v3 (tasks/schedules), long-running workers
  • Web/API: Express (API-key protected endpoints)
  • Data: PostgresQL, Prisma 6 (raw SQL + views), CSV tooling
  • Notifications/Comms: Knock, AWS SES/Azure SES, Resend, Azure Communication Services (SMS), Telegram (telegraf, node-telegram-bot-api), WebSockets
  • Storage/CDN: AWS S3, Cloudflare R2
  • Payments/Platform: Stripe, Supabase, Redis, Cloudflare
  • Rendering/Automation: EJS email templates, Puppeteer
  • Tooling/Quality: ESLint + Prettier + Husky, Nodemon, TSConfig

Architecture overview

  • Trigger.dev coordinates alert jobs, scheduled tasks, and long-running services (e.g., bots) with explicit concurrency/retry controls.
  • Express API exposes secure endpoints to trigger specific alert workflows on-demand.
  • Libraries in src/libs encapsulate integrations: Prisma, Knock, SES/Azure, Resend, SMS, Redis, Stripe, S3/R2, Supabase.
  • Templated emails with EJS provide branded, dynamic messages with conditional sections.

Core features

  • Token alerting: Price change, TM Trader/Investor grades, combined technical indicator signals.
  • Indices alerts: Trader and investor indices notifications with configurable frequency.
  • Market indicator alerts: Automated charting/screenshots (Puppeteer) and asset uploads to S3/R2.
  • Daily digests & moonshot: Curated content and signals delivered to users.
  • Multi-channel delivery: Knock fanout (email/SMS/Slack/Discord) plus native Telegram bot.
  • Operational automations: Stripe syncs and key checks, user plan syncs, usage resets, bounced/expiry email handling, WebSocket health checks, NFT/Stripe sync, alert-limit verification.

Notification pipeline highlights

  • Unified composition: Builds alert payloads, renders responsive EJS templates, and fans out via Knock channels (email/SMS/Slack/Discord) and Telegram.
  • Contextual content: Conditional sections display only relevant metrics (price, trader/investor grades, indicators).
  • Per-user routes: Injects Slack/Discord webhooks per user/partner to deliver to private channels when required.

Data & querying

  • Prisma 6 + raw SQL: Efficient reads from analytics/materialized views.
  • Extensive SQL views: Under prisma/views/** for analytics, token data, indices, hubs, etc.

Reliability & scale

  • Backoff & retries: Task-level retry policies for transient failures.
  • Concurrency control: Queue-level limits to protect downstream services.
  • Long-running services: Bots run persistently with clean lifecycle management.

Security & governance

  • API-key middleware: Protects manual-trigger endpoints.
  • Secrets management: Environment variables for DB, Knock, Stripe, AWS, Azure, etc.
  • Compliance: Email unsubscribe handling, alert-limit verification, and bounced email processing.

Deployment

  • Dockerized service.
  • Trigger.dev v3: Project configuration with Prisma and Puppeteer build extensions.

Developer experience

  • TypeScript-first with strict linting and formatting (ESLint + Prettier).
  • Husky hooks: Enforce tests/format/lint on commit.
  • Local dev: Nodemon and cross-platform scripts (run-script-os).
  • Config: Centralized src/config.ts drives env-based behavior.

Complexity highlights

  • Multi-channel orchestration with dynamic, channel-aware rendering and graceful fallbacks.
  • Real-time data fusion from Postgres with per-user delivery preferences and channel credentials.
  • Resilient long-running bot on Trigger.dev worker with controlled retries and logging.

Outcomes

  • Customer acquisition: Timely, high-signal alerts across preferred channels helped bring many customers to the app.
  • Engagement & retention: Unified analytics and notifications improved activation, DAU, and retention.
  • Operational efficiency: Automated workflows reduced manual toil and error rates.

3. Coinbase X402 Micropayments Integration for API

  • Built as Tech Lead at my current company to monetize premium API endpoints with frictionless crypto micropayments.
  • Result: Helped bring in many new customers; developers could instantly test paid endpoints for a very small fee and adopt true pay‑as‑you‑go with no long onboarding.

One‑liner

  • Purpose: Enable secure, low‑latency microtransactions (402 Payment Required) for API access using Coinbase X402, with dynamic per‑endpoint pricing and seamless developer UX.

Problems Solved

  • Monetization without friction: No lengthy trials, keys, or contracts; pay only for what you use.
  • Self‑serve evaluation: Developers can test paid endpoints instantly with tiny payments.
  • Granular pricing: Different endpoints priced appropriately; unknown endpoints safely default to highest tier.
  • Crypto‑native checkout: Supports USDC and discounted TMAI payments; testnet/mainnet toggles.
  • Operational clarity: Standardized 402 responses include an "accepts" payload so clients know how to pay.

My Role and Responsibilities

  • Lead and architect: Designed the payment flow, pricing model, and integration points across the API.
  • Implemented end‑to‑end: Payment header spec, validation, facilitator verification/settlement, price computation, response shaping, and request context wiring.
  • Productionized: Error handling, observability hooks, configuration, safe defaults, and compatibility with existing rate limiting.

Key Features

  • X402 middleware
    • Detects X402 requests via header.
    • Bypasses payment for free endpoints; otherwise enforces payment.
    • Builds resource‑specific payment requirements using an “exact” scheme.
    • Verifies payments with Coinbase facilitator; settles and returns X-PAYMENT-RESPONSE.
  • Robust payment decoding & validation
    • Base64 decode supporting Node and browser environments.
    • Strict schema validation using zod for authorization and signatures.
    • Supports standard ECDSA and 6492‑style signatures; strong EVM address/value validation.
    • Increased EVM atomic units limit to 21 to allow larger payments when needed.
  • Dynamic pricing
    • Tiered per‑endpoint pricing map with sensible defaults for unknown paths.
    • Free endpoints enumerated; premium endpoints tiered at $0.017 / $0.034 / $0.068.
  • Multi‑token support
    • USDC and TMAI allowed; discount for TMAI (e.g., 10% off).
    • Fetches live TMAI price to compute on‑chain atomic amounts precisely.
    • Selects token via header; defaults to USDC.
  • Network flexibility
    • Testnet/mainnet switch via USE_MAINNET; supports base and base‑sepolia.
    • Configurable facilitator URL and recipient address via env.
  • Developer experience
    • Clear 402 errors with accepts payload (JSON‑safe) describing how to pay.
    • Consistent response headers (X-PAYMENT-RESPONSE) after settlement for client bookkeeping.
    • Minimal integration burden: send X-PAYMENT per request—no complex sessioning required.

Architecture Overview

  • Middleware first: All X402 logic isolated in separate file for drop‑in use across routes.
  • Schema‑driven validation: zod schemas enforce payload correctness before verification.
  • Facilitator‑mediated: Uses Coinbase facilitator for payment verification and settlement, then returns a standardized header via settle response utilities.
  • Pricing & assets: Translates USD prices to on‑chain atomic amounts via helpers, with EIP‑712 metadata for assets.

Security & Reliability Considerations

  • Strict input validation: EVM address/hex patterns, integer checks, signature format validation (ECDSA and 6492).
  • Network‑scoped amounts: USD→atomic conversions bound to the active network to prevent mismatches.
  • Defensive defaults: Unknown endpoints priced at highest tier; missing facilitator yields a safe 500 error.
  • Short timeouts: Exact payments configured with max timeout to limit replay windows.

Tech Stack

  • Runtime: Node.js (Express middleware pattern).
  • Payments: Coinbase X402 facilitator (verify/settle), exact payment scheme.
  • Validation: zod for schema enforcement.
  • DB/ORM: Postgres to read live TMAI pricing (internal table).
  • Utilities: X402 shared helpers for USD→atomic conversions and JSON‑safe serialization.

Business Impact

  • Customer growth: Lowered evaluation friction; many customers onboarded by paying cents to test.
  • Usage‑based revenue: True pay‑as‑you‑go matches developer expectations and modern pricing models.
  • Better conversion: Instant access to paid features increased trial‑to‑paid conversion without sales intervention.

Results and Learnings

  • Reliable micro‑checkout with minimal client changes.
  • Predictable pricing via central map, safe defaults, and token‑aware conversions.
  • DX wins: Standardized 402 with accepts data made client implementations straightforward.