mcpField
D
D365FO MCP Server

D365FO MCP Server

ローカル
github.com/mafzaalビジネス・マーケティング403 日前に更新

D365FO MCP Server について

D365FO MCP Server は Microsoft Dynamics 365 Finance & Operations 向けのコミュニティ製 MCP サーバーで、FastMCP フレームワーク上に構築され、Python クライアントライブラリも同梱しています。D365 F&O 環境へ AI アシスタントからアクセスしたい開発者や組織を対象としています。stdio、HTTP、SSE のトランスポートに対応し、Azure AD 認証を利用できます。

主な機能

  1. 01D365 F&O の操作を扱う 49 のツール
  2. 02メタデータ検出に対応した 12 種類のリソース
  3. 03stdio、HTTP、SSE トランスポートへの対応
  4. 04認証情報を保存する複数環境のプロファイル
  5. 05Azure AD 認証と Key Vault への対応

活用シーン

  1. 01AI アシスタントから D365 F&O 環境の情報を照会する
  2. 02Web アプリケーション向けにリモート HTTP エンドポイントを公開する
  3. 03VS Code の GitHub Copilot から D365 F&O に接続する
  4. 04MCP サーバーを Docker コンテナーで実行する

MCP 対応

本プロジェクトは MCP サーバーであり、49 のツール、12 種類のリソース、2 つのプロンプトテンプレートを MCP クライアントに提供します。

設定

ローカルサーバーの設定はどのクライアントでも共通です。コピーしてクライアントの MCP 設定ファイルに貼り付けてください。

mcp.json · 共通設定
{
"mcpServers": {
"mafzaal-d365fo-client": {
"command": "uvx",
"args": [
"d365fo-client"
],
"env": {
"D365FO_CLIENT_ID": "<D365FO_CLIENT_ID>",
"D365FO_CLIENT_SECRET": "<D365FO_CLIENT_SECRET>",
"D365FO_TENANT_ID": "<D365FO_TENANT_ID>",
"D365FO_BASE_URL": "<D365FO_BASE_URL>"
}
}
}
}
起動コマンドuvx d365fo-client
設定が必要な環境変数
D365FO_CLIENT_IDYour D365FO Client ID
D365FO_CLIENT_SECRETシークレットYour D365FO Client Secret
D365FO_TENANT_IDYour D365FO Tenant ID
D365FO_BASE_URLYour D365FO Base URL

ローカルサーバーにはマシン上の実行環境(Node.js 18 以上など)が必要です。設定ファイルの場所はクライアントごとに異なります。

パッケージ
pypid365fo-client0.3.6
ocighcr.io/mafzaal/d365fo-client:0.3.6

ツール

ツール一覧はまだ取得されていません

ローカルサーバーのツールはマシン上で起動して初めて取得できます。メンテナーはまだツール一覧を提供していません。

詳細

Dynamics 365 Finance & Operations MCP サーバー

D365FO MCP サーバーのロゴ

本番環境対応の Model Context Protocol(MCP)サーバーです。Microsoft Dynamics 365 Finance & Operations(D365 F&O)のすべての機能を、AI アシスタントやその他の MCP 互換ツールに公開します。これにより、標準化されたプロトコルのやり取りを通じて、高度な Dynamics 365 統合ワークフローを実現できます。

GitHub ウォッチャー数 GitHub フォーク数 GitHub スター数

🚀 VS Code にワンクリックでインストール:

VS Code に UVX でインストール VS Code Insiders に UVX でインストール

🐳 VS Code 用 Docker インストール: Docker を使用して VS Code にインストール Docker を使用して VS Code Insiders にインストール

☁️ Azure Container Apps にデプロイ:

OAuth または API Key 認証を使用して、MCP サーバーを安全でインターネットからアクセス可能な HTTP エンドポイントとしてデプロイします。ウェブ連携やリモート AI アシスタントからのアクセスに最適です。

オプション 1:Bash スクリプトを使用(推奨)

# Download and run the deployment script
curl -O https://raw.githubusercontent.com/mafzaal/d365fo-client/main/deploy-aca.sh
chmod +x deploy-aca.sh

# Set authentication (choose OAuth or API Key)
export D365FO_MCP_AUTH_CLIENT_ID="your-client-id"
export D365FO_MCP_AUTH_CLIENT_SECRET="your-client-secret"
export D365FO_MCP_AUTH_TENANT_ID="your-tenant-id"
# OR
export D365FO_MCP_API_KEY_VALUE="your-secret-key"

# Deploy
./deploy-aca.sh

オプション 2:ARM テンプレートを使用

  1. azure-deploy.json をダウンロードします
  2. Azure Portal → カスタムテンプレートのデプロイ に移動します
  3. 「エディターで独自のテンプレートを作成」をクリックします
  4. azure-deploy.json の内容を貼り付けます
  5. パラメーターを入力してデプロイします

PyPI - ダウンロード数

また、OData エンドポイント、メタデータ操作、ラベル管理、CLI ツールを備えた、Microsoft Dynamics 365 Finance & Operations 用の包括的な Python クライアントライブラリも含まれています。

MCP サーバーの概要

d365fo-client には、FastMCP フレームワーク上に構築された本番環境対応の Model Context Protocol(MCP)サーバー(d365fo-fastmcp-server)が含まれており、D365 Finance & Operations のあらゆる機能を AI アシスタントやその他の MCP 対応ツールに公開します。

このサーバーは、パフォーマンスの向上と柔軟なデプロイを実現するマルチトランスポート(stdio、HTTP、SSE)に対応しています。

主な機能
  • 49 個の包括的なツールで、9 つの機能カテゴリにわたる D365 F&O の主要な操作を網羅
  • 12 種類のリソースで、包括的なメタデータの公開と検出機能を提供
  • 2 つのプロンプトテンプレートで、高度なワークフロー支援を実現
  • マルチトランスポート対応(FastMCP):stdio、HTTP、Server-Sent Events(SSE)
  • 適切なエラー処理、認証、セキュリティ検証を備えた本番環境対応の実装
  • パフォーマンスの向上(FastMCP):起動時間を 40% 短縮、メモリ使用量を 15% 削減
  • 複数の環境と安全な認証情報の保存に対応した高度なプロファイル管理
  • 安全な SQL クエリとメタデータの分析情報を備えたデータベース分析機能
  • 詳細な進捗追跡と複数の同期戦略を備えたセッションベースの同期
  • ラベル解決とローカライズ機能を備えた多言語対応
  • Azure AD 連携、Key Vault 対応、監査ログを備えたエンタープライズセキュリティ
v0.3.0 の新機能
  • 🔧 Pydantic Settings Model:35 以上の設定オプションを検証できる、型安全な環境変数管理
  • 📂 カスタムログファイル対応:柔軟なログファイルパスを設定する D365FO_LOG_FILE 環境変数
  • 🔄 レガシー設定の移行:レガシー設定ファイルを自動で検出して移行
  • 🌐 環境変数の標準化:一貫性を保つため、すべての MCP HTTP 変数で D365FO_ 接頭辞を使用
  • ⚡ FastMCP サーバーの強化:起動設定、エラー処理、正常なシャットダウンを改善
  • 🔀 MCP の戻り値型の標準化:型安全性の向上のため、すべての MCP ツールが JSON 文字列ではなく辞書を返すように変更
  • 🛠️ 設定の強化:.env ファイルに対応し、環境変数の包括的なドキュメントを追加
クイックスタート
インストールとセットアップ
# Install d365fo-client with MCP dependencies
pip install d365fo-client

# Set up environment variables
export D365FO_BASE_URL="https://your-environment.dynamics.com"
export D365FO_CLIENT_ID="your-client-id"          # Optional with default credentials
export D365FO_CLIENT_SECRET="your-client-secret"  # Optional with default credentials  
export D365FO_TENANT_ID="your-tenant-id"          # Optional with default credentials
FastMCP サーバー(推奨)

最新の FastMCP 実装では、パフォーマンスが向上し、複数のトランスポートオプションを利用できます。

# Development (stdio transport - default)
d365fo-fastmcp-server

# Production HTTP API
d365fo-fastmcp-server --transport http --port 8000 --host 0.0.0.0

# Real-time Web Applications (SSE)
d365fo-fastmcp-server --transport sse --port 8001 --host 0.0.0.0

主なメリット:

  • FastMCP フレームワークによるパフォーマンスの最適化
  • 最適化されたアーキテクチャによる効率的なリソース使用
  • マルチトランスポート対応:stdio、HTTP、Server-Sent Events(SSE)
  • async/await のサポートを改善した強化されたエラー処理
  • API 連携用のウェブトランスポートを備えた本番環境対応
AI アシスタントとの連携
VS Code との連携(推奨)

デフォルトの認証情報を使用する FastMCP サーバー: MCP 対応の GitHub Copilot 用に、VS Code の mcp.json に追加します。

{
  "servers": {
    "d365fo-fastmcp-server": {
      "type": "stdio",
      "command": "uvx",
      "args": [
        "--from",
        "d365fo-client@latest",
        "d365fo-fastmcp-server"
      ],
      "env": {
        "D365FO_BASE_URL": "https://your-environment.dynamics.com",
        "D365FO_LOG_LEVEL": "INFO"
      }
    }
  }
}

オプション 2:認証情報を明示的に指定 サービスプリンシパル認証が必要な環境向け:

{
  "servers": {
    "d365fo-fastmcp-server": {
      "type": "stdio", 
      "command": "uvx",
      "args": [
        "--from",
        "d365fo-client",
        "d365fo-fastmcp-server"
      ],
      "env": {
        "D365FO_BASE_URL": "https://your-environment.dynamics.com",
        "D365FO_LOG_LEVEL": "DEBUG",
        "D365FO_CLIENT_ID": "${input:client_id}",
        "D365FO_CLIENT_SECRET": "${input:client_secret}",
        "D365FO_TENANT_ID": "${input:tenant_id}"
      }
    }
  },
  "inputs": [
    {
      "id": "tenant_id",
      "type": "promptString",
      "description": "Azure AD Tenant ID for D365 F&O authentication",
      "password": true
    },
    {
      "id": "client_id", 
      "type": "promptString",
      "description": "Azure AD Client ID for D365 F&O authentication",
      "password": true
    },
    {
      "id": "client_secret",
      "type": "promptString", 
      "description": "Azure AD Client Secret for D365 F&O authentication",
      "password": true
    }
  ]
}

オプション 3:Docker との連携 コンテナ化された環境と、より強固な分離が必要な場合:

{
  "servers": {
    "d365fo-fastmcp-server": {
      "type": "stdio",
      "command": "docker",
      "args": [
        "run",
        "--rm",
        "-i",
        "-v",
        "d365fo-mcp:/home/mcp_user/",
        "-e",
        "D365FO_CLIENT_ID=${input:client_id}",
        "-e",
        "D365FO_CLIENT_SECRET=${input:client_secret}",
        "-e",
        "D365FO_TENANT_ID=${input:tenant_id}",
        "ghcr.io/mafzaal/d365fo-client:latest"
      ],
      "env": {
        "D365FO_LOG_LEVEL": "DEBUG",
        "D365FO_CLIENT_ID": "${input:client_id}",
        "D365FO_CLIENT_SECRET": "${input:client_secret}",
        "D365FO_TENANT_ID": "${input:tenant_id}"
      }
    }
  },
  "inputs": [
    {
      "id": "tenant_id",
      "type": "promptString",
      "description": "Azure AD Tenant ID for D365 F&O authentication",
      "password": true
    },
    {
      "id": "client_id",
      "type": "promptString",
      "description": "Azure AD Client ID for D365 F&O authentication",
      "password": true
    },
    {
      "id": "client_secret",
      "type": "promptString",
      "description": "Azure AD Client Secret for D365 F&O authentication",
      "password": true
    }
  ]
}

Docker 方式のメリット:

  • 環境を完全に分離し、再現性を確保
  • ローカルへの Python のインストールが不要
  • 異なるシステム間で一貫したランタイム環境
  • ビルド済みイメージによる依存関係の自動管理
  • コンテナ化によるセキュリティの強化
  • Docker ボリューム(d365fo-mcp)を使った永続的なデータ保存

前提条件:

  • Docker がインストールされ、起動していること
  • Docker Hub または GitHub Container Registry にアクセスできること
  • コンテナイメージを取得するためのネットワークアクセスがあること
Claude Desktop との連携

FastMCP サーバー: Claude Desktop の設定に追加します。

{
  "mcpServers": {
    "d365fo-fastmcp": {
      "command": "uvx",
      "args": [
        "--from",
        "d365fo-client",
        "d365fo-fastmcp-server"
      ],
      "env": {
        "D365FO_BASE_URL": "https://your-environment.dynamics.com",
        "D365FO_LOG_LEVEL": "INFO"
      }
    }
  }
}

従来の MCP サーバー(代替):

{
  "mcpServers": {
    "d365fo": {
      "command": "uvx",
      "args": [
        "--from",
        "d365fo-client",
        "d365fo-fastmcp-server"
      ],
      "env": {
        "D365FO_BASE_URL": "https://your-environment.dynamics.com",
        "D365FO_LOG_LEVEL": "INFO"
      }
    }
  }
}

uvx を使用するメリット:

  • リポジトリの最新バージョンを常に使用
  • ローカルへのインストールが不要
  • 依存関係を自動管理
  • さまざまな環境で動作
FastMCP を使用した Web 統合

FastMCP サーバーは、Web アプリケーションとの統合のために HTTP および SSE トランスポートを提供します。

Web API 向けの HTTP トランスポート
import aiohttp
import json

async def call_d365fo_api():
    """Example: Using HTTP transport for web API integration"""
    
    # Start FastMCP server with HTTP transport
    # d365fo-fastmcp-server --transport http --port 8000
    
    mcp_request = {
        "jsonrpc": "2.0",
        "id": 1,
        "method": "tools/call",
        "params": {
            "name": "d365fo_query_entities",
            "arguments": {
                "entityName": "CustomersV3",
                "top": 10,
                "select": ["CustomerAccount", "Name"]
            }
        }
    }
    
    async with aiohttp.ClientSession() as session:
        async with session.post(
            "http://localhost:8000/mcp",
            json=mcp_request,
            headers={"Content-Type": "application/json"}
        ) as response:
            result = await response.json()
            print(json.dumps(result, indent=2))
リアルタイムアプリケーション向けの SSE トランスポート
// Example: JavaScript client for real-time D365FO data
// Start FastMCP server: d365fo-fastmcp-server --transport sse --port 8001

const eventSource = new EventSource('http://localhost:8001/sse');

eventSource.onmessage = function(event) {
    const data = JSON.parse(event.data);
    console.log('Received D365FO data:', data);
    
    // Handle real-time updates from D365FO
    if (data.method === 'notification') {
        updateDashboard(data.params);
    }
};

// Send MCP requests via SSE
function queryCustomers() {
    const request = {
        jsonrpc: "2.0",
        id: Date.now(),
        method: "tools/call",
        params: {
            name: "d365fo_search_entities",
            arguments: {
                pattern: "customer",
                limit: 50
            }
        }
    };
    
    fetch('http://localhost:8001/sse/send', {
        method: 'POST',
        headers: {'Content-Type': 'application/json'},
        body: JSON.stringify(request)
    });
}
別の方法:プログラムによる使用
from d365fo_client.mcp import D365FOMCPServer

# Create and run server with custom configuration
config = {
    "default_environment": {
        "base_url": "https://your-environment.dynamics.com",
        "use_default_credentials": True
    }
}

server = D365FOMCPServer(config)
await server.run()
カスタム MCP クライアント

MCP 互換のクライアントライブラリを使用して接続します。

from mcp import Client

async with Client("d365fo-fastmcp-server") as client:
    # Discover available tools
    tools = await client.list_tools()
    
    # Execute operations
    result = await client.call_tool(
        "d365fo_query_entities",
        {"entityName": "Customers", "top": 5}
    )
Docker によるデプロイ

コンテナー化された環境や本番環境へのデプロイでは、次の手順を使用します。

Docker イメージをプル:

# Pull from GitHub Container Registry
docker pull ghcr.io/mafzaal/d365fo-client:latest

# Or pull a specific version
docker pull ghcr.io/mafzaal/d365fo-client:v0.2.3

スタンドアロン Docker の使用:

# Run MCP server with environment variables
docker run --rm -i \
  -e D365FO_BASE_URL="https://your-environment.dynamics.com" \
  -e D365FO_CLIENT_ID="your-client-id" \
  -e D365FO_CLIENT_SECRET="your-client-secret" \
  -e D365FO_TENANT_ID="your-tenant-id" \
  -e D365FO_LOG_LEVEL="INFO" \
  -v d365fo-mcp:/home/mcp_user/ \
  ghcr.io/mafzaal/d365fo-client:latest

# Run CLI commands with Docker
docker run --rm -it \
  -e D365FO_BASE_URL="https://your-environment.dynamics.com" \
  -e D365FO_CLIENT_ID="your-client-id" \
  -e D365FO_CLIENT_SECRET="your-client-secret" \
  -e D365FO_TENANT_ID="your-tenant-id" \
  ghcr.io/mafzaal/d365fo-client:latest \
  d365fo-client entities --limit 10

Docker Compose の例:

version: '3.8'
services:
  d365fo-mcp:
    image: ghcr.io/mafzaal/d365fo-client:latest
    environment:
      - D365FO_BASE_URL=https://your-environment.dynamics.com
      - D365FO_CLIENT_ID=${D365FO_CLIENT_ID}
      - D365FO_CLIENT_SECRET=${D365FO_CLIENT_SECRET}
      - D365FO_TENANT_ID=${D365FO_TENANT_ID}
      - D365FO_LOG_LEVEL=INFO
    volumes:
      - d365fo-mcp:/home/mcp_user/
    stdin_open: true
    tty: true

volumes:
  d365fo-mcp:

Docker の利点:

  • 環境を完全に分離し、再現性を確保
  • ローカルへの Python のインストールは不要
  • 異なるシステム間で一貫したランタイム環境を実現
  • 依存関係の管理機能を内蔵
  • コンテナー化によるセキュリティの強化
  • Docker ボリュームによる永続的なデータ保存
  • オーケストレーションプラットフォーム(Kubernetes、Docker Swarm)との簡単な統合
アーキテクチャの利点
AI アシスタント向け
  • 標準化されたインターフェース:D365 F&O への一貫した MCP プロトコルアクセス
  • 豊富なメタデータ:自己記述型のエンティティと操作
  • 型安全性:すべての操作に対するスキーマ検証
  • エラーコンテキスト:トラブルシューティングに役立つ詳細なエラー情報
開発者向け
  • 最小限の統合:標準的な MCP クライアントライブラリ
  • 包括的な機能範囲:D365 F&O の全機能を公開
  • パフォーマンスの最適化:効率的な接続およびキャッシュ戦略
  • 充実したドキュメント:完全な API ドキュメントと例
組織向け
  • セキュアなアクセス:エンタープライズレベルの認証(Azure AD、Managed Identity)
  • 監査ログ:操作の完全な追跡と監視
  • スケーラブルな設計:接続プーリングとセッション管理
  • メンテナンスの容易さ:明確なアーキテクチャと包括的なテストカバレッジ
トラブルシューティング
よくある問題

接続の失敗

# Test connectivity
d365fo-client version app --base-url https://your-environment.dynamics.com

# Check logs
tail -f ~/.d365fo-mcp/logs/mcp-server.log

認証の問題

# Verify Azure CLI authentication
az account show

# Test with explicit credentials
export D365FO_CLIENT_ID="your-client-id"
# ... set other variables
d365fo-fastmcp-server

パフォーマンスの問題

# Enable debug logging
export D365FO_LOG_LEVEL="DEBUG"

# Adjust connection settings
export D365FO_CONNECTION_TIMEOUT="120"
export D365FO_MAX_CONCURRENT_REQUESTS="5"
ヘルプの利用
  • ログ:詳細なエラー情報については、~/.d365fo-mcp/logs/mcp-server.log を確認してください
  • 環境:d365fo_get_environment_info ツールを使用して、システムの状態を確認してください
  • ドキュメント:技術的な詳細については、MCP 実装の概要を参照してください
  • 問題の報告:GitHub Issues で問題を報告してください
MCP ツール

サーバーは、機能別に分類された49 個の包括的なツールを提供します。

接続と環境に関するツール(2 個)
  • d365fo_test_connection - パフォーマンス指標とエラー診断機能を使用して、接続と認証をテストします
  • d365fo_get_environment_info - バージョン、構成、機能を含む環境の詳細情報を取得します
CRUD 操作ツール(7 個)
  • d365fo_query_entities - 「eq」フィルタリング、ワイルドカードパターン、フィールド選択、ページネーションに対応した、簡易化された OData クエリ
  • d365fo_get_entity_record - 展開オプションと ETag に対応し、キーを指定して特定のレコードを取得します
  • d365fo_create_entity_record - 検証とビジネスロジックの実行を伴って、新しいエンティティレコードを作成します
  • d365fo_update_entity_record - 部分更新と楽観的同時実行制御を使用して、既存のレコードを更新します
  • d365fo_delete_entity_record - 参照整合性のチェックとカスケードルールに従って、エンティティレコードを削除します
  • d365fo_call_action - 複雑なビジネス操作のために、OData アクションと関数を実行します
  • d365fo_call_json_service - パラメーターとレスポンス処理に対応した、汎用 JSON サービスエンドポイントを呼び出します
メタデータ検出ツール(6 個)
  • d365fo_search_entities - カテゴリによる絞り込みと全文検索機能を備えた、パターンに基づくエンティティの検索
  • d365fo_get_entity_schema - プロパティ、リレーションシップ、ラベル解決を含む、詳細なエンティティスキーマの取得
  • d365fo_search_actions - バインドの種類とパラメーター情報を含む、利用可能な OData アクションの検索
  • d365fo_search_enumerations - キーワードに基づく絞り込みによる、システム列挙型の検索
  • d365fo_get_enumeration_fields - 多言語サポートによる、詳細な列挙型メンバー情報の取得
  • d365fo_get_installed_modules - インストール済みモジュールとその構成に関する情報の取得
ラベル管理ツール(2 個)
  • d365fo_get_label - 多言語サポートとフォールバックオプションによる、ID を指定した単一ラベルテキストの取得
  • d365fo_get_labels_batch - バッチ処理とパフォーマンス最適化による、複数ラベルの効率的な取得
プロファイル管理ツール(14 個)
  • d365fo_list_profiles - ステータス情報を含む、構成済みのすべての D365FO 環境プロファイルの一覧表示
  • d365fo_get_profile - 特定のプロファイルの詳細な構成情報の取得
  • d365fo_create_profile - 包括的な認証オプションを使用した、新しい環境プロファイルの作成
  • d365fo_update_profile - 部分更新をサポートした、既存のプロファイル構成の変更
  • d365fo_delete_profile - 適切なクリーンアップと検証による、環境プロファイルの削除
  • d365fo_set_default_profile - 操作の既定として、特定のプロファイルを指定
  • d365fo_get_default_profile - 現在構成されている既定のプロファイル情報の取得
  • d365fo_validate_profile - 完全性とセキュリティ要件への準拠について、プロファイル構成を検証
  • d365fo_test_profile_connection - 特定のプロファイルの接続と認証をテスト
  • d365fo_clone_profile - 新しい環境向けのカスタマイズオプションを使用した、既存プロファイルの複製
  • d365fo_search_profiles - 絞り込みと並べ替え機能を備えた、パターンに基づくプロファイルの検索
  • d365fo_get_profile_names - すばやく参照できる、利用可能なプロファイル名の簡易一覧の取得
  • d365fo_import_profiles - 外部ソースまたはバックアップからのプロファイル構成のインポート
  • d365fo_export_profiles - バックアップまたはデプロイ用のプロファイル構成のエクスポート
データベース分析ツール(4 個)
  • d365fo_execute_sql_query - セキュリティ検証を伴う、メタデータデータベースに対する SELECT クエリの実行
  • d365fo_get_database_schema - リレーションシップを含む、包括的なデータベーススキーマ情報の取得
  • d365fo_get_table_info - サンプルデータを含む、特定のデータベーステーブルに関する詳細情報の取得
  • d365fo_get_database_statistics - パフォーマンス監視用のデータベース統計と分析情報の生成
同期ツール(5 個)
  • d365fo_start_sync - さまざまな戦略とセッション追跡による、メタデータ同期の開始
  • d365fo_get_sync_progress - 所要時間の推定を含む、同期セッションの詳細な進行状況の監視
  • d365fo_cancel_sync - 適切なクリーンアップを行いながら、実行中の同期セッションをキャンセル
  • d365fo_list_sync_sessions - ステータスと進行状況を含む、すべてのアクティブな同期セッションの一覧表示
  • d365fo_get_sync_history - 成功/失敗のステータスと統計情報を含む、完了した同期セッションの履歴取得
SRS レポートツール(6 個)
  • d365fo_download_srs_report - パラメーターに対応した SQL Server Reporting Services(SRS)レポートをダウンロードします
  • d365fo_download_sales_confirmation - さまざまな形式で販売確認レポートをダウンロードします
  • d365fo_download_purchase_order - 書式設定オプションを指定して発注書をダウンロードします
  • d365fo_download_customer_invoice - カスタマイズ可能な顧客請求書レポートをダウンロードします
  • d365fo_download_free_text_invoice - 自由形式請求書をダウンロードします
  • d365fo_download_debit_credit_note - 借方票と貸方票のレポートをダウンロードします
パフォーマンス監視ツール(3 個)
  • d365fo_get_server_performance - サーバーのパフォーマンス指標と統計を取得します
  • d365fo_get_server_config - サーバーの構成情報とシステム設定を取得します
  • d365fo_reset_performance_stats - 新たに監視を開始するため、パフォーマンス統計とカウンターをリセットします

📖 使用例やベストプラクティスを含む、すべての MCP ツールの詳細については、包括的な MCP ツール紹介をご覧ください。

🤖 AI エージェントとアシスタントについては、構造化されたワークフロー、ベストプラクティス、自動化パターンを紹介する AI エージェントガイドをご覧ください。

MCP リソース

サーバーは、検索とアクセスのために 4 種類のリソースを公開します。

エンティティリソース

エンティティのメタデータとサンプルデータにアクセスします。

d365fo://entities/CustomersV3     # Customer entity with metadata and sample data
d365fo://entities/SalesOrders     # Sales order entity information
d365fo://entities/Products        # Product entity details
メタデータリソース

システム全体のメタデータにアクセスします。

d365fo://metadata/entities        # All data entities metadata (V2 cache)
d365fo://metadata/actions         # Available OData actions  
d365fo://metadata/enumerations    # System enumerations
d365fo://metadata/labels          # System labels and translations
環境リソース

環境のステータスと情報にアクセスします。

d365fo://environment/status       # Environment health and connectivity
d365fo://environment/version      # Version information (app, platform, build)
d365fo://environment/cache        # Cache status and statistics V2
クエリリソース

事前定義されたクエリとテンプレート化されたクエリにアクセスします。

d365fo://queries/customers_recent # Recent customers query template
d365fo://queries/sales_summary    # Sales summary query with parameters
データベースリソース(V2 で新登場)

メタデータデータベースのクエリにアクセスします。

d365fo://database/entities        # SQL-based entity searches with FTS5
d365fo://database/actions         # Action discovery with metadata
d365fo://database/statistics      # Cache and performance statistics
使用例
基本的なツールの実行
{
  "tool": "d365fo_query_entities",
  "arguments": {
    "entityName": "CustomersV3",
    "select": ["CustomerAccount", "Name", "Email"],
    "filter": "CustomerGroup eq 'VIP'",
    "top": 10
  }
}
エンティティスキーマの検出
{
  "tool": "d365fo_get_entity_schema", 
  "arguments": {
    "entityName": "CustomersV3",
    "includeProperties": true,
    "resolveLabels": true,
    "language": "en-US"
  }
}
環境情報
{
  "tool": "d365fo_get_environment_info",
  "arguments": {}
}
認証と構成
既定の資格情報(推奨)

Azure Default Credential チェーン(Managed Identity、Azure CLI など)を使用します。

export D365FO_BASE_URL="https://your-environment.dynamics.com"
# No additional auth environment variables needed
d365fo-fastmcp-server
明示的な資格情報

サービスプリンシパル認証の場合:

export D365FO_BASE_URL="https://your-environment.dynamics.com"
export D365FO_CLIENT_ID="your-client-id"
export D365FO_CLIENT_SECRET="your-client-secret"
export D365FO_TENANT_ID="your-tenant-id"
d365fo-fastmcp-server
Azure Key Vault との統合(v0.2.3 で新登場)

Azure Key Vault を使用して資格情報を安全に保管する場合:

export D365FO_BASE_URL="https://your-environment.dynamics.com"
export D365FO_CREDENTIAL_SOURCE="keyvault"
export D365FO_KEYVAULT_URL="https://your-keyvault.vault.azure.net/"
d365fo-fastmcp-server
高度な構成

v0.3.0 で新登場:Pydantic settings を使用した、型安全性と検証機能を備えた包括的な環境変数管理です。

構成ファイルを作成するか、追加の環境変数を設定します。

# === Core D365FO Connection Settings ===
export D365FO_BASE_URL="https://your-environment.dynamics.com"
export D365FO_CLIENT_ID="your-client-id"
export D365FO_CLIENT_SECRET="your-client-secret"
export D365FO_TENANT_ID="your-tenant-id"

# === Logging Configuration ===
export D365FO_LOG_LEVEL="DEBUG"                        # DEBUG, INFO, WARNING, ERROR, CRITICAL
export D365FO_LOG_FILE="/custom/path/server.log"       # Custom log file path

# === MCP Server Transport Settings (v0.3.0+) ===
export D365FO_MCP_TRANSPORT="stdio"                    # stdio, sse, http, streamable-http
export D365FO_MCP_HTTP_HOST="0.0.0.0"                 # HTTP host (default: 127.0.0.1)
export D365FO_MCP_HTTP_PORT="8000"                     # HTTP port (default: 8000)
export D365FO_MCP_HTTP_STATELESS="true"                # Enable stateless mode
export D365FO_MCP_HTTP_JSON="true"                     # Enable JSON response mode

# === Cache and Performance Settings ===
export D365FO_CACHE_DIR="/custom/cache/path"           # General cache directory
export D365FO_META_CACHE_DIR="/custom/metadata/cache"  # Metadata cache directory
export D365FO_LABEL_CACHE="true"                       # Enable label caching (default: true)
export D365FO_LABEL_EXPIRY="1440"                      # Label cache expiry in minutes (24 hours)
export D365FO_USE_CACHE_FIRST="true"                   # Use cache before API calls

# === Connection and Performance Tuning ===
export D365FO_TIMEOUT="60"                             # General timeout in seconds
export D365FO_MCP_MAX_CONCURRENT_REQUESTS="10"         # Max concurrent requests
export D365FO_MCP_REQUEST_TIMEOUT="30"                 # Request timeout in seconds
export D365FO_VERIFY_SSL="true"                        # Verify SSL certificates

# === MCP Authentication Settings (Advanced) ===
export D365FO_MCP_AUTH_CLIENT_ID="your-mcp-client-id"
export D365FO_MCP_AUTH_CLIENT_SECRET="your-mcp-client-secret"
export D365FO_MCP_AUTH_TENANT_ID="your-mcp-tenant-id"
export D365FO_MCP_AUTH_BASE_URL="http://localhost:8000"
export D365FO_MCP_AUTH_REQUIRED_SCOPES="User.Read,email,openid,profile"

# === Debug Settings ===
export DEBUG="true"                                     # Enable debug mode

環境ファイルのサポート:開発時の利便性のため、プロジェクトディレクトリにこれらの変数を記述した .env ファイルを作成することもできます。

Python クライアントライブラリ

特長
  • 🔗 OData クライアント:複合キーに対応した、D365 F&O データエンティティの完全な CRUD 操作
  • 📊 メタデータ管理 V2:インテリジェントな同期機能と FTS5 検索を備えた、強化されたキャッシュシステム
  • 🏷️ ラベル操作 V2:パフォーマンスを改善し、非同期処理に対応した多言語ラベルのキャッシュ
  • 🔍 高度なクエリ:すべての OData クエリパラメーター($select、$filter、$expand など)に対応
  • ⚡ アクションの実行:包括的なパラメーター処理により、バインドされた OData アクションとバインドされていない OData アクションを実行
  • �️ JSON サービス:D365 F&O JSON サービスエンドポイント(/api/services パターン)への汎用アクセス
  • �🔒 認証:デフォルトの資格情報、サービスプリンシパル、Azure Key Vault に対応した Azure AD 統合
  • 💾 インテリジェントなキャッシュ:モジュールベースのバージョン検出による、環境をまたいだキャッシュ共有
  • 🌐 非同期処理:セッション管理を最適化した、最新の async/await パターン
  • 📝 型ヒント:強化されたデータモデルによる、完全な型注釈への対応
  • 🤖 MCP サーバー:49 個のツールと 4 種類のリソースを備えた、本番環境対応の Model Context Protocol サーバー
  • 🖥️ 包括的な CLI:すべての D365 F&O 操作用の階層型コマンドラインインターフェイス
  • 🧪 マルチティアテスト:モック、サンドボックス、ライブ統合テストのフレームワーク(17/17 件のテストに合格)
  • 📋 メタデータスクリプト:エンティティ、列挙型、アクションの検出に使える PowerShell および Python ユーティリティ
  • 🔐 強化された資格情報管理:Azure Key Vault と複数の資格情報ソースに対応
  • 📊 高度な同期管理:詳細な進捗追跡に対応したセッションベースの同期
  • 🔧 NEW v0.3.0:型安全な環境変数検証に対応した Pydantic 設定モデル
  • 📂 NEW v0.3.0:カスタムログファイルパスへの対応と柔軟なロギング設定
  • 🔄 NEW v0.3.0:レガシー設定の自動移行と互換性レイヤー
インストール
# Install from PyPI
pip install d365fo-client

# Or install from source
git clone https://github.com/mafzaal/d365fo-client.git
cd d365fo-client
uv sync  # Installs with exact dependencies from uv.lock

# Or use Docker (no local installation required)
docker pull ghcr.io/mafzaal/d365fo-client:latest

# Run with Docker
docker run --rm -it \
  -e D365FO_BASE_URL="https://your-environment.dynamics.com" \
  -e D365FO_CLIENT_ID="your-client-id" \
  -e D365FO_CLIENT_SECRET="your-client-secret" \
  -e D365FO_TENANT_ID="your-tenant-id" \
  -v d365fo-mcp:/home/mcp_user/ \
  ghcr.io/mafzaal/d365fo-client:latest

注記:このパッケージには MCP(Model Context Protocol)の依存関係がデフォルトで含まれており、AI アシスタントとの統合が可能です。インストール後は、d365fo-client CLI と d365fo-fastmcp-server コマンドの両方を使用できます。

v0.2.3 での破壊的変更:環境変数名が一貫性のために更新されました。

  • AZURE_CLIENT_ID → D365FO_CLIENT_ID
  • AZURE_CLIENT_SECRET → D365FO_CLIENT_SECRET
  • AZURE_TENANT_ID → D365FO_TENANT_ID

アップグレード時に、環境変数を適宜更新してください。

Python クライアントのクイックスタート

コマンドラインインターフェイス(CLI)

d365fo-client は、Dynamics 365 Finance & Operations API とメタデータを操作するための、階層型コマンドを備えた包括的な CLI を提供します。この CLI は、エンティティ管理、メタデータの検出、システム管理など、主要な操作すべてに対応しています。

使い方
# Use the installed CLI command
d365fo-client [GLOBAL_OPTIONS] COMMAND [SUBCOMMAND] [OPTIONS]

# Alternative: Module execution
python -m d365fo_client.main [OPTIONS] COMMAND [ARGS]
コマンドカテゴリ
エンティティ操作
# List entities with filtering
d365fo-client entities list --pattern "customer" --limit 10

# Get entity details and schema
d365fo-client entities get CustomersV3 --properties --keys --labels

# CRUD operations
d365fo-client entities create Customers --data '{"CustomerAccount":"US-999","Name":"Test"}'
d365fo-client entities update Customers US-999 --data '{"Name":"Updated Name"}'
d365fo-client entities delete Customers US-999
メタデータ操作
# Search and discover entities
d365fo-client metadata entities --search "sales" --output json

# Get available actions
d365fo-client metadata actions --pattern "calculate" --limit 5

# Enumerate system enumerations
d365fo-client metadata enums --search "status" --output table

# Synchronize metadata cache
d365fo-client metadata sync --force-refresh
バージョン情報
# Get application versions
d365fo-client version app
d365fo-client version platform  
d365fo-client version build
ラベル操作
# Resolve single label
d365fo-client labels resolve "@SYS13342"

# Search labels by pattern
d365fo-client labels search "customer" --language "en-US"
JSON サービス操作
# Call SQL diagnostic services  
d365fo-client service sql-diagnostic GetAxSqlExecuting
d365fo-client service sql-diagnostic GetAxSqlResourceStats --since-minutes 5
d365fo-client service sql-diagnostic GetAxSqlBlocking --output json

# Generic JSON service calls
d365fo-client service call SysSqlDiagnosticService SysSqlDiagnosticServiceOperations GetAxSqlExecuting
d365fo-client service call YourServiceGroup YourServiceName YourOperation --parameters '{"param1":"value1"}'
グローバルオプション
  • --base-url URL — D365 F&O 環境の URL を指定します
  • --profile NAME — 名前付き設定プロファイルを使用します
  • --output FORMAT — 出力形式を指定します:json、table、csv、yaml(デフォルト:table)
  • --verbose — デバッグ用の詳細出力を有効にします
  • --timeout SECONDS — リクエストのタイムアウト(デフォルト:30)
設定プロファイル

~/.d365fo-client/config.yaml に再利用可能な設定を作成します。

profiles:
  production:
    base_url: "https://prod.dynamics.com"
    use_default_credentials: true
    timeout: 60
    
  development:
    base_url: "https://dev.dynamics.com" 
    client_id: "${D365FO_CLIENT_ID}"
    client_secret: "${D365FO_CLIENT_SECRET}"
    tenant_id: "${D365FO_TENANT_ID}"
    use_cache_first: true

default_profile: "development"
例
# Quick entity discovery
d365fo-client entities list --pattern "cust.*" --output json

# Get comprehensive entity information
d365fo-client entities get CustomersV3 --properties --keys --labels --output yaml

# Search for calculation actions
d365fo-client metadata actions --pattern "calculate|compute" --output table

# Test environment connectivity
d365fo-client version app --verbose

すべてのコマンドのリファレンスについては、以下を参照してください。

d365fo-client --help
d365fo-client entities --help
d365fo-client metadata --help
基本的な使い方
import asyncio
from d365fo_client import D365FOClient, FOClientConfig

async def main():
    # Simple configuration with default credentials
    config = FOClientConfig(
        base_url="https://your-fo-environment.dynamics.com",
        use_default_credentials=True  # Uses Azure Default Credential
    )
    
    async with D365FOClient(config) as client:
        # Test connection
        if await client.test_connection():
            print("✅ Connected successfully!")
        
        # Get environment information
        env_info = await client.get_environment_info()
        print(f"Environment: {env_info.application_version}")
        
        # Search for entities (uses metadata cache v2)
        customer_entities = await client.search_entities("customer")
        print(f"Found {len(customer_entities)} customer entities")
        
        # Get customers with query options
        from d365fo_client import QueryOptions
        options = QueryOptions(
            select=["CustomerAccount", "Name", "SalesCurrencyCode"],
            top=10,
            orderby=["Name"]
        )
        
        customers = await client.get_data("/data/CustomersV3", options)
        print(f"Retrieved {len(customers['value'])} customers")

if __name__ == "__main__":
    asyncio.run(main())
便利な関数の使用
from d365fo_client import create_client

# Quick client creation with enhanced defaults
async with create_client("https://your-fo-environment.dynamics.com") as client:
    customers = await client.get_data("/data/CustomersV3", top=5)

設定

環境変数の管理(v0.3.0で追加)

d365fo-clientには、型安全な環境変数管理のための包括的なPydantic設定モデルが含まれるようになりました。

from d365fo_client import D365FOSettings, get_settings

# Get type-safe settings instance
settings = get_settings()

# Access settings with full IntelliSense support
print(f"Base URL: {settings.base_url}")
print(f"Log Level: {settings.log_level}")
print(f"Cache Directory: {settings.cache_dir}")

# Check configuration state
if settings.has_client_credentials():
    print("Client credentials configured")

startup_mode = settings.get_startup_mode()  # "profile_only", "default_auth", "client_credentials"

# Convert to environment dictionary for external tools
env_vars = settings.to_env_dict()

主なメリット:

  • 型安全性:35個以上のすべての環境変数を自動的に検証し、型変換します
  • IDEサポート:設定オプションの完全なIntelliSenseと自動補完を利用できます
  • 環境ファイル:開発環境で.envファイルをサポートします
  • 包括的なデフォルト値:すべての設定オプションに適切なデフォルト値を設定します
  • 検証:URL、ポート、タイムアウトなどの設定を組み込みで検証します
認証オプション
from d365fo_client import FOClientConfig

# Option 1: Default Azure credentials (recommended)
config = FOClientConfig(
    base_url="https://your-fo-environment.dynamics.com",
    use_default_credentials=True
)

# Option 2: Client credentials
config = FOClientConfig(
    base_url="https://your-fo-environment.dynamics.com",
    client_id="your-client-id",
    client_secret="your-client-secret", 
    tenant_id="your-tenant-id",
    use_default_credentials=False
)

# Option 3: Azure Key Vault integration (New in v0.2.3)
config = FOClientConfig(
    base_url="https://your-fo-environment.dynamics.com",
    credential_source="keyvault",  # Use Azure Key Vault for credentials
    keyvault_url="https://your-keyvault.vault.azure.net/"
)

# Option 4: With custom settings
config = FOClientConfig(
    base_url="https://your-fo-environment.dynamics.com",
    use_default_credentials=True,
    verify_ssl=False,  # For development environments
    timeout=60,  # Request timeout in seconds
    metadata_cache_dir="./my_cache",  # Custom cache directory
    use_label_cache=True,  # Enable label caching
    label_cache_expiry_minutes=120  # Cache for 2 hours
)
従来の設定の移行(v0.3.0で追加)

d365fo-clientは、従来の設定ファイルを自動的に検出して移行します。

  • 自動検出:従来の設定パターン(verify_sslがない、古いフィールド名など)を識別します
  • フィールドの移行:cache_dir → metadata_cache_dir、auth_mode → use_default_credentialsに更新します
  • バックアップの作成:移行前に元の設定のバックアップを作成します
  • シームレスなアップグレード:手動での操作なしに、旧バージョンからスムーズに移行できます
# Legacy configurations are automatically migrated when FastMCP server starts
# No manual intervention required - migration happens transparently

主な操作

CRUD操作
async with D365FOClient(config) as client:
    # CREATE - Create new customer (supports composite keys)
    new_customer = {
        "CustomerAccount": "US-999",
        "Name": "Test Customer",
        "SalesCurrencyCode": "USD"
    }
    created = await client.create_data("/data/CustomersV3", new_customer)
    
    # READ - Get single customer by key
    customer = await client.get_data("/data/CustomersV3('US-001')")
    
    # UPDATE - Update customer with optimistic concurrency
    updates = {"Name": "Updated Customer Name"}
    updated = await client.update_data("/data/CustomersV3('US-001')", updates)
    
    # DELETE - Delete customer
    success = await client.delete_data("/data/CustomersV3('US-999')")
    print(f"Delete successful: {success}")
高度なクエリ
from d365fo_client import QueryOptions

# Complex query with multiple options
options = QueryOptions(
    select=["CustomerAccount", "Name", "SalesCurrencyCode", "CustomerGroupId"],
    filter="SalesCurrencyCode eq 'USD' and contains(Name, 'Corp')",
    expand=["CustomerGroup"],
    orderby=["Name desc", "CustomerAccount"],
    top=50,
    skip=10,
    count=True
)

result = await client.get_data("/data/CustomersV3", options)
print(f"Total count: {result.get('@odata.count')}")
アクションの実行
# Unbound action
result = await client.post_data("/data/calculateTax", {
    "amount": 1000.00,
    "taxGroup": "STANDARD"
})

# Bound action on entity set
result = await client.post_data("/data/CustomersV3/calculateBalances", {
    "asOfDate": "2024-12-31"
})

# Bound action on specific entity instance  
result = await client.post_data("/data/CustomersV3('US-001')/calculateBalance", {
    "asOfDate": "2024-12-31"
})
JSONサービス操作
# Basic JSON service call (no parameters)
response = await client.post_json_service(
    service_group="SysSqlDiagnosticService",
    service_name="SysSqlDiagnosticServiceOperations",
    operation_name="GetAxSqlExecuting"
)

if response.success:
    print(f"Found {len(response.data)} executing SQL statements")
    print(f"Status: HTTP {response.status_code}")
else:
    print(f"Error: {response.error_message}")

# JSON service call with parameters
from datetime import datetime, timezone, timedelta

end_time = datetime.now(timezone.utc)
start_time = end_time - timedelta(minutes=10)

response = await client.post_json_service(
    service_group="SysSqlDiagnosticService",
    service_name="SysSqlDiagnosticServiceOperations",
    operation_name="GetAxSqlResourceStats",
    parameters={
        "start": start_time.isoformat(),
        "end": end_time.isoformat()
    }
)

# Using JsonServiceRequest object for better structure
from d365fo_client.models import JsonServiceRequest

request = JsonServiceRequest(
    service_group="SysSqlDiagnosticService",
    service_name="SysSqlDiagnosticServiceOperations",
    operation_name="GetAxSqlBlocking"
)

response = await client.call_json_service(request)
print(f"Service endpoint: {request.get_endpoint_path()}")

# Multiple SQL diagnostic operations
operations = ["GetAxSqlExecuting", "GetAxSqlBlocking", "GetAxSqlLockInfo"]
for operation in operations:
    response = await client.post_json_service(
        service_group="SysSqlDiagnosticService",
        service_name="SysSqlDiagnosticServiceOperations",
        operation_name=operation
    )
    
    if response.success:
        count = len(response.data) if isinstance(response.data, list) else 1
        print(f"{operation}: {count} records")

# Custom service call template
response = await client.post_json_service(
    service_group="YourServiceGroup",
    service_name="YourServiceName",
    operation_name="YourOperation",
    parameters={
        "parameter1": "value1",
        "parameter2": 123,
        "parameter3": True
    }
)
メタデータ操作
# Intelligent metadata synchronization (v2 system)
sync_manager = await client.get_sync_manager()
await sync_manager.smart_sync()

# Search entities with enhanced filtering
sales_entities = await client.search_entities("sales")
print("Sales-related entities:", [e.name for e in sales_entities])

# Get detailed entity information with labels
entity_info = await client.get_public_entity_info("CustomersV3")
if entity_info:
    print(f"Entity: {entity_info.name}")
    print(f"Label: {entity_info.label_text}")
    print(f"Data Service Enabled: {entity_info.data_service_enabled}")

# Search actions with caching
calc_actions = await client.search_actions("calculate")
print("Calculation actions:", [a.name for a in calc_actions])

# Get enumeration information
enum_info = await client.get_public_enumeration_info("NoYes")
if enum_info:
    print(f"Enum: {enum_info.name}")
    for member in enum_info.members:
        print(f"  {member.name} = {member.value}")
ラベル操作
# Get specific label (v2 caching system)
label_text = await client.get_label_text("@SYS13342")
print(f"Label text: {label_text}")

# Get multiple labels efficiently
labels = await client.get_labels_batch([
    "@SYS13342", "@SYS9490", "@GLS63332"
])
for label_id, text in labels.items():
    print(f"{label_id}: {text}")

# Enhanced entity info with resolved labels
entity_info = await client.get_public_entity_info_with_labels("CustomersV3")
if entity_info.label_text:
    print(f"Entity display name: {entity_info.label_text}")

# Access enhanced properties with labels
for prop in entity_info.enhanced_properties[:5]:
    if hasattr(prop, 'label_text') and prop.label_text:
        print(f"{prop.name}: {prop.label_text}")

エラー処理

from d365fo_client import D365FOClientError, AuthenticationError, ConnectionError

try:
    async with D365FOClient(config) as client:
        customer = await client.get_data("/data/CustomersV3('NON-EXISTENT')")
except ConnectionError as e:
    print(f"Connection failed: {e}")
except AuthenticationError as e:
    print(f"Authentication failed: {e}")
except D365FOClientError as e:
    print(f"Client operation failed: {e}")
    print(f"Status code: {e.status_code}")
    print(f"Response: {e.response_text}")

開発

開発環境のセットアップ
# Clone the repository
git clone https://github.com/mafzaal/d365fo-client.git
cd d365fo-client

# Install with development dependencies using uv
uv sync --dev

# Run tests
uv run pytest

# Run integration tests
.\tests\integration\integration-test-simple.ps1 test-sandbox

# Format code
uv run black .
uv run isort .

# Type checking
uv run mypy src/

# Quality checks
.\make.ps1 quality-check  # Windows PowerShell
# or
make quality-check       # Unix/Linux/macOS
プロジェクト構成
d365fo-client/
├── src/
│   └── d365fo_client/
│       ├── __init__.py          # Public API exports
│       ├── main.py              # CLI entry point  
│       ├── cli.py               # CLI command handlers
│       ├── client.py            # Enhanced D365FOClient class
│       ├── config.py            # Configuration management
│       ├── auth.py              # Authentication management
│       ├── session.py           # HTTP session management
│       ├── crud.py              # CRUD operations
│       ├── query.py             # OData query utilities
│       ├── metadata.py          # Legacy metadata operations
│       ├── metadata_api.py      # Metadata API client
│       ├── metadata_cache.py    # Metadata caching layer V2
│       ├── metadata_sync.py     # Metadata synchronization V2 with session management
│       ├── sync_session.py      # Enhanced sync session management (New in v0.2.3)
│       ├── credential_manager.py # Credential source management (New in v0.2.3)
│       ├── labels.py            # Label operations V2
│       ├── profiles.py          # Profile data models
│       ├── profile_manager.py   # Profile management
│       ├── models.py            # Data models and configurations
│       ├── output.py            # Output formatting
│       ├── utils.py             # Utility functions
│       ├── exceptions.py        # Custom exceptions
│       └── mcp/                 # Model Context Protocol server
│           ├── __init__.py      # MCP server exports
│           ├── main.py          # MCP server entry point
│           ├── server.py        # Core MCP server implementation
│           ├── client_manager.py# D365FO client connection pooling
│           ├── models.py        # MCP-specific data models
│           ├── mixins/          # FastMCP tool mixins (49 tools)
│           ├── tools/           # Legacy MCP tools (deprecated)
│           │   ├── connection_tools.py
│           │   ├── crud_tools.py
│           │   ├── metadata_tools.py
│           │   └── label_tools.py
│           ├── resources/       # MCP resource handlers (4 types)
│           │   ├── entity_handler.py
│           │   ├── metadata_handler.py
│           │   ├── environment_handler.py
│           │   └── query_handler.py
│           └── prompts/         # MCP prompt templates
├── tests/                       # Comprehensive test suite
│   ├── unit/                    # Unit tests (pytest-based)
│   ├── integration/             # Multi-tier integration testing
│   │   ├── mock_server/         # Mock D365 F&O API server
│   │   ├── test_mock_server.py  # Mock server tests
│   │   ├── test_sandbox.py      # Sandbox environment tests ✅
│   │   ├── test_live.py         # Live environment tests
│   │   ├── conftest.py          # Shared pytest fixtures
│   │   ├── test_runner.py       # Python test execution engine
│   │   └── integration-test-simple.ps1 # PowerShell automation
│   └── test_mcp_server.py       # MCP server unit tests ✅
├── scripts/                     # Metadata discovery scripts
│   ├── search_data_entities.ps1 # PowerShell entity search
│   ├── get_data_entity_schema.ps1 # PowerShell schema retrieval
│   ├── search_enums.py          # Python enumeration search
│   ├── get_enumeration_info.py  # Python enumeration info
│   ├── search_actions.ps1       # PowerShell action search
│   └── get_action_info.py       # Python action information
├── docs/                        # Comprehensive documentation
├── pyproject.toml               # Project configuration
└── README.md                    # This file

設定オプション

オプション型デフォルト説明
base_urlstr必須D365 F&OのベースURL
client_idstrNoneAzure ADのクライアントID
client_secretstrNoneAzure ADのクライアントシークレット
tenant_idstrNoneAzure ADのテナントID
use_default_credentialsboolTrueAzure Default Credentialを使用します
credential_sourcestr"environment"資格情報のソース:"environment"、"keyvault"
keyvault_urlstrNone資格情報を保存するAzure Key VaultのURL
verify_sslboolFalseSSL証明書を検証します
timeoutint30リクエストのタイムアウト(秒)
metadata_cache_dirstrプラットフォーム固有のユーザーキャッシュメタデータのキャッシュディレクトリ
use_label_cacheboolTrueラベルキャッシュV2を有効にします
label_cache_expiry_minutesint60ラベルキャッシュの有効期限
use_cache_firstboolFalseバックグラウンド同期を伴うキャッシュ優先モードを有効にします
キャッシュディレクトリの動作

デフォルトでは、クライアントはプラットフォームに適したユーザーキャッシュディレクトリを使用します。

  • Windows:%LOCALAPPDATA%\d365fo-client(例:C:\Users\username\AppData\Local\d365fo-client)
  • macOS:~/Library/Caches/d365fo-client(例:/Users/username/Library/Caches/d365fo-client)
  • Linux:~/.cache/d365fo-client(例:/home/username/.cache/d365fo-client)

metadata_cache_dirを明示的に設定すると、この値を上書きできます。

from d365fo_client import FOClientConfig

# Use custom cache directory
config = FOClientConfig(
    base_url="https://your-fo-environment.dynamics.com",
    metadata_cache_dir="/custom/cache/path"
)

# Or get the default cache directory programmatically
from d365fo_client import get_user_cache_dir

cache_dir = get_user_cache_dir("my-app")  # Platform-appropriate cache dir
config = FOClientConfig(
    base_url="https://your-fo-environment.dynamics.com", 
    metadata_cache_dir=str(cache_dir)
)

テスト

このプロジェクトでは、信頼性と品質を確保するため、複数のレベルで包括的なテストを実施しています。

単体テスト

コア機能の標準的な単体テストを実行します。

# Run all unit tests
uv run pytest

# Run with coverage
uv run pytest --cov=d365fo_client --cov-report=html

# Run specific test file
uv run pytest tests/test_client.py -v
統合テスト

このプロジェクトには、複数の階層からなる高度な統合テストフレームワークが含まれています。

クイックスタート
# Run sandbox integration tests (recommended)
.\tests\integration\integration-test-simple.ps1 test-sandbox

# Run mock server tests (no external dependencies)
.\tests\integration\integration-test-simple.ps1 test-mock

# Run with verbose output
.\tests\integration\integration-test-simple.ps1 test-sandbox -VerboseOutput
テストレベル
  1. モックサーバーテスト - シミュレートされたD365 F&O APIに対する、高速で独立したテスト

    • 外部依存関係がありません
    • APIを完全にシミュレートします
    • CI/CDパイプラインに最適です
  2. サンドボックステスト ⭐ (デフォルト) - 実際のD365 F&Oテスト環境に対するテスト

    • 認証を検証します
    • 実際のAPIの動作をテストします
    • テスト環境へのアクセスが必要です
  3. ライブテスト - 本番環境に対するオプションのテスト

    • 最終検証
    • パフォーマンスのベンチマーク
    • 慎重に実施してください
設定

環境変数を使って統合テストを設定します。

# Copy the template and configure
cp tests/integration/.env.template tests/integration/.env

# Edit .env file with your settings:
INTEGRATION_TEST_LEVEL=sandbox
D365FO_SANDBOX_BASE_URL=https://your-test.dynamics.com
D365FO_CLIENT_ID=your-client-id
D365FO_CLIENT_SECRET=your-client-secret
D365FO_TENANT_ID=your-tenant-id
使用可能なコマンド
# Test environment setup
.\tests\integration\integration-test-simple.ps1 setup

# Dependency checking
.\tests\integration\integration-test-simple.ps1 deps-check

# Run specific test levels
.\tests\integration\integration-test-simple.ps1 test-mock
.\tests\integration\integration-test-simple.ps1 test-sandbox
.\tests\integration\integration-test-simple.ps1 test-live

# Coverage and reporting
.\tests\integration\integration-test-simple.ps1 coverage

# Clean up test artifacts
.\tests\integration\integration-test-simple.ps1 clean
テストカバレッジ

統合テストでは、以下をカバーしています。

  • ✅ 接続と認証 - Azure AD 統合、SSL/TLS 検証
  • ✅ バージョン関連メソッド - アプリケーション、プラットフォーム、ビルドのバージョン取得
  • ✅ メタデータ操作 - エンティティの検出、メタデータ API の検証
  • ✅ データ操作 - CRUD 操作、OData クエリの検証
  • ✅ エラー処理 - ネットワーク障害、認証エラー、無効なリクエスト
  • ✅ パフォーマンス - 応答時間の検証、並行操作

詳細については、統合テストのドキュメントを参照してください。

テスト結果

最近のサンドボックス統合テストの結果:

✅ 17 passed, 0 failed, 2 warnings in 37.67s
====================================================== 
✅ TestSandboxConnection::test_connection_success
✅ TestSandboxConnection::test_metadata_connection_success  
✅ TestSandboxVersionMethods::test_get_application_version
✅ TestSandboxVersionMethods::test_get_platform_build_version
✅ TestSandboxVersionMethods::test_get_application_build_version
✅ TestSandboxVersionMethods::test_version_consistency
✅ TestSandboxMetadataOperations::test_download_metadata
✅ TestSandboxMetadataOperations::test_search_entities
✅ TestSandboxMetadataOperations::test_get_data_entities
✅ TestSandboxMetadataOperations::test_get_public_entities
✅ TestSandboxDataOperations::test_get_available_entities
✅ TestSandboxDataOperations::test_odata_query_options
✅ TestSandboxAuthentication::test_authenticated_requests
✅ TestSandboxErrorHandling::test_invalid_entity_error
✅ TestSandboxErrorHandling::test_invalid_action_error
✅ TestSandboxPerformance::test_response_times
✅ TestSandboxPerformance::test_concurrent_operations

貢献

  1. リポジトリをフォークします
  2. 機能ブランチを作成します(git checkout -b feature/amazing-feature)
  3. 変更を加えます
  4. テストを実行します(uv run pytest)
  5. 統合テストを実行します(.\tests\integration\integration-test-simple.ps1 test-sandbox)
  6. コードをフォーマットします(uv run black . && uv run isort .)
  7. 変更をコミットします(git commit -m 'Add amazing feature')
  8. ブランチにプッシュします(git push origin feature/amazing-feature)
  9. プルリクエストを作成します

ライセンス

このプロジェクトは MIT ライセンスの下でライセンスされています。詳細については、LICENSE ファイルを参照してください。

変更履歴

変更とバージョン履歴の一覧については、CHANGELOG.md を参照してください。

サポート

関連プロジェクト

コメント

MCP は初めてですか?

プロトコルの概要から最初のサーバーの導入まで、よくある疑問にまとめて答えます。

AI アプリケーションが外部のツールやデータソースに統一的な方法で接続するためのオープンなプロトコルです。クライアントはモデルとの対話を担い、MCP サーバーはツール・リソース・プロンプトテンプレートを提供します。標準メッセージでやり取りするため、1 つのサーバーを複数のクライアントで再利用できます。