Skip to main content
Glama

get_functions

Read-onlyIdempotent

Get Pine Script v6 functions filtered by namespace. Use this to see available functions before writing Pine Script code.

Instructions

Get valid Pine Script v6 functions, optionally filtered by namespace.

Use before writing Pine Script to see which functions exist. For checking a single function name, use validate_function() instead.

Input Schema

TableJSON Schema
NameRequiredDescriptionDefault
namespaceNoFilter by namespace (e.g., "ta", "strategy", "request"). Empty string returns all functions grouped by namespace.

Implementation Reference

  • The get_functions tool handler — returns all Pine Script v6 functions grouped by namespace (when namespace='') or filtered by a specific namespace (e.g., 'ta', 'strategy'). Uses PINE_V6_FUNCTIONS and PINE_V6_TOPLEVEL global sets loaded from pine_v6_functions.json.
    async def get_functions(namespace: str = ""):
        """Get valid Pine Script v6 functions, optionally filtered by namespace.
    
        Use before writing Pine Script to see which functions exist.
        For checking a single function name, use validate_function() instead.
    
        Args:
            namespace: Filter by namespace (e.g., "ta", "strategy", "request").
                       Empty string returns all functions grouped by namespace.
    
        Returns a formatted text list of function names.
        """
        with _timed_tool("get_functions", namespace=namespace or "(all)"):
            if not PINE_V6_FUNCTIONS:
                return (
                    "Error: Function data not loaded. "
                    "The pine_v6_functions.json file may be missing from the package."
                )
            if not namespace:
                by_ns: dict[str, list[str]] = {}
                for fn in sorted(PINE_V6_FUNCTIONS):
                    ns, _, name = fn.rpartition(".")
                    by_ns.setdefault(ns, []).append(name)
                lines = [f"{ns}.*: {', '.join(sorted(fns))}" for ns, fns in sorted(by_ns.items())]
                lines.append(f"Top-level: {', '.join(sorted(PINE_V6_TOPLEVEL))}")
                return "\n".join(lines)
    
            prefix = f"{namespace}."
            matches = sorted(fn for fn in PINE_V6_FUNCTIONS if fn.startswith(prefix))
            if not matches:
                available = ", ".join(sorted(PINE_V6_NAMESPACES))
                return f"No functions found for namespace '{namespace}'. Available namespaces: {available}"
            return f"# {namespace}.* functions ({len(matches)} total)\n\n" + "\n".join(f"- {fn}" for fn in matches)
  • The @mcp.tool decorator registering get_functions as an MCP tool with tags 'reference' and 'validation', and annotations readOnlyHint, idempotentHint, openWorldHint.
    @mcp.tool(
        tags={"reference", "validation"},
        annotations={"readOnlyHint": True, "idempotentHint": True, "openWorldHint": False}
    )
  • The function's docstring serves as the schema — defines the 'namespace' parameter (optional string, default empty) and describes return as a formatted text list.
    """Get valid Pine Script v6 functions, optionally filtered by namespace.
    
    Use before writing Pine Script to see which functions exist.
    For checking a single function name, use validate_function() instead.
    
    Args:
        namespace: Filter by namespace (e.g., "ta", "strategy", "request").
                   Empty string returns all functions grouped by namespace.
    
    Returns a formatted text list of function names.
    """
  • _load_functions() helper — loads function data from pine_v6_functions.json, returning three sets: functions, namespaces, and toplevel. These are stored as globals PINE_V6_FUNCTIONS, PINE_V6_NAMESPACES, PINE_V6_TOPLEVEL used by get_functions.
    def _load_functions() -> tuple[set, set, set]:
        """Load function data from JSON file."""
        if not FUNCTIONS_JSON.exists():
            return set(), set(), set()
        try:
            data = json.loads(FUNCTIONS_JSON.read_text(encoding="utf-8"))
            return (
                set(data.get("functions", [])),
                set(data.get("namespaces", [])),
                set(data.get("toplevel", [])),
            )
        except (json.JSONDecodeError, KeyError):
            return set(), set(), set()
  • _timed_tool context manager used for timing, logging, and Prometheus metrics for get_functions and all other tools.
    class _timed_tool:
        """Context manager for tool timing and logging.
    
        Usage:
            with _timed_tool("get_doc", path=path) as log:
                ...
                log["chars"] = len(content)  # add extra fields
        """
        def __init__(self, tool_name: str, **kwargs):
            self._tool_name = tool_name
            self._extra = kwargs
            self._data: dict = {}
    
        def __enter__(self):
            self._start = time.time()
            self._data = {}
            return self._data
    
        def __exit__(self, exc_type, exc_val, exc_tb):
            duration = time.time() - self._start
            transport = _current_transport.get() or _TRANSPORT
            tool_calls_total.labels(tool=self._tool_name, transport=transport, region=_FLY_REGION).inc()
            tool_duration_seconds.labels(tool=self._tool_name, transport=transport, region=_FLY_REGION).observe(duration)
            if exc_type is not None:
                tool_errors_total.labels(tool=self._tool_name, transport=transport, region=_FLY_REGION).inc()
            log_data = {
                "event": "tool_call",
                "tool": self._tool_name,
                **self._extra,
                **self._data,
                "duration_ms": int(duration * 1000),
            }
            _logger.info(json.dumps(log_data))
            return False
Behavior4/5

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

Annotations already declare readOnlyHint=true and idempotentHint=true. The description adds context about grouping by namespace and optional filtering, which is helpful but not extensive.

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?

Three sentences, front-loaded with purpose, no extraneous information. Efficiently structured.

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?

No output schema exists, and the description does not specify the output format (e.g., list of function names). However, the grouping hint and simple parameter set make it fairly complete.

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?

Schema coverage is 100% and the description largely repeats the schema's parameter description ('Empty string returns all functions grouped by namespace'). No additional meaning beyond the schema.

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 specifies 'Get valid Pine Script v6 functions', clearly stating the verb and resource. It distinguishes from sibling 'validate_function' by noting the alternative for single function checks.

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

Usage Guidelines5/5

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

Explicitly says 'Use before writing Pine Script to see which functions exist' and provides a direct alternative: 'For checking a single function name, use validate_function() instead.'

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/paulieb89/pinescript-mcp'

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