Serena: Symbol-Level Code Understanding
Serena:符号级代码理解
Navigate and manipulate code at the symbol level using IDE-like semantic analysis powered by Language Server Protocol (LSP).
借助Language Server Protocol(LSP)提供的类IDE语义分析功能,在符号级别导航和操作代码。
How You Can Access Serena
如何使用Serena
You may have Serena available in one or both of these ways:
Option 1: Direct MCP Tools (if configured by your orchestrator)
Check your available tools for:
- , - Symbol lookup
- , - Refactoring
- , - Precise insertions
- , - Project understanding
- , - Save context
- And 25+ more LSP-powered tools
If you see these tools, use them directly - they provide full Serena capabilities!
Option 2: CLI Commands (always available via execute_command)
You can run serena commands using:
bash
execute_command("uvx --from git+https://github.com/oraios/serena serena <command>")
This skill focuses on CLI usage patterns. If you have direct MCP tools, prefer those for better integration.
你可以通过以下一种或两种方式使用Serena:
选项1:直接使用MCP工具(若由编排器配置)
检查可用工具,看是否包含:
- 、 - 符号查找
- 、 - 重构
- 、 - 精准插入
- 、 - 项目理解
- 、 - 保存上下文
- 以及25+种更多基于LSP的工具
如果你看到这些工具,可以直接使用它们——它们提供完整的Serena功能!
选项2:CLI命令(始终可通过execute_command使用)
你可以使用以下命令运行serena命令:
bash
execute_command("uvx --from git+https://github.com/oraios/serena serena <command>")
本Skill重点介绍CLI使用模式。如果你可以直接使用MCP工具,优先使用它们以获得更好的集成效果。
The serena skill provides access to Serena, a coding agent toolkit that transforms text-based LLMs into symbol-aware code agents. Unlike traditional text search (ripgrep) or structural search (ast-grep), Serena understands code semantics through LSP integration.
Key capabilities:
- Symbol Discovery: Find classes, functions, variables, and types by name across 30+ languages
- Reference Tracking: Discover all locations where a symbol is referenced or used
- Precise Editing: Insert code at specific symbol locations with surgical precision
Serena operates at the symbol level rather than the text or syntax level, providing true IDE-like understanding of code structure, scope, and relationships.
Serena Skill可让你使用Serena——一个将基于文本的大语言模型转换为符号感知代码Agent的工具包。与传统的文本搜索(ripgrep)或结构搜索(ast-grep)不同,Serena通过LSP集成理解代码语义。
核心功能:
- 符号发现:在30+种语言中按名称查找类、函数、变量和类型
- 引用追踪:发现符号被引用或使用的所有位置
- 精准编辑:在特定符号位置精准插入代码
Serena在符号级别而非文本或语法级别运行,提供对代码结构、作用域和关系的真正类IDE理解。
When to Use This Skill
何时使用本Skill
Use the serena skill when you need symbol-level code understanding:
Code Navigation:
- Finding where a class, function, or variable is defined
- Discovering all places where a symbol is used (call sites, imports, references)
- Understanding code dependencies and relationships
- Tracing execution flow through function calls
Code Understanding:
- Analyzing impact of changes to a function or class
- Understanding inheritance hierarchies and type relationships
- Identifying dead code (symbols never referenced)
- Mapping API usage patterns across a codebase
Code Refactoring:
- Renaming symbols while tracking all usage locations
- Adding methods or fields to specific classes
- Inserting error handling after specific function calls
- Modifying all call sites of a deprecated function
Choose serena over file-search (ripgrep/ast-grep) when:
- You need to understand symbol semantics (not just text patterns)
- You want to track references across files and modules
- You need precise insertion points based on code structure
- You're working with complex, multi-file codebases
Still use file-search when:
- Searching for text patterns, comments, or strings
- Finding todos, security issues, or documentation
- You need faster, simpler pattern matching
- Symbol-level precision isn't required
当你需要符号级代码理解时,使用Serena Skill:
代码导航:
- 查找类、函数或变量的定义位置
- 发现符号被使用的所有位置(调用点、导入、引用)
- 理解代码依赖关系
- 通过函数调用追踪执行流程
代码理解:
- 分析修改函数或类带来的影响
- 理解继承层次和类型关系
- 识别死代码(从未被引用的符号)
- 映射代码库中的API使用模式
代码重构:
- 重命名符号同时追踪所有使用位置
- 为特定类添加方法或字段
- 在特定函数调用后插入错误处理
- 修改已弃用函数的所有调用点
选择Serena而非文件搜索工具(ripgrep/ast-grep)的场景:
- 你需要理解符号语义(而非仅文本模式)
- 你想要跨文件和模块追踪引用
- 你需要基于代码结构的精准插入点
- 你正在处理复杂的多文件代码库
仍需使用文件搜索工具的场景:
- 搜索文本模式、注释或字符串
- 查找TODO、安全问题或文档
- 你需要更快速、简单的模式匹配
- 不需要符号级精准度
Serena uses LSP servers for semantic analysis. Most common languages are supported out-of-the-box:
- Python (pyright, jedi)
- JavaScript/TypeScript (typescript-language-server)
- Rust (rust-analyzer)
- Go (gopls)
- Java (jdtls)
- C/C++ (clangd)
- C#, Ruby, PHP, Kotlin, Swift, Scala, and 15+ more
The LSP servers provide symbol information for the language you're working with.
Serena使用LSP服务器进行语义分析。大多数常用语言开箱即用:
- Python(pyright、jedi)
- JavaScript/TypeScript(typescript-language-server)
- Rust(rust-analyzer)
- Go(gopls)
- Java(jdtls)
- C/C++(clangd)
- C#、Ruby、PHP、Kotlin、Swift、Scala以及15+种其他语言
LSP服务器会为你正在使用的语言提供符号信息。
Locate where a symbol is defined in your codebase.
Note: All examples below use the short form
. The full command is:
bash
uvx --from git+https://github.com/oraios/serena serena <command>
定位符号在代码库中的定义位置。
bash
uvx --from git+https://github.com/oraios/serena serena <command>
Find a class definition
查找类定义
Find a function definition
查找函数定义
Find a variable definition
查找变量定义
execute_command("uvx --from git+
https://github.com/oraios/serena serena find_symbol --name 'API_KEY' --type variable")
**Use cases:**
- Locating the definition of a class before modifying it
- Finding where a function is implemented
- Understanding where constants are defined
- Tracing type definitions in typed languages
**Output format:**
File: src/services/user_service.py
Line: 42
Symbol: UserService (class)
Context: class UserService(BaseService):
execute_command("uvx --from git+
https://github.com/oraios/serena serena find_symbol --name 'API_KEY' --type variable")
**适用场景:**
- 修改类之前定位其定义
- 查找函数的实现位置
- 理解常量的定义位置
- 在类型化语言中追踪类型定义
**输出格式:**
File: src/services/user_service.py
Line: 42
Symbol: UserService (class)
Context: class UserService(BaseService):
Discover all locations where a symbol is used, imported, or referenced.
Find all usages of a class
查找类的所有用法
execute_command("serena find_referencing_symbols --name 'UserService'")
execute_command("serena find_referencing_symbols --name 'UserService'")
Find all call sites of a function
查找函数的所有调用点
execute_command("serena find_referencing_symbols --name 'authenticate'")
execute_command("serena find_referencing_symbols --name 'authenticate'")
Find all reads/writes of a variable
查找变量的所有读写位置
execute_command("serena find_referencing_symbols --name 'API_KEY'")
**Use cases:**
- Impact analysis before refactoring
- Finding all call sites of a function
- Tracking API usage across modules
- Identifying unused symbols (zero references)
- Understanding data flow and dependencies
**Output format:**
Found 12 references to 'authenticate':
-
src/api/routes.py:34
authenticate(user_credentials)
-
src/middleware/auth.py:18
from services import authenticate
-
tests/test_auth.py:56
mock_authenticate = Mock(spec=authenticate)
...
execute_command("serena find_referencing_symbols --name 'API_KEY'")
**适用场景:**
- 重构前的影响分析
- 查找函数的所有调用点
- 跨模块追踪API使用
- 识别未使用的符号(零引用)
- 理解数据流和依赖关系
**输出格式:**
Found 12 references to 'authenticate':
-
src/api/routes.py:34
authenticate(user_credentials)
-
src/middleware/auth.py:18
from services import authenticate
-
tests/test_auth.py:56
mock_authenticate = Mock(spec=authenticate)
...
3. Precise Code Insertion ()
Insert code at specific symbol locations with surgical precision.
Add a method to a class
为类添加方法
execute_command("""serena insert_after_symbol --name 'UserService' --type class --code '
def get_user_by_email(self, email: str) -> Optional[User]:
return self.db.query(User).filter_by(email=email).first()
'""")
execute_command("""serena insert_after_symbol --name 'UserService' --type class --code '
def get_user_by_email(self, email: str) -> Optional[User]:
return self.db.query(User).filter_by(email=email).first()
'""")
Insert error handling after a function call
在函数调用后插入错误处理
execute_command("""serena insert_after_symbol --name 'database_query' --code '
if result is None:
raise DatabaseError("Query returned no results")
'""")
execute_command("""serena insert_after_symbol --name 'database_query' --code '
if result is None:
raise DatabaseError("Query returned no results")
'""")
Add a field to a dataclass
为数据类添加字段
execute_command("""serena insert_after_symbol --name 'User' --type class --code '
email_verified: bool = False
'""")
**Use cases:**
- Adding methods to existing classes
- Inserting validation or error handling
- Adding fields to data structures
- Injecting logging or monitoring code
- Implementing missing functionality
**Safety features:**
- Respects indentation and code formatting
- Maintains syntactic validity
- Positions code correctly within scope
- Preserves existing code structure
execute_command("""serena insert_after_symbol --name 'User' --type class --code '
email_verified: bool = False
'""")
**适用场景:**
- 为现有类添加方法
- 插入验证或错误处理
- 为数据结构添加字段
- 注入日志或监控代码
- 实现缺失的功能
**安全特性:**
- 遵循缩进和代码格式
- 保持语法有效性
- 在作用域内正确定位代码
- 保留现有代码结构
Pattern 1: Safe Refactoring
模式1:安全重构
When changing a function signature or behavior:
Step 1: Find the function definition
步骤1:查找函数定义
serena find_symbol --name 'process_payment' --type function
serena find_symbol --name 'process_payment' --type function
Step 2: Find all call sites
步骤2:查找所有调用点
serena find_referencing_symbols --name 'process_payment'
serena find_referencing_symbols --name 'process_payment'
Step 3: Analyze impact (review output)
步骤3:分析影响(查看输出)
[Review all usage locations to understand impact]
[查看所有使用位置以理解影响]
Step 4: Make changes with confidence
步骤4:放心修改
[Update function and all call sites based on findings]
[根据发现更新函数和所有调用点]
Pattern 2: Adding Functionality
模式2:添加功能
When extending a class with new methods:
Step 1: Locate the class
步骤1:定位类
serena find_symbol --name 'PaymentProcessor' --type class
serena find_symbol --name 'PaymentProcessor' --type class
Step 2: Verify no conflicts
步骤2:验证无冲突
serena find_symbol --name 'process_refund' --type function
serena find_symbol --name 'process_refund' --type function
Step 3: Insert new method
步骤3:插入新方法
serena insert_after_symbol --name 'PaymentProcessor' --type class --code '
def process_refund(self, payment_id: str, amount: float) -> bool:
# Implementation here
pass
'
serena insert_after_symbol --name 'PaymentProcessor' --type class --code '
def process_refund(self, payment_id: str, amount: float) -> bool:
# 实现代码
pass
'
Pattern 3: Understanding Dependencies
模式3:理解依赖关系
When analyzing code relationships:
Step 1: Find class definition
步骤1:查找类定义
serena find_symbol --name 'DatabaseManager' --type class
serena find_symbol --name 'DatabaseManager' --type class
Step 2: Find all usages
步骤2:查找所有用法
serena find_referencing_symbols --name 'DatabaseManager'
serena find_referencing_symbols --name 'DatabaseManager'
Step 3: For each usage, find what symbols use that code
步骤3:对每个用法,查找使用该代码的符号
[Repeat reference tracking to build dependency graph]
[重复引用追踪以构建依赖图]
Pattern 4: Dead Code Detection
模式4:死代码检测
When identifying unused code:
Step 1: Find symbol definition
步骤1:查找符号定义
serena find_symbol --name 'legacy_auth_handler'
serena find_symbol --name 'legacy_auth_handler'
Step 2: Check references
步骤2:检查引用
serena find_referencing_symbols --name 'legacy_auth_handler'
serena find_referencing_symbols --name 'legacy_auth_handler'
Step 3: If zero references (except definition), mark for removal
步骤3:如果零引用(除定义外),标记为可删除
[If output shows only the definition, symbol is unused]
[如果输出仅显示定义,则该符号未被使用]
Integration with file-search
与文件搜索工具的集成
Serena and file-search (ripgrep/ast-grep) are complementary tools. Use them together:
Serena与文件搜索工具(ripgrep/ast-grep)是互补工具,可以结合使用:
When to Combine Tools
何时结合使用工具
1. Find potential matches with ripgrep (fast, broad)
1. 使用ripgrep快速找到潜在匹配项(快速、范围广)
rg "authenticate" --type py
rg "authenticate" --type py
2. Narrow to specific symbol with serena (precise)
2. 使用Serena缩小到特定符号(精准)
serena find_symbol --name 'authenticate' --type function
serena find_referencing_symbols --name 'authenticate'
**Use serena THEN ripgrep:**
```bash
serena find_symbol --name 'authenticate' --type function
serena find_referencing_symbols --name 'authenticate'
**先使用Serena再使用ripgrep:**
```bash
1. Find symbol definition with serena
1. 使用Serena查找符号定义
serena find_symbol --name 'UserService'
serena find_symbol --name 'UserService'
2. Search for related patterns with ripgrep
2. 使用ripgrep搜索相关模式
rg "UserService(" --type py # Find direct instantiations
rg "class.*UserService" --type py # Find subclasses
rg "UserService(" --type py # 查找直接实例化
rg "class.*UserService" --type py # 查找子类
Complementary Strengths
互补优势
| Task | Best Tool | Why |
|---|
| Find string literals | ripgrep | Text-based, fast |
| Find TODOs/comments | ripgrep | Text-based |
| Find symbol definition | serena | Symbol-aware |
| Find all references | serena | Semantic understanding |
| Find code patterns | ast-grep | Syntax-aware |
| Insert at symbol | serena | Precise positioning |
| Search across languages | ripgrep | Language-agnostic |
| Understand scope | serena | LSP semantic info |
| 任务 | 最佳工具 | 原因 |
|---|
| 查找字符串字面量 | ripgrep | 基于文本,速度快 |
| 查找TODO/注释 | ripgrep | 基于文本 |
| 查找符号定义 | Serena | 感知符号 |
| 查找所有引用 | Serena | 语义理解 |
| 查找代码模式 | ast-grep | 感知语法 |
| 在符号位置插入代码 | Serena | 精准定位 |
| 跨语言搜索 | ripgrep | 语言无关 |
| 理解作用域 | Serena | LSP语义信息 |
1. Start with Symbol Discovery
1. 从符号发现开始
Always locate the symbol definition first:
GOOD: Find definition, then references
推荐:先查找定义,再查找引用
serena find_symbol --name 'MyClass'
serena find_referencing_symbols --name 'MyClass'
serena find_symbol --name 'MyClass'
serena find_referencing_symbols --name 'MyClass'
AVOID: Searching for references without confirming definition exists
避免:未确认定义存在就搜索引用
2. Use Specific Symbol Types
2. 使用特定符号类型
Narrow searches with
when possible:
GOOD: Specific type reduces ambiguity
推荐:特定类型减少歧义
serena find_symbol --name 'User' --type class
serena find_symbol --name 'User' --type class
LESS PRECISE: May match User function, User variable, etc.
精准度较低:可能匹配User函数、User变量等
serena find_symbol --name 'User'
serena find_symbol --name 'User'
3. Verify Before Inserting
3. 插入前先验证
Always find the symbol before inserting code:
GOOD: Verify target exists first
推荐:先验证目标存在
serena find_symbol --name 'PaymentService' --type class
serena find_symbol --name 'PaymentService' --type class
[Review output to confirm correct class]
[查看输出确认正确的类]
serena insert_after_symbol --name 'PaymentService' --code '...'
serena insert_after_symbol --name 'PaymentService' --code '...'
RISKY: Inserting without verification
有风险:未验证就插入
serena insert_after_symbol --name 'PaymentService' --code '...'
serena insert_after_symbol --name 'PaymentService' --code '...'
4. Review Reference Counts
4. 查看引用数量
Check reference output for impact analysis:
Find references and assess impact
查找引用并评估影响
serena find_referencing_symbols --name 'deprecated_function'
serena find_referencing_symbols --name 'deprecated_function'
If 50+ references, plan careful migration
如果有50+引用,需规划仔细的迁移
If 0 references, safe to remove
如果零引用,可安全删除
5. Combine with git diff
5. 结合git diff使用
After insertions, verify changes:
bash
serena insert_after_symbol --name 'MyClass' --code '...'
git diff # Review actual changes before committing
插入后验证变更:
bash
serena insert_after_symbol --name 'MyClass' --code '...'
git diff # 提交前查看实际变更
Serena supports 30+ languages through LSP integration:
Tier 1 (Fully tested):
- Python, JavaScript, TypeScript, Rust, Go, Java, C/C++
Tier 2 (Community tested):
- C#, Ruby, PHP, Kotlin, Swift, Scala
Tier 3 (Experimental):
- Haskell, Elixir, Clojure, Erlang, Julia, R, and more
For the complete list and setup instructions, see
Serena language support docs.
Serena通过LSP集成支持30+种语言:
Tier 1(全面测试):
- Python、JavaScript、TypeScript、Rust、Go、Java、C/C++
Tier 2(社区测试):
- C#、Ruby、PHP、Kotlin、Swift、Scala
Tier 3(实验性):
- Haskell、Elixir、Clojure、Erlang、Julia、R等
完整列表和设置说明,请查看
Serena语言支持文档。
When NOT to Use Serena
何时不使用Serena
-
Searching text/comments: Use ripgrep instead
bash
# WRONG TOOL: Serena doesn't search comments
serena find_symbol --name "TODO"
# RIGHT TOOL: Use ripgrep for text
rg "TODO"
-
Generated code: LSP may not index auto-generated files
- Use ripgrep for build artifacts, generated code
-
Very large codebases: Symbol indexing can be slow
- Use ripgrep for initial broad searches
- Use serena for precise follow-up
-
Dynamic languages without types: Limited semantic info
- Python without type hints has reduced precision
- JavaScript without TypeScript has fewer guarantees
-
搜索文本/注释:使用ripgrep代替
bash
# 错误工具:Serena不搜索注释
serena find_symbol --name "TODO"
# 正确工具:使用ripgrep搜索文本
rg "TODO"
-
生成的代码:LSP可能不会索引自动生成的文件
-
超大代码库:符号索引可能较慢
- 初始广泛搜索使用ripgrep
- 精准查询使用Serena
-
无类型的动态语言:语义信息有限
- 无类型提示的Python精准度降低
- 无TypeScript的JavaScript保证更少
- Ambiguous symbols: Multiple symbols with same name may require manual disambiguation
- Macro-generated code: C/C++ macros may confuse LSP
- Circular dependencies: May affect reference tracking accuracy
- Incomplete projects: Missing dependencies can reduce LSP effectiveness
- 歧义符号:同名的多个符号可能需要手动消除歧义
- 宏生成的代码:C/C++宏可能会混淆LSP
- 循环依赖:可能影响引用追踪的准确性
- 不完整项目:缺失依赖会降低LSP的有效性
Performance Considerations
性能考量
Serena is designed for token-efficient code navigation:
Traditional approach (inefficient)
传统方法(低效)
execute_command("cat entire_file.py") # 1000+ tokens
execute_command("cat entire_file.py") # 1000+ Token
[Search for symbol manually in output]
[在输出中手动搜索符号]
Serena approach (efficient)
Serena方法(高效)
serena find_symbol --name 'MyClass' # 50 tokens
serena find_symbol --name 'MyClass' # 50 Token
[Get precise location immediately]
[立即获取精准位置]
Speed Characteristics
速度特性
- Symbol lookup: Near-instant (LSP indexed)
- Reference finding: Fast (O(log n) with indexing)
- Code insertion: Instant (direct file modification)
Comparison with alternatives:
- Ripgrep: Faster for text search (no semantic understanding)
- AST-grep: Comparable speed (syntax vs semantic)
- Serena: Slower initial startup (LSP indexing), faster precise queries
- 符号查找:近乎即时(LSP已索引)
- 引用查找:快速(索引后O(log n))
- 代码插入:即时(直接修改文件)
与替代工具的对比:
- Ripgrep:文本搜索更快(无语义理解)
- AST-grep:速度相当(语法vs语义)
- Serena:初始启动较慢(LSP索引),精准查询更快
-
Verify symbol exists: Use ripgrep to confirm
bash
rg "class MyClass" --type py
-
Check language server: Ensure LSP is configured for the language
bash
serena status # Check LSP server status
-
Try case variations: Symbol names are case-sensitive
bash
serena find_symbol --name 'myclass' # Try different cases
-
Rebuild index: Force LSP to re-index
bash
serena reindex # Rebuild symbol index
-
验证符号存在:使用ripgrep确认
bash
rg "class MyClass" --type py
-
检查语言服务器:确保为该语言配置了LSP
bash
serena status # 检查LSP服务器状态
-
尝试大小写变体:符号名称区分大小写
bash
serena find_symbol --name 'myclass' # 尝试不同大小写
-
重建索引:强制LSP重新索引
bash
serena reindex # 重建符号索引
Too Many References
引用结果过多
If
returns hundreds of results:
-
Use file-search first: Narrow scope with ripgrep
bash
rg "MyClass" src/services/ # Limit to specific directory
serena find_referencing_symbols --name 'MyClass' --path src/services/
-
Filter by reference type: Focus on specific usage patterns
bash
# Look for imports only
rg "from .* import.*MyClass" --type py
-
Prioritize recent changes: Check git history first
bash
git log --all -p -S 'MyClass' --since="1 week ago"
-
先使用文件搜索:用ripgrep缩小范围
bash
rg "MyClass" src/services/ # 限制到特定目录
serena find_referencing_symbols --name 'MyClass' --path src/services/
-
按引用类型过滤:聚焦特定使用模式
bash
# 仅查找导入
rg "from .* import.*MyClass" --type py
-
优先查看近期变更:先检查git历史
bash
git log --all -p -S 'MyClass' --since="1 week ago"
- Verify symbol exists: Find it first
- Check syntax: Ensure inserted code is valid
- Review indentation: Match surrounding code style
- Test incrementally: Insert small changes first
- 验证符号存在:先查找符号
- 检查语法:确保插入的代码有效
- 检查缩进:匹配周围代码风格
- 增量测试:先插入小改动