Skip to main content
Glama
phuihock

TA-Lib MCP Server

by phuihock

calculate_sma

Compute Simple Moving Average (SMA) for financial price data to identify trends and support technical analysis in market evaluation.

Instructions

Calculate Simple Moving Average (SMA).

Input Schema

TableJSON Schema
NameRequiredDescriptionDefault
kwargsYes

Output Schema

TableJSON Schema
NameRequiredDescriptionDefault
resultYes

Implementation Reference

  • MCP tool handler for 'calculate_sma': decorated with @mcp.tool(), delegates to SMAIndicator via registry.
    @mcp.tool()
    async def calculate_sma(
        close: List[float],
        timeperiod: int = 20
    ) -> Dict[str, Any]:
        """Calculate Simple Moving Average (SMA).
        
        Args:
            close: List of closing prices
            timeperiod: Number of periods to average (default: 20)
            
        Returns:
            Dictionary with SMA values and metadata
        """
        try:
            # Get indicator from registry
            indicator = registry.get_indicator("sma")
            if not indicator:
                raise ValueError("SMA indicator not found")
            
            # Create market data
            market_data = MarketData(close=close)
            
            # Calculate indicator
            result = await indicator.calculate(market_data, {"timeperiod": timeperiod})
            
            if result.success:
                return {
                    "success": True,
                    "values": result.values,
                    "metadata": result.metadata,
                }
            else:
                return {
                    "success": False,
                    "error": result.error_message,
                }
                
        except Exception as e:
            return {
                "success": False,
                "error": str(e),
            }
  • SMAIndicator class: core computation logic for SMA, including input validation, schema definition, and pure Python SMA calculation.
    class SMAIndicator(BaseIndicator):
        """Simple Moving Average (SMA) indicator implementation."""
        
        def __init__(self):
            """Initialize SMA indicator."""
            super().__init__(
                name="sma",
                description="Simple Moving Average (SMA) - calculates the arithmetic mean of prices over a specified time period"
            )
        
        @property
        def name(self) -> str:
            return "sma"
        
        @property
        def description(self) -> str:
            return "Simple Moving Average (SMA) - calculates the average price over a specified period"
        
        @property
        def input_schema(self) -> Dict[str, Any]:
            return {
                "type": "object",
                "properties": {
                    "close_prices": {
                        "type": "array",
                        "items": {"type": "number"},
                        "description": "List of closing prices"
                    },
                    "timeperiod": {
                        "type": "integer",
                        "default": 20,
                        "description": "Number of periods to average"
                    }
                },
                "required": ["close_prices"]
            }
        
        async def calculate(
            self, 
            market_data: MarketData, 
            options: Dict[str, Any] = None
        ) -> IndicatorResult:
            """Calculate SMA indicator."""
            if options is None:
                options = {}
            
            timeperiod = options.get("timeperiod", 20)
            close_prices = market_data.close
            
            if len(close_prices) < timeperiod:
                return IndicatorResult(
                    indicator_name=self.name,
                    success=False,
                    values={},
                    error_message=f"Not enough data points. Need at least {timeperiod}, got {len(close_prices)}"
                )
            
            # Calculate SMA
            sma_values = []
            for i in range(timeperiod - 1, len(close_prices)):
                avg = sum(close_prices[i - timeperiod + 1:i + 1]) / timeperiod
                sma_values.append(avg)
            
            return IndicatorResult(
                indicator_name=self.name,
                success=True,
                values={"sma": sma_values},
                metadata={
                    "timeperiod": timeperiod,
                    "input_points": len(close_prices),
                    "output_points": len(sma_values)
                }
            )
  • Registration of SMAIndicator class in the global indicator registry.
    registry.register("sma", SMAIndicator)
  • JSON schema definition for SMA indicator inputs (used indirectly by the tool).
    def input_schema(self) -> Dict[str, Any]:
        return {
            "type": "object",
            "properties": {
                "close_prices": {
                    "type": "array",
                    "items": {"type": "number"},
                    "description": "List of closing prices"
                },
                "timeperiod": {
                    "type": "integer",
                    "default": 20,
                    "description": "Number of periods to average"
                }
            },
            "required": ["close_prices"]
        }
Behavior1/5

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

No annotations are provided, so the description carries the full burden of behavioral disclosure. It only states what the tool does ('Calculate Simple Moving Average') without any information on how it behaves—such as input format, output structure, error handling, or computational characteristics. This leaves critical behavioral traits unspecified.

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 extremely concise—a single sentence—and front-loaded with the core action. There is no wasted text, making it efficient to parse, though this brevity contributes to gaps in other dimensions.

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

Completeness2/5

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

Given the complexity (a calculation tool with many siblings), lack of annotations, and low schema coverage (0%), the description is incomplete. While an output schema exists, the description does not compensate for missing context on usage, parameters, or behavior, making it insufficient for reliable tool selection and invocation.

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

Parameters1/5

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

The input schema has 1 parameter ('kwargs') with 0% description coverage, meaning the schema provides no details about its purpose or format. The description adds no parameter semantics beyond the tool's name, failing to explain what 'kwargs' should contain (e.g., data series, window size) or how to structure it, which is essential for correct invocation.

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

Purpose3/5

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

The description 'Calculate Simple Moving Average (SMA)' clearly states the verb ('Calculate') and resource ('Simple Moving Average'), making the purpose understandable. However, it does not differentiate this tool from its many siblings (e.g., calculate_ema, calculate_wma) that also calculate moving averages, leaving the specific distinction unclear.

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

Usage Guidelines2/5

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

The description provides no guidance on when to use this tool versus alternatives. With 17 sibling tools listed, including many for different types of moving averages (e.g., EMA, DEMA, WMA), the lack of any context or comparison makes it difficult for an agent to choose appropriately without external knowledge.

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

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/phuihock/mcp-talib'

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