ブログ一覧に戻る
🤖AI Lab

Claude Code × MCP完全ガイド:AIエージェントが外部ツールと連携する新時代

Model Context Protocol (MCP)を使ってClaude Codeを拡張。Figma、データベース、API、各種開発ツールとの統合で実現する完全自動化開発環境の構築方法。

11 min read
Claude CodeMCPAI自動化統合開発エージェント
シェア:

MCPとは:AIに「手足」を与える革命的プロトコル

Model Context Protocol (MCP)は、AIモデルに外部ツールやデータソースへのアクセスを提供する標準化されたプロトコルです。Claude Codeと組み合わせることで、AIが単なる「アドバイザー」から「実行者」へと進化します。

1. MCP アーキテクチャの理解

1.1 MCPの基本構造

// MCPの3層アーキテクチャ
interface MCPArchitecture {
  layers: {
    client: {
      description: 'Claude Code (AIクライアント)';
      role: 'リクエストの送信とレスポンスの処理';
      examples: ['Claude Desktop', 'VS Code Extension', 'CLI'];
    };

    server: {
      description: 'MCPサーバー(ブリッジ)';
      role: 'プロトコル変換と通信管理';
      examples: ['figma-mcp', 'postgres-mcp', 'github-mcp'];
    };

    resources: {
      description: '外部リソース';
      role: '実際のデータやサービス';
      examples: ['Figma API', 'PostgreSQL', 'GitHub API', 'AWS'];
    };
  };

  communication: {
    protocol: 'JSON-RPC 2.0';
    transport: 'stdio | HTTP | WebSocket';
    authentication: 'Bearer Token | API Key | OAuth';
  };
}

1.2 MCPサーバーの仕組み

# MCPサーバーの実装例
from mcp import Server, Tool, Resource
import asyncio

class CustomMCPServer(Server):
    def __init__(self):
        super().__init__("custom-mcp-server")
        self.register_tools()
        self.register_resources()

    def register_tools(self):
        @self.tool("database_query")
        async def query_database(sql: str):
            """データベースクエリを実行"""
            result = await self.execute_query(sql)
            return {"data": result, "rows_affected": len(result)}

        @self.tool("deploy_application")
        async def deploy(environment: str, version: str):
            """アプリケーションをデプロイ"""
            deployment_result = await self.deploy_to_environment(
                env=environment,
                version=version
            )
            return {"status": "success", "url": deployment_result.url}

        @self.tool("generate_report")
        async def generate_report(type: str, period: str):
            """レポートを生成"""
            report = await self.create_report(type, period)
            return {"report": report, "generated_at": datetime.now()}

    def register_resources(self):
        @self.resource("database_schema")
        async def get_schema():
            """データベーススキーマを提供"""
            return await self.fetch_database_schema()

        @self.resource("api_documentation")
        async def get_api_docs():
            """API仕様書を提供"""
            return await self.load_api_documentation()

2. Claude Code × MCP実践セットアップ

2.1 環境構築

# 1. Claude Codeのインストール
npm install -g @anthropic/claude-code-cli

# 2. MCP設定ファイルの作成
cat > ~/.claude/mcp_config.json << EOF
{
  "mcpServers": {
    "figma": {
      "command": "npx",
      "args": ["@figma/mcp-server"],
      "env": {
        "FIGMA_ACCESS_TOKEN": "${FIGMA_TOKEN}"
      }
    },
    "postgres": {
      "command": "npx",
      "args": ["@postgresql/mcp-server"],
      "env": {
        "DATABASE_URL": "${DATABASE_URL}"
      }
    },
    "github": {
      "command": "npx",
      "args": ["@github/mcp-server"],
      "env": {
        "GITHUB_TOKEN": "${GITHUB_TOKEN}"
      }
    },
    "aws": {
      "command": "npx",
      "args": ["@aws/mcp-server"],
      "env": {
        "AWS_ACCESS_KEY_ID": "${AWS_ACCESS_KEY_ID}",
        "AWS_SECRET_ACCESS_KEY": "${AWS_SECRET_ACCESS_KEY}"
      }
    }
  }
}
EOF

# 3. MCPサーバーの起動
claude-code mcp start --all

2.2 カスタムMCPサーバーの作成

// custom-mcp-server.ts
import { MCPServer, Tool, Resource } from '@anthropic/mcp-sdk';
import { Database } from './database';
import { APIClient } from './api-client';

export class ProjectMCPServer extends MCPServer {
  private db: Database;
  private api: APIClient;

  constructor() {
    super({
      name: 'project-mcp',
      version: '1.0.0',
      description: 'プロジェクト専用MCPサーバー',
    });

    this.db = new Database();
    this.api = new APIClient();
    this.setupTools();
    this.setupResources();
  }

  private setupTools() {
    // ツール1: データ分析
    this.registerTool({
      name: 'analyze_data',
      description: 'データを分析してインサイトを提供',
      parameters: {
        query: { type: 'string', required: true },
        format: { type: 'string', enum: ['json', 'csv', 'chart'] },
      },
      handler: async (params) => {
        const result = await this.db.query(params.query);
        const analysis = await this.analyzeResults(result);
        return this.formatOutput(analysis, params.format);
      },
    });

    // ツール2: 自動デプロイ
    this.registerTool({
      name: 'auto_deploy',
      description: '変更を自動的にデプロイ',
      parameters: {
        branch: { type: 'string', required: true },
        environment: { type: 'string', required: true },
        tests: { type: 'boolean', default: true },
      },
      handler: async (params) => {
        if (params.tests) {
          const testResult = await this.runTests(params.branch);
          if (!testResult.success) {
            throw new Error(`Tests failed: ${testResult.errors}`);
          }
        }

        const deployment = await this.deploy({
          branch: params.branch,
          env: params.environment,
        });

        return {
          success: true,
          url: deployment.url,
          version: deployment.version,
          timestamp: new Date().toISOString(),
        };
      },
    });

    // ツール3: コード生成
    this.registerTool({
      name: 'generate_code',
      description: '仕様からコードを自動生成',
      parameters: {
        specification: { type: 'object', required: true },
        language: { type: 'string', required: true },
        framework: { type: 'string' },
        includeTests: { type: 'boolean', default: true },
      },
      handler: async (params) => {
        const code = await this.generateFromSpec(params.specification, {
          language: params.language,
          framework: params.framework,
        });

        if (params.includeTests) {
          const tests = await this.generateTests(code);
          return { code, tests };
        }

        return { code };
      },
    });
  }

  private setupResources() {
    // リソース1: プロジェクト構造
    this.registerResource({
      name: 'project_structure',
      description: 'プロジェクトの構造とファイル情報',
      handler: async () => {
        return await this.scanProjectStructure();
      },
    });

    // リソース2: 依存関係グラフ
    this.registerResource({
      name: 'dependency_graph',
      description: '依存関係の可視化データ',
      handler: async () => {
        return await this.analyzeDependencies();
      },
    });
  }
}

3. 実践的な統合例

3.1 Figma → Code 完全自動化

// Figmaデザインから完全なアプリケーションを生成
async function figmaToApp(figmaUrl) {
  const claude = new ClaudeCode();

  // 1. Figmaからデザイン情報取得
  const design = await claude.mcp.figma.getDesign(figmaUrl);

  // 2. コンポーネント分析
  const components = await claude.analyze(
    `
    このFigmaデザインから以下を抽出してください:
    - UIコンポーネント構造
    - カラーパレット
    - タイポグラフィ
    - レイアウトグリッド
    - インタラクション
  `,
    design
  );

  // 3. アプリケーション生成
  const app = await claude.generate(`
    以下のコンポーネントでFlutterアプリを作成:
    ${JSON.stringify(components)}
    
    要件:
    - ピクセルパーフェクト
    - レスポンシブ対応
    - アニメーション実装
    - 状態管理(Riverpod)
  `);

  // 4. テスト生成
  const tests = await claude.generateTests(app);

  // 5. 自動デプロイ
  await claude.mcp.deploy({
    code: app,
    tests: tests,
    environment: 'staging',
  });

  return {
    previewUrl: 'https://staging.app.com',
    code: app,
    tests: tests,
    coverage: '100%',
  };
}

3.2 データベース駆動開発

// データベーススキーマからAPI全体を自動生成
class DatabaseDrivenDevelopment {
  async generateFromSchema(databaseUrl: string) {
    const claude = new ClaudeCode();

    // 1. スキーマ取得
    const schema = await claude.mcp.postgres.getSchema(databaseUrl);

    // 2. API設計
    const apiDesign = await claude.design(`
      以下のデータベーススキーマから
      RESTful APIを設計してください:
      ${schema}
      
      含めるもの:
      - CRUD操作
      - 認証・認可
      - バリデーション
      - ページネーション
      - フィルタリング
      - ソート
    `);

    // 3. 実装生成
    const implementation = await claude.implement({
      design: apiDesign,
      framework: 'NestJS',
      database: 'PostgreSQL',
      orm: 'Prisma',
      testing: 'Jest',
      documentation: 'Swagger',
    });

    // 4. マイグレーション生成
    const migrations = await claude.mcp.postgres.generateMigrations(schema);

    // 5. Dockerize
    const docker = await claude.containerize(implementation);

    return {
      api: implementation.code,
      tests: implementation.tests,
      migrations: migrations,
      docker: docker,
      documentation: implementation.swagger,
    };
  }
}

3.3 GitHub統合による自動化

# .github/claude-mcp.yml
name: Claude MCP Automation

on:
  issues:
    types: [opened, labeled]
  pull_request:
    types: [opened, review_requested]

jobs:
  auto-implementation:
    if: contains(github.event.issue.labels.*.name, 'claude-implement')
    runs-on: ubuntu-latest
    steps:
      - name: Setup Claude Code with MCP
        uses: anthropic/claude-code-action@v1
        with:
          mcp-servers: |
            - github
            - postgres
            - aws

      - name: Analyze Issue
        id: analyze
        run: |
          claude-code analyze-issue \
            --issue-number=${{ github.event.issue.number }} \
            --output=analysis.json

      - name: Generate Implementation
        run: |
          claude-code implement \
            --requirements=analysis.json \
            --auto-commit \
            --create-pr \
            --assign-reviewers

      - name: Run Tests
        run: |
          claude-code test \
            --coverage-threshold=90 \
            --mutation-testing

      - name: Deploy Preview
        if: success()
        run: |
          claude-code deploy \
            --environment=preview \
            --url-comment

4. 高度なMCP活用パターン

4.1 マルチエージェント協調

# 複数のMCPサーバーを協調させる
class MultiAgentOrchestrator:
    def __init__(self):
        self.agents = {
            'designer': FigmaMCPAgent(),
            'developer': CodeMCPAgent(),
            'tester': TestMCPAgent(),
            'deployer': DeployMCPAgent(),
            'monitor': MonitoringMCPAgent()
        }

    async def execute_project(self, requirements):
        # 1. デザインフェーズ
        design = await self.agents['designer'].create_design(requirements)

        # 2. 開発フェーズ(並列実行)
        tasks = [
            self.agents['developer'].generate_frontend(design),
            self.agents['developer'].generate_backend(requirements),
            self.agents['developer'].generate_database(requirements)
        ]
        frontend, backend, database = await asyncio.gather(*tasks)

        # 3. テストフェーズ
        test_results = await self.agents['tester'].comprehensive_test({
            'frontend': frontend,
            'backend': backend,
            'database': database,
            'integration': True,
            'performance': True,
            'security': True
        })

        # 4. デプロイフェーズ
        if test_results['pass_rate'] > 0.95:
            deployment = await self.agents['deployer'].deploy_all({
                'frontend': frontend,
                'backend': backend,
                'database': database,
                'environment': 'production',
                'strategy': 'blue-green'
            })

            # 5. モニタリング開始
            await self.agents['monitor'].setup_monitoring(deployment)

        return {
            'status': 'completed',
            'deployment': deployment,
            'metrics': test_results,
            'monitoring_dashboard': deployment['monitoring_url']
        }

4.2 自己改善型MCPシステム

// 使用パターンを学習して自己改善するMCP
class SelfImprovingMCP {
  private patterns: Map<string, UsagePattern> = new Map();
  private performance: PerformanceMetrics;

  async executeWithLearning(task: Task) {
    const startTime = Date.now();

    // 類似パターンの検索
    const similarPattern = this.findSimilarPattern(task);

    let result;
    if (similarPattern) {
      // 過去の成功パターンを適用
      result = await this.applyPattern(similarPattern, task);
    } else {
      // 新規パターンとして実行
      result = await this.executeNewPattern(task);
    }

    // パフォーマンス記録
    const executionTime = Date.now() - startTime;
    this.recordPerformance(task, result, executionTime);

    // パターン学習
    if (result.success) {
      this.learnPattern(task, result);
    }

    // 定期的な最適化
    if (this.patterns.size % 100 === 0) {
      await this.optimizePatterns();
    }

    return result;
  }

  private async optimizePatterns() {
    // 使用頻度と成功率でパターンをランク付け
    const rankedPatterns = Array.from(this.patterns.entries())
      .map(([key, pattern]) => ({
        key,
        score: pattern.successRate * pattern.usageCount,
        pattern,
      }))
      .sort((a, b) => b.score - a.score);

    // 上位パターンを保持、下位を削除
    this.patterns.clear();
    rankedPatterns.slice(0, 1000).forEach(({ key, pattern }) => {
      this.patterns.set(key, pattern);
    });

    // パターンの一般化
    await this.generalizePatterns();
  }
}

5. 実装のベストプラクティス

5.1 セキュリティ考慮事項

// セキュアなMCP実装
class SecureMCPImplementation {
  constructor() {
    this.setupSecurity();
  }

  setupSecurity() {
    // 1. 認証設定
    this.authentication = {
      method: 'JWT',
      expiresIn: '1h',
      refreshToken: true,
      mfa: true,
    };

    // 2. 認可設定
    this.authorization = {
      rbac: true,
      permissions: {
        read: ['viewer', 'editor', 'admin'],
        write: ['editor', 'admin'],
        delete: ['admin'],
        execute: ['admin'],
      },
    };

    // 3. 暗号化
    this.encryption = {
      transit: 'TLS 1.3',
      storage: 'AES-256-GCM',
      secrets: 'HashiCorp Vault',
    };

    // 4. 監査ログ
    this.auditLog = {
      enabled: true,
      level: 'verbose',
      storage: 'immutable',
      retention: '7 years',
    };
  }

  async executeSecureCommand(command, user) {
    // 認証チェック
    if (!(await this.authenticate(user))) {
      throw new Error('Authentication failed');
    }

    // 認可チェック
    if (!(await this.authorize(user, command))) {
      throw new Error('Unauthorized');
    }

    // コマンドサニタイゼーション
    const sanitized = this.sanitize(command);

    // 実行と監査
    try {
      const result = await this.execute(sanitized);
      await this.audit('SUCCESS', user, command, result);
      return result;
    } catch (error) {
      await this.audit('FAILURE', user, command, error);
      throw error;
    }
  }
}

5.2 パフォーマンス最適化

# 高性能MCP実装
class HighPerformanceMCP:
    def __init__(self):
        self.cache = RedisCache()
        self.connection_pool = ConnectionPool(max_size=100)
        self.rate_limiter = RateLimiter(requests_per_second=1000)

    async def optimized_execute(self, request):
        # 1. キャッシュチェック
        cache_key = self.generate_cache_key(request)
        cached = await self.cache.get(cache_key)
        if cached:
            return cached

        # 2. レート制限
        if not await self.rate_limiter.allow(request.user):
            raise RateLimitExceeded()

        # 3. コネクションプーリング
        connection = await self.connection_pool.acquire()

        try:
            # 4. バッチ処理
            if self.can_batch(request):
                result = await self.batch_execute(request)
            else:
                result = await self.single_execute(request, connection)

            # 5. 非同期キャッシュ更新
            asyncio.create_task(
                self.cache.set(cache_key, result, ttl=300)
            )

            return result

        finally:
            await self.connection_pool.release(connection)

    async def batch_execute(self, requests):
        # 複数リクエストを1つにまとめて実行
        batched = self.combine_requests(requests)
        results = await self.execute_batch(batched)
        return self.split_results(results, requests)

6. トラブルシューティング

6.1 よくある問題と解決策

問題 原因 解決策
MCP接続エラー サーバー未起動 claude-code mcp statusで確認
認証失敗 トークン期限切れ トークン更新またはリフレッシュ
タイムアウト 重い処理 非同期処理、バッチ処理化
メモリリーク 接続未解放 適切なクリーンアップ実装
データ不整合 同期問題 トランザクション、ロック機構

6.2 デバッグ手法

# MCPデバッグコマンド
# 1. ログレベル設定
export MCP_LOG_LEVEL=debug

# 2. トレース有効化
claude-code mcp trace --enable

# 3. 接続テスト
claude-code mcp test --server=figma --verbose

# 4. パフォーマンス分析
claude-code mcp profile --duration=60s

# 5. ヘルスチェック
claude-code mcp health --all

まとめ

Claude Code × MCPは、AI開発の新たな地平を開きます:

革命的な変化:

  • AIが「考える」から「実行する」へ
  • 完全自動化された開発フロー
  • 外部ツールとのシームレスな統合
  • 人間は戦略に集中、実装はAIに

実装のポイント:

  1. 段階的なMCP導入
  2. セキュリティファースト
  3. パフォーマンス最適化
  4. 継続的な改善

次のステップ:

  1. 基本的なMCPサーバーの構築
  2. 既存ツールとの統合
  3. カスタムMCPの開発
  4. マルチエージェントシステムへ

MCPは単なるツールではなく、AI駆動開発の新しいパラダイムです。今すぐ導入し、次世代の開発体験を手に入れましょう。

ゆうき|毎月20万円積立のプロフィール画像

ゆうき|毎月20万円積立

メガベンチャー シニアエンジニア

Flutter、Next.js、AIを活用した開発を専門とするエンジニア。29歳で資産1000万円を運用中。テクノロジーと投資を組み合わせて、45歳でのサイドFIRE達成を目指しています。

7年以上の開発経験
専門分野:
FlutterNext.jsAI/Claudeシステム設計投資戦略
資格・認定:
  • 年収850万円(29歳)
  • VOO・BND中心に1000万円運用
検証済み専門家