
    Ki|                    4
   U d Z ddlmZ ddlZddlZddlmZ ddlmZ ddl	m
Z
mZmZmZmZ ddlmZmZmZmZmZmZmZmZmZmZmZmZmZmZmZmZm Z m!Z!m"Z"m#Z#m$Z$m%Z%m&Z&m'Z'm(Z(m)Z)m*Z*m+Z+m,Z,m-Z- da.d	e/d
<   d4dZ0 edd      Z1e1je                         	 	 	 	 	 d5	 	 	 	 	 	 	 	 	 	 	 d6d       Z3e1je                         	 	 	 	 d7	 	 	 	 	 	 	 	 	 d8d       Z4e1je                         	 	 	 	 d9	 	 	 	 	 	 	 	 	 d:d       Z5e1je                         	 	 	 	 	 d;	 	 	 	 	 	 	 	 	 	 	 d<d       Z6e1je                         	 	 d=	 	 	 	 	 	 	 	 	 d>d       Z7e1je                         	 	 	 	 	 	 	 d?	 	 	 	 	 	 	 	 	 	 	 	 	 	 	 d@d       Z8e1je                         	 	 	 	 	 dA	 	 	 	 	 	 	 	 	 	 	 	 	 dBd       Z9e1je                         	 	 dC	 	 	 	 	 dDd       Z:e1je                         	 dE	 	 	 dFd       Z;e1je                         	 	 	 	 dGd       Z<e1je                         	 	 	 	 	 dH	 	 	 	 	 	 	 	 	 	 	 dId       Z=e1je                         	 	 	 	 	 dJ	 	 	 	 	 	 	 	 	 	 	 dKd       Z>e1je                         	 	 	 	 dL	 	 	 	 	 	 	 	 	 dMd       Z?e1je                         	 	 	 dN	 	 	 	 	 	 	 dOd       Z@e1je                         	 	 	 	 dP	 	 	 	 	 	 	 	 	 dQd       ZAe1je                         	 	 	 	 dL	 	 	 	 	 	 	 	 	 dRd       ZBe1je                         	 dE	 	 	 dFd       ZCe1je                         	 	 	 	 	 	 dS	 	 	 	 	 	 	 	 	 	 	 	 	 dTd        ZDe1je                         	 	 	 	 	 	 dU	 	 	 	 	 	 	 	 	 	 	 	 	 dVd!       ZEe1je                         	 	 dW	 	 	 	 	 	 	 dXd"       ZFe1je                         	 	 dW	 	 	 	 	 dYd#       ZGe1je                         	 dE	 	 	 	 	 dZd$       ZHe1je                         	 	 d[	 	 	 	 	 d\d%       ZIe1je                         	 	 d[	 	 	 	 	 d\d&       ZJe1je                         	 dE	 	 	 dFd'       ZKe1je                         	 	 d]	 	 	 	 	 d\d(       ZLe1je                         	 dE	 	 	 dFd)       ZMe1je                         	 	 	 	 d^	 	 	 	 	 	 	 	 	 	 	 d_d*       ZNe1je                         d`d+       ZOe1je                         	 	 da	 	 	 	 	 	 	 dbd,       ZPe1j                         dcddd-       ZRe1j                         ded.       ZSe1j                         dfdgd/       ZTe1j                         ded0       ZUe1j                         dcddd1       ZVdEdhd2ZWeXd3k(  r eW        yy)izMCP server entry point for Code Review Graph.

Run as: code-review-graph serve
Communicates via stdio (standard MCP transport).
    )annotationsN)Optional)FastMCP   )architecture_map_promptdebug_issue_promptonboard_developer_promptpre_merge_check_promptreview_changes_prompt)apply_refactor_funcbuild_or_update_graphcross_repo_search_funcdetect_changes_funcembed_graphfind_large_functionsgenerate_wiki_funcget_affected_flows_funcget_architecture_overview_funcget_bridge_nodes_funcget_community_funcget_docs_sectionget_flowget_hub_nodes_funcget_impact_radiusget_knowledge_gaps_funcget_minimal_contextget_review_contextget_suggested_questions_funcget_surprising_connections_funcget_wiki_page_functraverse_graph_funclist_communities_func
list_flowslist_graph_statslist_repos_funcquery_graphrefactor_funcrun_postprocesssemantic_search_nodes
str | None_default_repo_rootc                    | r| S t         S )u  Resolve repo_root for a tool call.

    Order of precedence:
    1. Explicit ``repo_root`` passed by the MCP client (highest).
    2. ``--repo`` CLI flag passed to ``code-review-graph serve``
       (captured in ``_default_repo_root``).
    3. None — the underlying impl will fall back to the server's cwd.

    Previously, only ``get_docs_section_tool`` consulted ``_default_repo_root``,
    so ``serve --repo <X>`` had no effect for the other 21 tools. See: #222
    follow-up.
    )r+   	repo_roots    b/home/jay/workspace/scripts/.codegraph-venv/lib/python3.12/site-packages/code_review_graph/main.py_resolve_repo_rootr0   <   s     "99'99    zcode-review-graphzPersistent incremental knowledge graph for token-efficient, context-aware code reviews. Parses your codebase with Tree-sitter, builds a structural graph, and provides smart impact analysis.)instructionsc                n   K   t        j                  t        | t        |      |||       d{   S 7 w)a  Build or incrementally update the code knowledge graph.

    Call this first to initialize the graph, or after making changes.
    By default performs an incremental update (only changed files).
    Set full_rebuild=True to re-parse every file.

    Runs the blocking full_build / incremental_update work in a thread
    via ``asyncio.to_thread`` so the stdio event loop stays responsive.
    Without this wrapper, long builds deadlocked on Windows because
    ``ProcessPoolExecutor`` (used by parallel parsing) interacted badly
    with the sync handler blocking the only event-loop thread. See:
    #46, #136.

    Args:
        full_rebuild: If True, re-parse all files. Default: False (incremental).
        repo_root: Repository root path. Auto-detected from current directory if omitted.
        base: Git ref to diff against for incremental updates. Default: HEAD~1.
        postprocess: Post-processing level: "full" (default), "minimal" (signatures+FTS only),
                     or "none" (skip all post-processing). Use "minimal" for faster builds.
        recurse_submodules: If True, include files from git submodules.
            When None (default), falls back to CRG_RECURSE_SUBMODULES env var.
    full_rebuildr.   basepostprocessrecurse_submodulesN)asyncio	to_threadr   r0   r4   s        r/   build_or_update_graph_toolr;   V   s<     < ""!$Y/-   s   ,535c           	     l   K   t        j                  t        | ||t        |             d{   S 7 w)a[  Run post-processing on existing graph (flows, communities, FTS index).

    Use after building with postprocess="none" or "minimal", or to re-run
    expensive steps independently. Signatures are always computed.

    Offloaded to a thread via ``asyncio.to_thread`` so community
    detection on large graphs doesn't block the MCP event loop. See:
    #46, #136.

    Args:
        flows: Run flow detection. Default: True.
        communities: Run community detection. Default: True.
        fts: Rebuild FTS index. Default: True.
        repo_root: Repository root path. Auto-detected if omitted.
    flowscommunitiesftsr.   N)r9   r:   r(   r0   r=   s       r/   run_postprocess_toolrA   ~   s7     , ""#$Y/   s   +424c                2    t        | |t        |      |      S )aJ  Get ultra-compact context for any task (~100 tokens). Always call this first.

    Returns graph stats, risk score, top communities/flows, and suggested
    next tools in a single compact response. Use this as the entry point
    before any other graph tool to minimize token usage.

    Args:
        task: What you are doing (e.g. "review PR #42", "debug login timeout").
        changed_files: Explicit list of changed files. Auto-detected if omitted.
        repo_root: Repository root path. Auto-detected if omitted.
        base: Git ref for diff comparison. Default: HEAD~1.
    taskchanged_filesr.   r6   )r   r0   rC   s       r/   get_minimal_context_toolrF      s     & $Y/d r1   c                4    t        | |t        |      ||      S )an  Analyze the blast radius of changed files in the codebase.

    Shows which functions, classes, and files are impacted by changes.
    Auto-detects changed files from git if not specified.

    Args:
        changed_files: List of changed file paths (relative to repo root). Auto-detected if omitted.
        max_depth: Number of hops to traverse in the dependency graph. Default: 2.
        repo_root: Repository root path. Auto-detected if omitted.
        base: Git ref for auto-detecting changes. Default: HEAD~1.
        detail_level: "standard" for full output, "minimal" for compact summary. Default: standard.
    rE   	max_depthr.   r6   detail_level)r   r0   rH   s        r/   get_impact_radius_toolrK      s"    ( #y$Y/d r1   c                2    t        | |t        |      |      S )a  Run a predefined graph query to explore code relationships.

    Available patterns:
    - callers_of: Find functions that call the target
    - callees_of: Find functions called by the target
    - imports_of: Find what the target imports
    - importers_of: Find files that import the target
    - children_of: Find nodes contained in a file or class
    - tests_for: Find tests for the target
    - inheritors_of: Find classes inheriting from the target
    - file_summary: Get all nodes in a file

    Args:
        pattern: Query pattern name (see above).
        target: Node name, qualified name, or file path to query.
        repo_root: Repository root path. Auto-detected if omitted.
        detail_level: "standard" for full output, "minimal" for compact summary. Default: standard.
    patterntargetr.   rJ   )r&   r0   rM   s       r/   query_graph_toolrP      s!    2 2DY2O! r1   c           	     8    t        | |||t        |      ||      S )a  Generate a focused, token-efficient review context for code changes.

    Combines impact analysis with source snippets and review guidance.
    Use this for comprehensive code reviews.

    Args:
        changed_files: Files to review. Auto-detected from git diff if omitted.
        max_depth: Impact radius depth. Default: 2.
        include_source: Include source code snippets. Default: True.
        max_lines_per_file: Max source lines per file. Default: 200.
        repo_root: Repository root path. Auto-detected if omitted.
        base: Git ref for change detection. Default: HEAD~1.
        detail_level: "standard" for full output, "minimal" for
            token-efficient summary. Default: standard.
    rE   rI   include_sourcemax_lines_per_filer.   r6   rJ   )r   r0   rR   s          r/   get_review_context_toolrU      s(    2 #y%:L$Y/d r1   c                6    t        | ||t        |      ||      S )a  Search for code entities by name, keyword, or semantic similarity.

    Uses vector embeddings for semantic search when available (run embed_graph_tool
    first, requires sentence-transformers). Falls back to keyword matching otherwise.

    Args:
        query: Search string to match against node names.
        kind: Optional filter: File, Class, Function, Type, or Test.
        limit: Maximum results. Default: 20.
        repo_root: Repository root path. Auto-detected if omitted.
        model: Embedding model for query vectors. Must match the model used
               during embed_graph. Falls back to CRG_EMBEDDING_MODEL env var,
               then all-MiniLM-L6-v2.
        detail_level: "standard" for full output, "minimal" for compact summary. Default: standard.
    querykindlimitr.   modelrJ   )r)   r0   rW   s         r/   semantic_search_nodes_toolr\     s&    0 !$e7I)7T\a! r1   c                h   K   t        j                  t        t        |       |       d{   S 7 w)u  Compute vector embeddings for all graph nodes to enable semantic search.

    Requires: pip install code-review-graph[embeddings]
    Default model: all-MiniLM-L6-v2. Override via `model` param or
    CRG_EMBEDDING_MODEL env var (any sentence-transformers compatible model).
    Changing the model re-embeds all nodes automatically.

    After running this, semantic_search_nodes_tool will use vector similarity
    instead of keyword matching for much better results.

    Runs the blocking sentence-transformers / Gemini inference in a
    thread via ``asyncio.to_thread`` so the stdio event loop stays
    responsive — without this wrapper, embedding a large graph would
    silently hang the MCP server on Windows. See: #46, #136.

    Args:
        repo_root: Repository root path. Auto-detected if omitted.
        model: Embedding model name (HuggingFace ID or local path).
               Falls back to CRG_EMBEDDING_MODEL env var, then all-MiniLM-L6-v2.
    r.   r[   N)r9   r:   r   r0   r^   s     r/   embed_graph_toolr_   +  s3     2 ""$Y/      )202c                ,    t        t        |             S )a  Get aggregate statistics about the code knowledge graph.

    Shows total nodes, edges, languages, files, and last update time.
    Useful for checking if the graph is built and up to date.

    Args:
        repo_root: Repository root path. Auto-detected if omitted.
    r-   )r$   r0   r-   s    r/   list_graph_stats_toolrb   K  s     &8&CDDr1   c                $    t        | t              S )a  Get a specific section from the LLM-optimized documentation reference.

    Returns only the requested section content for minimal token usage.
    Use this before answering any user question about the plugin.

    Available sections: usage, review-delta, review-pr, commands, legal,
    watch, embeddings, languages, troubleshooting.

    Args:
        section_name: The section to retrieve (e.g. "review-delta", "usage").
    )section_namer.   )r   r+   )rd   s    r/   get_docs_section_toolre   Z  s     ASTTr1   c           	     4    t        | |||t        |            S )a  Find functions, classes, or files exceeding a line-count threshold.

    Useful for decomposition audits, code quality checks, and enforcing
    size limits during code review. Results are ordered by line count.

    Args:
        min_lines: Minimum line count to flag. Default: 50.
        kind: Optional filter: Function, Class, File, or Test.
        file_path_pattern: Filter by file path substring (e.g. "components/").
        limit: Maximum results. Default: 50.
        repo_root: Repository root path. Auto-detected if omitted.
    	min_linesrY   file_path_patternrZ   r.   )r   r0   rg   s        r/   find_large_functions_toolrj   l  s$    (  $:K1)< r1   c                4    t        t        |      | |||      S )a  List execution flows in the codebase, sorted by criticality.

    Each flow represents a call chain starting from an entry point
    (HTTP handler, CLI command, test function, etc.). Use this to
    understand the main execution paths through the codebase.

    Args:
        sort_by: Sort column: criticality, depth, node_count, file_count, or name.
        limit: Maximum flows to return. Default: 50.
        kind: Optional filter by entry point kind (e.g. "Test", "Function").
        detail_level: "standard" (default) returns full flow data; "minimal"
                      returns only name, criticality, and node_count per flow.
        repo_root: Repository root path. Auto-detected if omitted.
    )r.   sort_byrZ   rY   rJ   )r#   r0   )rl   rZ   rY   rJ   r.   s        r/   list_flows_toolrm     s#    , $Y/TX! r1   c                2    t        | ||t        |            S )a@  Get detailed information about a single execution flow.

    Returns the full call path with each step's function name, file, and
    line numbers. Optionally includes source code snippets for each step.

    Provide either flow_id (from list_flows_tool) or flow_name to search by name.

    Args:
        flow_id: Database ID of the flow.
        flow_name: Name to search for (partial match). Ignored if flow_id given.
        include_source: Include source code snippets for each step. Default: False.
        repo_root: Repository root path. Auto-detected if omitted.
    flow_id	flow_namerS   r.   )r   r0   ro   s       r/   get_flow_toolrr     s!    ( 9%1CI1N r1   c                0    t        | |t        |            S )a  Find execution flows affected by changed files.

    Identifies which execution flows pass through nodes in the changed files.
    Useful during code review to understand which user-facing or critical paths
    are impacted by a change. Auto-detects changed files from git if not specified.

    Args:
        changed_files: List of changed file paths (relative to repo root). Auto-detected if omitted.
        base: Git ref for auto-detecting changes. Default: HEAD~1.
        repo_root: Repository root path. Auto-detected if omitted.
    rE   r6   r.   )r   r0   rt   s      r/   get_affected_flows_toolru     s    " ##$:LY:W r1   c                2    t        t        |      | ||      S )a  List detected code communities in the codebase.

    Each community represents a cluster of related code entities (functions,
    classes) detected via the Leiden algorithm or file-based grouping.
    Use this to understand the high-level structure of the codebase.

    Args:
        sort_by: Sort column: size, cohesion, or name.
        min_size: Minimum community size to include. Default: 0.
        detail_level: "standard" (default) returns full community data;
                      "minimal" returns only name, size, and cohesion
                      per community.
        repo_root: Repository root path. Auto-detected if omitted.
    )r.   rl   min_sizerJ   )r"   r0   )rl   rw   rJ   r.   s       r/   list_communities_toolrx     s     * !$Y/8! r1   c                2    t        | ||t        |            S )ad  Get detailed information about a single code community.

    Returns community metadata including size, cohesion, dominant language,
    and member list. Optionally includes full node details for each member.

    Provide either community_id (from list_communities_tool) or community_name
    to search by name.

    Args:
        community_name: Name to search for (partial match). Ignored if community_id given.
        community_id: Database ID of the community.
        include_members: Include full member node details. Default: False.
        repo_root: Repository root path. Auto-detected if omitted.
    community_namecommunity_idinclude_membersr.   )r   r0   rz   s       r/   get_community_toolr~     s!    * %L'3Ei3P r1   c                ,    t        t        |             S )aN  Generate an architecture overview based on community structure.

    Builds a high-level view of the codebase architecture by analyzing
    community boundaries and cross-community coupling. Includes warnings
    for high coupling between communities.

    Args:
        repo_root: Repository root path. Auto-detected if omitted.
    r-   )r   r0   r-   s    r/   get_architecture_overview_toolr     s     *4Fy4QRRr1   c           
     p   K   t        j                  t        | |||t        |      |       d{   S 7 w)u  Detect changes and produce risk-scored, priority-ordered review guidance.

    Primary tool for code review. Maps git diffs to affected functions,
    flows, communities, and test coverage gaps. Returns risk scores and
    prioritized review items. Replaces get_review_context for change-aware reviews.

    Offloaded to a thread via ``asyncio.to_thread`` — runs `git diff`
    subprocesses and BFS traversals that can take several seconds on
    large repos. See: #46, #136.

    Args:
        base: Git ref to diff against. Default: HEAD~1.
        changed_files: List of changed file paths (relative to repo root). Auto-detected if omitted.
        include_source: Include source code snippets for changed functions. Default: False.
        max_depth: Impact radius depth for BFS traversal. Default: 2.
        repo_root: Repository root path. Auto-detected if omitted.
        detail_level: "standard" for full output, "minimal" for
            token-efficient summary. Default: standard.
    r6   rE   rS   rI   r.   rJ   N)r9   r:   r   r0   r   s         r/   detect_changes_toolr     s<     8 ""%$Y/l	   s   -646c           
     6    t        | ||||t        |            S )a  Graph-powered refactoring operations.

    Unified entry point for rename previews, dead code detection, and
    refactoring suggestions.

    Modes:
    - rename: Preview renaming a symbol. Returns an edit list and a refactor_id
      to pass to apply_refactor_tool. Requires old_name and new_name.
    - dead_code: Find unreferenced functions/classes (no callers, tests, or
      importers, and not entry points).
    - suggest: Get community-driven refactoring suggestions (move misplaced
      functions, remove dead code).

    Args:
        mode: Operation mode: "rename", "dead_code", or "suggest".
        old_name: (rename) Current symbol name to rename.
        new_name: (rename) Desired new name for the symbol.
        kind: (dead_code) Optional filter: Function or Class.
        file_pattern: (dead_code) Filter by file path substring.
        repo_root: Repository root path. Auto-detected if omitted.
    modeold_namenew_namerY   file_patternr.   )r'   r0   r   s         r/   refactor_toolr   <  s%    < Hx8J98U r1   c                0    t        | t        |      |      S )a[  Apply a previously previewed refactoring to source files.

    Takes a refactor_id from a prior refactor_tool(mode="rename") call and
    applies the exact string replacements to the target files. Previews
    expire after 10 minutes.

    Security: All edit paths are validated to be within the repo root.
    Only exact string replacements are performed (no regex, no eval).

    Args:
        refactor_id: The refactor ID from refactor_tool's response.
        repo_root: Repository root path. Auto-detected if omitted.
        dry_run: If True, return a unified diff of what would change
            without touching any files. The refactor_id remains valid so
            the same preview can be applied in a follow-up call without
            dry_run. Use this for a human-in-the-loop review before
            committing changes to disk. See: #176
    refactor_idr.   dry_run)r   r0   r   s      r/   apply_refactor_toolr   `  s    0 +=i+H r1   c                h   K   t        j                  t        t        |       |       d{   S 7 w)u  Generate a markdown wiki from the code community structure.

    Creates a wiki page for each detected community and an index page.
    Pages are written to .code-review-graph/wiki/ inside the repository.
    Only regenerates pages whose content has changed unless force=True.

    Offloaded to a thread via ``asyncio.to_thread`` — on large graphs
    the page-generation loop touches every community and issues many
    SQLite reads, which would block the MCP event loop. See: #46, #136.

    Args:
        repo_root: Repository root path. Auto-detected if omitted.
        force: If True, regenerate all pages even if content unchanged. Default: False.
    r.   forceN)r9   r:   r   r0   r   s     r/   generate_wiki_toolr   ~  s3     & ""$Y/   r`   c                .    t        | t        |            S )aF  Retrieve a specific wiki page by community name.

    Returns the markdown content of the wiki page for the given community.
    The wiki must have been generated first via generate_wiki_tool.

    Args:
        community_name: Community name to look up.
        repo_root: Repository root path. Auto-detected if omitted.
    r{   r.   )r    r0   r   s     r/   get_wiki_page_toolr     s     %1CI1N r1   c                .    t        t        |      |       S )a`  Find the most connected nodes in the codebase (architectural hotspots).

    Hub nodes have the highest total degree (in + out edges). Changes to
    them have disproportionate blast radius. Excludes File nodes.

    Args:
        top_n: Number of top hubs to return. Default: 10.
        repo_root: Repository root path. Auto-detected if omitted.
    r.   top_n)r   r0   r   r.   s     r/   get_hub_nodes_toolr     s     $Y/u r1   c                .    t        t        |      |       S )a  Find architectural chokepoints via betweenness centrality.

    Bridge nodes sit on shortest paths between many node pairs.
    If they break, multiple code regions lose connectivity.
    Uses sampling approximation for graphs > 5000 nodes.

    Args:
        top_n: Number of top bridges to return. Default: 10.
        repo_root: Repository root path. Auto-detected if omitted.
    r   )r   r0   r   s     r/   get_bridge_nodes_toolr     s     !$Y/u r1   c                ,    t        t        |             S )a4  Identify structural weaknesses in the codebase graph.

    Finds isolated nodes (disconnected), thin communities (< 3 members),
    untested hotspots (high-degree nodes without test coverage), and
    single-file communities.

    Args:
        repo_root: Repository root path. Auto-detected if omitted.
    r-   )r   r0   r-   s    r/   get_knowledge_gaps_toolr     s     #$Y/ r1   c                .    t        t        |      |       S )a|  Find unexpected architectural coupling via composite surprise scoring.

    Scores edges by: cross-community (+0.3), cross-language (+0.2),
    peripheral-to-hub (+0.2), cross-test-boundary (+0.15), and
    unusual edge kinds (+0.15).

    Args:
        top_n: Number of top surprises to return. Default: 15.
        repo_root: Repository root path. Auto-detected if omitted.
    r   )r   r0   r   s     r/   get_surprising_connections_toolr     s     +$Y/u r1   c                ,    t        t        |             S )a7  Auto-generate review questions from graph analysis.

    Produces prioritized questions about: bridge nodes needing tests,
    untested hub nodes, surprising cross-community coupling, thin
    communities, and untested hotspots.

    Args:
        repo_root: Repository root path. Auto-detected if omitted.
    r-   )r   r0   r-   s    r/   get_suggested_questions_toolr     s     ($Y/ r1   c           	     <    t        | |||t        |      xs d      S )a}  BFS/DFS traversal from best-matching node with token budget.

    Free-form graph exploration: finds the node best matching your
    query, then traverses outward via BFS or DFS up to the given
    depth, collecting connected nodes within the token budget.

    Args:
        query: Search string to find the starting node.
        mode: Traversal mode: "bfs" (breadth-first) or "dfs"
            (depth-first). Default: bfs.
        depth: Max traversal depth (1-6). Default: 3.
        token_budget: Approximate token limit for results.
            Default: 2000.
        repo_root: Repository root path. Auto-detected if omitted.
     rX   r   depthtoken_budgetr.   )r!   r0   r   s        r/   traverse_graph_toolr   
  s(    . $e!$Y/52 r1   c                     t               S )zList all registered repositories in the multi-repo registry.

    Returns the list of repos registered at ~/.code-review-graph/registry.json.
    Use the CLI 'register' command to add repos.
    )r%    r1   r/   list_repos_toolr   (  s     r1   c                    t        | ||      S )a  Search for code entities across all registered repositories.

    Runs hybrid search on each registered repo's graph database and merges
    the results by score. Register repos first with the CLI 'register' command.

    Args:
        query: Search string to match against node names.
        kind: Optional filter: File, Class, Function, Type, or Test.
        limit: Maximum results per repo. Default: 20.
    rX   rY   rZ   )r   r   s      r/   cross_repo_search_toolr   2  s      "DFFr1   c                    t        |       S )zPre-commit review workflow using detect_changes, affected_flows, and test gaps.

    Produces a structured code review with risk levels and actionable findings.

    Args:
        base: Git ref to diff against. Default: HEAD~1.
    r6   )r   r   s    r/   review_changesr   E  s     !d++r1   c                     t               S )zArchitecture documentation using communities, flows, and Mermaid diagrams.

    Generates a comprehensive architecture map with module summaries and coupling warnings.
    )r   r   r1   r/   architecture_mapr   Q  s     #$$r1   c                    t        |       S )zGuided debugging using search, flow tracing, and recent changes.

    Systematic debugging workflow that traces execution paths and identifies root causes.

    Args:
        description: Description of the issue to debug.
    description)r   r   s    r/   debug_issuer   Z  s     +66r1   c                     t               S )zNew developer orientation using stats, architecture, and critical flows.

    Creates an onboarding guide covering codebase structure, key modules, and patterns.
    )r	   r   r1   r/   onboard_developerr   f  s     $%%r1   c                    t        |       S )zPR readiness check with risk scoring, test gaps, and dead code detection.

    Produces a merge readiness report with risk assessment and recommendations.

    Args:
        base: Git ref to diff against. Default: HEAD~1.
    r   )r
   r   s    r/   pre_merge_checkr   o  s     "t,,r1   c                    | a t        j                  dk(  r%ddl} |j                   |j
                                t        j                  d       y)u  Run the MCP server via stdio.

    On Windows, Python 3.8+ defaults to ``ProactorEventLoop``, which
    interacts poorly with ``concurrent.futures.ProcessPoolExecutor``
    (used by ``full_build``) over a stdio MCP transport — the combination
    produces silent hangs on ``build_or_update_graph_tool`` and
    ``embed_graph_tool``. Switching to ``WindowsSelectorEventLoopPolicy``
    before fastmcp starts its loop avoids the deadlock.
    See: #46, #136
    win32r   Nstdio)	transport)r+   sysplatformr9   set_event_loop_policyWindowsSelectorEventLoopPolicymcprun)r.   r9   s     r/   mainr   {  sC     #
||w%%%&Lg&L&L&NOGGgGr1   __main__)r.   Optional[str]returnr   )FNHEAD~1fullN)r5   boolr.   r   r6   strr7   r   r8   zOptional[bool]r   dict)TTTN)
r>   r   r?   r   r@   r   r.   r   r   r   )r   NNr   )
rD   r   rE   Optional[list[str]]r.   r   r6   r   r   r   )N   Nr   standard)rE   r   rI   intr.   r   r6   r   rJ   r   r   r   )Nr   )
rN   r   rO   r   r.   r   rJ   r   r   r   )Nr   T   Nr   r   )rE   r   rI   r   rS   r   rT   r   r.   r   r6   r   rJ   r   r   r   )N   NNr   )rX   r   rY   r   rZ   r   r.   r   r[   r   rJ   r   r   r   )NN)r.   r   r[   r   r   r   )N)r.   r   r   r   )rd   r   r   r   )2   NNr   N)rh   r   rY   r   ri   r   rZ   r   r.   r   r   r   )criticalityr   Nr   N)rl   r   rZ   r   rY   r   rJ   r   r.   r   r   r   )NNFN)
rp   Optional[int]rq   r   rS   r   r.   r   r   r   )Nr   N)rE   r   r6   r   r.   r   r   r   )sizer   r   N)
rl   r   rw   r   rJ   r   r.   r   r   r   )
r{   r   r|   r   r}   r   r.   r   r   r   )r   NFr   Nr   )r6   r   rE   r   rS   r   rI   r   r.   r   rJ   r   r   r   )renameNNNNN)r   r   r   r   r   r   rY   r   r   r   r.   r   r   r   )NF)r   r   r.   r   r   r   r   r   )r.   r   r   r   r   r   )r{   r   r.   r   r   r   )
   N)r   r   r.   r   r   r   )   N)bfs   i  N)rX   r   r   r   r   r   r   r   r.   r   r   r   )r   r   )Nr   )rX   r   rY   r   rZ   r   r   r   )r   )r6   r   r   
list[dict])r   r   )r   )r   r   r   r   )r.   r*   r   None)Y__doc__
__future__r   r9   r   typingr   fastmcpr   promptsr   r   r	   r
   r   toolsr   r   r   r   r   r   r   r   r   r   r   r   r   r   r   r   r   r   r   r   r    r!   r"   r#   r$   r%   r&   r'   r(   r)   r+   __annotations__r0   r   toolr;   rA   rF   rK   rP   rU   r\   r_   rb   re   rj   rm   rr   ru   rx   r~   r   r   r   r   r   r   r   r   r   r   r   r   r   r   promptr   r   r   r   r   r   __name__r   r1   r/   <module>r      s	   #  
          F "& J %:  	I #)-$$$ $ 	$
 '$ 
$ $N #	 
 	
 
 8 )-#	
&  	
 
 0 )-#"&  	
  
 2   $"	  	
 
 < )-!#"&  	
    
 >  #"
  	
   
 : # 
 > #EE	E E UU	U U" '+#
 % 	
  
 2  "#  	
  
 6 !# #	  	
 
 2 )-#&
  
	 * "#	  	
 
 4 $("&!#	!  	
 
 4 #SS	S S )- #" 
 &    	 
     
   F """&# 
     	 
      
   F   $  
	 : # 
 2   $ 
 $ # 
 $ # 
 & #	 " # 
 & #	 "  #
  	
  
 :    GG
G G 
	G G$ , , % % 7 7 & & - -& zF r1   