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]
Platform Note: This skill was designed for multi-agent execution. Perplexity Computer handles orchestration automatically — treat sub-agent instructions as sequential steps to complete thoroughly.
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-33description: <!-- 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> **Platform Note:** This skill was designed for multi-agent execution. Perplexity Computer handles orchestration automatically — treat sub-agent instructions as sequential steps to complete thoroughly.1314# Microsoft Dynamics 365 Integration1516Connect AI agents to Dynamics 365 (Sales, Service, Finance, Supply Chain) using Dataverse Web API (OData v4), F&O OData, and Azure OpenAI integration.1718## When to Use1920- Building AI agents that query or manage CRM data (leads, opportunities, cases, accounts)21- Integrating with Dynamics 365 Finance & Operations (journals, invoices, purchase orders)22- Combining Azure OpenAI with Dynamics data for deal analysis, case classification, or forecasting23- Using FetchXML for complex queries beyond OData $filter capability24- Triggering Power Automate flows from external AI agents2526## API Surface2728| Product | API Base URL | Style |29|---|---|---|30| **Sales / Service / Marketing** | `https://{org}.crm.dynamics.com/api/data/v9.2/` | Dataverse OData v4 |31| **Finance & Operations** | `https://{org}.cloudax.dynamics.com/data/` | F&O OData v4 |32| **Business Central** | `https://api.businesscentral.dynamics.com/v2.0/{tenant}/{env}/api/v2.0/` | BC OData v4 |3334## Key Entities3536### Sales3738| Entity | OData Set | Key Fields |39|---|---|---|40| Account | `accounts` | `name`, `revenue`, `industrycode` |41| Contact | `contacts` | `fullname`, `emailaddress1`, `telephone1` |42| Lead | `leads` | `fullname`, `companyname`, `estimatedvalue`, `statuscode` |43| Opportunity | `opportunities` | `name`, `estimatedvalue`, `closeprobability`, `estimatedclosedate` |44| Quote | `quotes` | `name`, `totalamount` |45| Invoice | `invoices` | `name`, `totalamount`, `statuscode` |4647### Customer Service4849| Entity | OData Set | Key Fields |50|---|---|---|51| Case | `incidents` | `title`, `ticketnumber`, `prioritycode`, `statuscode` |52| Knowledge Article | `knowledgearticles` | `title`, `content`, `statecode` |53| Queue | `queues` | `name` |5455### Finance & Operations5657| Entity | OData Set | Key Fields |58|---|---|---|59| Journal Headers | `GeneralJournalHeaders` | Journal batch headers |60| Journal Lines | `GeneralJournalAccountEntries` | Line entries |61| Vendor Invoices | `VendorInvoiceHeaders` | AP invoices |62| Purchase Orders | `PurchaseOrderHeaders` | Procurement |63| Customers | `CustomersV3` | AR customers |64| Vendors | `VendorsV2` | AP vendors |65| Chart of Accounts | `MainAccounts` | GL accounts |6667## Patterns6869### 1. Authentication (Entra ID / OAuth 2.0)7071```python72import msal73import requests7475class Dynamics365Client:76 """Dynamics 365 client using MSAL (Entra ID) client credentials."""7778 def __init__(self, tenant_id: str, client_id: str, client_secret: str, crm_url: str):79 self.crm_url = crm_url.rstrip("/")80 self.api_url = f"{self.crm_url}/api/data/v9.2"81 self._app = msal.ConfidentialClientApplication(82 client_id,83 authority=f"https://login.microsoftonline.com/{tenant_id}",84 client_credential=client_secret,85 )86 self._scope = [f"{self.crm_url}/.default"]87 self._session = requests.Session()88 self._session.headers.update({89 "OData-MaxVersion": "4.0",90 "OData-Version": "4.0",91 "Accept": "application/json",92 "Content-Type": "application/json; charset=utf-8",93 "Prefer": "odata.include-annotations=*",94 })9596 def _ensure_token(self):97 token = self._app.acquire_token_for_client(scopes=self._scope)98 if "access_token" not in token:99 raise Exception(f"Auth failed: {token.get('error_description')}")100 self._session.headers["Authorization"] = f"Bearer {token['access_token']}"101102 def get(self, entity_set: str, params: dict = None) -> dict:103 self._ensure_token()104 resp = self._session.get(f"{self.api_url}/{entity_set}", params=params)105 resp.raise_for_status()106 return resp.json()107108 def get_by_id(self, entity_set: str, record_id: str, select: str = None) -> dict:109 self._ensure_token()110 params = {"$select": select} if select else None111 resp = self._session.get(f"{self.api_url}/{entity_set}({record_id})", params=params)112 resp.raise_for_status()113 return resp.json()114115 def create(self, entity_set: str, data: dict) -> str:116 self._ensure_token()117 resp = self._session.post(f"{self.api_url}/{entity_set}", json=data)118 resp.raise_for_status()119 return resp.headers.get("OData-EntityId", "")120121 def update(self, entity_set: str, record_id: str, data: dict) -> None:122 self._ensure_token()123 resp = self._session.patch(f"{self.api_url}/{entity_set}({record_id})", json=data)124 resp.raise_for_status()125126 def delete(self, entity_set: str, record_id: str) -> None:127 self._ensure_token()128 resp = self._session.delete(f"{self.api_url}/{entity_set}({record_id})")129 resp.raise_for_status()130```131132### 2. Sales -- Leads, Opportunities, Accounts133134```python135# Query high-value opportunities with account expansion136def get_top_opportunities(client: Dynamics365Client, min_value: float = 10000) -> list[dict]:137 return client.get("opportunities", params={138 "$select": "name,estimatedvalue,closeprobability,estimatedclosedate",139 "$filter": f"statecode eq 0 and estimatedvalue gt {min_value}",140 "$orderby": "estimatedvalue desc",141 "$top": 20,142 "$expand": "parentaccountid($select=name,revenue)",143 }).get("value", [])144145# Create a new lead146def create_lead(client: Dynamics365Client, first_name: str, last_name: str,147 company: str, email: str, estimated_value: float = 0) -> str:148 return client.create("leads", {149 "firstname": first_name,150 "lastname": last_name,151 "companyname": company,152 "emailaddress1": email,153 "estimatedvalue": estimated_value,154 "subject": f"Interest from {company}",155 })156157# Qualify a lead (bound action)158def qualify_lead(client: Dynamics365Client, lead_id: str) -> dict:159 client._ensure_token()160 resp = client._session.post(161 f"{client.api_url}/leads({lead_id})/Microsoft.Dynamics.CRM.QualifyLead",162 json={"CreateAccount": True, "CreateContact": True, "CreateOpportunity": True, "Status": 3},163 )164 resp.raise_for_status()165 return resp.json()166167# Update opportunity stage168def update_opportunity_stage(client: Dynamics365Client, opp_id: str,169 stage: str, probability: int) -> None:170 client.update("opportunities", opp_id, {171 "stepname": stage,172 "closeprobability": probability,173 })174```175176### 3. Customer Service -- Cases and Knowledge177178```python179# Get open cases sorted by priority180def get_open_cases(client: Dynamics365Client, limit: int = 25) -> list[dict]:181 return client.get("incidents", params={182 "$select": "title,ticketnumber,prioritycode,statuscode,createdon",183 "$filter": "statecode eq 0",184 "$orderby": "prioritycode asc,createdon desc",185 "$top": limit,186 "$expand": "customerid_contact($select=fullname,emailaddress1)",187 }).get("value", [])188189# Create a support case190def create_case(client: Dynamics365Client, title: str, description: str,191 customer_id: str, priority: int = 2) -> str:192 return client.create("incidents", {193 "title": title,194 "description": description,195 "prioritycode": priority,196 "customerid_contact@odata.bind": f"/contacts({customer_id})",197 })198199# Search knowledge articles200def search_knowledge(client: Dynamics365Client, query: str) -> list[dict]:201 return client.get("knowledgearticles", params={202 "$select": "title,description,articlepublicnumber",203 "$filter": f"statecode eq 3 and contains(title,'{query}')",204 "$top": 10,205 }).get("value", [])206```207208### 4. Finance & Operations209210```python211class D365FinOpsClient:212 """Dynamics 365 Finance & Operations OData client."""213214 def __init__(self, tenant_id: str, client_id: str, client_secret: str, fo_url: str):215 self.fo_url = fo_url.rstrip("/")216 self.data_url = f"{self.fo_url}/data"217 self._app = msal.ConfidentialClientApplication(218 client_id,219 authority=f"https://login.microsoftonline.com/{tenant_id}",220 client_credential=client_secret,221 )222 self._scope = [f"{self.fo_url}/.default"]223 self._session = requests.Session()224 self._session.headers.update({225 "Content-Type": "application/json",226 "Accept": "application/json",227 })228229 def _ensure_token(self):230 token = self._app.acquire_token_for_client(scopes=self._scope)231 self._session.headers["Authorization"] = f"Bearer {token['access_token']}"232233 def get(self, entity: str, params: dict = None) -> list[dict]:234 self._ensure_token()235 resp = self._session.get(f"{self.data_url}/{entity}", params=params)236 resp.raise_for_status()237 return resp.json().get("value", [])238239# Query vendor invoices240def get_vendor_invoices(client: D365FinOpsClient, from_date: str) -> list[dict]:241 return client.get("VendorInvoiceHeaders", params={242 "$filter": f"InvoiceDate gt {from_date}",243 "$select": "InvoiceId,VendorName,InvoiceAmount,InvoiceDate",244 "$top": 50,245 "$orderby": "InvoiceDate desc",246 })247248# Query journal entries249def get_journal_entries(client: D365FinOpsClient, from_date: str) -> list[dict]:250 return client.get("GeneralJournalAccountEntries", params={251 "$filter": f"PostingDate gt {from_date}",252 "$select": "JournalNumber,MainAccount,TransactionCurrencyAmount",253 "$top": 100,254 })255256# Create a purchase order (F&O requires dataAreaId)257def create_purchase_order(client: D365FinOpsClient, po_number: str,258 vendor: str, legal_entity: str = "usmf") -> dict:259 client._ensure_token()260 resp = client._session.post(f"{client.data_url}/PurchaseOrderHeaders", json={261 "PurchaseOrderNumber": po_number,262 "OrderVendorAccountNumber": vendor,263 "dataAreaId": legal_entity,264 })265 resp.raise_for_status()266 return resp.json()267```268269### 5. FetchXML (Complex Queries)270271```python272import urllib.parse273274def fetch_xml_query(client: Dynamics365Client, entity_set: str, fetch_xml: str) -> list[dict]:275 """Execute a FetchXML query for complex joins and aggregations."""276 client._ensure_token()277 encoded = urllib.parse.quote(fetch_xml)278 resp = client._session.get(f"{client.api_url}/{entity_set}?fetchXml={encoded}")279 resp.raise_for_status()280 return resp.json().get("value", [])281282# High-value opportunities in a specific industry283opps = fetch_xml_query(client, "opportunities", """284<fetch top="50">285 <entity name="opportunity">286 <attribute name="name"/>287 <attribute name="estimatedvalue"/>288 <attribute name="closeprobability"/>289 <filter>290 <condition attribute="statecode" operator="eq" value="0"/>291 <condition attribute="estimatedvalue" operator="gt" value="50000"/>292 </filter>293 <link-entity name="account" from="accountid" to="parentaccountid" alias="acct">294 <attribute name="name"/>295 <filter>296 <condition attribute="industrycode" operator="eq" value="6"/>297 </filter>298 </link-entity>299 <order attribute="estimatedvalue" descending="true"/>300 </entity>301</fetch>302""")303```304305### 6. Change Tracking (Delta Sync)306307```python308def get_changes(client: Dynamics365Client, entity_set: str,309 delta_link: str = None) -> tuple[list[dict], str]:310 """Track record changes since last sync.311312 Returns (changed_records, next_delta_link).313 """314 client._ensure_token()315 if delta_link:316 resp = client._session.get(delta_link)317 else:318 resp = client._session.get(319 f"{client.api_url}/{entity_set}",320 headers={"Prefer": "odata.track-changes"},321 )322 resp.raise_for_status()323 data = resp.json()324 return data.get("value", []), data.get("@odata.deltaLink", "")325326# Initial sync327records, delta = get_changes(client, "accounts")328329# Subsequent sync -- only get changes330changed, delta = get_changes(client, "accounts", delta_link=delta)331```332333### 7. Pagination Helper334335```python336def get_all_records(client: Dynamics365Client, entity_set: str,337 params: dict = None) -> list[dict]:338 """Handle server-side paging (5000 record default page size)."""339 client._ensure_token()340 records = []341 url = f"{client.api_url}/{entity_set}"342 while url:343 resp = client._session.get(url, params=params)344 resp.raise_for_status()345 data = resp.json()346 records.extend(data.get("value", []))347 url = data.get("@odata.nextLink")348 params = None # nextLink already contains params349 return records350```351352### 8. Azure OpenAI + Dynamics 365353354```python355import openai356357def classify_case_with_ai(client: Dynamics365Client, case_id: str,358 aoai_client: openai.AzureOpenAI) -> str:359 """Classify a D365 case using Azure OpenAI and update the record."""360 case = client.get_by_id("incidents", case_id, select="title,description")361362 classification = aoai_client.chat.completions.create(363 model="gpt-4o",364 messages=[365 {"role": "system", "content": "Classify the support case into: Billing, Technical, Account, General. Return only the category."},366 {"role": "user", "content": f"Title: {case['title']}\nDescription: {case.get('description', 'N/A')}"},367 ],368 )369 category = classification.choices[0].message.content.strip()370 client.update("incidents", case_id, {"new_aicategory": category})371 return category372373def analyze_deal_risk(client: Dynamics365Client, opp_id: str,374 aoai_client: openai.AzureOpenAI) -> str:375 """Analyze deal risk using Azure OpenAI."""376 opp = client.get_by_id("opportunities", opp_id,377 select="name,estimatedvalue,closeprobability,estimatedclosedate,modifiedon")378 response = aoai_client.chat.completions.create(379 model="gpt-4o",380 messages=[381 {"role": "system", "content": "You are a sales operations analyst. Assess deal risk."},382 {"role": "user", "content": f"Opportunity: {opp['name']}, Value: ${opp.get('estimatedvalue', 0):,.2f}, "383 f"Probability: {opp.get('closeprobability', 'N/A')}%, "384 f"Close date: {opp.get('estimatedclosedate', 'N/A')}, "385 f"Last modified: {opp.get('modifiedon', 'N/A')}"},386 ],387 )388 return response.choices[0].message.content389```390391### 9. Agent Tool Functions392393```python394def search_accounts(account_name: str) -> str:395 """Search Dynamics 365 accounts by name.396397 Args:398 account_name: Full or partial account name399 """400 client = Dynamics365Client(TENANT_ID, CLIENT_ID, CLIENT_SECRET, CRM_URL)401 accounts = client.get("accounts", params={402 "$select": "name,revenue,telephone1",403 "$filter": f"contains(name,'{account_name}')",404 "$top": 10,405 }).get("value", [])406 if not accounts:407 return f"No accounts found matching '{account_name}'."408 lines = [f"- {a['name']} (Revenue: ${a.get('revenue', 0):,.0f})" for a in accounts]409 return f"Found {len(accounts)} account(s):\n" + "\n".join(lines)410411def get_pipeline_summary() -> str:412 """Get a summary of the open sales pipeline."""413 client = Dynamics365Client(TENANT_ID, CLIENT_ID, CLIENT_SECRET, CRM_URL)414 opps = client.get("opportunities", params={415 "$select": "name,estimatedvalue,closeprobability",416 "$filter": "statecode eq 0",417 "$orderby": "estimatedvalue desc",418 }).get("value", [])419 total = sum(o.get("estimatedvalue", 0) for o in opps)420 weighted = sum(o.get("estimatedvalue", 0) * o.get("closeprobability", 0) / 100 for o in opps)421 return (f"Pipeline: {len(opps)} open opportunities\n"422 f"Total value: ${total:,.0f}\n"423 f"Weighted value: ${weighted:,.0f}")424```425426## Dynamics 365 Copilot Features427428| Module | Copilot Capabilities |429|---|---|430| **Sales** | Record summarization, email drafting, meeting prep, lead research, pipeline insights |431| **Service** | Case summarization, KB article generation, similar case suggestions, AI routing |432| **Finance** | Account reconciliation agent, collections drafting, cash flow forecasting |433| **Supply Chain** | Demand forecasting, intelligent order management, inventory anomaly detection |434435## Anti-Patterns436437- Not using `$select` -- always specify fields to reduce payload and improve performance438- Ignoring `@odata.nextLink` -- results are capped at 5000 per page by default439- Using OData `$filter` for complex joins -- use FetchXML instead440- Hardcoding GUIDs -- use alternate keys where available (e.g., `accounts(accountnumber='A001')`)441- Skipping Application User setup -- client credentials flow requires a D365 Application User with security roles442- Sending raw D365 data to LLMs without field selection -- filter sensitive fields before AI processing443- Not handling F&O `dataAreaId` -- Finance & Operations requires legal entity on most write operations444445## References446447- [Dataverse Web API Reference](https://learn.microsoft.com/en-us/power-apps/developer/data-platform/webapi/reference/about)448- [Dynamics 365 F&O Data Entities](https://learn.microsoft.com/en-us/dynamics365/fin-ops-core/dev-itpro/data-entities/data-entities)449- [MSAL Python Documentation](https://learn.microsoft.com/en-us/entra/msal/python/)450- [FetchXML Reference](https://learn.microsoft.com/en-us/power-apps/developer/data-platform/use-fetchxml-construct-query)451- [Dynamics 365 Copilot](https://learn.microsoft.com/en-us/dynamics365/copilot/ai-get-started)452453<!-- Source: .faos/custom/skills/integrations/dynamics-365/SKILL.md -->