name: dynamics-365
description: Microsoft Dynamics 365 integration patterns for Sales, Service, Finance, and Supply Chain. Use when building AI agents that interact with Dataverse Web API (OData), F&O data entities, or integrate Azure OpenAI with Dynamics data.
tags: [dynamics-365, dataverse, microsoft, crm, erp]
Microsoft Dynamics 365 Integration
Connect AI agents to Dynamics 365 (Sales, Service, Finance, Supply Chain) using Dataverse Web API (OData v4), F&O OData, and Azure OpenAI integration.
When to Use
- Building AI agents that query or manage CRM data (leads, opportunities, cases, accounts)
- Integrating with Dynamics 365 Finance & Operations (journals, invoices, purchase orders)
- Combining Azure OpenAI with Dynamics data for deal analysis, case classification, or forecasting
- Using FetchXML for complex queries beyond OData $filter capability
- Triggering Power Automate flows from external AI agents
API Surface
| Product |
API Base URL |
Style |
| Sales / Service / Marketing |
https://{org}.crm.dynamics.com/api/data/v9.2/ |
Dataverse OData v4 |
| Finance & Operations |
https://{org}.cloudax.dynamics.com/data/ |
F&O OData v4 |
| Business Central |
https://api.businesscentral.dynamics.com/v2.0/{tenant}/{env}/api/v2.0/ |
BC OData v4 |
Key Entities
Sales
| Entity |
OData Set |
Key Fields |
| Account |
accounts |
name, revenue, industrycode |
| Contact |
contacts |
fullname, emailaddress1, telephone1 |
| Lead |
leads |
fullname, companyname, estimatedvalue, statuscode |
| Opportunity |
opportunities |
name, estimatedvalue, closeprobability, estimatedclosedate |
| Quote |
quotes |
name, totalamount |
| Invoice |
invoices |
name, totalamount, statuscode |
Customer Service
| Entity |
OData Set |
Key Fields |
| Case |
incidents |
title, ticketnumber, prioritycode, statuscode |
| Knowledge Article |
knowledgearticles |
title, content, statecode |
| Queue |
queues |
name |
Finance & Operations
| Entity |
OData Set |
Key Fields |
| Journal Headers |
GeneralJournalHeaders |
Journal batch headers |
| Journal Lines |
GeneralJournalAccountEntries |
Line entries |
| Vendor Invoices |
VendorInvoiceHeaders |
AP invoices |
| Purchase Orders |
PurchaseOrderHeaders |
Procurement |
| Customers |
CustomersV3 |
AR customers |
| Vendors |
VendorsV2 |
AP vendors |
| Chart of Accounts |
MainAccounts |
GL accounts |
Patterns
1. Authentication (Entra ID / OAuth 2.0)
import msal
import requests
class Dynamics365Client:
"""Dynamics 365 client using MSAL (Entra ID) client credentials."""
def __init__(self, tenant_id: str, client_id: str, client_secret: str, crm_url: str):
self.crm_url = crm_url.rstrip("/")
self.api_url = f"{self.crm_url}/api/data/v9.2"
self._app = msal.ConfidentialClientApplication(
client_id,
authority=f"https://login.microsoftonline.com/{tenant_id}",
client_credential=client_secret,
)
self._scope = [f"{self.crm_url}/.default"]
self._session = requests.Session()
self._session.headers.update({
"OData-MaxVersion": "4.0",
"OData-Version": "4.0",
"Accept": "application/json",
"Content-Type": "application/json; charset=utf-8",
"Prefer": "odata.include-annotations=*",
})
def _ensure_token(self):
token = self._app.acquire_token_for_client(scopes=self._scope)
if "access_token" not in token:
raise Exception(f"Auth failed: {token.get('error_description')}")
self._session.headers["Authorization"] = f"Bearer {token['access_token']}"
def get(self, entity_set: str, params: dict = None) -> dict:
self._ensure_token()
resp = self._session.get(f"{self.api_url}/{entity_set}", params=params)
resp.raise_for_status()
return resp.json()
def get_by_id(self, entity_set: str, record_id: str, select: str = None) -> dict:
self._ensure_token()
params = {"$select": select} if select else None
resp = self._session.get(f"{self.api_url}/{entity_set}({record_id})", params=params)
resp.raise_for_status()
return resp.json()
def create(self, entity_set: str, data: dict) -> str:
self._ensure_token()
resp = self._session.post(f"{self.api_url}/{entity_set}", json=data)
resp.raise_for_status()
return resp.headers.get("OData-EntityId", "")
def update(self, entity_set: str, record_id: str, data: dict) -> None:
self._ensure_token()
resp = self._session.patch(f"{self.api_url}/{entity_set}({record_id})", json=data)
resp.raise_for_status()
def delete(self, entity_set: str, record_id: str) -> None:
self._ensure_token()
resp = self._session.delete(f"{self.api_url}/{entity_set}({record_id})")
resp.raise_for_status()
2. Sales -- Leads, Opportunities, Accounts
# Query high-value opportunities with account expansion
def get_top_opportunities(client: Dynamics365Client, min_value: float = 10000) -> list[dict]:
return client.get("opportunities", params={
"$select": "name,estimatedvalue,closeprobability,estimatedclosedate",
"$filter": f"statecode eq 0 and estimatedvalue gt {min_value}",
"$orderby": "estimatedvalue desc",
"$top": 20,
"$expand": "parentaccountid($select=name,revenue)",
}).get("value", [])
# Create a new lead
def create_lead(client: Dynamics365Client, first_name: str, last_name: str,
company: str, email: str, estimated_value: float = 0) -> str:
return client.create("leads", {
"firstname": first_name,
"lastname": last_name,
"companyname": company,
"emailaddress1": email,
"estimatedvalue": estimated_value,
"subject": f"Interest from {company}",
})
# Qualify a lead (bound action)
def qualify_lead(client: Dynamics365Client, lead_id: str) -> dict:
client._ensure_token()
resp = client._session.post(
f"{client.api_url}/leads({lead_id})/Microsoft.Dynamics.CRM.QualifyLead",
json={"CreateAccount": True, "CreateContact": True, "CreateOpportunity": True, "Status": 3},
)
resp.raise_for_status()
return resp.json()
# Update opportunity stage
def update_opportunity_stage(client: Dynamics365Client, opp_id: str,
stage: str, probability: int) -> None:
client.update("opportunities", opp_id, {
"stepname": stage,
"closeprobability": probability,
})
3. Customer Service -- Cases and Knowledge
# Get open cases sorted by priority
def get_open_cases(client: Dynamics365Client, limit: int = 25) -> list[dict]:
return client.get("incidents", params={
"$select": "title,ticketnumber,prioritycode,statuscode,createdon",
"$filter": "statecode eq 0",
"$orderby": "prioritycode asc,createdon desc",
"$top": limit,
"$expand": "customerid_contact($select=fullname,emailaddress1)",
}).get("value", [])
# Create a support case
def create_case(client: Dynamics365Client, title: str, description: str,
customer_id: str, priority: int = 2) -> str:
return client.create("incidents", {
"title": title,
"description": description,
"prioritycode": priority,
"customerid_contact@odata.bind": f"/contacts({customer_id})",
})
# Search knowledge articles
def search_knowledge(client: Dynamics365Client, query: str) -> list[dict]:
return client.get("knowledgearticles", params={
"$select": "title,description,articlepublicnumber",
"$filter": f"statecode eq 3 and contains(title,'{query}')",
"$top": 10,
}).get("value", [])
4. Finance & Operations
class D365FinOpsClient:
"""Dynamics 365 Finance & Operations OData client."""
def __init__(self, tenant_id: str, client_id: str, client_secret: str, fo_url: str):
self.fo_url = fo_url.rstrip("/")
self.data_url = f"{self.fo_url}/data"
self._app = msal.ConfidentialClientApplication(
client_id,
authority=f"https://login.microsoftonline.com/{tenant_id}",
client_credential=client_secret,
)
self._scope = [f"{self.fo_url}/.default"]
self._session = requests.Session()
self._session.headers.update({
"Content-Type": "application/json",
"Accept": "application/json",
})
def _ensure_token(self):
token = self._app.acquire_token_for_client(scopes=self._scope)
self._session.headers["Authorization"] = f"Bearer {token['access_token']}"
def get(self, entity: str, params: dict = None) -> list[dict]:
self._ensure_token()
resp = self._session.get(f"{self.data_url}/{entity}", params=params)
resp.raise_for_status()
return resp.json().get("value", [])
# Query vendor invoices
def get_vendor_invoices(client: D365FinOpsClient, from_date: str) -> list[dict]:
return client.get("VendorInvoiceHeaders", params={
"$filter": f"InvoiceDate gt {from_date}",
"$select": "InvoiceId,VendorName,InvoiceAmount,InvoiceDate",
"$top": 50,
"$orderby": "InvoiceDate desc",
})
# Query journal entries
def get_journal_entries(client: D365FinOpsClient, from_date: str) -> list[dict]:
return client.get("GeneralJournalAccountEntries", params={
"$filter": f"PostingDate gt {from_date}",
"$select": "JournalNumber,MainAccount,TransactionCurrencyAmount",
"$top": 100,
})
# Create a purchase order (F&O requires dataAreaId)
def create_purchase_order(client: D365FinOpsClient, po_number: str,
vendor: str, legal_entity: str = "usmf") -> dict:
client._ensure_token()
resp = client._session.post(f"{client.data_url}/PurchaseOrderHeaders", json={
"PurchaseOrderNumber": po_number,
"OrderVendorAccountNumber": vendor,
"dataAreaId": legal_entity,
})
resp.raise_for_status()
return resp.json()
5. FetchXML (Complex Queries)
import urllib.parse
def fetch_xml_query(client: Dynamics365Client, entity_set: str, fetch_xml: str) -> list[dict]:
"""Execute a FetchXML query for complex joins and aggregations."""
client._ensure_token()
encoded = urllib.parse.quote(fetch_xml)
resp = client._session.get(f"{client.api_url}/{entity_set}?fetchXml={encoded}")
resp.raise_for_status()
return resp.json().get("value", [])
# High-value opportunities in a specific industry
opps = fetch_xml_query(client, "opportunities", """
<fetch top="50">
<entity name="opportunity">
<attribute name="name"/>
<attribute name="estimatedvalue"/>
<attribute name="closeprobability"/>
<filter>
<condition attribute="statecode" operator="eq" value="0"/>
<condition attribute="estimatedvalue" operator="gt" value="50000"/>
</filter>
<link-entity name="account" from="accountid" to="parentaccountid" alias="acct">
<attribute name="name"/>
<filter>
<condition attribute="industrycode" operator="eq" value="6"/>
</filter>
</link-entity>
<order attribute="estimatedvalue" descending="true"/>
</entity>
</fetch>
""")
6. Change Tracking (Delta Sync)
def get_changes(client: Dynamics365Client, entity_set: str,
delta_link: str = None) -> tuple[list[dict], str]:
"""Track record changes since last sync.
Returns (changed_records, next_delta_link).
"""
client._ensure_token()
if delta_link:
resp = client._session.get(delta_link)
else:
resp = client._session.get(
f"{client.api_url}/{entity_set}",
headers={"Prefer": "odata.track-changes"},
)
resp.raise_for_status()
data = resp.json()
return data.get("value", []), data.get("@odata.deltaLink", "")
# Initial sync
records, delta = get_changes(client, "accounts")
# Subsequent sync -- only get changes
changed, delta = get_changes(client, "accounts", delta_link=delta)
7. Pagination Helper
def get_all_records(client: Dynamics365Client, entity_set: str,
params: dict = None) -> list[dict]:
"""Handle server-side paging (5000 record default page size)."""
client._ensure_token()
records = []
url = f"{client.api_url}/{entity_set}"
while url:
resp = client._session.get(url, params=params)
resp.raise_for_status()
data = resp.json()
records.extend(data.get("value", []))
url = data.get("@odata.nextLink")
params = None # nextLink already contains params
return records
8. Azure OpenAI + Dynamics 365
import openai
def classify_case_with_ai(client: Dynamics365Client, case_id: str,
aoai_client: openai.AzureOpenAI) -> str:
"""Classify a D365 case using Azure OpenAI and update the record."""
case = client.get_by_id("incidents", case_id, select="title,description")
classification = aoai_client.chat.completions.create(
model="gpt-4o",
messages=[
{"role": "system", "content": "Classify the support case into: Billing, Technical, Account, General. Return only the category."},
{"role": "user", "content": f"Title: {case['title']}\nDescription: {case.get('description', 'N/A')}"},
],
)
category = classification.choices[0].message.content.strip()
client.update("incidents", case_id, {"new_aicategory": category})
return category
def analyze_deal_risk(client: Dynamics365Client, opp_id: str,
aoai_client: openai.AzureOpenAI) -> str:
"""Analyze deal risk using Azure OpenAI."""
opp = client.get_by_id("opportunities", opp_id,
select="name,estimatedvalue,closeprobability,estimatedclosedate,modifiedon")
response = aoai_client.chat.completions.create(
model="gpt-4o",
messages=[
{"role": "system", "content": "You are a sales operations analyst. Assess deal risk."},
{"role": "user", "content": f"Opportunity: {opp['name']}, Value: ${opp.get('estimatedvalue', 0):,.2f}, "
f"Probability: {opp.get('closeprobability', 'N/A')}%, "
f"Close date: {opp.get('estimatedclosedate', 'N/A')}, "
f"Last modified: {opp.get('modifiedon', 'N/A')}"},
],
)
return response.choices[0].message.content
9. Agent Tool Functions
def search_accounts(account_name: str) -> str:
"""Search Dynamics 365 accounts by name.
Args:
account_name: Full or partial account name
"""
client = Dynamics365Client(TENANT_ID, CLIENT_ID, CLIENT_SECRET, CRM_URL)
accounts = client.get("accounts", params={
"$select": "name,revenue,telephone1",
"$filter": f"contains(name,'{account_name}')",
"$top": 10,
}).get("value", [])
if not accounts:
return f"No accounts found matching '{account_name}'."
lines = [f"- {a['name']} (Revenue: ${a.get('revenue', 0):,.0f})" for a in accounts]
return f"Found {len(accounts)} account(s):\n" + "\n".join(lines)
def get_pipeline_summary() -> str:
"""Get a summary of the open sales pipeline."""
client = Dynamics365Client(TENANT_ID, CLIENT_ID, CLIENT_SECRET, CRM_URL)
opps = client.get("opportunities", params={
"$select": "name,estimatedvalue,closeprobability",
"$filter": "statecode eq 0",
"$orderby": "estimatedvalue desc",
}).get("value", [])
total = sum(o.get("estimatedvalue", 0) for o in opps)
weighted = sum(o.get("estimatedvalue", 0) * o.get("closeprobability", 0) / 100 for o in opps)
return (f"Pipeline: {len(opps)} open opportunities\n"
f"Total value: ${total:,.0f}\n"
f"Weighted value: ${weighted:,.0f}")
Dynamics 365 Copilot Features
| Module |
Copilot Capabilities |
| Sales |
Record summarization, email drafting, meeting prep, lead research, pipeline insights |
| Service |
Case summarization, KB article generation, similar case suggestions, AI routing |
| Finance |
Account reconciliation agent, collections drafting, cash flow forecasting |
| Supply Chain |
Demand forecasting, intelligent order management, inventory anomaly detection |
Anti-Patterns
- Not using
$select -- always specify fields to reduce payload and improve performance
- Ignoring
@odata.nextLink -- results are capped at 5000 per page by default
- Using OData
$filter for complex joins -- use FetchXML instead
- Hardcoding GUIDs -- use alternate keys where available (e.g.,
accounts(accountnumber='A001'))
- Skipping Application User setup -- client credentials flow requires a D365 Application User with security roles
- Sending raw D365 data to LLMs without field selection -- filter sensitive fields before AI processing
- Not handling F&O
dataAreaId -- Finance & Operations requires legal entity on most write operations
References
1---2name: dynamics-365-23description: <!-- AUTO-GENERATED by export-skills.py — DO NOT EDIT -->4---5<!-- AUTO-GENERATED by export-skills.py — DO NOT EDIT -->6---7name: dynamics-3658description: Microsoft Dynamics 365 integration patterns for Sales, Service, Finance, and Supply Chain. Use when building AI agents that interact with Dataverse Web API (OData), F&O data entities, or integrate Azure OpenAI with Dynamics data.9tags: [dynamics-365, dataverse, microsoft, crm, erp]10---1112# Microsoft Dynamics 365 Integration1314Connect AI agents to Dynamics 365 (Sales, Service, Finance, Supply Chain) using Dataverse Web API (OData v4), F&O OData, and Azure OpenAI integration.1516## When to Use1718- Building AI agents that query or manage CRM data (leads, opportunities, cases, accounts)19- Integrating with Dynamics 365 Finance & Operations (journals, invoices, purchase orders)20- Combining Azure OpenAI with Dynamics data for deal analysis, case classification, or forecasting21- Using FetchXML for complex queries beyond OData $filter capability22- Triggering Power Automate flows from external AI agents2324## API Surface2526| Product | API Base URL | Style |27|---|---|---|28| **Sales / Service / Marketing** | `https://{org}.crm.dynamics.com/api/data/v9.2/` | Dataverse OData v4 |29| **Finance & Operations** | `https://{org}.cloudax.dynamics.com/data/` | F&O OData v4 |30| **Business Central** | `https://api.businesscentral.dynamics.com/v2.0/{tenant}/{env}/api/v2.0/` | BC OData v4 |3132## Key Entities3334### Sales3536| Entity | OData Set | Key Fields |37|---|---|---|38| Account | `accounts` | `name`, `revenue`, `industrycode` |39| Contact | `contacts` | `fullname`, `emailaddress1`, `telephone1` |40| Lead | `leads` | `fullname`, `companyname`, `estimatedvalue`, `statuscode` |41| Opportunity | `opportunities` | `name`, `estimatedvalue`, `closeprobability`, `estimatedclosedate` |42| Quote | `quotes` | `name`, `totalamount` |43| Invoice | `invoices` | `name`, `totalamount`, `statuscode` |4445### Customer Service4647| Entity | OData Set | Key Fields |48|---|---|---|49| Case | `incidents` | `title`, `ticketnumber`, `prioritycode`, `statuscode` |50| Knowledge Article | `knowledgearticles` | `title`, `content`, `statecode` |51| Queue | `queues` | `name` |5253### Finance & Operations5455| Entity | OData Set | Key Fields |56|---|---|---|57| Journal Headers | `GeneralJournalHeaders` | Journal batch headers |58| Journal Lines | `GeneralJournalAccountEntries` | Line entries |59| Vendor Invoices | `VendorInvoiceHeaders` | AP invoices |60| Purchase Orders | `PurchaseOrderHeaders` | Procurement |61| Customers | `CustomersV3` | AR customers |62| Vendors | `VendorsV2` | AP vendors |63| Chart of Accounts | `MainAccounts` | GL accounts |6465## Patterns6667### 1. Authentication (Entra ID / OAuth 2.0)6869```python70import msal71import requests7273class Dynamics365Client:74 """Dynamics 365 client using MSAL (Entra ID) client credentials."""7576 def __init__(self, tenant_id: str, client_id: str, client_secret: str, crm_url: str):77 self.crm_url = crm_url.rstrip("/")78 self.api_url = f"{self.crm_url}/api/data/v9.2"79 self._app = msal.ConfidentialClientApplication(80 client_id,81 authority=f"https://login.microsoftonline.com/{tenant_id}",82 client_credential=client_secret,83 )84 self._scope = [f"{self.crm_url}/.default"]85 self._session = requests.Session()86 self._session.headers.update({87 "OData-MaxVersion": "4.0",88 "OData-Version": "4.0",89 "Accept": "application/json",90 "Content-Type": "application/json; charset=utf-8",91 "Prefer": "odata.include-annotations=*",92 })9394 def _ensure_token(self):95 token = self._app.acquire_token_for_client(scopes=self._scope)96 if "access_token" not in token:97 raise Exception(f"Auth failed: {token.get('error_description')}")98 self._session.headers["Authorization"] = f"Bearer {token['access_token']}"99100 def get(self, entity_set: str, params: dict = None) -> dict:101 self._ensure_token()102 resp = self._session.get(f"{self.api_url}/{entity_set}", params=params)103 resp.raise_for_status()104 return resp.json()105106 def get_by_id(self, entity_set: str, record_id: str, select: str = None) -> dict:107 self._ensure_token()108 params = {"$select": select} if select else None109 resp = self._session.get(f"{self.api_url}/{entity_set}({record_id})", params=params)110 resp.raise_for_status()111 return resp.json()112113 def create(self, entity_set: str, data: dict) -> str:114 self._ensure_token()115 resp = self._session.post(f"{self.api_url}/{entity_set}", json=data)116 resp.raise_for_status()117 return resp.headers.get("OData-EntityId", "")118119 def update(self, entity_set: str, record_id: str, data: dict) -> None:120 self._ensure_token()121 resp = self._session.patch(f"{self.api_url}/{entity_set}({record_id})", json=data)122 resp.raise_for_status()123124 def delete(self, entity_set: str, record_id: str) -> None:125 self._ensure_token()126 resp = self._session.delete(f"{self.api_url}/{entity_set}({record_id})")127 resp.raise_for_status()128```129130### 2. Sales -- Leads, Opportunities, Accounts131132```python133# Query high-value opportunities with account expansion134def get_top_opportunities(client: Dynamics365Client, min_value: float = 10000) -> list[dict]:135 return client.get("opportunities", params={136 "$select": "name,estimatedvalue,closeprobability,estimatedclosedate",137 "$filter": f"statecode eq 0 and estimatedvalue gt {min_value}",138 "$orderby": "estimatedvalue desc",139 "$top": 20,140 "$expand": "parentaccountid($select=name,revenue)",141 }).get("value", [])142143# Create a new lead144def create_lead(client: Dynamics365Client, first_name: str, last_name: str,145 company: str, email: str, estimated_value: float = 0) -> str:146 return client.create("leads", {147 "firstname": first_name,148 "lastname": last_name,149 "companyname": company,150 "emailaddress1": email,151 "estimatedvalue": estimated_value,152 "subject": f"Interest from {company}",153 })154155# Qualify a lead (bound action)156def qualify_lead(client: Dynamics365Client, lead_id: str) -> dict:157 client._ensure_token()158 resp = client._session.post(159 f"{client.api_url}/leads({lead_id})/Microsoft.Dynamics.CRM.QualifyLead",160 json={"CreateAccount": True, "CreateContact": True, "CreateOpportunity": True, "Status": 3},161 )162 resp.raise_for_status()163 return resp.json()164165# Update opportunity stage166def update_opportunity_stage(client: Dynamics365Client, opp_id: str,167 stage: str, probability: int) -> None:168 client.update("opportunities", opp_id, {169 "stepname": stage,170 "closeprobability": probability,171 })172```173174### 3. Customer Service -- Cases and Knowledge175176```python177# Get open cases sorted by priority178def get_open_cases(client: Dynamics365Client, limit: int = 25) -> list[dict]:179 return client.get("incidents", params={180 "$select": "title,ticketnumber,prioritycode,statuscode,createdon",181 "$filter": "statecode eq 0",182 "$orderby": "prioritycode asc,createdon desc",183 "$top": limit,184 "$expand": "customerid_contact($select=fullname,emailaddress1)",185 }).get("value", [])186187# Create a support case188def create_case(client: Dynamics365Client, title: str, description: str,189 customer_id: str, priority: int = 2) -> str:190 return client.create("incidents", {191 "title": title,192 "description": description,193 "prioritycode": priority,194 "customerid_contact@odata.bind": f"/contacts({customer_id})",195 })196197# Search knowledge articles198def search_knowledge(client: Dynamics365Client, query: str) -> list[dict]:199 return client.get("knowledgearticles", params={200 "$select": "title,description,articlepublicnumber",201 "$filter": f"statecode eq 3 and contains(title,'{query}')",202 "$top": 10,203 }).get("value", [])204```205206### 4. Finance & Operations207208```python209class D365FinOpsClient:210 """Dynamics 365 Finance & Operations OData client."""211212 def __init__(self, tenant_id: str, client_id: str, client_secret: str, fo_url: str):213 self.fo_url = fo_url.rstrip("/")214 self.data_url = f"{self.fo_url}/data"215 self._app = msal.ConfidentialClientApplication(216 client_id,217 authority=f"https://login.microsoftonline.com/{tenant_id}",218 client_credential=client_secret,219 )220 self._scope = [f"{self.fo_url}/.default"]221 self._session = requests.Session()222 self._session.headers.update({223 "Content-Type": "application/json",224 "Accept": "application/json",225 })226227 def _ensure_token(self):228 token = self._app.acquire_token_for_client(scopes=self._scope)229 self._session.headers["Authorization"] = f"Bearer {token['access_token']}"230231 def get(self, entity: str, params: dict = None) -> list[dict]:232 self._ensure_token()233 resp = self._session.get(f"{self.data_url}/{entity}", params=params)234 resp.raise_for_status()235 return resp.json().get("value", [])236237# Query vendor invoices238def get_vendor_invoices(client: D365FinOpsClient, from_date: str) -> list[dict]:239 return client.get("VendorInvoiceHeaders", params={240 "$filter": f"InvoiceDate gt {from_date}",241 "$select": "InvoiceId,VendorName,InvoiceAmount,InvoiceDate",242 "$top": 50,243 "$orderby": "InvoiceDate desc",244 })245246# Query journal entries247def get_journal_entries(client: D365FinOpsClient, from_date: str) -> list[dict]:248 return client.get("GeneralJournalAccountEntries", params={249 "$filter": f"PostingDate gt {from_date}",250 "$select": "JournalNumber,MainAccount,TransactionCurrencyAmount",251 "$top": 100,252 })253254# Create a purchase order (F&O requires dataAreaId)255def create_purchase_order(client: D365FinOpsClient, po_number: str,256 vendor: str, legal_entity: str = "usmf") -> dict:257 client._ensure_token()258 resp = client._session.post(f"{client.data_url}/PurchaseOrderHeaders", json={259 "PurchaseOrderNumber": po_number,260 "OrderVendorAccountNumber": vendor,261 "dataAreaId": legal_entity,262 })263 resp.raise_for_status()264 return resp.json()265```266267### 5. FetchXML (Complex Queries)268269```python270import urllib.parse271272def fetch_xml_query(client: Dynamics365Client, entity_set: str, fetch_xml: str) -> list[dict]:273 """Execute a FetchXML query for complex joins and aggregations."""274 client._ensure_token()275 encoded = urllib.parse.quote(fetch_xml)276 resp = client._session.get(f"{client.api_url}/{entity_set}?fetchXml={encoded}")277 resp.raise_for_status()278 return resp.json().get("value", [])279280# High-value opportunities in a specific industry281opps = fetch_xml_query(client, "opportunities", """282<fetch top="50">283 <entity name="opportunity">284 <attribute name="name"/>285 <attribute name="estimatedvalue"/>286 <attribute name="closeprobability"/>287 <filter>288 <condition attribute="statecode" operator="eq" value="0"/>289 <condition attribute="estimatedvalue" operator="gt" value="50000"/>290 </filter>291 <link-entity name="account" from="accountid" to="parentaccountid" alias="acct">292 <attribute name="name"/>293 <filter>294 <condition attribute="industrycode" operator="eq" value="6"/>295 </filter>296 </link-entity>297 <order attribute="estimatedvalue" descending="true"/>298 </entity>299</fetch>300""")301```302303### 6. Change Tracking (Delta Sync)304305```python306def get_changes(client: Dynamics365Client, entity_set: str,307 delta_link: str = None) -> tuple[list[dict], str]:308 """Track record changes since last sync.309310 Returns (changed_records, next_delta_link).311 """312 client._ensure_token()313 if delta_link:314 resp = client._session.get(delta_link)315 else:316 resp = client._session.get(317 f"{client.api_url}/{entity_set}",318 headers={"Prefer": "odata.track-changes"},319 )320 resp.raise_for_status()321 data = resp.json()322 return data.get("value", []), data.get("@odata.deltaLink", "")323324# Initial sync325records, delta = get_changes(client, "accounts")326327# Subsequent sync -- only get changes328changed, delta = get_changes(client, "accounts", delta_link=delta)329```330331### 7. Pagination Helper332333```python334def get_all_records(client: Dynamics365Client, entity_set: str,335 params: dict = None) -> list[dict]:336 """Handle server-side paging (5000 record default page size)."""337 client._ensure_token()338 records = []339 url = f"{client.api_url}/{entity_set}"340 while url:341 resp = client._session.get(url, params=params)342 resp.raise_for_status()343 data = resp.json()344 records.extend(data.get("value", []))345 url = data.get("@odata.nextLink")346 params = None # nextLink already contains params347 return records348```349350### 8. Azure OpenAI + Dynamics 365351352```python353import openai354355def classify_case_with_ai(client: Dynamics365Client, case_id: str,356 aoai_client: openai.AzureOpenAI) -> str:357 """Classify a D365 case using Azure OpenAI and update the record."""358 case = client.get_by_id("incidents", case_id, select="title,description")359360 classification = aoai_client.chat.completions.create(361 model="gpt-4o",362 messages=[363 {"role": "system", "content": "Classify the support case into: Billing, Technical, Account, General. Return only the category."},364 {"role": "user", "content": f"Title: {case['title']}\nDescription: {case.get('description', 'N/A')}"},365 ],366 )367 category = classification.choices[0].message.content.strip()368 client.update("incidents", case_id, {"new_aicategory": category})369 return category370371def analyze_deal_risk(client: Dynamics365Client, opp_id: str,372 aoai_client: openai.AzureOpenAI) -> str:373 """Analyze deal risk using Azure OpenAI."""374 opp = client.get_by_id("opportunities", opp_id,375 select="name,estimatedvalue,closeprobability,estimatedclosedate,modifiedon")376 response = aoai_client.chat.completions.create(377 model="gpt-4o",378 messages=[379 {"role": "system", "content": "You are a sales operations analyst. Assess deal risk."},380 {"role": "user", "content": f"Opportunity: {opp['name']}, Value: ${opp.get('estimatedvalue', 0):,.2f}, "381 f"Probability: {opp.get('closeprobability', 'N/A')}%, "382 f"Close date: {opp.get('estimatedclosedate', 'N/A')}, "383 f"Last modified: {opp.get('modifiedon', 'N/A')}"},384 ],385 )386 return response.choices[0].message.content387```388389### 9. Agent Tool Functions390391```python392def search_accounts(account_name: str) -> str:393 """Search Dynamics 365 accounts by name.394395 Args:396 account_name: Full or partial account name397 """398 client = Dynamics365Client(TENANT_ID, CLIENT_ID, CLIENT_SECRET, CRM_URL)399 accounts = client.get("accounts", params={400 "$select": "name,revenue,telephone1",401 "$filter": f"contains(name,'{account_name}')",402 "$top": 10,403 }).get("value", [])404 if not accounts:405 return f"No accounts found matching '{account_name}'."406 lines = [f"- {a['name']} (Revenue: ${a.get('revenue', 0):,.0f})" for a in accounts]407 return f"Found {len(accounts)} account(s):\n" + "\n".join(lines)408409def get_pipeline_summary() -> str:410 """Get a summary of the open sales pipeline."""411 client = Dynamics365Client(TENANT_ID, CLIENT_ID, CLIENT_SECRET, CRM_URL)412 opps = client.get("opportunities", params={413 "$select": "name,estimatedvalue,closeprobability",414 "$filter": "statecode eq 0",415 "$orderby": "estimatedvalue desc",416 }).get("value", [])417 total = sum(o.get("estimatedvalue", 0) for o in opps)418 weighted = sum(o.get("estimatedvalue", 0) * o.get("closeprobability", 0) / 100 for o in opps)419 return (f"Pipeline: {len(opps)} open opportunities\n"420 f"Total value: ${total:,.0f}\n"421 f"Weighted value: ${weighted:,.0f}")422```423424## Dynamics 365 Copilot Features425426| Module | Copilot Capabilities |427|---|---|428| **Sales** | Record summarization, email drafting, meeting prep, lead research, pipeline insights |429| **Service** | Case summarization, KB article generation, similar case suggestions, AI routing |430| **Finance** | Account reconciliation agent, collections drafting, cash flow forecasting |431| **Supply Chain** | Demand forecasting, intelligent order management, inventory anomaly detection |432433## Anti-Patterns434435- Not using `$select` -- always specify fields to reduce payload and improve performance436- Ignoring `@odata.nextLink` -- results are capped at 5000 per page by default437- Using OData `$filter` for complex joins -- use FetchXML instead438- Hardcoding GUIDs -- use alternate keys where available (e.g., `accounts(accountnumber='A001')`)439- Skipping Application User setup -- client credentials flow requires a D365 Application User with security roles440- Sending raw D365 data to LLMs without field selection -- filter sensitive fields before AI processing441- Not handling F&O `dataAreaId` -- Finance & Operations requires legal entity on most write operations442443## References444445- [Dataverse Web API Reference](https://learn.microsoft.com/en-us/power-apps/developer/data-platform/webapi/reference/about)446- [Dynamics 365 F&O Data Entities](https://learn.microsoft.com/en-us/dynamics365/fin-ops-core/dev-itpro/data-entities/data-entities)447- [MSAL Python Documentation](https://learn.microsoft.com/en-us/entra/msal/python/)448- [FetchXML Reference](https://learn.microsoft.com/en-us/power-apps/developer/data-platform/use-fetchxml-construct-query)449- [Dynamics 365 Copilot](https://learn.microsoft.com/en-us/dynamics365/copilot/ai-get-started)450451<!-- Source: .faos/custom/skills/integrations/dynamics-365/SKILL.md -->