from __future__ import annotations import logging from collections.abc import Callable from typing import TYPE_CHECKING from mcp.server.mcpserver import MCPServer from mcp.server.mcpserver.exceptions import ToolError from pipefy_mcp.tools.ai_agent_tools import AiAgentTools from pipefy_mcp.tools.ai_automation_tools import AiAutomationTools from pipefy_mcp.tools.attachment_tools import AttachmentTools from pipefy_mcp.tools.automation_tools import AutomationTools from pipefy_mcp.tools.field_condition_tools import FieldConditionTools from pipefy_mcp.tools.introspection_tools import IntrospectionTools from pipefy_mcp.tools.ipaas_tools import IpaasTools from pipefy_mcp.tools.knowledge_base_tools import KnowledgeBaseTools from pipefy_mcp.tools.llm_provider_tools import LlmProviderTools from pipefy_mcp.tools.member_tools import MemberTools from pipefy_mcp.tools.meta_tools import register_meta_tools from pipefy_mcp.tools.observability_tools import ObservabilityTools from pipefy_mcp.tools.organization_tools import OrganizationTools from pipefy_mcp.tools.pipe_config_tools import PipeConfigTools from pipefy_mcp.tools.pipe_tools import PipeTools from pipefy_mcp.tools.portal_tools import PortalTools from pipefy_mcp.tools.relation_tools import RelationTools from pipefy_mcp.tools.remote_profile import is_remote_tool from pipefy_mcp.tools.report_tools import ReportTools from pipefy_mcp.tools.service_account_tools import ServiceAccountTools from pipefy_mcp.tools.table_tools import TableTools from pipefy_mcp.tools.toolsets import POWER_GRAPHQL_TOOLS, resolve_selection from pipefy_mcp.tools.webhook_tools import WebhookTools if TYPE_CHECKING: from mcp.server.mcpserver.tools.base import Tool logger = logging.getLogger(__name__) # Keep PIPEFY_TOOL_NAMES in sync with docs/parity.md. PIPEFY_TOOL_NAMES = frozenset( { "add_card_comment", "add_phase_move_targets", "add_service_account_to_pipe", "call_ipaas_tool", "clone_pipe", "create_ai_agent", "create_ai_automation", "create_attachment_presigned_url", "create_automation", "create_card", "create_card_relation", "create_ai_knowledge_base_data_lookup", "create_ai_knowledge_base_document", "create_ai_knowledge_base_plain_text", "create_field_condition", "create_html_interface", "create_ipaas_connection", "create_label", "create_llm_provider", "create_organization_report", "create_phase", "create_phase_field", "create_pipe", "create_pipe_relation", "create_pipe_report", "create_portal", "create_portal_element", "create_portal_page", "create_sub_portal", "create_send_task_automation", "create_service_account", "create_table", "create_table_field", "create_table_record", "create_webhook", "delete_ai_agent", "delete_ai_automation", "delete_ai_knowledge_base_data_lookup", "delete_ai_knowledge_base_document", "delete_ai_knowledge_base_plain_text", "delete_automation", "delete_card", "delete_card_relation", "delete_comment", "delete_field_condition", "delete_label", "delete_llm_provider", "delete_organization_report", "delete_phase", "delete_phase_field", "delete_pipe", "delete_pipe_relation", "delete_pipe_report", "delete_portal", "delete_portal_element", "delete_portal_page", "delete_service_account", "delete_sub_portal", "delete_sub_portal_element", "delete_table", "delete_table_field", "delete_table_record", "delete_webhook", "duplicate_portal_element", "execute_graphql", "export_automation_jobs", "export_organization_report", "export_pipe_audit_logs", "export_pipe_report", "fill_card_phase_fields", "find_cards", "find_records", "get_agents_usage", "get_ai_agent", "get_ai_agent_log_details", "get_ai_agent_logs", "get_ai_agents", "get_ai_automation", "get_ai_automations", "get_ai_credit_usage", "get_ai_knowledge_base_data_lookup", "get_ai_knowledge_base_document", "get_ai_knowledge_base_plain_text", "get_ai_knowledge_bases", "get_automation", "get_automation_actions", "get_automation_event_attributes", "get_automation_execution_metrics", "get_automation_events", "get_automation_jobs_export", "get_automation_jobs_export_csv", "get_automation_logs", "get_automation_logs_by_repo", "get_automation_simulation", "get_automations", "get_automations_usage", "get_available_ai_models", "get_default_llm_provider", "get_field_condition", "get_field_conditions", "get_card", "get_card_inbox_emails", "get_card_relations", "get_cards", "get_email_templates", "get_interface_html_guidelines", "get_interface_repo_fields", "get_ipaas_connection_auth_url", "get_ipaas_tools", "get_labels", "get_llm_provider_dependencies", "get_llm_providers", "get_organization", "get_organization_report", "get_organization_report_export", "get_organization_reports", "get_phase_allowed_move_targets", "get_phase_cards", "get_phase_cards_count", "get_interface_html", "get_phase_fields", "get_portal", "get_pipe", "get_pipe_members", "get_pipe_relations", "get_pipe_report", "get_pipe_report_columns", "get_pipe_report_export", "get_pipe_report_filterable_fields", "get_pipe_reports", "get_records", "get_start_form_fields", "get_table", "get_table_record", "get_table_records", "get_tables", "get_table_relations", "get_webhooks", "introspect_mutation", "introspect_query", "introspect_type", "invite_members", "list_interface_repos", "list_interfaces", "list_organizations", "list_portals", "move_card_to_phase", "publish_sub_portal", "remove_member_from_pipe", "reset_default_llm_provider", "search_pipes", "search_schema", "search_tables", "send_email_with_template", "send_inbox_email", "simulate_automation", "sort_portal_pages", "set_default_llm_provider", "set_interface_actions", "set_interface_sources", "set_llm_provider_active_status", "set_role", "set_table_record_field_value", "toggle_ai_agent_status", "unpublish_sub_portal", "update_ai_agent", "update_ai_automation", "update_ai_knowledge_base_data_lookup", "update_ai_knowledge_base_document", "update_ai_knowledge_base_plain_text", "update_automation", "update_card", "update_card_field", "update_comment", "update_field_condition", "update_label", "update_llm_provider", "update_organization_report", "update_phase", "update_phase_field", "update_pipe", "update_pipe_relation", "update_pipe_report", "update_portal", "update_portal_element", "update_portal_page", "update_portal_page_layout", "update_sub_portal_element", "update_table", "update_table_field", "update_table_record", "update_webhook", "upload_attachment_to_card", "upload_attachment_to_table_record", "validate_ai_agent_behaviors", "validate_ai_automation_prompt", "validate_knowledge_base_access", "validate_llm_provider_access", "write_interface_html", } ) # Toolsets registered on the server, in registration order. Each exposes a # ``register(mcp, client)`` static method. Add a toolset by appending it here. _TOOLSETS = ( PipeTools, PipeConfigTools, FieldConditionTools, TableTools, RelationTools, ReportTools, AttachmentTools, MemberTools, ServiceAccountTools, WebhookTools, AutomationTools, IntrospectionTools, IpaasTools, OrganizationTools, PortalTools, ObservabilityTools, AiAutomationTools, AiAgentTools, LlmProviderTools, KnowledgeBaseTools, ) class ToolRegistry: """Responsible for registering tools with the MCP server.""" def __init__(self, mcp: MCPServer): self.mcp = mcp self.pipefy_tool_names: frozenset[str] = PIPEFY_TOOL_NAMES @staticmethod def _live_tools(mcp: MCPServer) -> list[Tool]: """The tools currently registered, as server-tier ``Tool`` objects. The one private-API touchpoint left in this class, and deliberate, for two reasons. ``apply_power_profile`` keeps these objects themselves in the catalog that ``execute_tool`` dispatches through, and ``describe_tool`` reads their ``parameters``; the public ``MCPServer.list_tools()`` returns wire ``mcp.types.Tool`` models, which carry neither ``run`` nor ``parameters``. And that public method is async, while registration and filtering run synchronously at build time, so awaiting here would push ``async`` up through the composition root into both transports. Note the ``meta`` marker is NOT among the reasons: it is present on the wire model too, so the remote floor alone could read it either way. Removal goes through the public ``MCPServer.remove_tool``. If upstream renames ``_tool_manager`` this raises ``AttributeError`` at startup, which is the failure mode to want: loud, before serving, rather than a floor that silently fails to apply. """ return list(mcp._tool_manager.list_tools()) @staticmethod def _snapshot_tool_names(mcp: MCPServer) -> set[str]: return {tool.name for tool in ToolRegistry._live_tools(mcp)} def _remove_tools_by_name(self, names: set[str]) -> None: """Remove tools by exact name, tolerating one that is already gone. Only names the caller selected out of the live set are passed in, so a missing one means another path removed it first; that is not an error worth failing a build over. """ for name in names: try: self.mcp.remove_tool(name) except ToolError: logger.debug("Tool %r not registered; skipping remove.", name) def check_for_name_collisions(self) -> None: """Fail fast if any Pipefy tool name is already registered on the app. The SDK keeps the first handler when names collide; preflight avoids silently running a foreign ``create_card`` (or other) handler. """ existing = self._snapshot_tool_names(self.mcp) collisions = existing & set(self.pipefy_tool_names) if collisions: names = ", ".join(sorted(collisions)) raise RuntimeError( "Cannot register Pipefy tools because these names already exist: " f"{names}" ) def register_tools(self) -> None: """Register tools with the MCP server. Tool functions resolve the live Pipefy client per request from the MCP lifespan context (see :func:`pipefy_mcp.tools.tool_context.get_pipefy_client`), so registration needs no client and runs once, at construction, rather than inside the lifespan. """ for toolset in _TOOLSETS: toolset.register(self.mcp) def retain_only(self, predicate: Callable[[Tool], bool]) -> set[str]: """Remove every Pipefy tool that does not satisfy ``predicate``. Runs after :meth:`register_tools`: the marker rides on the ``@mcp.tool`` decorator, so a tool must be registered before its marker can be read. Only names in ``pipefy_tool_names`` are eligible for removal, so third-party or test-registered tools are never touched. Returns the set of withheld (removed) tool names. """ withheld = { tool.name for tool in self._live_tools(self.mcp) if tool.name in self.pipefy_tool_names and not predicate(tool) } self._remove_tools_by_name(withheld) return withheld def apply_remote_profile(self, *, remote_mode: bool) -> set[str]: """When ``remote_mode`` is on, withhold every tool not marked remote-safe. Default-deny: only tools carrying ``meta=REMOTE`` survive. When off, a no-op that returns an empty set (local stdio profile keeps all tools). """ if not remote_mode: return set() withheld = self.retain_only(is_remote_tool) logger.info( "Remote profile: exposed %d, withheld %d Pipefy tools.", len(self.pipefy_tool_names) - len(withheld), len(withheld), ) return withheld def apply_toolset_selection(self, spec: str | None) -> set[str]: """Narrow the exposed surface to the toolsets named in ``spec``. Runs after :meth:`apply_remote_profile` (floor then selection), so on the remote profile the survivors are the intersection of the remote-safe floor and the selection — selection only ever removes, never widens past the floor. ``spec`` is a comma-separated list of subject domains; an empty spec or the ``all`` / ``default`` keyword is no curation (a no-op returning an empty set), keeping the default surface backward-compatible. Raises: ValueError: on an unknown toolset name (surfaced by ``resolve_selection``). """ selection = resolve_selection(spec) if selection is None: return set() withheld = self.retain_only(lambda tool: tool.name in selection) exposed = sum( 1 for tool in self._live_tools(self.mcp) if tool.name in self.pipefy_tool_names ) logger.info( "Toolset selection %r: exposed %d, withheld %d Pipefy tools.", spec, exposed, len(withheld), ) return withheld def apply_power_profile(self) -> set[str]: """Hide the curated tools behind the catalog meta-tools (the ``power`` profile). Snapshots the live curated tools (post-floor, minus the raw-GraphQL tools that stay visible by name), removes them from ``tools/list``, and registers the four meta-tools over that snapshot. Because the snapshot is taken after :meth:`apply_remote_profile`, ``execute_tool`` can reach only tools the floor already allowed. Returns the set of hidden (snapshotted) tool names. """ catalog = { tool.name: tool for tool in self._live_tools(self.mcp) if tool.name in self.pipefy_tool_names and tool.name not in POWER_GRAPHQL_TOOLS } hidden = self.retain_only(lambda tool: tool.name in POWER_GRAPHQL_TOOLS) register_meta_tools(self.mcp, catalog) visible = sum( 1 for tool in self._live_tools(self.mcp) if tool.name in self.pipefy_tool_names ) logger.info( "Power profile: hid %d curated tools behind meta-tools; " "%d raw-GraphQL tools stay visible.", len(hidden), visible, ) return hidden