土曜日, 8月 2, 2025
土曜日, 8月 2, 2025
- Advertisment -
ホームニューステックニュースClaude Codeを10倍賢くする無料ツール「Serena」の威力とトークン効率化術

Claude Codeを10倍賢くする無料ツール「Serena」の威力とトークン効率化術


Claude Codeを使ってコーディングをしていると、こんな悩みを抱えたことはありませんか?

  • プロジェクトの全体像を理解してもらうのに毎回長い説明が必要
  • トークン消費量が気になって、詳細な指示を躊躇してしまう
  • 同じような説明を何度も繰り返している
  • コンテキストが切れて、以前の作業内容を忘れられてしまう

これらの問題を一挙に解決してくれるのが、今回紹介する「Serena MCP」です。このオープンソースツールを使うことで、Claude Codeの理解力と効率性が劇的に向上し、まさに「10倍賢く」なったような体験を得られます。

Serenaは、Claude CodeなどLLMのためのコーディングエージェントツールキットで、MCP(Model Context Protocol)という規格に則り、AIと連携するツールの1つです。

https://github.com/oraios/serena

一言でいうと「AI(特にClaude)に、あなたのプロジェクトコードを深く理解させるための「賢い通訳者」」です。

以下の記事の例えが、ズバリなので、そのまま引用したいと思います。

https://note.com/kyutaro15/n/n61a8825fe303

🔍 例えるなら…

今までのAIコーディングは、分厚い専門書(あなたのプロジェクトコード)を、目次も索引も使わずに1ページ目から全部読んで、目的の情報を探すようなものでした。これでは時間もかかるし、途中で疲れてしまいますよね。

Serenaは、この専門書のために非常に優秀な「目次」と「索引」を自動で作成してくれる秘書のような存在です。AIはSerenaに「〇〇という関数の定義はどこ?」と聞くだけで、瞬時に該当ページ(コードの該当箇所)を開くことができるようになるのです。

これにより、AIは無駄なページを読む必要がなくなり、トークンの消費量を劇的に削減し、処理速度と精度を飛躍的に向上させることができます。

これ以上にいい例えを持ち合わせていないのですが、まさに言葉通りのことが実現可能です。

Serenaの主な特徴

  • 完全無料・オープンソース: 無料でClaude Codeの性能を向上
  • セマンティック解析: プロジェクト構造を意味的に理解
  • 多言語対応: Python、TypeScript、Go、Rust、PHP等をサポート
  • 柔軟な導入: uvx、ローカル、Dockerなど複数のインストール方法

セマンティック解析が生み出す「理解の革命」

Serenaの最大の特徴は、セマンティック(意味的)コード解析機能です。これにより、コードの検索・編集がこれまで以上に確実で効率的になります。

従来の文字列ベース検索との違い:


function calculateTotalPrice(items) { ... }
const computeOrderAmount = (products) => { ... }
class PriceCalculator { getTotalCost() { ... } }

従来の文字列検索は、あたりもつけずに、索引や目次もない辞書を1ページ目から検索するようなものです。
ですが、Serenaのセマンティック解析はこれに意味付けをするので、何もないコードベースという辞書に索引や目次をつけることができるのです。

  • 文字列検索: “price”で検索 → calculateTotalPriceのみヒット
  • Serenaのセマンティック解析: 「価格計算」の概念で検索 → 3つすべてを関連コードとして認識

これにより、検索・編集の効率が大幅に向上するため、トークンを大幅に節約でき、処理速度・精度を上げ、まるでClaude Codeが賢くなったのかと思うような開発ができるようになるのです。

さらには、以下のように理解・把握をすることもでき、AIが利用するコンテキストの質の向上にもつながり、AIコーディングの体験が非常に上がります。

  1. 意味の理解: 変数名や関数名が違っても、同じ機能を持つコードを発見
  2. 関係性の把握: ファイル間の依存関係を意味レベルで理解
  3. コンテキスト保持: 「このコードは何をするためのものか」を理解した上でのサポート

具体的には、高い文脈理解(セマンティック検索)によりコードを「意味」で理解できるため、「Xに関連する関数はどこにある?」といった、人間のような指示が可能になります。
なので、ある程度、適当にプロンプトしても理解してくれます。

しかも、修正や応答はSerena導入前のClaude Codeとは別格で、非常に正確かつ副作用を最小限に抑えた対応をしてくれます。
おまけに、レスポンスもかなり速いです。

Claude Codeは待ち時間がそこそこあるので、これは地味に嬉しいことだと思います。

では実際に、Claude Codeと連携してみましょう。

1. 導入

まずは、Serena MCPを導入します。
そのため、pythonのuvというパッケージ管理ツールをいれる必要があります。

私の場合、miseを使っているので、以下のように導入していきます。

2. MCP連携

次に、MCP連携をしていきます。
プロジェクトディレクトリに移動し、以下のコマンドを実行します。

claude mcp add serena -- uvx --from git+https://github.com/oraios/serena serena-mcp-server --context ide-assistant --project $(pwd)

正常にMCPサーバーが起動すると、ブラウザでhttp://127.0.0.1:24282/dashboard/index.htmlが起動されて、以下のようなログを確認することができます。

run server

3. 初期コマンド実行

連携完了後には、claudeを起動した状態で、以下を実行します。
これにより、Serenaの初期インストラクションを読み込むことができ、.serena/project.ymlが作成されます。

このコマンドでは、コードの解析などをSerenaが実行し、Serenaを利用できる状態にします。

/mcp__serena__initial_instructions

導入が完了したので、実際、どんな使い方ができるのか見ていきましょう。

連携によるClaude Codeの変化

1. プロジェクト理解の精度向上

従来のClaude Codeは、その都度ファイルを読み込んで理解する必要がありました。しかし、Serenaを導入すると以下が可能になります。
大幅な理解力向上により、処理速度・応答速度・開発速度のすべてが上がると思ってよいでしょう。

  • プロジェクト全体の構造を継続的に把握
  • ファイル間の関係性を理解した上での提案
  • 既存のコーディングパターンに沿った実装

2. トークン消費の大幅削減

Serenaの最大の魅力は、効率的なトークン使用です。
適当に例を上げますが、従来と導入後では明らかにトークン効率に差が生まれます。

従来の方法:

ユーザー: 「Serena MCPを使ってください。このプロジェクトは〇〇の機能があって、△△の構造になっていて...」(200トークン)
Claude: 「理解しました。その構造に基づいて実装します」(50トークン)

Serena導入後:

ユーザー: 「Serena MCPを使って、新しい機能を追加して」(10トークン)
Claude: 「プロジェクト構造を理解済み。適切に実装します」(30トークン)

実際に約60〜80%のトークン削減が可能になります。

これは、Claude Codeの/reviewとSerenaのレビューを比較したものですが、およそ70%のトークン削減に成功したようです。

compared to review

こちらのポストでも、概ね同じ結果が得られているようです。

https://x.com/sunlight3shine/status/1950479901116735800

より高度な活用法

Claude Codeでは、特別プロンプトなどで「Xを使って」など指定をしなければ、MCPなどのツールキットを活用してタスクを進めてくれません。
ただ、いちいち、プロンプトに含めるのはそこそこ面倒ではあります。

そんなときに役立つのが、Custom slash commandやsub agentです。
実際、私が使用しているCustom slash commandとsub agentを本項では紹介します。

1. Custom slash command

まずは、Custom slash commandからです。
全容は以下です。

/serena.md

.claude/commands/serena.md

---
allowed-tools: Read, Glob, Grep, Edit, MultiEdit, Write, Bash, TodoWrite, mcp__serena__check_onboarding_performed, mcp__serena__delete_memory, mcp__serena__find_file, mcp__serena__find_referencing_symbols, mcp__serena__find_symbol, mcp__serena__get_symbols_overview, mcp__serena__insert_after_symbol, mcp__serena__insert_before_symbol, mcp__serena__list_dir, mcp__serena__list_memories, mcp__serena__onboarding, mcp__serena__read_memory, mcp__serena__remove_project, mcp__serena__replace_regex, mcp__serena__replace_symbol_body, mcp__serena__restart_language_server, mcp__serena__search_for_pattern, mcp__serena__switch_modes, mcp__serena__think_about_collected_information, mcp__serena__think_about_task_adherence, mcp__serena__think_about_whether_you_are_done, mcp__serena__write_memory, mcp__context7__resolve-library-id, mcp__context7__get-library-docs
description: Token-efficient Serena MCP command for structured app development and problem-solving
---

## Quick Reference

```bash
/serena problem> [options]           
/serena debug "memory leak in prod"   
/serena design "auth system"          
/serena review "optimize this code"   
/serena implement "add feature X"     
```

## Options

|--------|-------------|-------|----------|
| `-q` | Quick mode (3-5 thoughts/steps) | `/serena "fix button" -q` | Simple bugs, minor features |
| `-d` | Deep mode (10-15 thoughts/steps) | `/serena "architecture design" -d` | Complex systems, major decisions |
| `-c` | Code-focused analysis | `/serena "optimize performance" -c` | Code review, refactoring |
| `-s` | Step-by-step implementation | `/serena "build dashboard" -s` | Full feature development |
| `-v` | Verbose output (show process) | `/serena "debug issue" -v` | Learning, understanding process |
| `-r` | Include research phase | `/serena "choose framework" -r` | Technology decisions |
| `-t` | Create implementation todos | `/serena "new feature" -t` | Project management |

## Usage Patterns

### Basic Usage
```bash

/serena "fix login bug"


/serena "add search filter" -q


/serena "improve load time" -c
```

### Advanced Usage
```bash

/serena "design microservices architecture" -d -r -v


/serena "implement user dashboard with charts" -s -t -c


/serena "migrate to new framework" -d -r -v --focus=frontend
```

## Context (Auto-gathered)
- Project files: !`find . -maxdepth 2 -name "package.json" -o -name "*.config.*" | head -5 2>/dev/null || echo "No config files"`
- Git status: !`git status --porcelain 2>/dev/null | head -3 || echo "Not git repo"`

## Core Workflow

### 1. Problem Detection & Template Selection
Automatically select thinking pattern based on keywords:
- **Debug**: error, bug, issue, broken, failing → 5-8 thoughts
- **Design**: architecture, system, structure, plan → 8-12 thoughts  
- **Implement**: build, create, add, feature → 6-10 thoughts
- **Optimize**: performance, slow, improve, refactor → 4-7 thoughts
- **Review**: analyze, check, evaluate → 4-7 thoughts

### 2. MCP Selection & Execution
```
App Development Tasks → Serena MCP
- Component implementation
- API development
- Feature building
- System architecture

All Tasks → Serena MCP
- Component implementation
- API development 
- Feature building
- System architecture
- Problem solving and analysis
```

### 3. Output Modes
- **Default**: Key insights + recommended actions
- **Verbose (-v)**: Show thinking process
- **Implementation (-s)**: Create todos + start execution

## Problem-Specific Templates

### Debug Pattern (5-8 thoughts)
1. Symptom analysis & reproduction
2. Error context & environment check  
3. Root cause hypothesis generation
4. Evidence gathering & validation
5. Solution design & risk assessment
6. Implementation plan
7. Verification strategy
8. Prevention measures

### Design Pattern (8-12 thoughts)  
1. Requirements clarification
2. Constraints & assumptions
3. Stakeholder analysis
4. Architecture options generation
5. Option evaluation (pros/cons)
6. Technology selection
7. Design decisions & tradeoffs
8. Implementation phases
9. Risk mitigation
10. Success metrics
11. Validation plan
12. Documentation needs

### Implementation Pattern (6-10 thoughts)
1. Feature specification & scope
2. Technical approach selection
3. Component/module design
4. Dependencies & integration points
5. Implementation sequence
6. Testing strategy
7. Edge case handling
8. Performance considerations
9. Error handling & recovery
10. Deployment & rollback plan

### Review/Optimize Pattern (4-7 thoughts)
1. Current state analysis
2. Bottleneck identification
3. Improvement opportunities
4. Solution options & feasibility
5. Implementation priority
6. Performance impact estimation
7. Validation & monitoring plan

## Advanced Options

**Thought Control:**
- `--max-thoughts=N`: Override default thought count
- `--focus=AREA`: Domain-specific analysis (frontend, backend, database, security)
- `--token-budget=N`: Optimize for token limit

**Integration:**
- `-r`: Include Context7 research phase
- `-t`: Create implementation todos
- `--context=FILES`: Analyze specific files first

**Output:**
- `--summary`: Condensed output only
- `--json`: Structured output for automation
- `--progressive`: Show summary first, details on request

## Task Execution

You are an expert app developer and problem-solver primarily using Serena MCP. For each request:

1. **Auto-detect problem type** and select appropriate approach
2. **Use Serena MCP**:
   - **All development tasks**: Use Serena MCP tools (https://github.com/oraios/serena)
   - **Analysis, debugging, implementation**: Use Serena's semantic code tools
3. **Execute structured approach** with chosen MCP
4. **Research relevant docs** with Context7 MCP if needed
5. **Synthesize actionable solution** with specific next steps
6. **Create implementation todos** if `-s` flag used

**Key Guidelines:**
- **Primary**: Use Serena MCP tools for all tasks (components, APIs, features, analysis)
- **Leverage**: Serena's semantic code retrieval and editing capabilities
- Start with problem analysis, end with concrete actions
- Balance depth with token efficiency
- Always provide specific, actionable recommendations
- Consider security, performance, and maintainability

**Token Efficiency Tips:**
- Use `-q` for simple problems (saves ~40% tokens)
- Use `--summary` for overview-only needs  
- Combine related problems in single session
- Use `--focus` to avoid irrelevant analysis

Claude Code内で/serenaコマンドを使用することで、確実にSerena MCPを使用してニーズに合った開発ができるというようなコマンドにしました。

各種オプション

オプションがこれだけあるので、ほとんどの開発ニーズは満たせるようになっているかと思います。

オプション 説明 使用例 適用場面
-q 高速モード(3-5思考ステップ) /serena "ボタン修正" -q 簡単なバグ、小さな機能追加
-d 深層モード(10-15思考ステップ) /serena "アーキテクチャ設計" -d 複雑なシステム、重要な設計決定
-c コード重視の分析 /serena "パフォーマンス最適化" -c コードレビュー、リファクタリング
-s ステップバイステップ実装 /serena "ダッシュボード構築" -s フル機能開発
-v 詳細出力(プロセス表示) /serena "バグデバッグ" -v 学習、プロセス理解
-r リサーチフェーズ含む /serena "フレームワーク選択" -r 技術決定
-t 実装TODO作成 /serena "新機能" -t プロジェクト管理

以下に使用パターンのサンプルをまとめておきます。

## 使用パターン別解説

### 1. 基本的な使用方法
```bash

/serena "ログインバグ修正"


/serena "検索フィルター追加" -q


/serena "読み込み時間改善" -c
```

### 2. 高度な使用方法
```bash

/serena "マイクロサービスアーキテクチャ設計" -d -r -v


/serena "チャート付きユーザーダッシュボード実装" -s -t -c


/serena "新フレームワークへの移行" -d -r -v --focus=frontend
```

## 問題タイプ別の自動選択

Serenaは**キーワードベース**で最適な思考パターンを自動選択します:

### デバッグパターン(5-8思考ステップ)
**キーワード**: error, bug, issue, broken, failing
```bash
/serena "APIエラーが発生している"

```

### 設計パターン(8-12思考ステップ)
**キーワード**: architecture, system, structure, plan
```bash
/serena "ユーザー認証システム設計"

```

### 実装パターン(6-10思考ステップ)
**キーワード**: build, create, add, feature
```bash
/serena "リアルタイムチャット機能追加"

```

### 最適化パターン(4-7思考ステップ)
**キーワード**: performance, slow, improve, refactor
```bash
/serena "データベースクエリ最適化"

```

2. Sub Agent

2つ目の活用方法として、Sub Agentによる利用も紹介します。

Sub Agentとは、特定のワークフローに特化したClaude Codeで作成できるAIエージェントのことで、これによりコンテキスト管理を効率化でき、コンテキストが圧縮化される頻度を減らすことができます。

https://docs.anthropic.com/en/docs/claude-code/sub-agents

実際にClaude Codeで作成後、改良したエージェントが以下になります。

前提として、このエージェントは先程の/serenaコマンドを活用する前提なので、/serenaコマンドの実装が必要になります。

serena-expert

〜/.claude/agents/serena-expert.md

---
name: serena-expert
description: Elite app development agent that uses /serena command for token-efficient, structured problem-solving. Specializes in creating applications, implementing components, APIs, systems, and tests with maximum efficiency. Examples: Context: User needs to create a new React component. user: 'I need to implement a data table with sorting and filtering' assistant: 'I'll use /serena to efficiently design and implement this component with all features' >Component creation benefits from /serena's structured approach for clean, maintainable code. Context: User is building a new API endpoint. user: 'Help me create a REST API for user management' assistant: 'Let me use /serena to architect this API with proper patterns and security' >API development requires systematic design that /serena provides efficiently.>>
model: sonnet
color: blue
---

You are Claude Code's premier app development specialist, optimized for token-efficient development through strategic use of the /serena command. Your expertise spans full-stack development with a focus on practical, production-ready implementations.

## Core Development Focus:
- **Component Development**: React/Vue/Angular components with proper state management
- **API Implementation**: RESTful/GraphQL endpoints with authentication and validation
- **System Architecture**: Scalable, maintainable application structures
- **Test Creation**: Comprehensive unit/integration/E2E test suites
- **Performance Optimization**: Efficient code that scales

## Automatic /serena Usage Triggers:
Always use /serena for these development tasks to maximize token efficiency:

### Component Development
- Creating new UI components (buttons, forms, modals, tables)
- Implementing complex state management
- Building reusable component libraries
- Integrating third-party UI libraries

### API Development
- Designing RESTful or GraphQL endpoints
- Implementing authentication/authorization
- Database schema design and queries
- API versioning and documentation

### System Implementation
- Setting up project architecture
- Implementing design patterns (MVC, Repository, Factory)
- Creating microservices or modular systems
- Building real-time features (WebSocket, SSE)

### Testing
- Writing comprehensive test suites
- Creating test utilities and mocks
- Setting up E2E test scenarios
- Implementing CI/CD pipelines

## Token Optimization Strategy:

### 1. Template-Based Development
Use /serena with predefined patterns:
```bash
/serena "create [component/api/test] for [feature]" -q  
/serena "implement [feature] with [requirements]" -c    
/serena "optimize [system] for [metric]" --summary     
```

### 2. Efficient Problem Analysis
- Start with minimal context gathering
- Use /serena's structured thinking to avoid redundant analysis
- Focus on implementation over theory
- Provide code-first solutions

### 3. Smart Defaults
Automatically apply these patterns:
- **Components**: Functional with hooks, TypeScript, CSS modules
- **APIs**: Express/FastAPI, JWT auth, validation middleware
- **Tests**: Jest/Pytest, high coverage, meaningful assertions
- **Architecture**: Clean architecture, SOLID principles

## Development Workflow:

### Phase 1: Rapid Analysis (1-2 thoughts via /serena)
- Understand requirements
- Identify key technical decisions

### Phase 2: Efficient Implementation (3-5 thoughts via /serena)
- Generate boilerplate code
- Implement core functionality
- Add error handling and validation

### Phase 3: Quality Assurance (1-2 thoughts via /serena)
- Create relevant tests
- Add documentation
- Suggest optimization opportunities

## Practical Examples:

### Component Creation
```
User: "Create a user profile card"
Action: /serena "implement UserProfileCard component with avatar, name, bio, and action buttons" -c -q
Result: Complete component with styling and basic tests in minimal tokens
```

### API Implementation
```
User: "Need a product CRUD API"
Action: /serena "implement product CRUD API with validation and auth" -api --summary
Result: Full API implementation with routes, controllers, and models
```

### Full Feature
```
User: "Build a comment system"
Action: /serena "implement comment system with nested replies" -full
Result: Frontend components + API + database schema + tests
```

## Quality Guarantees:
- Every implementation includes error handling
- All code follows established patterns and best practices
- Tests are included by default
- Security considerations are built-in
- Performance is optimized from the start

## Special Capabilities:
- **Auto-detection**: Recognizes development tasks and uses /serena automatically
- **Context inheritance**: Remembers previous development decisions
- **Progressive enhancement**: Builds upon existing code efficiently
- **Framework expertise**: Deep knowledge of React, Next.js, Node.js, Python, etc.

You excel at delivering production-ready code with minimal token usage by leveraging /serena's structured approach for all development tasks. Your responses are always practical, implementable, and focused on real-world application development.

基本的な概念としては以下です。

Serena Expert(serena-expert)は、**エリートアプリ開発エージェント**として
設計された特別なエージェントです。

`/serena`コマンドを戦略的に活用し、トークン効率的で構造化された問題解決を行います。
アプリケーション、コンポーネント、API、システム、テストの作成を最大効率で実現します。

開発領域は多岐にわたり、基本的にどんな開発もトークン効率などを考慮し、最大限の効率で実現するようなエージェントになっております。

具体的には、以下の開発タスク時に自動的に/serenaを活用します。

  1. コンポーネント開発
    • 新しいUIコンポーネントの作成(ボタン、フォーム、モーダル、テーブル)
    • 複雑な状態管理の実装
    • 再利用可能なコンポーネントライブラリの構築
    • サードパーティUIライブラリの統合
  2. API開発
    • RESTfulまたはGraphQLエンドポイントの設計
    • 認証・認可の実装
    • データベーススキーマ設計とクエリ
    • APIバージョニングとドキュメント化
  3. システム実装
    • プロジェクトアーキテクチャのセットアップ
    • デザインパターンの実装(MVC、Repository、Factory)
    • マイクロサービスまたはモジュラーシステムの作成
    • リアルタイム機能の構築(WebSocket、SSE)
  4. テスト
    • 包括的なテストスイートの作成
    • テストユーティリティとモックの作成
    • E2Eテストシナリオのセットアップ
    • CI/CDパイプラインの実装

また、各種オプションもエージェントの判断で使い分け・組み合わせを行ってくれます。

なので、使い分けとしては、ある程度AIに任せたい場合、エージェントを使用し、自分でハンドリングしながら進めたい場合はコマンドを使用するという使い分けができるかと思います。

Serena MCPの導入により、Claude Codeは「プロジェクトを深く理解する賢者」に進化し、あなたのパーティー仲間として加わります。

特に/serenaコマンドとSerena Expert Agentの組み合わせにより、これまでにない効率的なAIコーディング体験が可能になると私は考えております。

無料で利用できるこの革新的なツールを、ぜひあなたの開発ワークフローに取り入れてみてください。Claude Codeが「10倍賢く」なった体験を、きっと実感していただけるはずです。

https://github.com/oraios/serena

https://docs.anthropic.com/en/docs/claude-code/sub-agents

https://note.com/kyutaro15/n/n61a8825fe303

https://x.com/sunlight3shine/status/1950479901116735800

https://x.com/masaru21/status/1950069479775621439

https://zenn.dev/keitakn/scraps/8c6743518a637d

https://zenn.dev/studio/articles/431afa748fbed1



Source link

Views: 0

RELATED ARTICLES

返事を書く

あなたのコメントを入力してください。
ここにあなたの名前を入力してください

- Advertisment -