mcpField
G
grepai-trace-graph

grepai-trace-graph

github.com/yoanbernabeu开发20813 次安装38 周前更新
代码仓库

关于 grepai-trace-graph

该技能介绍如何用 GrepAI 的 `trace graph` 递归生成函数调用依赖图,适合分析代码流程、依赖和重构影响,并可控制深度及导出数据。

主要功能

  1. 01递归构建函数调用图
  2. 02设置图的递归深度
  3. 03选择快速或精准提取模式
  4. 04以 JSON 或 TOON 输出结果
  5. 05检测并标记循环依赖

适用场景

  1. 01梳理应用启动和代码流程
  2. 02评估函数变更的影响范围
  3. 03为重构或代码审查分析依赖
  4. 04导出图数据生成架构图

MCP 相关

GrepAI MCP 服务提供 `grepai_trace_graph` 工具,可通过 `symbol`、`depth` 和 `format` 参数生成调用图。

安装

复制下面的命令,在终端中运行。

$npx skills add https://github.com/yoanbernabeu/grepai-skills --skill grepai-trace-graph

安装后在 Claude Code 中输入/grepai-trace-graph确认已加载。

详细介绍

GrepAI Trace Graph

本技能介绍如何使用 grepai trace graph 递归构建完整的调用图,展示所有依赖关系。

何时使用此技能

  • 映射完整的函数依赖关系
  • 理解复杂的代码流
  • 分析重大重构的影响
  • 可视化应用架构

什么是 Trace Graph?

grepai trace graph 会构建递归依赖树:

main
├── initialize
│   ├── loadConfig
│   │   └── parseYAML
│   └── connectDB
│       ├── createPool
│       └── ping
├── startServer
│   ├── registerRoutes
│   │   ├── authMiddleware
│   │   └── loggingMiddleware
│   └── listen
└── gracefulShutdown
    └── closeDB

基本用法

grepai trace graph "FunctionName"
示例
grepai trace graph "main"

输出:

🔍 Call Graph for "main"

main
├── initialize
│   ├── loadConfig
│   └── connectDB
├── startServer
│   ├── registerRoutes
│   └── listen
└── gracefulShutdown
    └── closeDB

Nodes: 9
Max depth: 3

深度控制

使用 --depth 限制递归深度:

# Default depth (2 levels)
grepai trace graph "main"

# Deeper analysis (3 levels)
grepai trace graph "main" --depth 3

# Shallow (1 level, same as callees)
grepai trace graph "main" --depth 1

# Very deep (5 levels)
grepai trace graph "main" --depth 5
深度示例

--depth 1(与 callees 相同):

main
├── initialize
├── startServer
└── gracefulShutdown

--depth 2(默认值):

main
├── initialize
│   ├── loadConfig
│   └── connectDB
├── startServer
│   ├── registerRoutes
│   └── listen
└── gracefulShutdown
    └── closeDB

--depth 3:

main
├── initialize
│   ├── loadConfig
│   │   └── parseYAML
│   └── connectDB
│       ├── createPool
│       └── ping
├── startServer
│   ├── registerRoutes
│   │   ├── authMiddleware
│   │   └── loggingMiddleware
│   └── listen
└── gracefulShutdown
    └── closeDB

JSON 输出

grepai trace graph "main" --depth 2 --json

输出:

{
  "query": "main",
  "mode": "graph",
  "depth": 2,
  "root": {
    "name": "main",
    "file": "cmd/main.go",
    "line": 10,
    "children": [
      {
        "name": "initialize",
        "file": "cmd/main.go",
        "line": 15,
        "children": [
          {
            "name": "loadConfig",
            "file": "config/config.go",
            "line": 20,
            "children": []
          },
          {
            "name": "connectDB",
            "file": "db/db.go",
            "line": 30,
            "children": []
          }
        ]
      },
      {
        "name": "startServer",
        "file": "server/server.go",
        "line": 25,
        "children": [
          {
            "name": "registerRoutes",
            "file": "server/routes.go",
            "line": 10,
            "children": []
          }
        ]
      }
    ]
  },
  "stats": {
    "nodes": 6,
    "max_depth": 2
  }
}

紧凑 JSON

grepai trace graph "main" --depth 2 --json --compact

输出:

{
  "q": "main",
  "d": 2,
  "r": {
    "n": "main",
    "c": [
      {"n": "initialize", "c": [{"n": "loadConfig"}, {"n": "connectDB"}]},
      {"n": "startServer", "c": [{"n": "registerRoutes"}]}
    ]
  },
  "s": {"nodes": 6, "depth": 2}
}

TOON 输出(v0.26.0+)

TOON 格式比 JSON 少约 50% 的令牌:

grepai trace graph "main" --depth 2 --toon

注意: --json 和 --toon 不能同时使用。

提取模式

# Fast mode (regex-based)
grepai trace graph "main" --mode fast

# Precise mode (tree-sitter AST)
grepai trace graph "main" --mode precise

使用场景

理解应用流程
# Map entire application startup
grepai trace graph "main" --depth 4
影响分析
# What depends on this utility function?
grepai trace graph "validateInput" --depth 3

# Full impact of changing database layer
grepai trace graph "executeQuery" --depth 2
代码审查
# Is this function too complex?
grepai trace graph "processOrder" --depth 5
# Many nodes = high complexity
文档编写
# Generate architecture diagram data
grepai trace graph "main" --depth 3 --json > architecture.json
重构规划
# What would break if we change this?
grepai trace graph "legacyAuth" --depth 3

处理循环依赖

GrepAI 会检测并标记循环依赖:

main
├── processA
│   └── processB
│       └── processA [CYCLE]

在 JSON 中:

{
  "name": "processA",
  "cycle": true
}

大型图

对于非常大的代码库,图可能会过于庞大:

限制深度
# Start shallow
grepai trace graph "main" --depth 2
聚焦特定区域
# Instead of main, trace specific subsystem
grepai trace graph "authMiddleware" --depth 3
在后处理中筛选
# Get JSON and filter
grepai trace graph "main" --depth 3 --json | jq '...'

可视化图

导出为 DOT 格式(Graphviz)
# Convert JSON to DOT
grepai trace graph "main" --depth 3 --json | python3 << 'EOF'
import json
import sys

data = json.load(sys.stdin)

print("digraph G {")
print("  rankdir=TB;")

def traverse(node, parent=None):
    name = node.get('name') or node.get('n')
    if parent:
        print(f'  "{parent}" -> "{name}";')
    children = node.get('children') or node.get('c') or []
    for child in children:
        traverse(child, name)

traverse(data.get('root') or data.get('r'))
print("}")
EOF

然后渲染:

dot -Tpng graph.dot -o graph.png
Mermaid 图表
grepai trace graph "main" --depth 2 --json | python3 << 'EOF'
import json
import sys

data = json.load(sys.stdin)

print("```mermaid")
print("graph TD")

def traverse(node, parent=None):
    name = node.get('name') or node.get('n')
    if parent:
        print(f"  {parent} --> {name}")
    children = node.get('children') or node.get('c') or []
    for child in children:
        traverse(child, name)

traverse(data.get('root') or data.get('r'))
print("```")
EOF

比较图的大小

跟踪复杂度随时间的变化:

# Get node count
grepai trace graph "main" --depth 3 --json | jq '.stats.nodes'

# Compare before/after refactoring
echo "Before: $(grepai trace graph 'main' --depth 3 --json | jq '.stats.nodes') nodes"
# ... refactoring ...
echo "After: $(grepai trace graph 'main' --depth 3 --json | jq '.stats.nodes') nodes"

常见问题

❌ 问题: 图过大/超时 ✅ 解决方案:

  • 降低深度:--depth 2
  • 跟踪特定函数,而不是 main
  • 使用 --mode fast

❌ 问题: 检测到许多循环依赖 ✅ 解决方案: 这表明代码中存在循环依赖。请考虑重构。

❌ 问题: 缺少分支 ✅ 解决方案:

  • 尝试 --mode precise
  • 检查文件是否已编入索引
  • 确认已启用相应语言

最佳实践

  1. 从浅层开始: 先使用 --depth 2,再按需增加深度
  2. 聚焦分析: 跟踪特定函数,不要总是跟踪 main
  3. 导出用于文档: 使用 JSON 生成图表
  4. 持续跟踪: 将节点数量作为复杂度指标进行监控
  5. 调查循环依赖: 循环依赖是代码异味

输出格式

Trace graph 结果:

🔍 Call Graph for "main"

Depth: 3
Mode: fast

main
├── initialize
│   ├── loadConfig
│   │   └── parseYAML
│   └── connectDB
│       ├── createPool
│       └── ping
├── startServer
│   ├── registerRoutes
│   │   ├── authMiddleware
│   │   └── loggingMiddleware
│   └── listen
└── gracefulShutdown
    └── closeDB

Statistics:
- Total nodes: 12
- Maximum depth reached: 3
- Cycles detected: 0

Tip: Use --json for machine-readable output
     Use --depth N to control recursion depth

评论

支持 Markdown