TECHSCORE BLOG

クラウドCRMを提供するシナジーマーケティングのエンジニアブログです。

VS Code の GitHub Copilot をカスタム指示と MCP で高度に使いこなす(応用編)

GitHub Copilot の基本的な操作に慣れた開発者の皆様へ、本記事ではさらに一歩進んだ活用方法をご紹介します。(GitHub Copilot の基本的な機能については、VS Code の GitHub Copilot の基本機能をマスターする(基本編) をご参照ください。)
GitHub Copilot は標準機能だけでも十分に強力ですが、「カスタム指示」を用いることで、より個別のプロジェクトの要件に応じたコード生成を行うことが可能になります。加えて、「MCP (Model Context Protocol) サーバー」との連携により、外部の情報源を活用し、Copilot の提案の幅と質を高めることができます。
この応用編では、これらの高度な機能について、その概要、設定方法、そして具体的な利用例を解説していきます。

1. カスタム指示による Copilot のカスタマイズ

GitHub Copilot は優れたコード補完と生成を提供しますが、デフォルトでは必ずしもあなたのプロジェクト固有のルールやコーディングスタイルに従いません。
カスタム指示は、あなたやチームのコーディング規約、技術スタック、プロジェクト要件に合わせて Copilot の出力を調整する強力な機能です。
この章では、カスタム指示やプロンプトファイルを使って、コード補完やコード生成が要件に合った出力になるようにカスタマイズする方法を説明します。

1.1 settings.json の設定

settings.json を使うことによって、カスタム指示の指定することができます。

設定できる内容は以下です。

設定内容 設定名
コード生成 github.copilot.chat.codeGeneration.instructions
テスト生成 github.copilot.chat.testGeneration.instructions
コードレビュー github.copilot.chat.reviewSelection.instructions
コミットメッセージの生成 github.copilot.chat.commitMessageGeneration.instructions
プルリクエストのタイトルと説明の生成 github.copilot.chat.pullRequestDescriptionGeneration.instructions

例えば、 生成されるコミットメッセージが英語で困ってしまうことがあると思います。 その場合、以下のように settings.json に設定します。

  "github.copilot.chat.commitMessageGeneration.instructions": [
    { "text": "必ず日本語で簡潔に記述してください" }
  ],

コミットメッセージを生成すると、今までは英語で出力されていたのが、日本語で出力されるようになりました。

コミットメッセージの生成を日本語で出力する

1.2 コード生成のカスタム指示の変更

前節では、settings.json を用いたカスタム指示の指定方法について解説しました。本節では、コード生成に特化したカスタム指示の設定方法を説明します。

コード生成の指示ファイルの種類

コード生成の指示ファイルは 2 種類あります。

ファイル 説明
.github/copilot-instructions.md ワークスペースに関するすべての指示が含まれた単一の指示ファイルです。これらの指示は、すべてのチャットリクエストに自動的に含まれます。
.instructions.md 特定のタスクに関するカスタム指示を含む 1 つ以上のプロンプトファイル。チャットリクエストに個別のプロンプトファイルを添付することも、特定のファイルやフォルダに自動的に添付されるように設定することもできます。

両方のファイルを使って、カスタム指示をすることも可能です。その場合は、指示が競合しないように注意してください。 あと、これらの指示ファイルはコード生成のときに使用されます。コード補完には使用されません。

前提として、このプロジェクト固有のカスタム指示を作成します。プロジェクトごとに技術スタックやバージョンなどが異なることを考慮すると、この方法が実務においてより一般的であると考えられます。もちろん、VS Code 全体にカスタム指示を設定することも可能ですが、ここではその説明は省略します。

カスタム指示の追加

ここで扱う指示ファイルは、.instructions.mdのみを使ってカスタム指示を実現します。

.instructions.mdの指示ファイルは、2つのセクションで構成されています。

セクション 説明
メタデータを含むヘッダー(フロントマター形式) 指示を自動的に適用するファイルの glob パターンを指定します。カスタム指示を常に含めるには、**パターンを使用します。
指示内容の本文 Markdown フォーマットを使用して、自然言語でカスタム指示を指定します。見出し、リスト、コードブロックを使用して指示を構造化できます。

例として、以下のファイルを作成して、カスタム指示を実施します。

ファイル名 説明
general-coding.instructions.md すべてのコードに適用される一般的なカスタム指示を記載する
typescript-react.instructions.md TypeScript や React に関するカスタム指示を記載する

他に適用するファイルを追加したい場合は、対象のファイルを追加することで対応できます。

settings.json の設定

settings.json に以下の設定を追加します。

"github.copilot.chat.codeGeneration.instructions": [
  {
    "file": "general.instructions.md"
  },
  { "file": "typescript-react.instructions.md" }
],

これで、2つのファイルが、コード生成のカスタム指示を記載したファイルだと認識されます。

指示ファイルの保存

以下のディレクトリにそれぞれのファイルを保存してください。

.github/
└── instructions/
      ├── general-coding.instructions.md
      └── typescript-react.instructions.md

general-coding.instructions.md ファイル

ここでは、GitHub Copilot 用のカスタム指示ファイルを作成します。前述の通り、.github/copilot-instructions.md ファイルはヘッダーと指示内容の本文で構成されていることをご確認ください。

提示しているプロンプトは、公式サイトのサンプルをベースに生成 AI に架空のユースケースを設定し、サンプルとして作成しました。

これはあくまでサンプルですので、実際のプロジェクトのコーディング規約や技術スタックに合わせて適宜変更してご利用ください。

筆者がカスタム指示を作成する時は、そのプロジェクトの技術スタックや要件、各ライブラリのバージョンやコードスニペットを記述したベースのプロンプトを作ります。
それを生成 AI に流し込み、プロンプトをブラッシュアップして完成させます。

---
applyTo: "**"
---

# General Coding Best Practices

## Code Quality & Maintainability
- Write self-documenting code with clear variable and function names
- Limit function length to 30 lines max, break larger functions into smaller ones
- Follow the Single Responsibility Principle - each function does one thing well
- Use meaningful comments for "why" not "what" (code should explain itself)
- Apply consistent indentation and formatting throughout the codebase
- Avoid nested conditionals deeper than 3 levels - refactor when necessary
- Implement proper error handling with informative error messages
- Avoid magic numbers and strings - use named constants instead

## Performance & Optimization
- Optimize for readability first, then performance if needed
- Avoid premature optimization - measure before optimizing
- Use appropriate data structures for the task (consider time/space complexity)
- Be mindful of memory usage, especially with large datasets
- Implement lazy loading where appropriate for better initial load times
- Consider pagination for large result sets

## Security Practices
- Never trust user input - always validate and sanitize
- Implement proper authentication and authorization
- Use parametrized queries to prevent SQL injection
- Avoid hardcoding sensitive information (keys, passwords)
- Follow the principle of least privilege
- Set appropriate CORS policies
- Implement rate limiting for APIs

## Modern Development Practices
- Use async/await for asynchronous operations instead of callbacks
- Apply functional programming techniques where appropriate
- Write code with testability in mind
- Implement proper logging for monitoring and debugging
- Use environment variables for configuration
- Follow semantic versioning for releases
- Write useful commit messages explaining the "why" of changes

## Project Structure
- Maintain a clear, logical project structure
- Use appropriate design patterns but avoid overengineering
- Separate concerns between layers (presentation, business logic, data access)
- Organize code by feature rather than by technical function when appropriate
- Create reusable, modular components
- Use dependency injection to manage dependencies

## When Generating Code
- Generate code that follows these principles
- Include appropriate error handling
- Add helpful comments for complex logic
- Include examples of usage when generating functions or classes
- Ensure backward compatibility unless explicitly requested otherwise
- Suggest unit tests for critical functionality
- Provide optimization tips for resource-intensive operations

typescript-react.instructions.md ファイル

typescript-react.instructions.md ファイルには、TypeScript と React に関するカスタム指示を記述しています。

---
applyTo: "**/*.ts,**/*.tsx"
---
# TypeScript & React Best Practices

Apply the [general coding guidelines](./general-coding.instructions.md) to all code.

## TypeScript Guidelines
- Use strict TypeScript configuration with `strict: true`
- Define explicit types for function parameters and return values
- Use interfaces for objects that represent entities, types for simpler constructs
- Leverage TypeScript utility types (Pick, Omit, Partial, Required, etc.)
- Avoid using `any` - use `unknown` with type guards when type is uncertain
- Define readonly properties for immutable data
- Use discriminated unions for handling state with different shapes
- Create generic components and functions when appropriate
- Define proper typing for API responses and requests
- Use enums for fixed sets of related values
- Properly handle nullable types with optional chaining (?.) and nullish coalescing (??)
- Add JSDoc comments for complex types and non-obvious behavior

## React Fundamentals
- Use functional components with hooks instead of class components
- Apply proper dependency arrays in useEffect and useMemo hooks
- Extract business logic to custom hooks for reusability
- Memoize expensive calculations with useMemo
- Prevent unnecessary re-renders with React.memo for pure components
- Use useCallback for functions passed to child components
- Implement controlled components for form inputs
- Pass only required props to components (avoid prop drilling)
- Avoid direct DOM manipulation - use refs when necessary
- Keep components small and focused on a single responsibility

## React State Management
- Use useState for simple component-level state
- Implement useReducer for complex state logic
- Apply useContext for sharing state across component trees
- Consider global state management only when necessary (Redux, Zustand, Jotai)
- Keep state as close as possible to where it's used
- Separate UI state from application state
- Minimize state duplication and ensure single source of truth
- Normalize complex state structures for better performance

## Component Design
- Create atomic, reusable components
- Implement proper prop validation with TypeScript
- Use composition over inheritance
- Design components with accessibility in mind
- Support keyboard navigation for interactive elements
- Implement theming using CSS variables or styled-components
- Follow responsive design principles
- Use CSS modules or styled-components for component styling
- Implement lazy loading for larger components with React.lazy

## React Performance Optimization
- Virtualize long lists with react-window or react-virtualized
- Implement code splitting with dynamic imports
- Use proper keys for list items (avoid using index as key)
- Avoid inline function definitions in render
- Properly handle cleanup in useEffect to prevent memory leaks
- Use debouncing/throttling for frequently firing events
- Implement memoization judiciously

## Testing in React & TypeScript
- Write unit tests for components using React Testing Library
- Test for accessibility with axe-core or similar tools
- Use TypeScript to ensure prop types are correct
- Test custom hooks with renderHook
- Implement integration tests for complex workflows
- Mock external dependencies in tests
- Use snapshot testing sparingly

## React & API Integration
- Implement proper loading and error states
- Use React Query or SWR for data fetching and caching
- Handle optimistic updates for better UX
- Properly type API responses with TypeScript interfaces
- Implement retry logic for failed requests
- Add cancellation for abandoned requests

余談ですが、生成 AI に指示を出すプロンプトは、英語で記述した方が精度の高い回答が得られるという検証結果があります。
そのため、カスタム指示についても英語で記述することで、より高い精度が期待できるでしょう。

2. MCP (Model Context Protocol) による機能拡張

VS Code は、バージョン 1.99.0 でエージェントモードに対応しました。これにより、Web コンテンツの取得、シンボル参照の検索、そしてより高度な思考処理が可能になりました。
また、MCP クライアントとして機能するようになり、様々な MCP サーバーとの連携も実現されています。MCP サーバー は AI を活用した強力な開発支援ツールです。
そのため、本章では MCP サーバーを用いて開発を効率化し、飛躍的に高速化するための手順を説明します。

2.1 エージェントモードについて

エージェントモード、VS Code バージョン 1.99 で新たに追加された、GitHub Copilot の非常に強力な機能の一つです。
この機能を利用することで、Copilot がコードベースを深く理解し、複雑なタスクを自律的に実行できるようになります。
エージェントモードに関する詳細な説明はここでは割愛しますが、より詳しい情報については公式サイトをご参照ください。

2.2 MCP の概要

MCP は、AI モデルと外部のデータソースやツールとの接続を容易にするためのオープンスタンダードです。
このプロトコルは、2024 年 11 月に Anthropic によって発表されました。従来、AI モデルを外部サービスと連携させるには、各システムに対応した個別の API 連携を開発する必要がありました。
しかし、MCP を利用することで、単一の標準化されたプロトコルを通じて、様々なサービスやツールとの連携が可能になります。
これにより、開発者は特定の AI モデルやプラットフォームへの依存を減らし、より柔軟かつ効率的に AI アプリケーションを構築できるようになります。

以下は、MCP を用いた処理の簡単な概要を示すシーケンス図です。

sequenceDiagram
    participant ユーザー
    participant VSCode_MCPClient as VS Code (MCP クライアント)
    participant MCP サーバー
    participant LLM

    ユーザー->>VSCode_MCPClient: プロンプト入力
    VSCode_MCPClient->>VSCode_MCPClient: プロンプト解析、必要なツール/リソース特定
    VSCode_MCPClient->>MCP サーバー: JSON-RPCリクエスト (リソース探索、リソース読み取り)
    MCP サーバー-->>VSCode_MCPClient: JSON-RPCレスポンス (リソース情報、データ)
    VSCode_MCPClient->>LLM: コンテキストとプロンプトを送信
    LLM-->>VSCode_MCPClient: 応答生成
    VSCode_MCPClient-->>ユーザー: 応答表示

    note over VSCode_MCPClient: VSCodeはMCPクライアントとして動作し、<br/>MCP サーバーとの通信を仲介します。
    note over MCP サーバー: データソースやツールへのアクセスを提供します。
    note over LLM: テキスト生成を行う中核エンジンです。

特筆すべき点として、ユーザーは VS Code などの対応アプリケーションにおいて、利用したい MCP サーバーを任意に設定することが可能です。これにより、ユーザーは自身のニーズに合わせて AI の機能を柔軟に拡張できます。

2.3 MCP サーバー の設定

MCP の種類

開発を快適にする MCP はたくさん存在します。例えば、Web 検索 MCP には Brave Search や Tavily があり、ウェブサイトを効率的にクロールしデータを抽出する Firecrawl MCP、ブラウザ自動化ツールと連携する Playwright MCP、デザイン分野では Figma と連携する Figma MCP なども利用可能です。
さらに、ファイルシステムと連携する Filesystem MCP や、GitHub と連携する GitHub MCP など、様々な MCP が存在します。

筆者の最近のおすすめとしては、Context7 という MCP があります。 生成 AI は時々、古い情報のコードを提案することがあります。
これは、生成 AI が持つ情報が特定の期間までのものに限られ、最新情報に追いついていない「ナレッジカットオフ」が原因です。この問題を補うのが Context7 で、これを使用することで、常に最新バージョンのドキュメントやコード例に基づいた提案が期待できるようになります。
対応しているドキュメントについては、Context7 の公式サイトを参照いただければと思います。

ここでは、この Context7 を設定する手順で説明します。

MCP の設定

MCP の設定方法はいろいろありますが、ここではローカルで MCP を動作させる方法で説明します。 settings.json で以下の設定を行います。

  "mcp": {
    "servers": {
      "Context7": {
        "type": "stdio",
        "command": "npx",
        "args": ["-y", "@upstash/context7-mcp@latest"]
      }
    }
  },

これで設定は完了です。

設定できているか確認します。以下のアイコンをクリックしてください。

GitHub Copilotの入力UI

VS Code の上部に、Context7 が表示されていれば正常に設定できています。

利用方法の一例として、エージェントモードで Context7 の MCP を使用するよう指示することで、この機能を利用できます。

具体例として、React 19 で新たに追加された useActionState フックを使ったサンプルコード作成を指示してみましょう。

使わない場合:

これは生成 AI を使っていると「あるある」かもしれませんが、今回試した AI は useActionState フックに関する情報をまだ学習していなかったようで、結果的に独自に useActionState という名前の関数を実装しようとしてしまいました。

使った場合:

一方、エージェントモードで Context7 の MCP を利用するように指示したところ、AI は React の最新ドキュメントを参照し、今度は useActionState の正しいサンプルコードを期待通りに出力しました(コードの詳細はここでは割愛します)。

開発環境を快適化する MCP サーバーは、ここで紹介したもの以外にも多数あります。ぜひご自身の環境でいくつか試し、最適なものを選んで、開発環境のカスタマイズを楽しんでください。

まとめ

本記事応用編では、GitHub Copilot の可能性をさらに広げるための「カスタム指示」と「MCP サーバー連携」という 2 つの強力な機能について、その設定方法から具体的な活用例までを解説しました。

カスタム指示を利用すれば、Copilot の提案をプロジェクトのコーディング規約や特定の技術スタックに、よりきめ細かく適合させることができます。また、MCP サーバーを介して外部の知識ソースと連携させることで、Copilot は常に最新の情報や専門性の高いドキュメントに基づいた、質の高いサポートを提供できるようになります。

今回ご紹介したテクニックを参考に、ぜひご自身の開発環境で設定を試み、最適なカスタマイズを見つけてください。

GitHub Copilot を最大限に活用し、より快適で生産性の高い開発を実現されることを期待しています。

参考リンク

hiraokuのプロフィール画像
hiraoku

暇があったらクライミングしているフロントエンドエンジニアです。

シナジーマーケティング株式会社では一緒に働く仲間を募集しています。