Dynamics 365 Finance & Operations MCP Server
Click on "Deploy Server".
Wait a few minutes for the server to deploy. Once ready, it will show a "Started" state.
In the chat, type
@followed by the MCP server name and your instructions, e.g., "@Dynamics 365 Finance & Operations MCP Server list the top 10 sales orders for company USMF"
That's it! The server will respond to your query, and you can continue using it as needed.
Here is a step-by-step guide with screenshots.
Dynamics 365 Finance & Operations MCP Server
Production-ready Model Context Protocol (MCP) server that exposes the full capabilities of Microsoft Dynamics 365 Finance & Operations (D365 F&O) to AI assistants and other MCP-compatible tools. This enables sophisticated Dynamics 365 integration workflows through standardized protocol interactions.
🚀 One-Click Installation for VS Code:
🐳 Docker Installation for VS Code:
☁️ Deploy to Azure Container Apps:
Deploy the MCP server as a secure, internet-accessible HTTP endpoint with OAuth or API Key authentication. Perfect for web integrations and remote AI assistant access.
Option 1: Using Bash Script (Recommended)
# 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.shOption 2: Using ARM Template
Download azure-deploy.json
Click "Build your own template in the editor"
Paste the contents of
azure-deploy.jsonFill in the parameters and deploy
Also includes a comprehensive Python client library for Microsoft Dynamics 365 Finance & Operations with OData endpoints, metadata operations, label management, and CLI tools.
MCP Server Overview
The d365fo-client includes a production-ready Model Context Protocol (MCP) server (d365fo-fastmcp-server) built on the FastMCP framework that exposes the full capabilities of D365 Finance & Operations to AI assistants and other MCP-compatible tools.
The server provides multi-transport support (stdio, HTTP, SSE) with enhanced performance and deployment flexibility.
Key Features
49 comprehensive tools covering all major D365 F&O operations across 9 functional categories
12 resource types with comprehensive metadata exposure and discovery capabilities
2 prompt templates for advanced workflow assistance
Multi-transport support (FastMCP): stdio, HTTP, Server-Sent Events (SSE)
Production-ready implementation with proper error handling, authentication, and security validation
Enhanced performance (FastMCP): 40% faster startup, 15% lower memory usage
Advanced profile management supporting multiple environments with secure credential storage
Database analysis capabilities with secure SQL querying and metadata insights
Session-based synchronization with detailed progress tracking and multiple sync strategies
Multi-language support with label resolution and localization capabilities
Enterprise security with Azure AD integration, Key Vault support, and audit logging
New in v0.3.0
🔧 Pydantic Settings Model: Type-safe environment variable management with validation for 35+ configuration options
📂 Custom Log File Support:
D365FO_LOG_FILEenvironment variable for flexible log file paths🔄 Legacy Config Migration: Automatic detection and migration of legacy configuration files
🌐 Environment Variable Standardization: All MCP HTTP variables now use
D365FO_prefix for consistency⚡ Enhanced FastMCP Server: Improved startup configuration, error handling, and graceful shutdown
🔀 MCP Return Type Standardization: All MCP tools now return dictionaries instead of JSON strings for better type safety
🛠️ Enhanced Configuration: Support for
.envfiles and comprehensive environment variable documentation
Quick Start
Installation and Setup
# 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 credentialsFastMCP Server (Recommended)
The modern FastMCP implementation provides enhanced performance and multiple transport options:
# 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.0Key Benefits:
Optimized performance with FastMCP framework
Efficient resource usage through optimized architecture
Multi-transport support: stdio, HTTP, Server-Sent Events (SSE)
Enhanced error handling with better async/await support
Production ready with web transports for API integration
Integration with AI Assistants
VS Code Integration (Recommended)
FastMCP Server with Default Credentials:
Add to your VS Code mcp.json for GitHub Copilot with MCP:
{
"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"
}
}
}
}Option 2: Explicit Credentials For environments requiring service principal authentication:
{
"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
}
]
}Option 3: Docker Integration For containerized environments and enhanced isolation:
{
"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
}
]
}Benefits of Docker approach:
Complete environment isolation and reproducibility
No local Python installation required
Consistent runtime environment across different systems
Automatic dependency management with pre-built image
Enhanced security through containerization
Persistent data storage via Docker volume (
d365fo-mcp)
Prerequisites:
Docker installed and running
Access to Docker Hub or GitHub Container Registry
Network access for pulling the container image
Claude Desktop Integration
FastMCP Server: Add to your Claude Desktop configuration:
{
"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"
}
}
}
}Traditional MCP Server (Alternative):
{
"mcpServers": {
"d365fo": {
"command": "uvx",
"args": [
"--from",
"d365fo-client",
"d365fo-fastmcp-server"
],
"env": {
"D365FO_BASE_URL": "https://your-environment.dynamics.com",
"D365FO_LOG_LEVEL": "INFO"
}
}
}
}Benefits of uvx approach:
Always uses the latest version from the repository
No local installation required
Automatic dependency management
Works across different environments
Web Integration with FastMCP
The FastMCP server provides HTTP and SSE transports for web application integration:
HTTP Transport for Web APIs
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 Transport for Real-time Applications
// 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)
});
}Alternative: Programmatic Usage
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()Custom MCP Clients
Connect using any MCP-compatible client library:
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 Deployment
For containerized environments and production deployments:
Pull the Docker Image:
# 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.3Standalone Docker Usage:
# 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 10Docker Compose Example:
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 Benefits:
Complete environment isolation and reproducibility
No local Python installation required
Consistent runtime environment across different systems
Built-in dependency management
Enhanced security through containerization
Persistent data storage via Docker volumes
Easy integration with orchestration platforms (Kubernetes, Docker Swarm)
Architecture Benefits
For AI Assistants
Standardized Interface: Consistent MCP protocol access to D365 F&O
Rich Metadata: Self-describing entities and operations
Type Safety: Schema validation for all operations
Error Context: Detailed error information for troubleshooting
For Developers
Minimal Integration: Standard MCP client libraries
Comprehensive Coverage: Full D365 F&O functionality exposed
Performance Optimized: Efficient connection and caching strategies
Well Documented: Complete API documentation and examples
For Organizations
Secure Access: Enterprise-grade authentication (Azure AD, Managed Identity)
Audit Logging: Complete operation tracking and monitoring
Scalable Design: Connection pooling and session management
Maintenance Friendly: Clear architecture and comprehensive test coverage
Troubleshooting
Common Issues
Connection Failures
# Test connectivity
d365fo-client version app --base-url https://your-environment.dynamics.com
# Check logs
tail -f ~/.d365fo-mcp/logs/mcp-server.logAuthentication Issues
# Verify Azure CLI authentication
az account show
# Test with explicit credentials
export D365FO_CLIENT_ID="your-client-id"
# ... set other variables
d365fo-fastmcp-serverPerformance Issues
# Enable debug logging
export D365FO_LOG_LEVEL="DEBUG"
# Adjust connection settings
export D365FO_CONNECTION_TIMEOUT="120"
export D365FO_MAX_CONCURRENT_REQUESTS="5"Getting Help
Logs: Check
~/.d365fo-mcp/logs/mcp-server.logfor detailed error informationEnvironment: Use
d365fo_get_environment_infotool to check system statusDocumentation: See MCP Implementation Summary for technical details
Issues: Report problems at GitHub Issues
MCP Tools
The server provides 49 comprehensive tools organized into functional categories:
Connection & Environment Tools (2 tools)
d365fo_test_connection- Test connectivity and authentication with performance metrics and error diagnosticsd365fo_get_environment_info- Get comprehensive environment details including versions, configurations, and capabilities
CRUD Operations Tools (7 tools)
d365fo_query_entities- Simplified OData querying with 'eq' filtering, wildcard patterns, field selection, and paginationd365fo_get_entity_record- Retrieve specific records by key with expansion options and ETag supportd365fo_create_entity_record- Create new entity records with validation and business logic executiond365fo_update_entity_record- Update existing records with partial updates and optimistic concurrency controld365fo_delete_entity_record- Delete entity records with referential integrity checking and cascading rulesd365fo_call_action- Execute OData actions and functions for complex business operationsd365fo_call_json_service- Call generic JSON service endpoints with parameter support and response handling
Metadata Discovery Tools (6 tools)
d365fo_search_entities- Search entities by pattern with category filtering and full-text search capabilitiesd365fo_get_entity_schema- Get detailed entity schemas with properties, relationships, and label resolutiond365fo_search_actions- Search available OData actions with binding type and parameter informationd365fo_search_enumerations- Search system enumerations with keyword-based filteringd365fo_get_enumeration_fields- Get detailed enumeration member information with multi-language supportd365fo_get_installed_modules- Retrieve information about installed modules and their configurations
Label Management Tools (2 tools)
d365fo_get_label- Get single label text by ID with multi-language support and fallback optionsd365fo_get_labels_batch- Get multiple labels efficiently with batch processing and performance optimization
Profile Management Tools (14 tools)
d365fo_list_profiles- List all configured D365FO environment profiles with status informationd365fo_get_profile- Get detailed configuration information for specific profilesd365fo_create_profile- Create new environment profiles with comprehensive authentication optionsd365fo_update_profile- Modify existing profile configurations with partial update supportd365fo_delete_profile- Remove environment profiles with proper cleanup and validationd365fo_set_default_profile- Designate a specific profile as the default for operationsd365fo_get_default_profile- Retrieve information about the currently configured default profiled365fo_validate_profile- Validate profile configurations for completeness and security complianced365fo_test_profile_connection- Test connectivity and authentication for specific profilesd365fo_clone_profile- Clone existing profiles with customization options for new environmentsd365fo_search_profiles- Search profiles by pattern with filtering and sorting capabilitiesd365fo_get_profile_names- Get simplified list of available profile names for quick referenced365fo_import_profiles- Import profile configurations from external sources or backupsd365fo_export_profiles- Export profile configurations for backup or deployment purposes
Database Analysis Tools (4 tools)
d365fo_execute_sql_query- Execute SELECT queries against metadata database with security validationd365fo_get_database_schema- Get comprehensive database schema information including relationshipsd365fo_get_table_info- Get detailed information about specific database tables with sample datad365fo_get_database_statistics- Generate database statistics and analytics for performance monitoring
Synchronization Tools (5 tools)
d365fo_start_sync- Initiate metadata synchronization with various strategies and session trackingd365fo_get_sync_progress- Monitor detailed progress of sync sessions with time estimatesd365fo_cancel_sync- Cancel running sync sessions with graceful cleanupd365fo_list_sync_sessions- List all active sync sessions with status and progress informationd365fo_get_sync_history- Get history of completed sync sessions with success/failure status and statistics
SRS Reporting Tools (6 tools)
d365fo_download_srs_report- Download SQL Server Reporting Services (SRS) reports with parameter supportd365fo_download_sales_confirmation- Download sales confirmation reports in various formatsd365fo_download_purchase_order- Download purchase order documents with formatting optionsd365fo_download_customer_invoice- Download customer invoice reports with customizationd365fo_download_free_text_invoice- Download free text invoice documentsd365fo_download_debit_credit_note- Download debit and credit note reports
Performance Monitoring Tools (3 tools)
d365fo_get_server_performance- Get server performance metrics and statisticsd365fo_get_server_config- Get server configuration information and system settingsd365fo_reset_performance_stats- Reset performance statistics and counters for fresh monitoring
📖 For detailed information about all MCP tools including usage examples and best practices, see the Comprehensive MCP Tools Introduction.
🤖 For AI agents and assistants, see the AI Agent Guide for structured workflows, best practices, and automation patterns.
MCP Resources
The server exposes four types of resources for discovery and access:
Entity Resources
Access entity metadata and sample data:
d365fo://entities/CustomersV3 # Customer entity with metadata and sample data
d365fo://entities/SalesOrders # Sales order entity information
d365fo://entities/Products # Product entity detailsMetadata Resources
Access system-wide metadata:
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 translationsEnvironment Resources
Access environment status and information:
d365fo://environment/status # Environment health and connectivity
d365fo://environment/version # Version information (app, platform, build)
d365fo://environment/cache # Cache status and statistics V2Query Resources
Access predefined and templated queries:
d365fo://queries/customers_recent # Recent customers query template
d365fo://queries/sales_summary # Sales summary query with parametersDatabase Resources (New in V2)
Access metadata database queries:
d365fo://database/entities # SQL-based entity searches with FTS5
d365fo://database/actions # Action discovery with metadata
d365fo://database/statistics # Cache and performance statisticsUsage Examples
Basic Tool Execution
{
"tool": "d365fo_query_entities",
"arguments": {
"entityName": "CustomersV3",
"select": ["CustomerAccount", "Name", "Email"],
"filter": "CustomerGroup eq 'VIP'",
"top": 10
}
}Entity Schema Discovery
{
"tool": "d365fo_get_entity_schema",
"arguments": {
"entityName": "CustomersV3",
"includeProperties": true,
"resolveLabels": true,
"language": "en-US"
}
}Environment Information
{
"tool": "d365fo_get_environment_info",
"arguments": {}
}Authentication & Configuration
Default Credentials (Recommended)
Uses Azure Default Credential chain (Managed Identity, Azure CLI, etc.):
export D365FO_BASE_URL="https://your-environment.dynamics.com"
# No additional auth environment variables needed
d365fo-fastmcp-serverExplicit Credentials
For service principal authentication:
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-serverAzure Key Vault Integration (New in v0.2.3)
For secure credential storage using 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-serverAdvanced Configuration
New in v0.3.0: Comprehensive environment variable management with type safety and validation using Pydantic settings.
Create a configuration file or set additional environment variables:
# === 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 modeEnvironment File Support: You can also create a .env file in your project directory with these variables for development convenience.
Related MCP server: D365 Finance & Operations MCP Server
Python Client Library
Features
🔗 OData Client: Full CRUD operations on D365 F&O data entities with composite key support
📊 Metadata Management V2: Enhanced caching system with intelligent synchronization and FTS5 search
🏷️ Label Operations V2: Multilingual label caching with performance improvements and async support
🔍 Advanced Querying: Support for all OData query parameters ($select, $filter, $expand, etc.)
⚡ Action Execution: Execute bound and unbound OData actions with comprehensive parameter handling
�️ JSON Services: Generic access to D365 F&O JSON service endpoints (/api/services pattern)
�🔒 Authentication: Azure AD integration with default credentials, service principal, and Azure Key Vault support
💾 Intelligent Caching: Cross-environment cache sharing with module-based version detection
🌐 Async/Await: Modern async/await patterns with optimized session management
📝 Type Hints: Full type annotation support with enhanced data models
🤖 MCP Server: Production-ready Model Context Protocol server with 49 tools and 4 resource types
🖥️ Comprehensive CLI: Hierarchical command-line interface for all D365 F&O operations
🧪 Multi-tier Testing: Mock, sandbox, and live integration testing framework (17/17 tests passing)
📋 Metadata Scripts: PowerShell and Python utilities for entity, enumeration, and action discovery
🔐 Enhanced Credential Management: Support for Azure Key Vault and multiple credential sources
📊 Advanced Sync Management: Session-based synchronization with detailed progress tracking
🔧 NEW v0.3.0: Pydantic settings model with type-safe environment variable validation
📂 NEW v0.3.0: Custom log file path support and flexible logging configuration
🔄 NEW v0.3.0: Automatic legacy configuration migration and compatibility layer
Installation
# 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:latestNote: The package includes MCP (Model Context Protocol) dependencies by default, enabling AI assistant integration. Both d365fo-client CLI and d365fo-fastmcp-server commands will be available after installation.
Breaking Change in v0.2.3: Environment variable names have been updated for consistency:
AZURE_CLIENT_ID→D365FO_CLIENT_IDAZURE_CLIENT_SECRET→D365FO_CLIENT_SECRETAZURE_TENANT_ID→D365FO_TENANT_ID
Please update your environment variables accordingly when upgrading.
Python Client Quick Start
Command Line Interface (CLI)
d365fo-client provides a comprehensive CLI with hierarchical commands for interacting with Dynamics 365 Finance & Operations APIs and metadata. The CLI supports all major operations including entity management, metadata discovery, and system administration.
Usage
# Use the installed CLI command
d365fo-client [GLOBAL_OPTIONS] COMMAND [SUBCOMMAND] [OPTIONS]
# Alternative: Module execution
python -m d365fo_client.main [OPTIONS] COMMAND [ARGS]Command Categories
Entity Operations
# 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-999Metadata Operations
# 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-refreshVersion Information
# Get application versions
d365fo-client version app
d365fo-client version platform
d365fo-client version buildLabel Operations
# Resolve single label
d365fo-client labels resolve "@SYS13342"
# Search labels by pattern
d365fo-client labels search "customer" --language "en-US"JSON Service Operations
# 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"}'Global Options
--base-url URL— Specify D365 F&O environment URL--profile NAME— Use named configuration profile--output FORMAT— Output format: json, table, csv, yaml (default: table)--verbose— Enable verbose output for debugging--timeout SECONDS— Request timeout (default: 30)
Configuration Profiles
Create reusable configurations in ~/.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"Examples
# 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 --verboseFor a complete command reference:
d365fo-client --help
d365fo-client entities --help
d365fo-client metadata --helpBasic Usage
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())Using Convenience Function
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)Configuration
Environment Variable Management (New in v0.3.0)
The d365fo-client now includes a comprehensive Pydantic settings model for type-safe environment variable management:
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()Key Benefits:
Type Safety: Automatic validation and type conversion for all 35+ environment variables
IDE Support: Full IntelliSense and autocompletion for configuration options
Environment Files: Support for
.envfiles in developmentComprehensive Defaults: Sensible defaults for all configuration options
Validation: Built-in validation for URLs, ports, timeouts, and other settings
Authentication Options
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
)Legacy Configuration Migration (New in v0.3.0)
The d365fo-client automatically detects and migrates legacy configuration files:
Automatic Detection: Identifies legacy configuration patterns (missing
verify_ssl, outdated field names)Field Migration: Updates
cache_dir→metadata_cache_dir,auth_mode→use_default_credentialsBackup Creation: Creates backup of original configuration before migration
Seamless Upgrade: Ensures smooth transition from older versions without manual intervention
# Legacy configurations are automatically migrated when FastMCP server starts
# No manual intervention required - migration happens transparentlyCore Operations
CRUD Operations
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}")Advanced Querying
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')}")Action Execution
# 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 Service Operations
# 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
}
)Metadata Operations
# 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}")Label Operations
# 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}")Error Handling
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}")Development
Setting up Development Environment
# 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/macOSProject Structure
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 fileConfiguration Options
Option | Type | Default | Description |
| str | Required | D365 F&O base URL |
| str | None | Azure AD client ID |
| str | None | Azure AD client secret |
| str | None | Azure AD tenant ID |
| bool | True | Use Azure Default Credential |
| str | "environment" | Credential source: "environment", "keyvault" |
| str | None | Azure Key Vault URL for credential storage |
| bool | False | Verify SSL certificates |
| int | 30 | Request timeout in seconds |
| str | Platform-specific user cache | Metadata cache directory |
| bool | True | Enable label caching V2 |
| int | 60 | Label cache expiry time |
| bool | False | Enable cache-first mode with background sync |
Cache Directory Behavior
By default, the client uses platform-appropriate user cache directories:
Windows:
%LOCALAPPDATA%\d365fo-client(e.g.,C:\Users\username\AppData\Local\d365fo-client)macOS:
~/Library/Caches/d365fo-client(e.g.,/Users/username/Library/Caches/d365fo-client)Linux:
~/.cache/d365fo-client(e.g.,/home/username/.cache/d365fo-client)
You can override this by explicitly setting 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)
)Testing
This project includes comprehensive testing at multiple levels to ensure reliability and quality.
Unit Tests
Run standard unit tests for core functionality:
# 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 -vIntegration Tests
The project includes a sophisticated multi-tier integration testing framework:
Quick Start
# 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 -VerboseOutputTest Levels
Mock Server Tests - Fast, isolated tests against a simulated D365 F&O API
No external dependencies
Complete API simulation
Ideal for CI/CD pipelines
Sandbox Tests ⭐ (Default) - Tests against real D365 F&O test environments
Validates authentication
Tests real API behavior
Requires test environment access
Live Tests - Optional tests against production environments
Final validation
Performance benchmarking
Use with caution
Configuration
Set up integration testing with environment variables:
# 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-idAvailable Commands
# 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 cleanTest Coverage
Integration tests cover:
✅ Connection & Authentication - Azure AD integration, SSL/TLS validation
✅ Version Methods - Application, platform, and build version retrieval
✅ Metadata Operations - Entity discovery, metadata API validation
✅ Data Operations - CRUD operations, OData query validation
✅ Error Handling - Network failures, authentication errors, invalid requests
✅ Performance - Response time validation, concurrent operations
For detailed information, see Integration Testing Documentation.
Test Results
Recent sandbox integration test results:
✅ 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_operationsContributing
Fork the repository
Create a feature branch (
git checkout -b feature/amazing-feature)Make your changes
Run tests (
uv run pytest)Run integration tests (
.\tests\integration\integration-test-simple.ps1 test-sandbox)Format code (
uv run black . && uv run isort .)Commit changes (
git commit -m 'Add amazing feature')Push to branch (
git push origin feature/amazing-feature)Open a Pull Request
License
This project is licensed under the MIT License - see the LICENSE file for details.
Changelog
See CHANGELOG.md for a list of changes and version history.
Support
📧 Email: mo@thedataguy.pro
🐛 Issues: GitHub Issues
Related Projects
Model Context Protocol (MCP) - For AI assistant integration
Available Tools
49 toolsd365fo_call_actionB
Execute an OData action method in D365 Finance & Operations.
Args: action_name: Full name of the OData action to invoke parameters: Action parameters as key-value pairs entity_name: The entity's public collection name or entity set name (e.g., "CustomersV3", "SalesOrders", "DataManagementEntities") key_fields: Primary key fields for entity-bound actions key_values: Primary key values for entity-bound actions profile: Optional profile name
Returns: Dictionary with action result
Inputs: action_name (required), profile, key_fields, key_values, +2 more.
d365fo_call_json_serviceA
Call a D365 F&O JSON service endpoint using the /api/services pattern.
This provides a generic way to invoke any JSON service operation in D365 F&O.
Args: service_group: Service group name (e.g., 'SysSqlDiagnosticService') service_name: Service name (e.g., 'SysSqlDiagnosticServiceOperations') operation_name: Operation name (e.g., 'GetAxSqlExecuting') parameters: Optional parameters to send in the POST body profile: Configuration profile to use
Returns: Dictionary with service response data and metadata
Example: Call a service without parameters: { "service_group": "SysSqlDiagnosticService", "service_name": "SysSqlDiagnosticServiceOperations", "operation_name": "GetAxSqlExecuting" }
Call a service with parameters:
{
"service_group": "SysSqlDiagnosticService",
"service_name": "SysSqlDiagnosticServiceOperations",
"operation_name": "GetAxSqlResourceStats",
"parameters": {
"start": "2023-01-01T00:00:00Z",
"end": "2023-01-02T00:00:00Z"
}
}
Inputs: service_name (required), service_group (required), operation_name (required), profile, +1 more.
d365fo_cancel_syncA
Cancel a running sync session. Only sessions that are currently running and marked as cancellable can be cancelled.
Args: session_id: Session ID of the sync operation to cancel profile: Configuration profile to use (optional - uses default profile if not specified)
Returns: Dictionary with cancellation result
Inputs: session_id (required), profile.
d365fo_clone_profileB
Clone an existing D365FO environment profile with optional modifications.
Args: sourceProfileName: Name of the profile to clone newProfileName: Name for the new profile description: Description for the new profile
Returns: Dictionary with cloning result
Inputs: newProfileName (required), sourceProfileName (required), description. Returns: result
d365fo_create_entity_recordB
Create a new record in a D365 Finance & Operations data entity.
Args: entity_name: The entity's public collection name or entity set name (e.g., "CustomersV3", "SalesOrders", "DataManagementEntities") data: Record data containing field names and values return_record: Whether to return the complete created record profile: Optional profile name
Returns: Dictionary with creation result
Inputs: data (required), entity_name (required), profile, return_record.
d365fo_create_profileA
Create a new D365FO environment profile with full configuration options.
Args: name: Profile name baseUrl: D365FO base URL description: Profile description verifySsl: Whether to verify SSL certificates (default: True) timeout: Request timeout in seconds (default: 60) useLabelCache: Whether to enable label caching (default: True) labelCacheExpiryMinutes: Label cache expiry in minutes (default: 60) useCacheFirst: Whether to use cache-first behavior (default: True) language: Default language code (default: "en-US") cacheDir: Custom cache directory path (optional) outputFormat: Default output format for CLI operations (default: "table") setAsDefault: Set as default profile (default: False) credentialSource: Credential source configuration. If None, uses Azure Default Credentials. Can be: - Environment variables: {"sourceType": "environment", "clientIdVar": "MY_CLIENT_ID", "clientSecretVar": "MY_CLIENT_SECRET", "tenantIdVar": "MY_TENANT_ID"} - Azure Key Vault: {"sourceType": "keyvault", "vaultUrl": "https://vault.vault.azure.net/", "clientIdSecretName": "D365FO_CLIENT_ID", "clientSecretSecretName": "D365FO_CLIENT_SECRET", "tenantIdSecretName": "D365FO_TENANT_ID"}
Returns: Dictionary with creation result
Inputs: name (required), baseUrl (required), timeout, cacheDir, +9 more. Returns: result
d365fo_delete_entity_recordA
Delete a record from a D365 Finance & Operations data entity.
Args: entity_name: The entity's public collection name or entity set name (e.g., "CustomersV3", "SalesOrders", "DataManagementEntities") key_fields: List of key field names for composite keys key_values: List of key values corresponding to key fields profile: Optional profile name
Returns: Dictionary with deletion result
Inputs: key_fields (required), key_values (required), entity_name (required), profile.
d365fo_delete_profileA
Delete a D365FO environment profile.
Automatically invalidates all cached client connections since the profile is no longer available.
Args: profileName: Name of the profile to delete
Returns: Dictionary with deletion result including number of clients invalidated
Inputs: profileName (required). Returns: result
d365fo_download_customer_invoiceA
Download a customer invoice report as PDF from D365 Finance & Operations.
This is a convenience tool with preset configurations for customer invoices. Use this when you need to quickly download customer invoices without specifying all the technical parameters.
To find available invoices to download, query the Customer Invoice Journal entity:
Entity name: CustInvoiceJourBiEntity
Collection name: CustInvoiceJourBiEntities
Key fields: InvoiceId, InvoiceDate, InvoiceAccount, InvoiceAmount, SalesType, dataAreaId
Use d365fo_query_entities tool to search for invoices
Example query to find invoices: d365fo_query_entities( entityName="CustInvoiceJourBiEntities", filter="InvoiceDate ge 2024-01-01", select=["InvoiceId", "InvoiceDate", "InvoiceAccount", "InvoiceAmount", "SalesType"] )
Args: invoice_id: The customer invoice number/ID (e.g., 'CIV-000708', 'INV-2024-001') legal_entity: The legal entity/company code (e.g., 'USMF', 'DEMF') save_path: Full path where PDF should be saved (optional, auto-generates if not provided) profile: Configuration profile name (default: 'default')
Returns: Dictionary with download result including saved file path
Inputs: invoice_id (required), legal_entity (required), profile, save_path. Returns: object
d365fo_download_debit_credit_noteA
Download a debit/credit note report as PDF from D365 Finance & Operations.
This is a convenience tool specifically configured for debit and credit notes using the CustDebitCreditNoteController. These are adjustment documents for customer invoices.
To find available documents to download, query the Customer Invoice Journal entity:
Entity name: CustInvoiceJourBiEntity
Collection name: CustInvoiceJourBiEntities
Key fields: InvoiceId, InvoiceDate, InvoiceAccount, InvoiceAmount, SalesType, dataAreaId
Use d365fo_query_entities tool to search for invoices
Example query to find invoices: d365fo_query_entities( entityName="CustInvoiceJourBiEntities", filter="InvoiceDate ge 2024-01-01", select=["InvoiceId", "InvoiceDate", "InvoiceAccount", "InvoiceAmount", "SalesType"] )
Args: invoice_id: The debit/credit note invoice ID (e.g., 'DN-000123', 'CN-000456') legal_entity: The legal entity/company code (e.g., 'USMF', 'DEMF') save_path: Full path where PDF should be saved (optional, auto-generates if not provided) profile: Configuration profile name (default: 'default')
Returns: Dictionary with download result including saved file path
Inputs: invoice_id (required), legal_entity (required), profile, save_path. Returns: object
d365fo_download_free_text_invoiceA
Download a free text invoice report as PDF from D365 Finance & Operations.
This is a convenience tool specifically configured for free text invoices using the FreeTextInvoiceController. Free text invoices are customer invoices that don't originate from sales orders.
To find available invoices to download, query the Customer Invoice Journal entity:
Entity name: CustInvoiceJourBiEntity
Collection name: CustInvoiceJourBiEntities
Key fields: InvoiceId, InvoiceDate, InvoiceAccount, InvoiceAmount, SalesType, dataAreaId
Use d365fo_query_entities tool to search for invoices
Example query to find free text invoices: d365fo_query_entities( entityName="CustInvoiceJourBiEntities", filter="InvoiceDate ge 2024-01-01", select=["InvoiceId", "InvoiceDate", "InvoiceAccount", "InvoiceAmount", "SalesType"] )
Args: invoice_id: The free text invoice number/ID (e.g., 'FTI-00000021', 'FTI-2024-001') legal_entity: The legal entity/company code (e.g., 'USMF', 'DEMF') save_path: Full path where PDF should be saved (optional, auto-generates if not provided) profile: Configuration profile name (default: 'default')
Returns: Dictionary with download result including saved file path
Inputs: invoice_id (required), legal_entity (required), profile, save_path. Returns: object
d365fo_download_purchase_orderA
Download a purchase order report as PDF from D365 Finance & Operations.
This is a convenience tool specifically configured for purchase orders using the PurchPurchaseOrderController. Purchase orders are documents sent to vendors to order goods or services.
To find available purchase orders to download, query the Purchase Order Confirmation Headers entity:
Entity name: PurchPurchaseOrderConfirmationHeaderEntity
Collection name: PurchaseOrderConfirmationHeaders
Key fields: PurchaseOrderNumber, ConfirmationNumber, ConfirmationDate, OrderVendorAccountNumber, TotalConfirmedAmount, dataAreaId
Use d365fo_query_entities tool to search for purchase orders
Example query to find purchase orders: d365fo_query_entities( entityName="PurchaseOrderConfirmationHeaders", filter="ConfirmDate ge 2024-01-01", select=["PurchaseOrderNumber", "ConfirmDate", "VendorAccount", "OrderStatus"] )
Args: purchase_order_id: The purchase order ID (e.g., 'PO-000123', 'P00001234') legal_entity: The legal entity/company code (e.g., 'USMF', 'DEMF') save_path: Full path where PDF should be saved (optional, auto-generates if not provided) profile: Configuration profile name (default: 'default')
Returns: Dictionary with download result including saved file path
Inputs: legal_entity (required), purchase_order_id (required), profile, save_path. Returns: object
d365fo_download_sales_confirmationA
Download a sales confirmation report as PDF from D365 Finance & Operations.
This is a convenience tool specifically configured for sales order confirmations using the SalesConfirmController. Sales confirmations are documents sent to customers to confirm sales orders.
To find available confirmations to download, query the Sales Order Confirmation Headers entity:
Entity name: SalesOrderConfirmationHeaderEntity
Collection name: SalesOrderConfirmationHeaders
Key fields: ConfirmationNumber, SalesOrderNumber, ConfirmationDate, OrderingCustomerAccountNumber, TotalConfirmedAmount, dataAreaId
Use d365fo_query_entities tool to search for confirmations
Example query to find confirmations: d365fo_query_entities( entityName="SalesOrderConfirmationHeaders", filter="ConfirmationDate ge 2024-01-01", select=["ConfirmationNumber", "SalesOrderNumber", "ConfirmationDate", "OrderingCustomerAccountNumber", "TotalConfirmedAmount"] )
Args: confirmation_id: The confirmation ID or sales order ID (e.g., 'SC-000123', 'SO-001234') legal_entity: The legal entity/company code (e.g., 'USMF', 'DEMF') save_path: Full path where PDF should be saved (optional, auto-generates if not provided) profile: Configuration profile name (default: 'default')
Returns: Dictionary with download result including saved file path
Inputs: legal_entity (required), confirmation_id (required), profile, save_path. Returns: object
d365fo_download_srs_reportA
Download SQL Server Reporting Services (SSRS/SRS) reports from D365 Finance & Operations as PDF files.
This tool generates and downloads business documents like invoices, purchase orders, confirmations, and other reports by calling the D365FO SRS reporting engine. The report is returned as a PDF file saved to a specified location.
Args: document_id: The unique identifier/key of the document (e.g., 'CIV-000708', 'SO-001234') legal_entity: The legal entity/company code (DataAreaId) where the document exists (e.g., 'USMF') controller_name: The SSRS controller class name (default: 'SalesInvoiceController') Common controllers: - SalesInvoiceController: Customer invoices - FreeTextInvoiceController: Free text invoices - CustDebitCreditNoteController: Debit/credit notes - SalesConfirmController: Sales confirmations - PurchPurchaseOrderController: Purchase orders data_table: The database table containing the document (default: 'CustInvoiceJour') data_field: The field name that stores the document ID (default: 'InvoiceId') document_type: Human-readable document type for filename (default: 'SalesInvoice') save_path: Full path where PDF should be saved (optional, auto-generates if not provided) profile: Configuration profile name (default: 'default')
Common controller/table/field combinations:
| Controller | Table | Field Name | Field Type | Document Type |
|-----------|-------|-----------|------------|---------------|
| SalesInvoiceController | CustInvoiceJour | InvoiceId | Invoice ID | Sales Invoice |
| FreeTextInvoiceController | CustInvoiceJour | InvoiceId | Invoice ID | Free Text Invoice |
| CustDebitCreditNoteController | CustInvoiceJour | InvoiceId | Invoice ID | Debit/Credit Note |
| SalesConfirmController | CustConfirmJour | ConfirmId or SalesId | Confirm/Sales ID | Sales Confirmation |
| PurchPurchaseOrderController | VendPurchOrderJour | PurchId | Purchase Order ID | Purchase Order |
Returns:
Dictionary with download result including saved file path
Inputs: document_id (required), legal_entity (required), profile, save_path, +4 more. Returns: object
d365fo_execute_sql_queryA
Execute a SELECT query against the D365FO metadata database to get insights from cached metadata.
IMPORTANT SAFETY NOTES:
Only SELECT queries are allowed (no INSERT, UPDATE, DELETE, DROP, etc.)
Query results are limited to 1000 rows maximum
Queries timeout after 30 seconds
Some sensitive tables may be restricted
AVAILABLE TABLES AND THEIR PURPOSE:
metadata_environments: D365FO environments and their details
global_versions: Global version registry with hash and reference counts
environment_versions: Links between environments and global versions
data_entities: D365FO data entities metadata
public_entities: Public entity schemas and configurations
entity_properties: Detailed property information for entities
entity_actions: Available OData actions for entities
enumerations: System enumerations and their metadata
enumeration_members: Individual enumeration values and labels
metadata_search_v2: FTS5 search index for metadata
EXAMPLE QUERIES:
Get most used entities by category: SELECT entity_category, COUNT(*) as count FROM data_entities GROUP BY entity_category ORDER BY count DESC
Find entities with most properties: SELECT pe.name, COUNT(ep.id) as property_count FROM public_entities pe LEFT JOIN entity_properties ep ON pe.id = ep.entity_id GROUP BY pe.id ORDER BY property_count DESC LIMIT 10
Analyze environment versions: SELECT me.environment_name, gv.version_hash, ev.detected_at FROM metadata_environments me JOIN environment_versions ev ON me.id = ev.environment_id JOIN global_versions gv ON ev.global_version_id = gv.id
Use this tool to analyze metadata patterns, generate reports, and gain insights into D365FO structure.
Args: query: SQL SELECT query to execute. Must be a SELECT statement only. Query will be validated for safety before execution. limit: Maximum number of rows to return. Default is 100, maximum is 1000. format: Output format for results. 'table' for human-readable format, 'json' for structured data, 'csv' for spreadsheet-compatible format. profile: Configuration profile to use (optional - uses default profile if not specified)
Returns: Dictionary with query results
Inputs: query (required), limit, format, profile.
d365fo_export_profilesB
Export all D365FO environment profiles to a file.
Args: filePath: Path where to export the profiles
Returns: Dictionary with export result
Inputs: filePath (required). Returns: result
d365fo_get_database_schemaA
Get comprehensive schema information for the D365FO metadata database.
This tool provides detailed information about:
All database tables and their structures
Column definitions with types and constraints
Indexes and their purposes
Foreign key relationships
Table statistics (row counts, sizes)
FTS5 virtual table information
Use this tool to understand the database structure before writing SQL queries.
Args: table_name: Optional. Get schema for a specific table only. If omitted, returns schema for all tables. include_statistics: Include table statistics like row counts and sizes. include_indexes: Include index information for tables. include_relationships: Include foreign key relationships between tables. profile: Configuration profile to use (optional - uses default profile if not specified)
Returns: Dictionary with database schema
Inputs: profile, table_name, include_indexes, include_statistics, +1 more.
d365fo_get_database_statisticsA
Get comprehensive database statistics and analytics including:
Overall database size and table counts
Record counts by table
Global version statistics
Environment statistics
Cache hit rates and performance metrics
Storage utilization analysis
Data distribution insights
Use this tool to understand the overall state and health of the metadata database.
Args: include_table_stats: Include per-table statistics (row counts, sizes). include_version_stats: Include global version and environment statistics. include_performance_stats: Include cache performance and query statistics. profile: Configuration profile to use (optional - uses default profile if not specified)
Returns: Dictionary with database statistics
Inputs: profile, include_table_stats, include_version_stats, include_performance_stats.
d365fo_get_default_profileA
Get the current default D365FO environment profile.
Returns: Dictionary with default profile
Inputs: no named parameters. Returns: result
d365fo_get_entity_recordA
Get a specific record from a D365FO data entity.
Args: entity_name: The entity's public collection name or entity set name (e.g., "CustomersV3", "SalesOrders", "DataManagementEntities") key_fields: List of key field names for composite keys key_values: List of key values corresponding to key fields select: List of fields to include in response expand: List of navigation properties to expand profile: Optional profile name
Returns: Dictionary with the entity record
Inputs: key_fields (required), key_values (required), entity_name (required), expand, +2 more.
d365fo_get_entity_schemaA
Get the detailed schema for a specific D365 F&O data entity, including properties, keys, and available actions.
Args: entityName: The public name of the entity (e.g., 'CustomerV3'). include_properties: Set to true to include detailed information about each property (field) in the entity. resolve_labels: Set to true to resolve and include human-readable labels for the entity and its properties. language: The language to use for resolving labels (e.g., 'en-US', 'fr-FR'). profile: Configuration profile to use (optional - uses default profile if not specified)
Returns: Dictionary with entity schema
Inputs: entityName (required), profile, language, resolve_labels, +1 more.
d365fo_get_enumeration_fieldsA
Get the detailed members (fields) and their values for a specific D365 F&O enumeration.
Args: enumeration_name: The exact name of the enumeration (e.g., 'NoYes', 'CustVendorBlocked'). resolve_labels: Set to true to resolve and include human-readable labels for the enumeration and its members. language: The language to use for resolving labels (e.g., 'en-US', 'fr-FR'). profile: Configuration profile to use (optional - uses default profile if not specified)
Returns: Dictionary with enumeration details
Inputs: enumeration_name (required), profile, language, resolve_labels.
d365fo_get_environment_infoA
Get D365FO environment information and version details.
Args: profile: Optional profile name (uses default if not specified)
Returns: JSON string with environment information
Inputs: profile.
d365fo_get_installed_modulesB
Get the list of installed modules in the D365 F&O environment with their details including name, version, module ID, publisher, and display name.
Args: profile: Configuration profile to use (optional - uses default profile if not specified)
Returns: Dictionary with installed modules
Inputs: profile.
d365fo_get_labelC
Get label text by label ID.
Args: labelId: Label ID (e.g., @SYS1234) language: Language code for label text fallbackToEnglish: Fallback to English if translation not found profile: Optional profile name
Returns: Dictionary with label text
Inputs: labelId (required), profile, language.
d365fo_get_labels_batchB
Get multiple labels in a single request.
Args: labelIds: List of label IDs to retrieve language: Language code for label texts fallbackToEnglish: Fallback to English if translation not found profile: Optional profile name
Returns: Dictionary with label texts
Inputs: labelIds (required), profile, language.
d365fo_get_profileA
Get details of a specific D365FO environment profile.
Args: profileName: Name of the profile to retrieve
Returns: Dictionary with profile details
Inputs: profileName (required). Returns: result
d365fo_get_profile_namesB
Get list of all D365FO environment profile names.
Returns: Dictionary with profile names
Inputs: no named parameters. Returns: result
d365fo_get_server_configC
Get current FastMCP server configuration and feature status.
Returns: Dict with server configuration
Inputs: no named parameters.
d365fo_get_server_performanceA
Get FastMCP server performance statistics and health metrics.
Returns: Dict with server performance data
Inputs: no named parameters.
d365fo_get_sync_historyB
Get the history of completed sync sessions including success/failure status, duration, and statistics.
Args: limit: Maximum number of historical sessions to return (default: 20, max: 100) profile: Configuration profile to use (optional - uses default profile if not specified)
Returns: Dictionary with sync history
Inputs: limit, profile.
d365fo_get_sync_progressA
Get detailed progress information for a specific sync session including current phase, completion percentage, items processed, and estimated time remaining.
Args: session_id: Session ID of the sync operation to check progress for profile: Configuration profile to use (optional - uses default profile if not specified)
Returns: Dictionary with sync progress
Inputs: session_id (required), profile.
d365fo_get_table_infoA
Get detailed information about a specific database table including:
Column definitions with types, nullability, and defaults
Primary and foreign key constraints
Indexes and their characteristics
Table statistics (row count, size, last updated)
Sample data (first few rows)
Relationships to other tables
This tool is useful for exploring specific tables before writing queries.
Args: table_name: Name of the table to get information about (e.g., 'data_entities', 'public_entities', 'entity_properties'). include_sample_data: Include sample data from the table (first 5 rows). include_relationships: Include information about relationships to other tables. profile: Configuration profile to use (optional - uses default profile if not specified)
Returns: Dictionary with table information
Inputs: table_name (required), profile, include_sample_data, include_relationships.
d365fo_import_profilesA
Import D365FO environment profiles from a file.
Args: filePath: Path to the file containing profiles to import overwrite: Whether to overwrite existing profiles with the same name
Returns: Dictionary with import results
Inputs: filePath (required), overwrite. Returns: result
d365fo_list_profilesA
Get list of all available D365FO environment profiles.
Returns: Dictionary with list of profiles
Inputs: no named parameters. Returns: result
d365fo_list_sync_sessionsA
Get a list of all currently active sync sessions with their status, progress, and details.
Args: profile: Configuration profile to use (optional - uses default profile if not specified)
Returns: Dictionary with active sync sessions
Inputs: profile.
d365fo_query_entitiesA
Query D365FO data entities with simplified filtering capabilities.
Args: entity_name: The entity's public collection name or entity set name (e.g., "CustomersV3", "SalesOrders", "DataManagementEntities") select: List of field names to include in response filter: Simplified filter expression using only "eq" operation with wildcard support: - Basic equality: "FieldName eq 'value'" - Starts with: "FieldName eq 'value*'" - Ends with: "FieldName eq '*value'" - Contains: "FieldName eq 'value'" - Enum values: "StatusField eq Microsoft.Dynamics.DataEntities.EnumType'EnumValue'" Example: "SalesOrderStatus eq Microsoft.Dynamics.DataEntities.SalesStatus'OpenOrder'" order_by: List of field names to sort by (e.g., ["CreatedDateTime desc", "SalesId"]) top: Maximum number of records to return (default: 100) skip: Number of records to skip for pagination count: Whether to include total count in response expand: List of navigation properties to expand profile: Profile name for connection configuration
Returns: Dictionary with query results including data array, count, and pagination info
Note: This tool uses simplified OData filtering that only supports "eq" operations with wildcard patterns. For complex queries, retrieve data first and filter programmatically.
Inputs: entity_name (required), top, skip, count, +5 more.
d365fo_reset_performance_statsB
Reset server performance statistics.
Returns: Dict with reset confirmation
Inputs: no named parameters.
d365fo_search_actionsA
Search for available OData actions in D365 F&O using simple keyword-based search.
IMPORTANT: When searching for actions, break down user requests into individual keywords and perform MULTIPLE searches:
Extract keywords from requests (e.g., "posting actions" → "post", "posting")
Perform separate searches for each keyword using simple text matching
Combine and analyze results from all searches
Look for actions that match the combination of concepts
SEARCH STRATEGY EXAMPLES:
"posting actions" → Search for "post", then look for posting-related actions
"validation functions" → Search for "valid" and "check", then find validation actions
"workflow actions" → Search for "workflow" and "approve", then combine results
Use simple keywords, not complex patterns. Actions are operations that can be performed on entities or globally.
Args: pattern: Simple keyword or text to search for in action names. Use plain text keywords, not regex patterns. For requests like 'posting actions': 1) Extract keywords: 'post', 'posting' 2) Search for each keyword: 'post' 3) Perform multiple searches for related terms 4) Analyze combined results. Use simple text matching. entityName: Optional. Filter actions that are bound to a specific data entity (e.g., 'CustomersV3'). bindingKind: Optional. Filter by binding type: 'Unbound' (can call directly), 'BoundToEntitySet' (operates on entity collections), 'BoundToEntityInstance' (requires specific entity key). isFunction: Optional. Filter by type: 'true' for functions (read-only), 'false' for actions (may have side-effects). Note: This filter may not be fully supported yet. limit: Maximum number of matching actions to return. profile: Configuration profile to use (optional - uses default profile if not specified)
Returns: Dictionary with matching actions
Inputs: pattern (required), limit, profile, entityName, +2 more.
d365fo_search_entitiesB
Search for D365 F&O data entities using simple keyword-based search.
IMPORTANT: When a user asks for something like "Get data management entities" or "Find customer group entities", break the request into individual keywords and perform MULTIPLE searches, then analyze all results:
Extract individual keywords from the request (e.g. "data management entities" → "data", "management", "entities")
Perform separate searches for each significant keyword using simple text matching
Combine and analyze results from all searches
Look for entities that match the combination of concepts
SEARCH STRATEGY EXAMPLES:
"data management entities" → Search for "data", then "management", then find entities matching both concepts
"customer groups" → Search for "customer", then "group", then find intersection
"sales orders" → Search for "sales", then "order", then combine results
Use simple keywords, not complex patterns. The search will find entities containing those keywords.
Args: pattern: Simple keyword or text to search for in entity names. Use plain text keywords, not regex patterns. For multi-word requests like 'data management entities': 1) Break into keywords: 'data', 'management' 2) Search for each keyword separately: 'data' then 'management' 3) Run separate searches for each keyword 4) Analyze combined results. Examples: use 'customer' to find customer entities, 'group' to find group entities. entity_category: Filter entities by their functional category (e.g., Master, Transaction). data_service_enabled: Filter entities that are enabled for OData API access (e.g., for querying). data_management_enabled: Filter entities that can be used with the Data Management Framework (DMF). is_read_only: Filter entities based on whether they are read-only or support write operations. limit: Maximum number of matching entities to return. Use smaller values (10-50) for initial exploration, larger values (100-500) for comprehensive searches. profile: Configuration profile to use (optional - uses default profile if not specified)
Returns: Dictionary with matching entities
Inputs: pattern (required), limit, profile, is_read_only, +3 more.
d365fo_search_enumerationsA
Search for enumerations (enums) in D365 F&O using simple keyword-based search.
IMPORTANT: When searching for enumerations, break down user requests into individual keywords and perform MULTIPLE searches:
Extract keywords from requests (e.g., "customer status enums" → "customer", "status")
Perform separate searches for each keyword using simple text matching
Combine and analyze results from all searches
Look for enums that match the combination of concepts
SEARCH STRATEGY EXAMPLES:
"customer status enums" → Search for "customer", then "status", then find status-related customer enums
"blocking reasons" → Search for "block" and "reason", then combine results
"approval states" → Search for "approval" and "state", then find approval-related enums
Use simple keywords, not complex patterns. Enums represent lists of named constants (e.g., NoYes, CustVendorBlocked).
Args: pattern: Simple keyword or text to search for in enumeration names. Use plain text keywords, not regex patterns. For requests like 'customer blocking enums': 1) Extract keywords: 'customer', 'blocking' 2) Search for each keyword: 'customer' then 'blocking' 3) Perform multiple searches 4) Analyze combined results. Use simple text matching. limit: Maximum number of matching enumerations to return. profile: Configuration profile to use (optional - uses default profile if not specified)
Returns: Dictionary with matching enumerations
Inputs: pattern (required), limit, profile.
d365fo_search_profilesA
Search D365FO environment profiles based on criteria.
Args: pattern: Pattern to match in profile name, description, or base URL hasCredentialSource: Filter by presence of credential source (True=has credential source, False=uses default credentials) credentialSourceType: Filter by credential source type ("environment", "keyvault")
Returns: Dictionary with matching profiles
Inputs: pattern, hasCredentialSource, credentialSourceType. Returns: result
d365fo_set_default_profileA
Set the default D365FO environment profile.
Automatically refreshes all cached client connections since changing the default profile may affect client resolution for operations that use the default profile.
Args: profileName: Name of the profile to set as default
Returns: Dictionary with result including client refresh status
Inputs: profileName (required). Returns: result
d365fo_start_syncB
Start a metadata synchronization session and return a session ID for tracking progress.
This downloads and caches metadata from D365 F&O including entities, schemas, enumerations, and labels.
Args: strategy: Sync strategy to use. 'full' downloads all metadata, 'entities_only' downloads just entities for quick refresh, 'labels_only' downloads only labels, 'full_without_labels' downloads all metadata except labels, 'sharing_mode' copies from compatible versions, 'incremental' updates only changes (fallback to full). global_version_id: Specific global version ID to sync. If not provided, will detect current version automatically. profile: Configuration profile to use (optional - uses default profile if not specified)
Returns: Dictionary with sync session details
Inputs: profile, strategy, global_version_id.
d365fo_test_connectionC
Test connection to D365FO environment.
Args: profile: Optional profile name to test (uses default if not specified)
Returns: JSON string with connection test results
Inputs: profile.
d365fo_test_profile_connectionA
Test connection for a specific D365FO environment profile.
Args: profileName: Name of the profile to test
Returns: Dictionary with connection test result
Inputs: profileName (required). Returns: result
d365fo_update_entity_recordB
Update an existing record in a D365 Finance & Operations data entity.
Args: entity_name: The entity's public collection name or entity set name (e.g., "CustomersV3", "SalesOrders", "DataManagementEntities") key_fields: List of key field names for composite keys key_values: List of key values corresponding to key fields data: Record data containing fields to update return_record: Whether to return the complete updated record profile: Optional profile name
Returns: Dictionary with update result
Inputs: data (required), key_fields (required), key_values (required), entity_name (required), +2 more.
d365fo_update_profileB
Update an existing D365FO environment profile with full configuration options.
Automatically invalidates all cached client connections to ensure they pick up the new profile settings on next use.
Args: name: Profile name baseUrl: D365FO base URL description: Profile description verifySsl: Whether to verify SSL certificates timeout: Request timeout in seconds useLabelCache: Whether to enable label caching labelCacheExpiryMinutes: Label cache expiry in minutes useCacheFirst: Whether to use cache-first behavior language: Default language code cacheDir: Custom cache directory path outputFormat: Default output format for CLI operations credentialSource: Credential source configuration. Set to null to use Azure Default Credentials. Can be: - Environment variables: {"sourceType": "environment", "clientIdVar": "MY_CLIENT_ID", "clientSecretVar": "MY_CLIENT_SECRET", "tenantIdVar": "MY_TENANT_ID"} - Azure Key Vault: {"sourceType": "keyvault", "vaultUrl": "https://vault.vault.azure.net/", "clientIdSecretName": "D365FO_CLIENT_ID", "clientSecretSecretName": "D365FO_CLIENT_SECRET", "tenantIdSecretName": "D365FO_TENANT_ID"}
Returns: Dictionary with update result including number of clients invalidated
Inputs: name (required), baseUrl, timeout, cacheDir, +8 more. Returns: result
d365fo_validate_profileA
Validate a D365FO environment profile configuration.
Args: profileName: Name of the profile to validate
Returns: Dictionary with validation result
Inputs: profileName (required). Returns: result
Tool Schema Changelog
Recent tool additions, removals, and schema changes observed during successful MCP inspections.
Loading tool schema changelog…
TDQS
Scored across 49 tools
Most tools are clearly distinct (query, CRUD, profiles, sync, reports). Some overlap exists between generic report download (d365fo_download_srs_report) and the specific report tools (e.g., d365fo_download_customer_invoice), but descriptions clarify the convenience vs generic nature. The search tools (search_entities, search_actions, search_enumerations) are distinct by domain.
Naming follows a consistent d365fo_ prefix with verb_noun structure (get_, list_, create_, update_, delete_, search_, download_). Minor inconsistency: list_profiles vs get_profile_names are semantically similar but have different verbs (list vs get) and different pluralization patterns, which could confuse agents. Overall pattern is strong.
With 49 tools, the server is comprehensive but pushes the upper boundary. The count is justified given the broad scope (profiles, sync, metadata, CRUD, reports, actions), but could feel heavy for agents. A few tools like download_customer_invoice and download_free_text_invoice are conveniences that add slight redundancy but are useful.
The tool surface covers core workflows: CRUD on entities, profile management, metadata exploration, sync operations, and report downloads. Minor gaps: no tool for listing report controllers or managing sync sessions beyond start/cancel, and no explicit way to list available OData actions bound to specific entities (though search covers this). Overall, the surface is well-rounded.
Maintenance
Related MCP Connectors
Read-only finance and operations controls for AI agents with evidence and safe next actions.
Give AI agents 30,000+ safe, token-optimized actions across Workday, SAP, Oracle + hundreds more.
Query your team's drift, vulnerability, and upgrade data from any AI assistant. OAuth 2.1, 51 tools.
Protocol-native energy infrastructure orchestration for AI data centers. Provides 46 MCP tools across 8 grid protocols (IEC-61850, DNP3, Modbus, OCPP, OpenADR, IEEE 2030.5, IEC 60870-5-104, ICCP) with 5 core API primitives: connect, dispatch, settle, comply, and intel. Enables AI agents to programmatically interact with substations, grid interfaces, and energy assets for real-time workload-grid coordination.
Related MCP Servers
- AlicenseNot gradedqualityDmaintenanceEnables AI assistants to interact with Dynamics 365 Commerce systems through 125+ tools covering customer management, sales orders, cart operations, product searches, inventory tracking, and store operations. Provides comprehensive mock data for development and testing purposes.3MIT
- AlicenseNot gradedqualityDmaintenanceEnables AI assistants to explore metadata, query data, and perform write operations across multiple Microsoft Dynamics 365 Finance & Operations environments. It features specialized tools for OData execution and data analysis with built-in read-only safety for production environments.44 npm10MIT
- FlicenseNot gradedqualityBmaintenanceEnables AI assistants to search and analyze Microsoft Dynamics 365 Finance & Operations artifacts, read local source code, and generate context-aware solutions through natural language.71 npm12-
- AlicenseAqualityAmaintenanceEnables AI-assisted X++ development for Dynamics 365 Finance and Operations by pre-indexing the entire codebase and providing 54 specialized tools for metadata lookup, code generation, and best practice validation.20433 npm171MIT