Skip to main content
Glama

get_etf_flow

Retrieve historical ETF flow data for BTC or ETH from the CoinGlass API, formatted as a Markdown table with tickers and dates for analysis.

Instructions

Fetch historical ETF flow data for BTC or ETH from CoinGlass API and return as a Markdown table.

Parameters:
    coin (str): Cryptocurrency to query ('BTC' or 'ETH').

Returns:
    str: Markdown table with ETF flow data (tickers as columns, dates as rows, with total column).

Input Schema

TableJSON Schema
NameRequiredDescriptionDefault
coinYes

Implementation Reference

  • The primary handler function for the 'get_etf_flow' tool. It handles input validation, API calls to CoinGlass, data processing, and returns formatted Markdown table. Registered via @mcp.tool() decorator.
    @mcp.tool()
    async def get_etf_flow(coin: str, ctx: Context = None) -> str:
        """
        Fetch historical ETF flow data for BTC or ETH from CoinGlass API and return as a Markdown table.
    
        Parameters:
            coin (str): Cryptocurrency to query ('BTC' or 'ETH').
    
        Returns:
            str: Markdown table with ETF flow data (tickers as columns, dates as rows, with total column).
        """
        coin = coin.upper()
        if coin not in ["BTC", "ETH"]:
            return "Invalid coin specified. Please use 'BTC' or 'ETH'."
    
        ctx.info(f"Fetching {coin} ETF flow data")
        endpoint = f"/api/etf/{'bitcoin' if coin == 'BTC' else 'ethereum'}/flow-history"
    
        try:
            data = await fetch_coinglass_data(endpoint)
            if data.get("code") == "0" and data.get("data"):
                return format_to_markdown_table(data["data"], coin)
            else:
                return f"No {coin} ETF flow data available"
        except Exception as e:
            return f"Error fetching {coin} ETF flow: {str(e)}"
  • Helper function to make authenticated HTTP requests to the CoinGlass API, used by get_etf_flow.
    async def fetch_coinglass_data(endpoint: str) -> Dict:
        """
        Make an HTTP GET request to the CoinGlass API.
        
        Args:
            endpoint (str): API endpoint (e.g., '/api/etf/bitcoin/flow-history')
        
        Returns:
            Dict: JSON response from the API
        """
        headers = {
            "accept": "application/json",
            "CG-API-KEY": COINGLASS_API_KEY
        }
        async with httpx.AsyncClient() as client:
            try:
                response = await client.get(
                    f"{COINGLASS_API_BASE}{endpoint}",
                    headers=headers
                )
                response.raise_for_status()
                return response.json()
            except httpx.HTTPError as e:
                raise Exception(f"API request failed: {str(e)}")
  • Helper function to process raw ETF flow data into a pivoted Markdown table with dates as rows, tickers as columns, and totals, using pandas. Called by get_etf_flow.
    def format_to_markdown_table(data: List[Dict], coin: str) -> str:
        """
        Format ETF flow data into a Markdown table using pandas pivot table.
        
        Args:
            data (List[Dict]): List of ETF flow data entries
            coin (str): Cryptocurrency ('BTC' or 'ETH')
        
        Returns:
            str: Markdown table string
        """
        if not data:
            return f"No {coin} ETF flow data available"
    
        # Prepare data for pandas
        records = []
        for entry in data:
            timestamp = entry.get("timestamp")
            if not timestamp:
                continue
            date_str = datetime.fromtimestamp(timestamp / 1000).strftime("%Y-%m-%d")
            for etf in entry.get("etf_flows", []):
                ticker = etf.get("etf_ticker")
                flow = etf.get("change_usd")
                if ticker:
                    records.append({
                        "Date": date_str,
                        "Ticker": ticker,
                        "Flow": flow
                    })
    
        if not records:
            return f"No {coin} ETF flow data available"
    
        # Create DataFrame
        df = pd.DataFrame(records)
    
        # Create pivot table
        pivot = df.pivot_table(
            values="Flow",
            index="Date",
            columns="Ticker",
            aggfunc="sum",
            fill_value=0
        )
    
        # Sort dates in descending order
        pivot = pivot.sort_index(ascending=False)
    
        # Calculate total column
        pivot["Total"] = pivot.sum(axis=1)
    
        # Convert to Markdown table
        markdown = pivot.to_markdown(floatfmt=".0f")
        return markdown
  • The @mcp.tool() decorator registers the get_etf_flow function as an MCP tool.
    @mcp.tool()
Behavior3/5

Does the description disclose side effects, auth requirements, rate limits, or destructive behavior?

With no annotations provided, the description carries the full burden of behavioral disclosure. It describes the action ('Fetch') and output format ('Markdown table'), but lacks details on error handling, rate limits, authentication needs, or data freshness. It adequately covers basic behavior but misses advanced operational context.

Agents need to know what a tool does to the world before calling it. Descriptions should go beyond structured annotations to explain consequences.

Conciseness5/5

Is the description appropriately sized, front-loaded, and free of redundancy?

The description is well-structured and front-loaded, with a clear opening sentence followed by specific sections for parameters and returns. Every sentence adds value without redundancy, making it efficient and easy to parse.

Shorter descriptions cost fewer tokens and are easier for agents to parse. Every sentence should earn its place.

Completeness4/5

Given the tool's complexity, does the description cover enough for an agent to succeed on first attempt?

Given the tool's moderate complexity (single parameter, no output schema, no annotations), the description is mostly complete. It covers purpose, parameters, and return format, but could improve by addressing behavioral aspects like error cases or data limitations, which would enhance completeness for an API-based tool.

Complex tools with many parameters or behaviors need more documentation. Simple tools need less. This dimension scales expectations accordingly.

Parameters5/5

Does the description clarify parameter syntax, constraints, interactions, or defaults beyond what the schema provides?

The description adds significant meaning beyond the input schema, which has 0% coverage. It explicitly defines the 'coin' parameter as a string with allowed values ('BTC' or 'ETH') and explains its purpose ('Cryptocurrency to query'), compensating fully for the schema's lack of documentation.

Input schemas describe structure but not intent. Descriptions should explain non-obvious parameter relationships and valid value ranges.

Purpose5/5

Does the description clearly state what the tool does and how it differs from similar tools?

The description clearly states the tool's purpose with a specific verb ('Fetch'), resource ('historical ETF flow data'), and scope ('for BTC or ETH from CoinGlass API'). It distinguishes the data source and format, making the function unambiguous even without sibling tools.

Agents choose between tools based on descriptions. A clear purpose with a specific verb and resource helps agents select the right tool.

Usage Guidelines3/5

Does the description explain when to use this tool, when not to, or what alternatives exist?

The description implies usage context by specifying the cryptocurrency options ('BTC' or 'ETH') and the data source (CoinGlass API), but it does not provide explicit guidance on when to use this tool versus alternatives or any prerequisites. Since there are no sibling tools, the lack of comparative guidance is less critical.

Agents often have multiple tools that could apply. Explicit usage guidance like "use X instead of Y when Z" prevents misuse.

Install Server

Other Tools

Related Tools

Latest Blog Posts

MCP directory API

We provide all the information about MCP servers via our MCP API.

curl -X GET 'https://glama.ai/api/mcp/v1/servers/kukapay/etf-flow-mcp'

If you have feedback or need assistance with the MCP directory API, please join our Discord server