概要

MCP(Model Context Protocol)ツールは、拡張機能のためのMCPサーバーとの統合を可能にします。これらのツールを使用すると、ローカルとリモートの両方のMCPサーバーに接続し、利用可能なツールを発見し、Python SDKを使用してカスタム入力でそれらを実行できます。

主な機能

MCP_LOCAL_RUN

  • ローカルMCPサーバーに接続
  • ローカル環境でツールを実行
  • 直接Python SDK統合
  • リアルタイムツール発見と実行

MCP_REMOTE_RUN

  • HTTP経由でリモートMCPサーバーに接続
  • ストリーム可能なHTTP接続
  • クラウドベースのツール実行
  • スケーラブルなリモート処理

認証

MCPツールは、サーバー設定に応じて認証が必要な場合があります。特定の要件については、MCPサーバー管理者に確認してください。

例: ローカルMCPサーバー統合

- id: connect_local_mcp
  name: connect_local_mcp
  tool: MCP_LOCAL_RUN
  input:
    - name: server_config
      value: |
        {
          "server_path": "/path/to/mcp-server",
          "server_args": ["--config", "/path/to/config.json"],
          "timeout": 30
        }
    - name: tool_name
      value: "file_reader"
    - name: tool_inputs
      value: |
        {
          "file_path": "/home/user/documents/report.txt",
          "encoding": "utf-8"
        }

- id: process_mcp_result
  name: process_mcp_result
  tool: PYTHON_SANDBOX_RUN
  input:
    - name: code
      value: |
        import json
        
        # MCPツール結果を処理
        mcp_result = json.loads('''{{steps.connect_local_mcp.result.output}}''')
        
        print("MCPツール実行結果:")
        print("=" * 30)
        print(f"ツール: {mcp_result.get('tool_name', '不明')}")
        print(f"ステータス: {mcp_result.get('status', '不明')}")
        print(f"実行時間: {mcp_result.get('execution_time', 'N/A')}ms")
        print()
        
        if 'data' in mcp_result:
            print("出力データ:")
            print(mcp_result['data'])

例: リモートMCPサービス統合

- id: discover_remote_tools
  name: discover_remote_tools
  tool: MCP_REMOTE_RUN
  input:
    - name: server_url
      value: "https://mcp-server.example.com/api"
    - name: auth_token
      value: "{{secrets.MCP_AUTH_TOKEN}}"
    - name: action
      value: "list_tools"
    - name: tool_inputs
      value: "{}"

- id: execute_remote_analysis
  name: execute_remote_analysis
  tool: MCP_REMOTE_RUN
  input:
    - name: server_url
      value: "https://mcp-server.example.com/api"
    - name: auth_token
      value: "{{secrets.MCP_AUTH_TOKEN}}"
    - name: tool_name
      value: "data_analyzer"
    - name: tool_inputs
      value: |
        {
          "data_source": "{{steps.input_data.result.file_url}}",
          "analysis_type": "statistical_summary",
          "output_format": "json",
          "include_charts": true
        }

- id: save_analysis_results
  name: save_analysis_results
  tool: OUTPUT_FILE
  input:
    - name: content
      value: "{{steps.execute_remote_analysis.result.output}}"
    - name: filename
      value: "mcp_analysis_results_{{date | format('YYYY-MM-DD')}}.json"
    - name: fileType
      value: "json"

例: マルチツールMCPワークフロー

- id: setup_mcp_environment
  name: setup_mcp_environment
  tool: PYTHON_SANDBOX_RUN
  input:
    - name: code
      value: |
        # MCPワークフロー設定を定義
        mcp_workflow = {
            "server_config": {
                "local_server": "/opt/mcp-tools/server",
                "remote_server": "https://api.mcp-cloud.example.com",
                "timeout": 60,
                "retry_attempts": 3
            },
            "tools_to_execute": [
                {
                    "name": "document_parser",
                    "type": "local",
                    "inputs": {
                        "document_url": "{{input.document_url}}",
                        "extract_images": True,
                        "extract_tables": True
                    }
                },
                {
                    "name": "content_analyzer", 
                    "type": "remote",
                    "inputs": {
                        "content_type": "document",
                        "analysis_depth": "comprehensive"
                    }
                },
                {
                    "name": "report_generator",
                    "type": "remote",
                    "inputs": {
                        "template": "standard_report",
                        "include_summary": True
                    }
                }
            ]
        }
        
        import json
        print(json.dumps(mcp_workflow, indent=2, ensure_ascii=False))

- id: parse_document_local
  name: parse_document_local
  tool: MCP_LOCAL_RUN
  input:
    - name: server_config
      value: |
        {
          "server_path": "/opt/mcp-tools/server",
          "timeout": 60
        }
    - name: tool_name
      value: "document_parser"
    - name: tool_inputs
      value: |
        {
          "document_url": "{{input.document_url}}",
          "extract_images": true,
          "extract_tables": true,
          "output_format": "structured_json"
        }

- id: analyze_content_remote
  name: analyze_content_remote
  tool: MCP_REMOTE_RUN
  input:
    - name: server_url
      value: "https://api.mcp-cloud.example.com"
    - name: auth_token
      value: "{{secrets.MCP_CLOUD_TOKEN}}"
    - name: tool_name
      value: "content_analyzer"
    - name: tool_inputs
      value: |
        {
          "parsed_content": {{steps.parse_document_local.result.output}},
          "analysis_type": "comprehensive",
          "include_sentiment": true,
          "include_entities": true,
          "include_summary": true
        }

- id: generate_final_report
  name: generate_final_report
  tool: MCP_REMOTE_RUN
  input:
    - name: server_url
      value: "https://api.mcp-cloud.example.com"
    - name: auth_token
      value: "{{secrets.MCP_CLOUD_TOKEN}}"
    - name: tool_name
      value: "report_generator"
    - name: tool_inputs
      value: |
        {
          "analysis_results": {{steps.analyze_content_remote.result.output}},
          "template": "executive_summary",
          "format": "markdown",
          "include_charts": true,
          "include_recommendations": true
        }

- id: save_comprehensive_report
  name: save_comprehensive_report
  tool: OUTPUT_FILE
  input:
    - name: content
      value: "{{steps.generate_final_report.result.output}}"
    - name: filename
      value: "comprehensive_analysis_report.md"
    - name: fileType
      value: "txt"

例: カスタムMCPツール開発

- id: deploy_custom_mcp_tool
  name: deploy_custom_mcp_tool
  tool: MCP_LOCAL_RUN
  input:
    - name: server_config
      value: |
        {
          "server_path": "/usr/local/bin/custom-mcp-server",
          "server_args": ["--plugin-dir", "/home/user/mcp-plugins"],
          "environment": {
            "MCP_DEBUG": "true",
            "MCP_LOG_LEVEL": "info"
          }
        }
    - name: tool_name
      value: "custom_data_processor"
    - name: tool_inputs
      value: |
        {
          "input_data": {{steps.prepare_data.result.processed_data}},
          "processing_rules": {
            "remove_duplicates": true,
            "normalize_dates": true,
            "validate_emails": true,
            "standardize_phone_numbers": true
          },
          "output_options": {
            "format": "json",
            "include_metadata": true,
            "include_statistics": true
          }
        }

- id: validate_mcp_output
  name: validate_mcp_output
  tool: PYTHON_SANDBOX_RUN
  input:
    - name: code
      value: |
        import json
        
        # MCPツール出力を検証
        try:
            mcp_output = json.loads('''{{steps.deploy_custom_mcp_tool.result.output}}''')
            
            print("MCPツール検証結果:")
            print("=" * 25)
            
            # 必須フィールドを確認
            required_fields = ['processed_data', 'metadata', 'statistics']
            missing_fields = [field for field in required_fields if field not in mcp_output]
            
            if missing_fields:
                print(f"❌ 必須フィールドが不足: {', '.join(missing_fields)}")
            else:
                print("✅ すべての必須フィールドが存在")
            
            # データ構造を検証
            if 'processed_data' in mcp_output:
                data_count = len(mcp_output['processed_data'])
                print(f"📊 {data_count}件のレコードを処理")
            
            if 'statistics' in mcp_output:
                stats = mcp_output['statistics']
                print(f"📈 処理統計:")
                for key, value in stats.items():
                    print(f"   {key}: {value}")
            
            print("✅ MCPツールが正常に実行されました")
            
        except json.JSONDecodeError as e:
            print(f"❌ MCPツールからの無効なJSON出力: {e}")
        except Exception as e:
            print(f"❌ MCP出力検証エラー: {e}")

MCPサーバー設定

ローカルサーバーセットアップ

{
  "server_path": "/path/to/mcp-server",
  "server_args": ["--config", "/path/to/config.json"],
  "environment": {
    "MCP_LOG_LEVEL": "info",
    "MCP_TIMEOUT": "30"
  },
  "timeout": 60,
  "retry_attempts": 3
}

リモートサーバーセットアップ

{
  "server_url": "https://mcp-server.example.com/api",
  "auth_method": "bearer_token",
  "auth_token": "your-auth-token",
  "timeout": 30,
  "stream_response": true
}

ツール発見

利用可能なツールの一覧表示

- id: discover_tools
  name: discover_tools  
  tool: MCP_LOCAL_RUN
  input:
    - name: action
      value: "list_tools"
    - name: server_config
      value: '{"server_path": "/path/to/mcp-server"}'

ツールスキーマの取得

- id: get_tool_info
  name: get_tool_info
  tool: MCP_REMOTE_RUN
  input:
    - name: action
      value: "describe_tool"
    - name: tool_name
      value: "data_processor"
    - name: server_url
      value: "https://mcp-server.example.com/api"

エラーハンドリング

一般的なエラータイプ

  • 接続エラー: サーバーに到達できない、または認証に失敗
  • ツールが見つからない: 指定されたツールがサーバーに存在しない
  • 入力検証: ツール実行用の無効な入力
  • タイムアウトエラー: ツール実行が制限時間を超過
  • サーバーエラー: 実行中の内部サーバーエラー

エラーレスポンス形式

{
  "error": {
    "type": "tool_execution_error",
    "message": "ツール実行に失敗しました",
    "details": {
      "tool_name": "data_processor",
      "error_code": "INPUT_VALIDATION_FAILED",
      "timestamp": "2024-01-15T14:30:00Z"
    }
  }
}

使用例

  • データ処理: 高度なデータ変換と分析
  • 文書処理: 複雑な文書解析と抽出
  • AI/ML統合: 機械学習モデルの実行
  • カスタムワークフロー: ドメイン固有のビジネスロジック実行
  • 外部API統合: 外部サービスのラッパー
  • バッチ処理: 大規模データ処理操作
  • 専門ツール: 業界固有の処理ツール
  • 研究ツール: 学術・科学計算ツール

ベストプラクティス

パフォーマンス最適化

  • 頻繁な操作にはローカルサーバーを使用
  • 計算集約的なタスクにはリモートサーバーを使用
  • 適切なタイムアウト処理を実装
  • ツール発見結果をキャッシュ

セキュリティ考慮事項

  • 認証トークンを安全に保護
  • すべての入力と出力を検証
  • リモート接続にはHTTPSを使用
  • 適切なエラーハンドリングを実装

開発ガイドライン

  • カスタムMCPツールを徹底的に文書化
  • 適切なログと監視を実装
  • 一貫した入力/出力スキーマを使用
  • デプロイ前にツールを徹底的にテスト