Skip to main content
Glama

detect_patterns

Identify patterns, communities, and anomalies in graph data to analyze network structures and detect insights.

Instructions

Identify patterns, communities, and anomalies within graphs. Runs all supported analyses and returns a combined report.

Args:
    graph_id: ID of the graph to analyze
    ctx: MCP context for progress reporting

Returns:
    Dictionary with results from all analyses that succeeded. Keys may include:
        - degree_centrality
        - betweenness_centrality
        - closeness_centrality
        - communities (if community detection is available)
        - shortest_path (if path finding is possible)
        - path_length
        - anomalies (if anomaly detection is available)
        - errors (dict of analysis_type -> error message)

Input Schema

TableJSON Schema
NameRequiredDescriptionDefault
graph_idYes
ctxNo

Implementation Reference

  • The detect_patterns tool handler. This async function performs graph pattern detection using NetworkX for centrality measures, community detection (Louvain), shortest paths, and simple anomaly detection (degree 1 nodes). It is registered via the @mcp.tool() decorator. The function signature and docstring define the input schema (graph_id: str, optional ctx) and output (dict of results).
    @mcp.tool()
    async def detect_patterns(graph_id: str, ctx: Optional[Context] = None) -> Dict[str, Any]:
        """
        Identify patterns, communities, and anomalies within graphs. Runs all supported analyses and returns a combined report.
    
        Args:
            graph_id: ID of the graph to analyze
            ctx: MCP context for progress reporting
    
        Returns:
            Dictionary with results from all analyses that succeeded. Keys may include:
                - degree_centrality
                - betweenness_centrality
                - closeness_centrality
                - communities (if community detection is available)
                - shortest_path (if path finding is possible)
                - path_length
                - anomalies (if anomaly detection is available)
                - errors (dict of analysis_type -> error message)
    
        """
        try:
            if graph_id not in graph_cache:
                raise ValueError(f"Graph not found: {graph_id}")
    
            if ctx:
                await ctx.info("Starting pattern detection (all analyses)...")
    
            graph_data = graph_cache[graph_id]
            nx_graph = graph_data["nx_graph"]
            edges_df = graph_data["edges_df"]
            source = graph_data["source"]
            destination = graph_data["destination"]
    
            # Convert to NetworkX graph if needed
            if nx_graph is None and edges_df is not None:
                nx_graph = nx.from_pandas_edgelist(edges_df, source=source, target=destination)
    
            if nx_graph is None:
                raise ValueError("Graph data not available for analysis")
    
            results = {}
            errors = {}
    
            # Centrality
            try:
                results["degree_centrality"] = nx.degree_centrality(nx_graph)
                results["betweenness_centrality"] = nx.betweenness_centrality(nx_graph)
                results["closeness_centrality"] = nx.closeness_centrality(nx_graph)
            except Exception as e:
                errors["centrality"] = str(e)
    
            # Community detection
            try:
                import community as community_louvain
                partition = community_louvain.best_partition(nx_graph)
                results["communities"] = partition
            except Exception as e:
                errors["community_detection"] = str(e)
    
            # Path finding (try between first two nodes if possible)
            try:
                nodes = list(nx_graph.nodes())
                if len(nodes) >= 2:
                    path = nx.shortest_path(nx_graph, nodes[0], nodes[1])
                    results["shortest_path"] = path
                    results["path_length"] = len(path) - 1
            except Exception as e:
                errors["path_finding"] = str(e)
    
            # Anomaly detection (placeholder)
            try:
                # Example: nodes with degree 1 as "anomalies"
                anomalies = [n for n, d in nx_graph.degree() if d == 1]
                results["anomalies"] = anomalies
            except Exception as e:
                errors["anomaly_detection"] = str(e)
    
            if errors:
                results["errors"] = errors
    
            if ctx:
                await ctx.info("Pattern detection complete!")
    
            return results
        except Exception as e:
            logger.error(f"Error in detect_patterns: {e}")
            raise
  • The @mcp.tool() decorator registers the detect_patterns function as an MCP tool.
    @mcp.tool()
  • Docstring providing detailed input/output schema for the detect_patterns tool.
    """
    Identify patterns, communities, and anomalies within graphs. Runs all supported analyses and returns a combined report.
    
    Args:
        graph_id: ID of the graph to analyze
        ctx: MCP context for progress reporting
    
    Returns:
        Dictionary with results from all analyses that succeeded. Keys may include:
            - degree_centrality
            - betweenness_centrality
            - closeness_centrality
            - communities (if community detection is available)
            - shortest_path (if path finding is possible)
            - path_length
            - anomalies (if anomaly detection is available)
            - errors (dict of analysis_type -> error message)
    
    """
Behavior3/5

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

With no annotations provided, the description carries the full burden of behavioral disclosure. It effectively describes the tool's behavior: it runs multiple analyses, returns a combined report, and includes error handling. However, it lacks details on performance (e.g., execution time for large graphs), side effects (e.g., whether it modifies the graph), or limitations (e.g., graph size constraints).

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

Conciseness4/5

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

The description is well-structured and appropriately sized. It starts with a clear purpose statement, then details arguments and returns in separate sections. Every sentence adds value, with no redundancy. However, the 'Returns' section is somewhat lengthy due to listing all possible keys, which could be streamlined or moved to an output schema if available.

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

Completeness3/5

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

Given the tool's complexity (running multiple graph analyses) and lack of annotations or output schema, the description is moderately complete. It covers the purpose, parameters, and return structure, but misses contextual details like error conditions, performance implications, or how it integrates with sibling tools. The absence of an output schema means the description must fully explain returns, which it does adequately but not exhaustively.

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

Parameters4/5

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

The description adds significant value beyond the input schema, which has 0% description coverage. It explains that 'graph_id' is the 'ID of the graph to analyze' and 'ctx' is for 'MCP context for progress reporting', clarifying their purposes. Since there are only 2 parameters and the schema provides minimal documentation, this compensation is adequate, though it could elaborate on graph_id format or ctx usage examples.

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's purpose: 'Identify patterns, communities, and anomalies within graphs. Runs all supported analyses and returns a combined report.' This specifies the verb ('identify'), resource ('graphs'), and scope ('all supported analyses'). However, it doesn't explicitly differentiate from sibling tools like 'get_graph_info' or 'visualize_graph', which might also analyze graphs but with different approaches.

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. It mentions running 'all supported analyses' but doesn't specify prerequisites (e.g., requires an existing graph), exclusions (e.g., not for simple queries), or when to choose sibling tools like 'get_graph_info' for metadata or 'visualize_graph' for visual output 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/graphistry/graphistry-mcp'

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