Skip to main content
Glama
danielbres

massive-mcp

by danielbres

get_trades

Retrieve historical trades for a stock by ticker symbol. Filter by date range and set row limit for paginated results.

Instructions

Historical trades for a stock.

Input Schema

TableJSON Schema
NameRequiredDescriptionDefault
tickerYesStock symbol.
timestamp_gteNoInclusive lower bound ("YYYY-MM-DD" or ns/ms unix).
timestamp_ltNoExclusive upper bound.
limitNoMax rows. Default 50.
cursorNoPagination cursor.

Output Schema

TableJSON Schema
NameRequiredDescriptionDefault

No arguments

Implementation Reference

  • The get_trades handler function. Fetches historical trades for a stock via GET /v3/trades/{ticker} with optional timestamp filtering, limit, and cursor pagination.
    @mcp.tool()
    async def get_trades(
        ticker: str,
        timestamp_gte: str | None = None,
        timestamp_lt: str | None = None,
        limit: int = 50,
        cursor: str | None = None,
    ) -> dict[str, Any]:
        """Historical trades for a stock.
    
        Args:
            ticker: Stock symbol.
            timestamp_gte: Inclusive lower bound ("YYYY-MM-DD" or ns/ms unix).
            timestamp_lt: Exclusive upper bound.
            limit: Max rows. Default 50.
            cursor: Pagination cursor.
        """
        return await client.get(
            f"/v3/trades/{ticker}",
            {
                "timestamp.gte": timestamp_gte,
                "timestamp.lt": timestamp_lt,
                "limit": limit,
                "cursor": cursor,
            },
        )
  • Registration: quotes.register(mcp, client) is called for each tool module in build_server().
    for module in (
        aggregates,
        quotes,
        snapshots,
        tickers,
        news,
        reference,
        indicators,
        corporate,
        financials,
    ):
        module.register(mcp, client)
  • The register() function that registers all tools in quotes.py (including get_trades) via the @mcp.tool() decorator.
    def register(mcp: FastMCP, client: MassiveClient) -> None:
        @mcp.tool()
  • MassiveClient.get() – the HTTP client helper used by get_trades to make the actual API call.
    class MassiveClient:
        def __init__(self, settings: Settings) -> None:
            self._settings = settings
            headers = {"User-Agent": "massive-mcp/0.1"}
            if settings.auth_mode == "bearer":
                headers["Authorization"] = f"Bearer {settings.api_key}"
            self._http = httpx.AsyncClient(
                base_url=settings.base_url,
                headers=headers,
                timeout=DEFAULT_TIMEOUT,
            )
    
        async def aclose(self) -> None:
            await self._http.aclose()
    
        async def get(
            self, path: str, params: dict[str, Any] | None = None, *, trim: bool = True
        ) -> dict[str, Any]:
            merged: dict[str, Any] = {k: v for k, v in (params or {}).items() if v is not None}
            if self._settings.auth_mode == "query":
                merged["apiKey"] = self._settings.api_key
    
            last_exc: Exception | None = None
            for attempt in range(MAX_RETRIES):
                try:
                    resp = await self._http.get(path, params=merged)
                except httpx.HTTPError as exc:
                    last_exc = exc
                    await asyncio.sleep(2**attempt)
                    continue
    
                if resp.status_code == 429:
                    retry_after = float(resp.headers.get("Retry-After", 2**attempt))
                    await asyncio.sleep(min(retry_after, 30))
                    continue
                if 500 <= resp.status_code < 600 and attempt < MAX_RETRIES - 1:
                    await asyncio.sleep(2**attempt)
                    continue
    
                if resp.status_code == 401:
                    hint = (
                        "auth rejected — verify MASSIVE_API_KEY; "
                        "if you used MASSIVE_AUTH_MODE=bearer, try 'query' (or vice versa)"
                    )
                    raise MassiveAPIError(401, hint, _strip_secrets(str(resp.request.url)))
    
                try:
                    data = resp.json()
                except ValueError:
                    data = {"raw": resp.text}
    
                if not resp.is_success:
                    msg = data.get("error") or data.get("message") or resp.reason_phrase or "request failed"
                    raise MassiveAPIError(resp.status_code, str(msg), _strip_secrets(str(resp.request.url)))
    
                return _trim(data) if trim else data
    
            raise MassiveAPIError(0, f"network error after {MAX_RETRIES} retries: {last_exc}", path)
    
    
    def _trim(data: dict[str, Any]) -> dict[str, Any]:
        """If `results` is a huge array, truncate and surface a hint to paginate."""
        results = data.get("results")
        if isinstance(results, list) and len(results) > TRIM_THRESHOLD:
            kept = results[:TRIM_THRESHOLD]
            data = dict(data)
            data["results"] = kept
            data["_truncated_note"] = (
                f"response had {len(results)} items; truncated to {TRIM_THRESHOLD}. "
                "Re-call with a tighter `limit` or use `cursor`/`next_url` to page."
            )
        if "next_url" in data and data.get("next_url"):
            cursor = _extract_cursor(data["next_url"])
            if cursor:
                data["next_cursor"] = cursor
        return data
    
    
    def _extract_cursor(next_url: str) -> str | None:
        parts = urlsplit(next_url)
        for kv in parts.query.split("&"):
            if kv.startswith("cursor="):
                return kv.split("=", 1)[1]
        return None
  • Input schema for get_trades: ticker (str), timestamp_gte (optional str), timestamp_lt (optional str), limit (int, default 50), cursor (optional str). Returns dict[str, Any].
    async def get_trades(
        ticker: str,
        timestamp_gte: str | None = None,
        timestamp_lt: str | None = None,
        limit: int = 50,
        cursor: str | None = None,
    ) -> dict[str, Any]:
Behavior2/5

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

With no annotations provided, the description should disclose behavioral traits like read-only nature, data source, or rate limits. It only states 'historical trades,' leaving out important context about what the data includes.

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

Conciseness2/5

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

The description is a single sentence, which is efficient, but it is underspecified and does not earn its place by providing necessary information. It lacks key details that should be present.

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?

Despite 5 parameters and an existing output schema, the description fails to explain pagination (cursor, limit), date format preferences, or what fields the output contains. It is incomplete for a tool with this complexity.

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

Parameters3/5

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

The input schema has 100% description coverage, so the schema already explains all parameters. The description does not add any additional semantic meaning beyond what is in the schema, maintaining a baseline score.

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

Purpose4/5

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

The description clearly states the tool retrieves 'historical trades for a stock,' which is a specific verb+resource combination. It distinguishes from sibling tools like get_last_trade and get_quotes by emphasizing the historical nature of the data.

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

Usage Guidelines1/5

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

No guidance is provided on when to use this tool versus alternatives, such as get_quotes for current data or get_aggregates for aggregated data. There is no mention of prerequisites or context.

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/danielbres/Massive-MCP'

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