# How to integrate Twelve data MCP with Pydantic AI

```json
{
  "title": "How to integrate Twelve data MCP with Pydantic AI",
  "toolkit": "Twelve data",
  "toolkit_slug": "twelve_data",
  "framework": "Pydantic AI",
  "framework_slug": "pydantic-ai",
  "url": "https://composio.dev/toolkits/twelve_data/framework/pydantic-ai",
  "markdown_url": "https://composio.dev/toolkits/twelve_data/framework/pydantic-ai.md",
  "updated_at": "2026-10-12T13:47:44.394Z"
}
```

## Introduction

This guide walks you through connecting Twelve data to Pydantic AI using the Composio tool router. By the end, you'll have a working Twelve data agent that can list all supported cryptocurrencies today, convert 100 usd to eur right now, show recent dividend payouts for aapl through natural language commands.
This guide will help you understand how to give your Pydantic AI agent real control over a Twelve data account through Composio's Twelve data MCP server.
Before we dive in, let's take a quick look at the key ideas and tools involved.

## Also integrate Twelve data with

- [Claude Code](https://composio.dev/toolkits/twelve_data/framework/claude-code)
- [Claude Cowork](https://composio.dev/toolkits/twelve_data/framework/claude-cowork)
- [OpenAI Agents SDK](https://composio.dev/toolkits/twelve_data/framework/open-ai-agents-sdk)
- [Claude Agent SDK](https://composio.dev/toolkits/twelve_data/framework/claude-agents-sdk)
- [Codex](https://composio.dev/toolkits/twelve_data/framework/codex)
- [OpenClaw](https://composio.dev/toolkits/twelve_data/framework/openclaw)
- [Hermes](https://composio.dev/toolkits/twelve_data/framework/hermes-agent)
- [Atomic Agent](https://composio.dev/toolkits/twelve_data/framework/atomic-agent)
- [Google ADK](https://composio.dev/toolkits/twelve_data/framework/google-adk)
- [LangChain](https://composio.dev/toolkits/twelve_data/framework/langchain)
- [Vercel AI SDK](https://composio.dev/toolkits/twelve_data/framework/ai-sdk)
- [Mastra AI](https://composio.dev/toolkits/twelve_data/framework/mastra-ai)
- [LlamaIndex](https://composio.dev/toolkits/twelve_data/framework/llama-index)
- [CrewAI](https://composio.dev/toolkits/twelve_data/framework/crew-ai)
- [AutoGen](https://composio.dev/toolkits/twelve_data/framework/autogen)

## TL;DR

Here's what you'll learn:
- How to set up your Composio API key and User ID
- How to create a Composio Tool Router session for Twelve data
- How to attach an MCP Server to a Pydantic AI agent
- How to stream responses and maintain chat history
- How to build a simple REPL-style chat interface to test your Twelve data workflows

## What is Pydantic AI?

Pydantic AI is a Python framework for building AI agents with strong typing and validation. It leverages Pydantic's data validation capabilities to create robust, type-safe AI applications.
Key features include:
- Type Safety: Built on Pydantic for automatic data validation
- MCP Support: Native support for Model Context Protocol servers
- Streaming: Built-in support for streaming responses
- Async First: Designed for async/await patterns

## What is the Twelve data MCP server, and what's possible with it?

The Twelve data MCP server is an implementation of the Model Context Protocol that connects your AI agent and assistants like Claude, Cursor, etc directly to your Twelve Data account. It provides structured and secure access to real-time and historical financial market data, so your agent can retrieve stock prices, analyze dividend and earnings history, explore ETFs, and perform currency conversions on your behalf.
- Comprehensive market data access: Instantly pull up-to-date information on stocks, forex, cryptocurrencies, commodities, and indices to support analysis or decision-making.
- Dividend and earnings insights: Retrieve detailed dividend payout history and earnings reports, including EPS estimates, actuals, and trend analysis for specific companies.
- ETF exploration and categorization: Ask your agent to fetch directories of ETFs, sort by assets, family, or market, and explore various ETF types for in-depth portfolio research.
- Real-time currency conversion: Effortlessly convert amounts between currencies using live exchange rates for accurate financial planning and reporting.
- Cryptocurrency and commodity discovery: List all supported cryptocurrencies and commodities, helping you quickly identify available assets for further analysis or trading strategies.

## Supported Tools

| Tool slug | Name | Description |
|---|---|---|
| `TWELVE_DATA_BATCH_GET_QUOTES` | Batch Get Quotes | Fetch quotes for 1-8 symbols in one batch, returning success or error for every symbol; partial child failures do not fail successful quotes. Each symbol consumes one API credit. |
| `TWELVE_DATA_CASH_FLOW` | Cash Flow | Tool to get company cash flow statement. Use when you need operating, investing, and financing cash flow details after selecting a company. |
| `TWELVE_DATA_CASH_FLOW_CONSOLIDATED` | Consolidated Cash Flow | Tool to get raw consolidated cash flow statements. Use when you need detailed cash flow data for a company. |
| `TWELVE_DATA_COMMODITIES_LIST` | List Commodities | Retrieve the complete list of supported commodities. |
| `TWELVE_DATA_CONVERT_CURRENCY` | Convert Currency | Convert an amount from the base to the quote currency using a current or historical forex or cryptocurrency rate. Costs one API credit. |
| `TWELVE_DATA_CORREL` | Correlation Coefficient | Tool to fetch Pearson correlation coefficient between two series over a period. Use after selecting identifiers and interval. |
| `TWELVE_DATA_COUNTRIES_LIST` | List Countries | Retrieve country metadata including ISO codes, names, capitals, and currencies. |
| `TWELVE_DATA_CROSS_LISTINGS` | Cross Listings | Tool to retrieve cross-listed symbols for a security across multiple exchanges. Use when you need to list all market listings of a given instrument. |
| `TWELVE_DATA_CRYPTOCURRENCIES` | List Cryptocurrencies | Tool to list all supported cryptocurrencies. Use when you need the complete set of crypto symbols. |
| `TWELVE_DATA_CRYPTOCURRENCY_EXCHANGES_LIST_GET` | List Cryptocurrency Exchanges | Tool to list supported cryptocurrency exchanges. Use when you need a list of available crypto trading platforms. |
| `TWELVE_DATA_DIVIDENDS` | Dividends | Tool to retrieve dividend payout history for a specified symbol. Use when you need historical dividends over multiple years. |
| `TWELVE_DATA_EARNINGS` | Earnings | Tool to retrieve earnings data including EPS estimates and actuals. Use when you need detailed earnings history for a selected stock symbol. |
| `TWELVE_DATA_EPS_REVISIONS` | EPS Revisions | Tool to provide analysts’ revisions of a company’s future EPS over the last week and month. Use after confirming the stock symbol. |
| `TWELVE_DATA_EPS_TREND_ACTION` | EPS Trend | Tool to retrieve EPS trend estimates for a specified company. Use after selecting a stock symbol to view how EPS estimates have changed over time. Returns EPS estimates for next quarter, current year, and next year, showing how estimates have evolved from 7, 30, 60, and 90 days ago. |
| `TWELVE_DATA_ETFS_DIRECTORY` | ETFS Directory | Tool to fetch a daily updated list of exchange-traded funds sorted by total assets. Use when you need a directory of ETFs by exchange or country. |
| `TWELVE_DATA_ETFS_FAMILY` | ETFS Family | Tool to fetch a comprehensive list of ETFs by family. Use when you need to list ETFs managed by a specific investment company. |
| `TWELVE_DATA_ETFS_TYPE` | Get ETF Types | Tool to retrieve ETF categories by market, including types like 'Equity Precious Metals'. No parameters are needed. Returns a dictionary mapping country names to lists of ETF types available in that country. |
| `TWELVE_DATA_ETFS_WORLD` | ETF World | Tool to fetch comprehensive ETF analytics (summary, performance, risk, composition). Use when you need a detailed overview of an ETF's metrics and holdings. |
| `TWELVE_DATA_ETFS_WORLD_COMPOSITION` | ETF World Composition | Tool to fetch global ETF composition details including sector, country, asset allocations, top holdings, and bond metrics. Use after selecting an ETF to analyze its composition. |
| `TWELVE_DATA_ETFS_WORLD_RISK` | ETF World Risk | Tool to get global ETF risk metrics. Use when you need to analyze volatility and valuation ratios for an ETF. |
| `TWELVE_DATA_EXCHANGES` | List supported exchanges | Tool to retrieve a list of supported exchanges. Use when you need all available stock and forex exchanges. |
| `TWELVE_DATA_FOREX_PAIRS` | List supported forex pairs | Tool to retrieve a list of all supported forex currency pairs. Use when exploring available forex pairs before making other forex data requests. |
| `TWELVE_DATA_GET_AD` | Get AD Indicator | Tool to retrieve Accumulation/Distribution (AD) indicator data for a financial instrument. The AD line uses closing price, price range, and trading volume to identify buying or selling pressure and assess price movement strength. |
| `TWELVE_DATA_GET_APO` | Get APO (Absolute Price Oscillator) | Tool to calculate the Absolute Price Oscillator (APO) for a financial instrument. The APO measures the difference between two moving averages to identify price trends and momentum changes. Use when you need to analyze momentum and potential price reversals. |
| `TWELVE_DATA_GET_AROON` | Get Aroon Indicator | Tool to retrieve Aroon Indicator data for identifying market trends. Returns Aroon Up and Aroon Down values showing time elapsed since highest high and lowest low. Use when analyzing trend direction and momentum for a specific symbol. |
| `TWELVE_DATA_GET_BALANCE_SHEET` | Balance Sheet | Tool to retrieve a company's balance sheet (assets, liabilities, equity). Use when you need annual or quarterly financial position data for a given symbol or identifier. |
| `TWELVE_DATA_GET_BALANCE_SHEET_CONSOLIDATED` | Balance Sheet Consolidated | Tool to get raw consolidated balance sheet data (assets, liabilities, equity) for a company. Use when you need detailed historical balance sheet by period. |
| `TWELVE_DATA_GET_BBANDS` | Get Bollinger Bands | Tool to calculate Bollinger Bands (BBANDS) for a financial instrument. Returns upper band, lower band, and simple moving average (SMA) to assess market volatility and identify potential price reversals. |
| `TWELVE_DATA_GET_BONDS` | Get Bonds | Tool to retrieve a daily updated list of available bonds (fixed income securities). Use when you need to fetch bonds with optional filtering by symbol, exchange, or country. |
| `TWELVE_DATA_GET_CCI` | Get CCI | Tool to retrieve Commodity Channel Index (CCI) values for a specified security. Use when you need to detect potential price reversals by identifying overbought or oversold conditions through momentum analysis. |
| `TWELVE_DATA_GET_CEIL` | Get Ceiling (CEIL) | Tool to retrieve the Ceiling (CEIL) transformation for a time series. Rounds each value in the input data series up to the nearest whole number. Use when you need ceiling-adjusted price data for a symbol. |
| `TWELVE_DATA_GET_CMO` | Get Chande Momentum Oscillator | Tool to retrieve Chande Momentum Oscillator (CMO) data for a security. Use when you need to analyze momentum and identify overbought or oversold conditions. Requires at least one instrument identifier (symbol, isin, figi, or cusip) and an interval. |
| `TWELVE_DATA_GET_DPO` | Get Detrended Price Oscillator | Tool to calculate the Detrended Price Oscillator (DPO) for a specified financial instrument. Use when you need to identify short-term price cycles and potential overbought or oversold conditions without long-term trend influence. |
| `TWELVE_DATA_GET_EARLIEST_TIMESTAMP` | Get Earliest Timestamp | Tool to return the first available timestamp for a symbol and interval. Use after selecting instrument identifiers and interval to discover the earliest data point. |
| `TWELVE_DATA_GET_EOD` | Get End of Day Price | Tool to retrieve end of day (EOD) closing price and metadata for a financial instrument. Use when you need daily historical data for stocks, ETFs, or other securities to track performance over time. |
| `TWELVE_DATA_GET_ETFS_WORLD_PERFORMANCE` | Global ETF Performance | Tool to get global ETF performance metrics (trailing and annual returns). Use when you need detailed performance analytics for an ETF. |
| `TWELVE_DATA_GET_EXCHANGE_RATE` | Get Exchange Rate | Return the current or historical exchange rate for one forex or cryptocurrency pair. Costs one API credit. |
| `TWELVE_DATA_GET_EXCHANGE_SCHEDULE` | Get exchange schedule | Tool to get trading sessions and hours for exchanges. Use when you need pre-market, main, and post-market hours for a given exchange and date. |
| `TWELVE_DATA_GET_FUND_HOLDERS` | Get Fund Holders | Tool to retrieve mutual fund holders for a company. Use when you need details about mutual fund ownership including shares held and percentage of outstanding shares. |
| `TWELVE_DATA_GET_FUNDS` | Get Funds | Tool to fetch a daily updated list of available investment funds. Use when you need a directory of funds with optional filtering by symbol, country, exchange, or other identifiers. |
| `TWELVE_DATA_GET_HEIKINASHI_CANDLES` | Get Heikin Ashi Candles | Tool to retrieve Heikin Ashi candlestick data that smooths price action by averaging values. Use when you need to identify trends with reduced market noise for technical analysis. |
| `TWELVE_DATA_GET_HLC3` | Get HLC3 Average | Tool to calculate the High, Low, Close Average (HLC3) for a security over a specified period. Use when you need to assess average price trends quickly. |
| `TWELVE_DATA_GET_HT_SINE` | Get Hilbert Transform Sine Wave | Tool to fetch Hilbert Transform Sine Wave (HT_SINE) data for an instrument. The HT_SINE provides sine and cosine wave components derived from the dominant market cycle, helping traders pinpoint potential market turning points and assess trend directions by analyzing cyclical patterns. Use when analyzing market cycles for a specific symbol and interval. |
| `TWELVE_DATA_GET_ICHIMOKU` | Get Ichimoku Cloud Indicator | Tool to retrieve Ichimoku Kinko Hyo indicator data for analyzing trend direction, support/resistance levels, and trading opportunities. Use when you need to evaluate market trends and identify strategic entry/exit points. |
| `TWELVE_DATA_GET_INCOME_STATEMENT` | Income Statement | Tool to retrieve a company's income statement data (annual or quarterly). Use when you need detailed income metrics for a given symbol or identifier. |
| `TWELVE_DATA_GET_INSIDER_TRANSACTIONS` | Insider Transactions | REQUIRES PRO, ULTRA, OR ENTERPRISE PLAN. Retrieve insider trading transactions for a company including officer/trader names, transaction types (Buy/Sell), dates, share counts, and amounts. Use when you need detailed insider trading activity data. This endpoint is only available to Pro/Ultra/Enterprise subscribers - requests with lower-tier API keys will fail with a 403 error. |
| `TWELVE_DATA_GET_INTERVALS` | Get Available Intervals | Tool to retrieve a list of available time intervals supported by the API. Use when you need to know which interval values are valid for time series queries. |
| `TWELVE_DATA_GET_KELTNER` | Get Keltner Channel | Tool to retrieve Keltner Channel indicator data for volatility-based technical analysis. Use when you need to identify potential overbought/oversold conditions, assess trend direction, or analyze price volatility using the combination of Exponential Moving Average (EMA) and Average True Range (ATR). |
| `TWELVE_DATA_GET_KEY_EXECUTIVES` | Key Executives | REQUIRES ULTRA OR ENTERPRISE PLAN. Retrieve company leadership data including executive names, titles, ages, and compensation. Use when you need detailed management info by symbol or other identifier. This endpoint costs 1000 credits per request and is only available to Ultra/Enterprise subscribers - requests with lower-tier API keys will fail. |
| `TWELVE_DATA_GET_LAST_CHANGE` | Get Last Change | Tool to retrieve the latest update timestamps for a fundamentals dataset. Use when checking recent changes (e.g., dividends, splits). |
| `TWELVE_DATA_GET_LATEST_PRICE` | Get Latest Price | Return only the latest available price for one market symbol; use Get Quote when OHLC, volume, change, or market status is needed. Costs one API credit. |
| `TWELVE_DATA_GET_LINEARREGANGLE` | Get Linear Regression Angle | Tool to calculate the linear regression angle for a given time series of stock prices. Returns the slope of the trend line expressed in degrees, which helps identify the direction and steepness of a trend over a specified period. Use when you need to detect upward or downward trends in asset prices. |
| `TWELVE_DATA_GET_LINEAR_REG_INTERCEPT` | Get Linear Regression Intercept | Tool to calculate the y-intercept of a linear regression line for a given dataset. Returns the value where the regression line crosses the y-axis over a specified period. |
| `TWELVE_DATA_GET_LINEAR_REGSLOPE` | Get Linear Regression Slope | Tool to calculate the linear regression slope for a given dataset over a specified period. Returns the slope of a linear regression line, reflecting the rate of change in the data trend. Use when you need to assess the direction and strength of a trend in financial time series data. |
| `TWELVE_DATA_GET_LOG10` | Get Base-10 Logarithm (LOG10) | Tool to compute the base-10 logarithm (LOG10) of a specified input value. Returns the power to which 10 must be raised to obtain the input value. Use when you need to transform data into a logarithmic scale for analyzing exponential growth patterns or compressing large ranges of financial data. |
| `TWELVE_DATA_GET_LOGO` | Get Logo | Tool to retrieve official logo URLs for a symbol. Use when displaying company, crypto, or forex pair logos in UIs. |
| `TWELVE_DATA_GET_MACD` | Get MACD | Tool to calculate the Moving Average Convergence Divergence (MACD) for a specified financial instrument. Returns the MACD line, signal line, and histogram values to identify potential trend reversals and trading opportunities. |
| `TWELVE_DATA_GET_MAMA` | Get MAMA | Tool to fetch MESA Adaptive Moving Average (MAMA) indicator data. Use when you need to calculate an adaptive moving average that adjusts to market cycles for trend identification and reversal analysis. |
| `TWELVE_DATA_GET_MARKET_MOVERS` | Market Movers | Tool to retrieve a snapshot of top gainers or losers for a specified market. Use when you need to quickly see market movers after choosing a market type. |
| `TWELVE_DATA_GET_MARKET_STATE` | Get Market State | Tool to report current open/closed status for exchanges. Use when you need real-time market status updates after selecting exchanges. |
| `TWELVE_DATA_GET_MAX` | Get Maximum Value | Tool to calculate and return the highest value within a specified data series over a given period. Use when identifying potential resistance levels or detecting extreme price movements in financial data. |
| `TWELVE_DATA_GET_MC_GINLEY_DYNAMIC` | Get McGinley Dynamic Indicator | Tool to calculate the McGinley Dynamic indicator, which provides a refined moving average that adapts to market volatility. Use when tracking price movements with reduced lag and identifying support or resistance levels. |
| `TWELVE_DATA_GET_MEDPRICE` | Get Median Price | Tool to calculate and retrieve the Median Price (MEDPRICE) technical indicator for a security. MEDPRICE represents the average of high and low prices over a specified period, providing a simplified view of price trends. Use when you need to assess price movements by focusing on the midpoint of price action. |
| `TWELVE_DATA_GET_MINUS_DI` | Get Minus Directional Indicator | Tool to calculate and return the Minus Directional Indicator (MINUS_DI) for a security. Use when analyzing bearish trends and assessing downward price movement strength. |
| `TWELVE_DATA_GET_MUTUAL_FUNDS_WORLD_PERFORMANCE` | Global Mutual Fund Performance | Tool to get global mutual fund performance metrics (trailing, annual, quarterly, load-adjusted returns). Use when you need detailed performance analytics for a mutual fund. |
| `TWELVE_DATA_GET_MUTUAL_FUNDS_WORLD_RISK` | Mutual Funds World Risk | Tool to fetch global mutual fund risk metrics. Use when you need detailed risk analytics (standard deviation, beta, Sharpe ratio) for a specific mutual fund identifier. |
| `TWELVE_DATA_GET_MUTUAL_FUNDS_WORLD_SUMMARY` | Global Mutual Fund Summary | Tool to retrieve a global mutual fund summary snapshot. Use when you need a high-level overview of a fund’s key identifiers and attributes. |
| `TWELVE_DATA_GET_MUTUAL_FUNDS_WORLD_SUSTAINABILITY` | Global Mutual Fund Sustainability | Tool to get global mutual fund sustainability and ESG metrics. Use when you need fund ESG scores and pillar breakdowns. |
| `TWELVE_DATA_GET_PLUS_DI` | Get Plus Directional Indicator | Tool to fetch the Plus Directional Indicator (PLUS_DI) time series data for a security. Use when you need to assess the strength and intensity of upward price movements over a specified period. |
| `TWELVE_DATA_GET_PRICE_TARGET` | Price Target | Tool to fetch analysts' price target dataset for equities. Use when you need the latest and historical price forecasts for a symbol. |
| `TWELVE_DATA_GET_PROFILE` | Get Profile | Tool to retrieve company profile. Use when you need company details like industry, sector, and identifiers after selecting a symbol. |
| `TWELVE_DATA_GET_QUOTE` | Get Quote | Return the latest quote for one symbol, including OHLC, volume when available, change, market-open status, and 52-week range. Costs one API credit. |
| `TWELVE_DATA_GET_RECOMMENDATIONS` | Recommendations | Retrieve aggregated analyst recommendations for a stock. Returns buy/sell/hold consensus ratings across multiple time periods (current month, previous month, 2 and 3 months ago). Use this to understand Wall Street sentiment and analyst opinions about a company. |
| `TWELVE_DATA_GET_ROC` | Get Rate of Change (ROC) | Tool to retrieve Rate of Change (ROC) indicator data for a security. ROC calculates the percentage change in price over a defined period, returning a time series of values that help track momentum. Use after selecting a symbol and interval to identify potential price movements. |
| `TWELVE_DATA_GET_ROCP` | Get ROCP (Rate of Change Percentage) | Tool to calculate and return the Rate of Change Percentage (ROCP) for a financial security. Use when you need to identify shifts in price momentum and potential trend reversals. |
| `TWELVE_DATA_GET_ROCR100` | Get ROCR100 | Tool to calculate the Rate of Change Ratio 100 (ROCR100) for a security. The ROCR100 calculates the percentage change in a security's price over a specified period, expressed as a ratio to 100. Use when you need to assess the momentum and direction of a security's price trend over time. |
| `TWELVE_DATA_GET_RVOL` | Get Relative Volume | Tool to fetch relative volume (RVOL) data for a security. RVOL provides a ratio comparing a security's current trading volume to its average volume over a specified period, helping detect unusual trading activity and assess the strength of price movements. |
| `TWELVE_DATA_GET_SIMPLE_MOVING_AVERAGE` | Get Simple Moving Average | Return a bounded simple moving average series for one symbol, interval, price field, and averaging period. Costs one API credit. |
| `TWELVE_DATA_GET_SPLITS` | Stock Splits | Tool to retrieve historical stock split events. Use when you need to fetch split history for a particular instrument. |
| `TWELVE_DATA_GET_SPLITS_CALENDAR` | Splits Calendar | Tool to retrieve a calendar of stock split events. Use when you need to fetch split events for instruments over a date range. |
| `TWELVE_DATA_GET_STATISTICS` | Get Statistics | Tool to retrieve key company statistics including valuation and financial overview. Use when you need a company financial snapshot after selecting an instrument. |
| `TWELVE_DATA_GET_STOCHRSI` | Get Stochastic RSI | Tool to calculate the Stochastic Relative Strength Index (Stochastic RSI) for a specified financial instrument. Returns %K and %D line values to identify overbought or oversold conditions and potential price reversals. Use when you need to refine entry and exit points by analyzing momentum indicators. |
| `TWELVE_DATA_GET_SUM` | Get Summation (SUM) | Tool to calculate the cumulative total (Summation) of a specified data series over a defined time period. Returns numerical values representing the sum of financial data such as stock prices or trading volumes. Use when you need to track the aggregate value of a dataset for further analysis. |
| `TWELVE_DATA_GET_TECHNICAL_INDICATORS_LIST` | Get Technical Indicators List | Tool to retrieve a comprehensive list of available technical indicators. Use when you need to discover which technical analysis tools are available. |
| `TWELVE_DATA_GET_TEMA` | Get TEMA (Triple Exponential Moving Average) | Tool to calculate the Triple Exponential Moving Average (TEMA) for a financial instrument. TEMA applies three layers of exponential smoothing to price data, providing a smoother trend line with reduced lag compared to simple moving averages. Use when you need to identify trends with minimal delay for trading signals. |
| `TWELVE_DATA_GET_TIME_SERIES` | Get Time Series | Return a bounded OHLCV history window for one symbol and interval; this does not paginate or fetch an unbounded history. Costs one API credit. |
| `TWELVE_DATA_GET_USAGE_LIMITS` | Get Usage Limits | Return the connected key's current minute and daily usage, limits, plan category, and timestamp. The check itself consumes one API credit. |
| `TWELVE_DATA_GET_VAR` | Get Variance (VAR) | Tool to calculate the statistical variance of a financial data series. Use when you need to measure the volatility or dispersion of security prices over a specified period to assess risk. |
| `TWELVE_DATA_GET_WCLPRICE` | Get Weighted Close Price | Tool to calculate and retrieve the Weighted Close Price (WCLPRICE) for a security. WCLPRICE gives additional weight to the closing price using the formula (High + Low + Close * 2) / 4. Use when you need to analyze price trends with emphasis on closing values. |
| `TWELVE_DATA_GET_WMA` | Get Weighted Moving Average (WMA) | Tool to calculate and retrieve the Weighted Moving Average (WMA) for a security over a specified period. Use when you need to analyze short-term price trends with recent prices having higher influence. |
| `TWELVE_DATA_INDICES` | List market indices | Tool to retrieve a list of market indices. Use when you need to fetch available indices filtered by country. |
| `TWELVE_DATA_INSTITUTIONAL_HOLDERS` | Institutional Holders | Tool to retrieve institutional holders positions for a company. Use when you need summary ownership metrics and top institutions. |
| `TWELVE_DATA_LIST_STOCKS` | List Stocks | List and filter stocks in Twelve Data's reference directory, one explicit page at a time. Increment page while has_more is true. Each page costs one API credit; this tool never fetches additional pages automatically. |
| `TWELVE_DATA_MUTUAL_FUNDS_FAMILY` | Mutual Funds Family | List the mutual fund families available from investment companies. |
| `TWELVE_DATA_MUTUAL_FUNDS_LIST` | Mutual Funds List | Tool to retrieve a daily updated list of mutual funds sorted by total assets. Use when you need to enumerate available mutual funds for analysis. |
| `TWELVE_DATA_MUTUAL_FUNDS_WORLD_COMPOSITION` | Mutual Funds World Composition | Tool to fetch global mutual fund portfolio composition including sectors, asset allocation, top holdings, and bond metrics. Use after selecting a mutual fund to analyze its composition. |
| `TWELVE_DATA_OPTIONS_CHAIN_ACTION` | Options Chain | Tool to retrieve the options chain for a given symbol and optional expiration date. Use when you need detailed option contract data and Greeks. Omitting date returns all expirations. |
| `TWELVE_DATA_OPTIONS_EXPIRATION` | Options Expiration | Tool to retrieve available option expiration dates. Use when exploring available expiration dates for a given options symbol. |
| `TWELVE_DATA_SEARCH_SYMBOLS` | Search Symbols | Find tradable instrument symbols and exchange identifiers by ticker or name; returns a bounded match list with no pagination. |
| `TWELVE_DATA_TECHNICAL_INDICATORS` | Technical Indicators | Tool to fetch time-series data for a specific technical indicator. Use when you have a symbol, interval, and indicator name. |

## Supported Triggers

None listed.

## Creating MCP Server - Stand-alone vs Composio SDK

The Twelve data MCP server is an implementation of the Model Context Protocol that connects your AI agent to Twelve data. It provides structured and secure access so your agent can perform Twelve data operations on your behalf through a secure, permission-based interface.
With Composio's managed implementation, you don't have to create your own developer app. For production, if you're building an end product, we recommend using your own credentials. The managed server helps you prototype fast and go from 0-1 faster.

## Step-by-step Guide

### 1. Prerequisites

Before starting, make sure you have:
- Python 3.9 or higher
- A Composio account with an active API key
- Basic familiarity with Python and async programming

### 1. Getting API Keys for OpenAI and Composio

OpenAI API Key
- Go to the [OpenAI dashboard](https://platform.openai.com/settings/organization/api-keys) and create an API key. You'll need credits to use the models, or you can connect to another model provider.
- Keep the API key safe.
Composio API Key
- Log in to the [Composio dashboard](https://dashboard.composio.dev?utm_source=toolkits&utm_medium=framework_docs).
- Navigate to your API settings and generate a new API key.
- Store this key securely as you'll need it for authentication.

### 2. Install dependencies

Install the required libraries.
What's happening:
- composio connects your agent to external SaaS tools like Twelve data
- pydantic-ai lets you create structured AI agents with tool support
- python-dotenv loads your environment variables securely from a .env file
```bash
pip install composio pydantic-ai python-dotenv
```

### 3. Set up environment variables

Create a .env file in your project root.
What's happening:
- COMPOSIO_API_KEY authenticates your agent to Composio's API
- USER_ID associates your session with your account for secure tool access
- OPENAI_API_KEY to access OpenAI LLMs
```bash
COMPOSIO_API_KEY=your_composio_api_key_here
USER_ID=your_user_id_here
OPENAI_API_KEY=your_openai_api_key
```

### 4. Import dependencies

What's happening:
- We load environment variables and import required modules
- Composio manages connections to Twelve data
- MCPServerStreamableHTTP connects to the Twelve data MCP server endpoint
- Agent from Pydantic AI lets you define and run the AI assistant
```python
import asyncio
import os
from dotenv import load_dotenv
from composio import Composio
from pydantic_ai import Agent
from pydantic_ai.mcp import MCPServerStreamableHTTP

load_dotenv()
```

### 5. Create a Tool Router Session

What's happening:
- We're creating a Tool Router session that gives your agent access to Twelve data tools
- The create method takes the user ID and specifies which toolkits should be available
- The returned session.mcp.url is the MCP server URL that your agent will use
```python
async def main():
    api_key = os.getenv("COMPOSIO_API_KEY")
    user_id = os.getenv("USER_ID")
    if not api_key or not user_id:
        raise RuntimeError("Set COMPOSIO_API_KEY and USER_ID in your environment")

    # Create a Composio Tool Router session for Twelve data
    composio = Composio(api_key=api_key)
    session = composio.create(
        user_id=user_id,
        toolkits=["twelve_data"],
    )
    url = session.mcp.url
    if not url:
        raise ValueError("Composio session did not return an MCP URL")
```

### 6. Initialize the Pydantic AI Agent

What's happening:
- The MCP client connects to the Twelve data endpoint
- The agent uses GPT-5 to interpret user commands and perform Twelve data operations
- The instructions field defines the agent's role and behavior
```python
# Attach the MCP server to a Pydantic AI Agent
twelve_data_mcp = MCPServerStreamableHTTP(url, headers={"x-api-key": COMPOSIO_API_KEY})
agent = Agent(
    "openai:gpt-5",
    toolsets=[twelve_data_mcp],
    instructions=(
        "You are a Twelve data assistant. Use Twelve data tools to help users "
        "with their requests. Ask clarifying questions when needed."
    ),
)
```

### 7. Build the chat interface

What's happening:
- The agent reads input from the terminal and streams its response
- Twelve data API calls happen automatically under the hood
- The model keeps conversation history to maintain context across turns
```python
# Simple REPL with message history
history = []
print("Chat started! Type 'exit' or 'quit' to end.\n")
print("Try asking the agent to help you with Twelve data.\n")

while True:
    user_input = input("You: ").strip()
    if user_input.lower() in {"exit", "quit", "bye"}:
        print("\nGoodbye!")
        break
    if not user_input:
        continue

    print("\nAgent is thinking...\n", flush=True)

    async with agent.run_stream(user_input, message_history=history) as stream_result:
        collected_text = ""
        async for chunk in stream_result.stream_output():
            text_piece = None
            if isinstance(chunk, str):
                text_piece = chunk
            elif hasattr(chunk, "delta") and isinstance(chunk.delta, str):
                text_piece = chunk.delta
            elif hasattr(chunk, "text"):
                text_piece = chunk.text
            if text_piece:
                collected_text += text_piece
        result = stream_result

    print(f"Agent: {collected_text}\n")
    history = result.all_messages()
```

### 8. Run the application

What's happening:
- The asyncio loop launches the agent and keeps it running until you exit
```python
if __name__ == "__main__":
    asyncio.run(main())
```

## Complete Code

```python
import asyncio
import os
from dotenv import load_dotenv
from composio import Composio
from pydantic_ai import Agent
from pydantic_ai.mcp import MCPServerStreamableHTTP

load_dotenv()

async def main():
    api_key = os.getenv("COMPOSIO_API_KEY")
    user_id = os.getenv("USER_ID")
    if not api_key or not user_id:
        raise RuntimeError("Set COMPOSIO_API_KEY and USER_ID in your environment")

    # Create a Composio Tool Router session for Twelve data
    composio = Composio(api_key=api_key)
    session = composio.create(
        user_id=user_id,
        toolkits=["twelve_data"],
    )
    url = session.mcp.url
    if not url:
        raise ValueError("Composio session did not return an MCP URL")

    # Attach the MCP server to a Pydantic AI Agent
    twelve_data_mcp = MCPServerStreamableHTTP(url, headers={"x-api-key": COMPOSIO_API_KEY})
    agent = Agent(
        "openai:gpt-5",
        toolsets=[twelve_data_mcp],
        instructions=(
            "You are a Twelve data assistant. Use Twelve data tools to help users "
            "with their requests. Ask clarifying questions when needed."
        ),
    )

    # Simple REPL with message history
    history = []
    print("Chat started! Type 'exit' or 'quit' to end.\n")
    print("Try asking the agent to help you with Twelve data.\n")

    while True:
        user_input = input("You: ").strip()
        if user_input.lower() in {"exit", "quit", "bye"}:
            print("\nGoodbye!")
            break
        if not user_input:
            continue

        print("\nAgent is thinking...\n", flush=True)

        async with agent.run_stream(user_input, message_history=history) as stream_result:
            collected_text = ""
            async for chunk in stream_result.stream_output():
                text_piece = None
                if isinstance(chunk, str):
                    text_piece = chunk
                elif hasattr(chunk, "delta") and isinstance(chunk.delta, str):
                    text_piece = chunk.delta
                elif hasattr(chunk, "text"):
                    text_piece = chunk.text
                if text_piece:
                    collected_text += text_piece
            result = stream_result

        print(f"Agent: {collected_text}\n")
        history = result.all_messages()

if __name__ == "__main__":
    asyncio.run(main())
```

## Conclusion

You've built a Pydantic AI agent that can interact with Twelve data through Composio's Tool Router. With this setup, your agent can perform real Twelve data actions through natural language.
You can extend this further by:
- Adding other toolkits like Gmail, HubSpot, or Salesforce
- Building a web-based chat interface around this agent
- Using multiple MCP endpoints to enable cross-app workflows (for example, Gmail + Twelve data for workflow automation)
This architecture makes your AI agent "agent-native", able to securely use APIs in a unified, composable way without custom integrations.

## How to build Twelve data MCP Agent with another framework

- [Claude Code](https://composio.dev/toolkits/twelve_data/framework/claude-code)
- [Claude Cowork](https://composio.dev/toolkits/twelve_data/framework/claude-cowork)
- [OpenAI Agents SDK](https://composio.dev/toolkits/twelve_data/framework/open-ai-agents-sdk)
- [Claude Agent SDK](https://composio.dev/toolkits/twelve_data/framework/claude-agents-sdk)
- [Codex](https://composio.dev/toolkits/twelve_data/framework/codex)
- [OpenClaw](https://composio.dev/toolkits/twelve_data/framework/openclaw)
- [Hermes](https://composio.dev/toolkits/twelve_data/framework/hermes-agent)
- [Atomic Agent](https://composio.dev/toolkits/twelve_data/framework/atomic-agent)
- [Google ADK](https://composio.dev/toolkits/twelve_data/framework/google-adk)
- [LangChain](https://composio.dev/toolkits/twelve_data/framework/langchain)
- [Vercel AI SDK](https://composio.dev/toolkits/twelve_data/framework/ai-sdk)
- [Mastra AI](https://composio.dev/toolkits/twelve_data/framework/mastra-ai)
- [LlamaIndex](https://composio.dev/toolkits/twelve_data/framework/llama-index)
- [CrewAI](https://composio.dev/toolkits/twelve_data/framework/crew-ai)
- [AutoGen](https://composio.dev/toolkits/twelve_data/framework/autogen)

## Related Toolkits

- [Stripe](https://composio.dev/toolkits/stripe) - Stripe is a global online payments platform offering APIs for managing payments, customers, and subscriptions. Trusted by businesses for secure, efficient, and scalable payment processing worldwide.
- [44API](https://composio.dev/toolkits/44api) - 44API is an API service for validating VAT and tax identifiers and returning company details. Use it to verify business tax data and manage account IP whitelists quickly.
- [Airwallex](https://composio.dev/toolkits/airwallex) - Airwallex is a global financial platform providing business accounts, payments, payouts, FX, and cards. Built to simplify cross-border payments and streamline financial operations for businesses.
- [Aiwyn Tax MCP](https://composio.dev/toolkits/aiwyn_tax_mcp) - Aiwyn Tax MCP is a tax estimation service powered by Aiwyn's federal and state tax engine. It helps teams estimate tax outcomes without building tax calculation logic from scratch.
- [Alpaca](https://composio.dev/toolkits/alpaca) - Alpaca is a stock and crypto trading platform for commission-free trading, real-time market data, and algorithmic strategies. Use it to build brokerage apps, trading bots, and portfolio workflows with market connectivity.
- [Alpha vantage](https://composio.dev/toolkits/alpha_vantage) - Alpha Vantage is a financial data platform offering real-time and historical stock market APIs. Get instant, reliable access to equities, forex, and technical analysis data for smarter trading decisions.
- [Altoviz](https://composio.dev/toolkits/altoviz) - Altoviz is a cloud-based billing and invoicing platform for businesses. It streamlines online payments, expense tracking, and customizable invoice management.
- [Benzinga](https://composio.dev/toolkits/benzinga) - Benzinga provides real-time financial news and data APIs for market coverage. It helps you track breaking news and actionable market insights instantly.
- [Bigdata.com MCP](https://composio.dev/toolkits/bigdata_com_mcp) - Bigdata.com MCP provides grounded access to financial news, transcripts, filings, and entity intelligence. Ideal for building research workflows and generating timely market insights.
- [Billsby](https://composio.dev/toolkits/billsby) - Billsby is a subscription billing platform for managing customers, subscriptions, invoices, products, plans, usage counters, add-ons, and allowances. It helps SaaS and subscription teams automate billing operations without building complex billing logic from scratch.
- [Brex](https://composio.dev/toolkits/brex) - Brex provides corporate credit cards and spend management tailored for startups and tech businesses. It helps optimize company cash flow, streamline accounting, and accelerate business growth.
- [Cashfree Payments MCP](https://composio.dev/toolkits/cashfree_payments_mcp) - Cashfree Payments MCP is a merchant payments platform that handles collection, payouts, subscriptions, settlements, refunds, and identity verification. Simplifies merchant money lifecycle management with unified, API-driven workflows.
- [Chaser](https://composio.dev/toolkits/chaser) - Chaser is accounts receivable automation software that sends invoice reminders and helps businesses get paid faster. It streamlines the collections process to save time and improve cash flow.
- [Clarity AI MCP](https://composio.dev/toolkits/clarity_ai_mcp) - Clarity AI MCP is an MCP toolkit for simulating SFDR 2.0 fund classifications from a fund name, ISIN, or CUSIP. Use it to tap Clarity AI disclosure data and modeling without building custom sustainability-data workflows.
- [Clientary](https://composio.dev/toolkits/clientary) - Clientary is a platform for managing clients, invoices, projects, proposals, and more. It streamlines client work and saves you serious admin time.
- [Coinbase](https://composio.dev/toolkits/coinbase) - Coinbase is a platform for buying, selling, and storing cryptocurrency. It makes exchanging and managing crypto simple and secure for everyone.
- [Coinbase Agents MCP](https://composio.dev/toolkits/coinbase_agents_mcp) - Coinbase Agents MCP is Coinbase's managed toolkit exposing accounts, portfolios, orders, fills, and market data. Use it to let authorized agents inspect holdings, execute trades, perform transfers, and handle payments.
- [Coinbase Wallet MCP](https://composio.dev/toolkits/coinbase_wallet_mcp) - Coinbase Wallet MCP is Coinbase's wallet service for interacting with onchain accounts. Use it to give agents secure, structured access to inspect wallets and request onchain actions.
- [Coinranking](https://composio.dev/toolkits/coinranking) - Coinranking is a comprehensive cryptocurrency market data platform offering access to real-time coin prices, market caps, and historical data. Get accurate, up-to-date stats for thousands of digital assets in one place.
- [Coupa](https://composio.dev/toolkits/coupa) - Coupa is a business spend management platform for procurement, invoicing, and expenses. It helps organizations streamline purchasing, control costs, and gain complete visibility over financial operations.

## Frequently Asked Questions

### What are the differences in Tool Router MCP and Twelve data MCP?

With a standalone Twelve data MCP server, the agents and LLMs can only access a fixed set of Twelve data tools tied to that server. However, with the Composio Tool Router, agents can dynamically load tools from Twelve data and many other apps based on the task at hand, all through a single MCP endpoint.

### Can I use Tool Router MCP with Pydantic AI?

Yes, you can. Pydantic AI fully supports MCP integration. You get structured tool calling, message history handling, and model orchestration while Tool Router takes care of discovering and serving the right Twelve data tools.

### Can I manage the permissions and scopes for Twelve data while using Tool Router?

Yes, absolutely. You can configure which Twelve data scopes and actions are allowed when connecting your account to Composio. You can also bring your own OAuth credentials or API configuration so you keep full control over what the agent can do.

### How safe is my data with Composio Tool Router?

All sensitive data such as tokens, keys, and configuration is fully encrypted at rest and in transit. Composio is SOC 2 Type 2 compliant and follows strict security practices so your Twelve data data and credentials are handled as safely as possible.

---
[See all toolkits](https://composio.dev/toolkits) · [Composio docs](https://docs.composio.dev/llms.txt)
