Introducing Agentic DeFi with DeFiPy v2
Ian Moore, PhD6 min read·Just now--
- DeFiPy v2 enables proactive reasoning via its State Twin interface serving as the mathematical cortex of the AI
- Introduces 21 new agentic primitives built on top of v1
- Includes MCP integration serving as the bridge to agentic systems
From a desktop tool to industrial infrastructure
DeFiPy v1 was built for the human research analyst, a Python library you imported into a notebook to answer questions about DeFi. This was built to ask questions like: Why is this LP position losing money? What’s the impermanent loss at 30% drawdown? How does this V3 fee tier compare to V2 for the same capital? One would typically open Jupyter, import defipy, apply core primitives on various scenarios, read the result, apply it to your analysis, and write your report.
However, DeFiPy v2 is built for the agentic era. The same hand-derived AMM math now ships as MCP tools, which is callable by autonomous systems at production scale, utilizing an additional 21 new agentic primitives built on top. The State Twin abstraction lets the same primitive call run against a synthetic recipe, live mainnet state, or a historical block; one shape in and one shape out, just like how an analyst would reason about something for proactive reasoning. An LLM agent can discover the tool schemas, pick a primitive, run it against a twin built from real chain state, and synthesize a proactively reasoned response grounded in the math.
The math underneath is the same, however, now the surface around it is different. What v2 ships is the surface that an agentic system can build on.
DeFiPy v1 first went out in 2024, and today in 2026, v2 has just been released on PyPI. This article introduces the three pieces that make v2 a substrate for agentic DeFi: (1) Agentic Primitives, (2) State Twins, and (3) MCP integration. Each one is its own deeper article in the series ahead; this is the high-level map.
Three pieces
1. Agentic primitives — the math layer
DeFiPy ships 21 stateless, typed primitives across seven categories — position analysis, pool health, risk, execution, optimization, comparison, and portfolio aggregation. Each one answers a specific LP question with exact math derived from the protocol’s invariant; xy = k for V2, concentrated-tick math for V3, weighted geometric mean for Balancer, the ε ↔ δ amplification relation for Stableswap. The same call shape works across all four AMM families.
Most DeFi tools wrap APIs, however DeFiPy ships the math. When something like a notebook, a backtest, an LLM agent — asks “is this pool healthy?” the answer comes from hand-derived invariants applied to typed pool state, not from a probabilistic interpretation of cached chain data. Every primitive returns a structured dataclass with named fields, ready to feed into whatever consumes it next.
from defipy import CheckPoolHealth
health = CheckPoolHealth().apply(lp)
print(f"TVL (token0): {health.tvl_in_token0:,.2f}")
print(f"Fee tier: {health.fee_pips} pips")
print(f"Current tick: {health.tick_current}")That same lp argument can come from a synthetic recipe, a live chain read, or a custom data source — the primitive doesn’t know or care. Which brings us to the second piece.
A later article in this series goes deeper into the primitive catalog and how each category maps to the LP questions it answers.
2. State Twin — the substrate layer
A State Twin is a mathematically exact off-chain replica of an AMM pool’s state, built from a typed snapshot. The architecture has three parts:
- Provider — knows about sources.
MockProviderproduces synthetic recipes;LiveProviderpulls live chain state; a custom provider could read from a CSV or a database. - Snapshot — a typed dataclass (
V2PoolSnapshot,V3PoolSnapshot, etc.) emitted by the provider. Decimal-adjusted reserves, block context, the full pool state in normalized form. - Builder —
StateTwinBuilder().build(snapshot)dispatches on snapshot type and returns the protocol’s exchange object — thelpthat every primitive consumes.
The point is the symmetry. Two lines change between synthetic and live; the third — the primitive call — is identical:
# Synthetic recipe - for tests, notebooks, CI
provider = MockProvider()
lp = StateTwinBuilder().build(provider.snapshot("eth_dai_v2"))
# Live mainnet state - for analytics on real pools
provider = LiveProvider("https://eth-mainnet.g.alchemy.com/v2/<key>")
lp = StateTwinBuilder().build(
provider.snapshot("uniswap_v2:0xB4e16d0168e52d35CaCD2c6185b44281Ec28C9Dc")
)
# Same primitive call against either lp
health = CheckPoolHealth().apply(lp)This is the layer most agentic-DeFi systems are missing. Without it, every reasoning step is bound to chain time — every “what if?” requires an RPC roundtrip. With it, state lives in memory, off-chain, replayable. The agent can fork a twin a hundred ways under price scenarios and run the math against each fork before committing to anything.
LiveProvider shipped for Uniswap V2 and V3 in v2.1; Balancer and Stableswap LiveProvider follow in v2.2. Block pinning is automatic, Multicall3 batches V3 reads into one RPC roundtrip, and provider.get_w3() is the read-only escape hatch for callers who want to wire their own signing infrastructure on top.
Next week’s article goes deep on the State Twin, what it is, why it’s the load-bearing abstraction, and what it makes possible that wasn’t possible before.
3. MCP integration — the bridge to agentic systems
The third piece is the bridge from substrate to LLM. defipy.tools emits Model Context Protocol (MCP) schemas for 10 curated leaf primitives, and a reference MCP server at python/mcp/defipy_mcp_server.py closes the end-to-end loop.
What that means in practice: ask Claude ”is the eth_dai_v2 pool healthy? any rug signals?” The MCP server dispatches CheckPoolHealth and DetectRugSignals against a twin, the primitives return typed dataclass results, and Claude synthesizes a response that’s correct because the primitives encoded the domain — not because the LLM hallucinated DeFi math well. The LLM doesn’t need to know how to compute impermanent loss from sqrt-price ratios. It needs to know that AnalyzePosition exists, what its inputs are, and what its result fields mean. The schema does the rest.
pip install 'defipy[agentic]' # composes [chain] + [mcp]That’s the install for the full stack — LiveProvider for chain reads, plus the MCP server SDK for serving primitives as tools to Claude Desktop, Claude Code, or any MCP-compatible client. Equivalent to pip install ‘defipy[chain,mcp]’ but spelled with intent.
DeFiPy itself stays LLM-free. The math layer has zero LLM dependencies and zero network calls at core. MCP is the integration surface — it wires the substrate up to consumers that are LLMs, without contaminating the substrate with their concerns.
A later article in this series develops the trust-layer thesis — why deterministic primitives at the LLM boundary matter, and what’s still missing.
The architectural shape
Three layers, each with zero dependencies on the layer above. Agentic primitives are the math layer which is pure analytics, importable in any Python environment. The State Twin is the substrate layer which are typed snapshots and exchange objects, optional chain reads behind the [chain] install. Finally, MCP integration is the agentic integration layer which are schemas and a stdio-transport server, behind the [mcp] install.
A notebook user installs defipy and gets the math. An analytics consumer adds [chain] and gets live state. An agent runtime adds [mcp] (or [agentic] for the full stack) and gets the substrate exposed as tools. Each consumer gets exactly the surface they need; nothing is imposed.
That’s what makes it a substrate. The library has no opinions about who’s consuming it, what they’re consuming it for, or how the result gets used downstream. This is composition by design.
What’s preserved
DeFiPy v1 isn’t deprecated; the 21 primitives all existed in v1.2.0, what v2 added is the surface around them. The legacy monolithic event-driven agents in python/prod/agents/ are preserved as chapter 9 reference material from Hands-On AMMs with Python. v1 readers and textbook users don’t lose anything — v2 is a different architectural pattern for a different consumer, its an extension of v1’s correctness for AI utility.
Where to start
pip install 'defipy[agentic]'> Note for zsh users (default on macOS): wrap the install spec in single quotes so zsh doesn’t try to glob the brackets. Bash users can use either form.
- Documentation: defipy.org
- State Twin concept: defipy.org/twin-concept/
- LiveProvider docs: defipy.org/live-provider/
- Fork-and-evaluate worked example: defipy.org/fork-evaluate/
- GitHub: github.com/defipy-devs/defipy
- Textbook (v1 reference): DeFiPy: Python SDK for On-Chain Analytics
If the architectural argument resonates — or if you’ve been hitting the chain-reality ceiling without a name for it — the docs are the next click.
🔗 SPDX-Anchor: anchorregistry.ai/AR-2026-YdPXB5g
DeFiPy is built and maintained by Ian Moore. Apache 2.0 licensed. The full v2.1.0 release notes are on GitHub. For consulting inquiries on integrating DeFiPy into agent runtimes, fund analytics pipelines, or protocol monitoring infrastructure, please reach out via defimind.ai.