Skip to content

:hedgehog: PostHog is the leading platform for building self-driving products. Our developer tools – AI observability, analytics, session replay, flags, experiments, error tracking, logs, and more – capture all the context agents need to diagnose problems, uncover opportunities, and ship fixes. Steer it all from Slack, web, desktop, or the MCP.

3.6 KB
Raw Blame
from abc import ABC, abstractmethod
from dataclasses import dataclass
from typing import Any, Generic, TypeVar

from pydantic import BaseModel, Field, JsonValue

from posthog.event_usage import EventSource
from posthog.models import Team, User

ArgsT = TypeVar("ArgsT", bound=BaseModel)


class MCPToolResult(BaseModel):
    content: str = Field(description="Formatted tool output for the model.")
    structured_content: dict[str, JsonValue] | None = Field(
        default=None, description="Structured tool output for native widgets."
    )


class MCPTool(ABC, Generic[ArgsT]):
    """
    Base class for tools executable via MCP callers.

    Unlike MaxTool, this interface:
    - Only takes args (no LangChain state, config, context_manager)
    - Team/user stored as instance fields from API authentication
    - No artifact creation (returns data directly)
    - Raises MaxToolError on failure (matching MaxTool conventions)
    """

    name: str
    args_schema: type[ArgsT]

    def __init__(self, team: Team, user: User, event_source: EventSource = EventSource.MCP):
        self._team = team
        self._user = user
        self._event_source = event_source

    @abstractmethod
    async def execute(self, args: ArgsT) -> str | MCPToolResult:
        """
        Execute the tool with validated args.

        Returns:
            Model-facing text, optionally accompanied by structured widget data.

        Raises:
            MaxToolRetryableError: For errors that can be fixed with adjusted inputs.
            MaxToolFatalError: For errors that cannot be recovered from.
        """
        pass


@dataclass(frozen=True)
class MCPToolRegistration:
    tool_cls: type[MCPTool[Any]]
    scopes: list[str]


class MCPToolRegistry:
    """Singleton registry for MCP tools."""

    _instance: "MCPToolRegistry | None" = None
    _tools: dict[str, MCPToolRegistration]

    def __new__(cls) -> "MCPToolRegistry":
        if cls._instance is None:
            cls._instance = super().__new__(cls)
            cls._instance._tools = {}
        return cls._instance

    def register(self, scopes: list[str] | None = None):
        """Decorator factory to register an MCP tool with optional scopes."""

        def decorator[T: MCPTool[Any]](cls: type[T]) -> type[T]:
            self._tools[cls.name] = MCPToolRegistration(
                tool_cls=cls,
                scopes=scopes or [],
            )
            return cls

        return decorator

    def _ensure_loaded(self) -> dict[str, MCPToolRegistration]:
        # Tools self-register on import, so every read must trigger the import first. Keep the
        # load-then-read invariant in one place — function-local import to avoid the tools <-> mcp_tool cycle.
        from ee.hogai.tools import load_all_tools  # noqa: PLC0415 - ensure tools are registered

        load_all_tools()
        return self._tools

    def get(
        self, name: str, team: Team, user: User, event_source: EventSource = EventSource.MCP
    ) -> MCPTool[Any] | None:
        """Get an MCP tool instance by name, constructed with team/user."""
        registration = self._ensure_loaded().get(name)
        if registration:
            return registration.tool_cls(team=team, user=user, event_source=event_source)
        return None

    def get_scopes(self, name: str) -> list[str]:
        """Get the required scopes for a registered MCP tool."""
        registration = self._ensure_loaded().get(name)
        if registration:
            return registration.scopes
        return []

    def get_names(self) -> list[str]:
        """Get list of registered MCP tool names."""
        return list(self._ensure_loaded().keys())


mcp_tool_registry = MCPToolRegistry()