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.
Platform Note: This skill was designed for multi-agent execution. In Codex, treat sub-agent instructions as sequential steps to complete thoroughly within a single agent context.
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-3653description: <!-- 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.9---1011> **Platform Note:** This skill was designed for multi-agent execution. In Codex, treat sub-agent instructions as sequential steps to complete thoroughly within a single agent context.1213# Microsoft Dynamics 365 Integration1415Connect AI agents to Dynamics 365 (Sales, Service, Finance, Supply Chain) using Dataverse Web API (OData v4), F&O OData, and Azure OpenAI integration.1617## When to Use1819- Building AI agents that query or manage CRM data (leads, opportunities, cases, accounts)20- Integrating with Dynamics 365 Finance & Operations (journals, invoices, purchase orders)21- Combining Azure OpenAI with Dynamics data for deal analysis, case classification, or forecasting22- Using FetchXML for complex queries beyond OData $filter capability23- Triggering Power Automate flows from external AI agents2425## API Surface2627| Product | API Base URL | Style |28|---|---|---|29| **Sales / Service / Marketing** | `https://{org}.crm.dynamics.com/api/data/v9.2/` | Dataverse OData v4 |30| **Finance & Operations** | `https://{org}.cloudax.dynamics.com/data/` | F&O OData v4 |31| **Business Central** | `https://api.businesscentral.dynamics.com/v2.0/{tenant}/{env}/api/v2.0/` | BC OData v4 |3233## Key Entities3435### Sales3637| Entity | OData Set | Key Fields |38|---|---|---|39| Account | `accounts` | `name`, `revenue`, `industrycode` |40| Contact | `contacts` | `fullname`, `emailaddress1`, `telephone1` |41| Lead | `leads` | `fullname`, `companyname`, `estimatedvalue`, `statuscode` |42| Opportunity | `opportunities` | `name`, `estimatedvalue`, `closeprobability`, `estimatedclosedate` |43| Quote | `quotes` | `name`, `totalamount` |44| Invoice | `invoices` | `name`, `totalamount`, `statuscode` |4546### Customer Service4748| Entity | OData Set | Key Fields |49|---|---|---|50| Case | `incidents` | `title`, `ticketnumber`, `prioritycode`, `statuscode` |51| Knowledge Article | `knowledgearticles` | `title`, `content`, `statecode` |52| Queue | `queues` | `name` |5354### Finance & Operations5556| Entity | OData Set | Key Fields |57|---|---|---|58| Journal Headers | `GeneralJournalHeaders` | Journal batch headers |59| Journal Lines | `GeneralJournalAccountEntries` | Line entries |60| Vendor Invoices | `VendorInvoiceHeaders` | AP invoices |61| Purchase Orders | `PurchaseOrderHeaders` | Procurement |62| Customers | `CustomersV3` | AR customers |63| Vendors | `VendorsV2` | AP vendors |64| Chart of Accounts | `MainAccounts` | GL accounts |6566## Patterns6768### 1. Authentication (Entra ID / OAuth 2.0)6970```python71import msal72import requests7374class Dynamics365Client:75 """Dynamics 365 client using MSAL (Entra ID) client credentials."""7677 def __init__(self, tenant_id: str, client_id: str, client_secret: str, crm_url: str):78 self.crm_url = crm_url.rstrip("/")79 self.api_url = f"{self.crm_url}/api/data/v9.2"80 self._app = msal.ConfidentialClientApplication(81 client_id,82 authority=f"https://login.microsoftonline.com/{tenant_id}",83 client_credential=client_secret,84 )85 self._scope = [f"{self.crm_url}/.default"]86 self._session = requests.Session()87 self._session.headers.update({88 "OData-MaxVersion": "4.0",89 "OData-Version": "4.0",90 "Accept": "application/json",91 "Content-Type": "application/json; charset=utf-8",92 "Prefer": "odata.include-annotations=*",93 })9495 def _ensure_token(self):96 token = self._app.acquire_token_for_client(scopes=self._scope)97 if "access_token" not in token:98 raise Exception(f"Auth failed: {token.get('error_description')}")99 self._session.headers["Authorization"] = f"Bearer {token['access_token']}"100101 def get(self, entity_set: str, params: dict = None) -> dict:102 self._ensure_token()103 resp = self._session.get(f"{self.api_url}/{entity_set}", params=params)104 resp.raise_for_status()105 return resp.json()106107 def get_by_id(self, entity_set: str, record_id: str, select: str = None) -> dict:108 self._ensure_token()109 params = {"$select": select} if select else None110 resp = self._session.get(f"{self.api_url}/{entity_set}({record_id})", params=params)111 resp.raise_for_status()112 return resp.json()113114 def create(self, entity_set: str, data: dict) -> str:115 self._ensure_token()116 resp = self._session.post(f"{self.api_url}/{entity_set}", json=data)117 resp.raise_for_status()118 return resp.headers.get("OData-EntityId", "")119120 def update(self, entity_set: str, record_id: str, data: dict) -> None:121 self._ensure_token()122 resp = self._session.patch(f"{self.api_url}/{entity_set}({record_id})", json=data)123 resp.raise_for_status()124125 def delete(self, entity_set: str, record_id: str) -> None:126 self._ensure_token()127 resp = self._session.delete(f"{self.api_url}/{entity_set}({record_id})")128 resp.raise_for_status()129```130131### 2. Sales -- Leads, Opportunities, Accounts132133```python134# Query high-value opportunities with account expansion135def get_top_opportunities(client: Dynamics365Client, min_value: float = 10000) -> list[dict]:136 return client.get("opportunities", params={137 "$select": "name,estimatedvalue,closeprobability,estimatedclosedate",138 "$filter": f"statecode eq 0 and estimatedvalue gt {min_value}",139 "$orderby": "estimatedvalue desc",140 "$top": 20,141 "$expand": "parentaccountid($select=name,revenue)",142 }).get("value", [])143144# Create a new lead145def create_lead(client: Dynamics365Client, first_name: str, last_name: str,146 company: str, email: str, estimated_value: float = 0) -> str:147 return client.create("leads", {148 "firstname": first_name,149 "lastname": last_name,150 "companyname": company,151 "emailaddress1": email,152 "estimatedvalue": estimated_value,153 "subject": f"Interest from {company}",154 })155156# Qualify a lead (bound action)157def qualify_lead(client: Dynamics365Client, lead_id: str) -> dict:158 client._ensure_token()159 resp = client._session.post(160 f"{client.api_url}/leads({lead_id})/Microsoft.Dynamics.CRM.QualifyLead",161 json={"CreateAccount": True, "CreateContact": True, "CreateOpportunity": True, "Status": 3},162 )163 resp.raise_for_status()164 return resp.json()165166# Update opportunity stage167def update_opportunity_stage(client: Dynamics365Client, opp_id: str,168 stage: str, probability: int) -> None:169 client.update("opportunities", opp_id, {170 "stepname": stage,171 "closeprobability": probability,172 })173```174175### 3. Customer Service -- Cases and Knowledge176177```python178# Get open cases sorted by priority179def get_open_cases(client: Dynamics365Client, limit: int = 25) -> list[dict]:180 return client.get("incidents", params={181 "$select": "title,ticketnumber,prioritycode,statuscode,createdon",182 "$filter": "statecode eq 0",183 "$orderby": "prioritycode asc,createdon desc",184 "$top": limit,185 "$expand": "customerid_contact($select=fullname,emailaddress1)",186 }).get("value", [])187188# Create a support case189def create_case(client: Dynamics365Client, title: str, description: str,190 customer_id: str, priority: int = 2) -> str:191 return client.create("incidents", {192 "title": title,193 "description": description,194 "prioritycode": priority,195 "customerid_contact@odata.bind": f"/contacts({customer_id})",196 })197198# Search knowledge articles199def search_knowledge(client: Dynamics365Client, query: str) -> list[dict]:200 return client.get("knowledgearticles", params={201 "$select": "title,description,articlepublicnumber",202 "$filter": f"statecode eq 3 and contains(title,'{query}')",203 "$top": 10,204 }).get("value", [])205```206207### 4. Finance & Operations208209```python210class D365FinOpsClient:211 """Dynamics 365 Finance & Operations OData client."""212213 def __init__(self, tenant_id: str, client_id: str, client_secret: str, fo_url: str):214 self.fo_url = fo_url.rstrip("/")215 self.data_url = f"{self.fo_url}/data"216 self._app = msal.ConfidentialClientApplication(217 client_id,218 authority=f"https://login.microsoftonline.com/{tenant_id}",219 client_credential=client_secret,220 )221 self._scope = [f"{self.fo_url}/.default"]222 self._session = requests.Session()223 self._session.headers.update({224 "Content-Type": "application/json",225 "Accept": "application/json",226 })227228 def _ensure_token(self):229 token = self._app.acquire_token_for_client(scopes=self._scope)230 self._session.headers["Authorization"] = f"Bearer {token['access_token']}"231232 def get(self, entity: str, params: dict = None) -> list[dict]:233 self._ensure_token()234 resp = self._session.get(f"{self.data_url}/{entity}", params=params)235 resp.raise_for_status()236 return resp.json().get("value", [])237238# Query vendor invoices239def get_vendor_invoices(client: D365FinOpsClient, from_date: str) -> list[dict]:240 return client.get("VendorInvoiceHeaders", params={241 "$filter": f"InvoiceDate gt {from_date}",242 "$select": "InvoiceId,VendorName,InvoiceAmount,InvoiceDate",243 "$top": 50,244 "$orderby": "InvoiceDate desc",245 })246247# Query journal entries248def get_journal_entries(client: D365FinOpsClient, from_date: str) -> list[dict]:249 return client.get("GeneralJournalAccountEntries", params={250 "$filter": f"PostingDate gt {from_date}",251 "$select": "JournalNumber,MainAccount,TransactionCurrencyAmount",252 "$top": 100,253 })254255# Create a purchase order (F&O requires dataAreaId)256def create_purchase_order(client: D365FinOpsClient, po_number: str,257 vendor: str, legal_entity: str = "usmf") -> dict:258 client._ensure_token()259 resp = client._session.post(f"{client.data_url}/PurchaseOrderHeaders", json={260 "PurchaseOrderNumber": po_number,261 "OrderVendorAccountNumber": vendor,262 "dataAreaId": legal_entity,263 })264 resp.raise_for_status()265 return resp.json()266```267268### 5. FetchXML (Complex Queries)269270```python271import urllib.parse272273def fetch_xml_query(client: Dynamics365Client, entity_set: str, fetch_xml: str) -> list[dict]:274 """Execute a FetchXML query for complex joins and aggregations."""275 client._ensure_token()276 encoded = urllib.parse.quote(fetch_xml)277 resp = client._session.get(f"{client.api_url}/{entity_set}?fetchXml={encoded}")278 resp.raise_for_status()279 return resp.json().get("value", [])280281# High-value opportunities in a specific industry282opps = fetch_xml_query(client, "opportunities", """283<fetch top="50">284 <entity name="opportunity">285 <attribute name="name"/>286 <attribute name="estimatedvalue"/>287 <attribute name="closeprobability"/>288 <filter>289 <condition attribute="statecode" operator="eq" value="0"/>290 <condition attribute="estimatedvalue" operator="gt" value="50000"/>291 </filter>292 <link-entity name="account" from="accountid" to="parentaccountid" alias="acct">293 <attribute name="name"/>294 <filter>295 <condition attribute="industrycode" operator="eq" value="6"/>296 </filter>297 </link-entity>298 <order attribute="estimatedvalue" descending="true"/>299 </entity>300</fetch>301""")302```303304### 6. Change Tracking (Delta Sync)305306```python307def get_changes(client: Dynamics365Client, entity_set: str,308 delta_link: str = None) -> tuple[list[dict], str]:309 """Track record changes since last sync.310311 Returns (changed_records, next_delta_link).312 """313 client._ensure_token()314 if delta_link:315 resp = client._session.get(delta_link)316 else:317 resp = client._session.get(318 f"{client.api_url}/{entity_set}",319 headers={"Prefer": "odata.track-changes"},320 )321 resp.raise_for_status()322 data = resp.json()323 return data.get("value", []), data.get("@odata.deltaLink", "")324325# Initial sync326records, delta = get_changes(client, "accounts")327328# Subsequent sync -- only get changes329changed, delta = get_changes(client, "accounts", delta_link=delta)330```331332### 7. Pagination Helper333334```python335def get_all_records(client: Dynamics365Client, entity_set: str,336 params: dict = None) -> list[dict]:337 """Handle server-side paging (5000 record default page size)."""338 client._ensure_token()339 records = []340 url = f"{client.api_url}/{entity_set}"341 while url:342 resp = client._session.get(url, params=params)343 resp.raise_for_status()344 data = resp.json()345 records.extend(data.get("value", []))346 url = data.get("@odata.nextLink")347 params = None # nextLink already contains params348 return records349```350351### 8. Azure OpenAI + Dynamics 365352353```python354import openai355356def classify_case_with_ai(client: Dynamics365Client, case_id: str,357 aoai_client: openai.AzureOpenAI) -> str:358 """Classify a D365 case using Azure OpenAI and update the record."""359 case = client.get_by_id("incidents", case_id, select="title,description")360361 classification = aoai_client.chat.completions.create(362 model="gpt-4o",363 messages=[364 {"role": "system", "content": "Classify the support case into: Billing, Technical, Account, General. Return only the category."},365 {"role": "user", "content": f"Title: {case['title']}\nDescription: {case.get('description', 'N/A')}"},366 ],367 )368 category = classification.choices[0].message.content.strip()369 client.update("incidents", case_id, {"new_aicategory": category})370 return category371372def analyze_deal_risk(client: Dynamics365Client, opp_id: str,373 aoai_client: openai.AzureOpenAI) -> str:374 """Analyze deal risk using Azure OpenAI."""375 opp = client.get_by_id("opportunities", opp_id,376 select="name,estimatedvalue,closeprobability,estimatedclosedate,modifiedon")377 response = aoai_client.chat.completions.create(378 model="gpt-4o",379 messages=[380 {"role": "system", "content": "You are a sales operations analyst. Assess deal risk."},381 {"role": "user", "content": f"Opportunity: {opp['name']}, Value: ${opp.get('estimatedvalue', 0):,.2f}, "382 f"Probability: {opp.get('closeprobability', 'N/A')}%, "383 f"Close date: {opp.get('estimatedclosedate', 'N/A')}, "384 f"Last modified: {opp.get('modifiedon', 'N/A')}"},385 ],386 )387 return response.choices[0].message.content388```389390### 9. Agent Tool Functions391392```python393def search_accounts(account_name: str) -> str:394 """Search Dynamics 365 accounts by name.395396 Args:397 account_name: Full or partial account name398 """399 client = Dynamics365Client(TENANT_ID, CLIENT_ID, CLIENT_SECRET, CRM_URL)400 accounts = client.get("accounts", params={401 "$select": "name,revenue,telephone1",402 "$filter": f"contains(name,'{account_name}')",403 "$top": 10,404 }).get("value", [])405 if not accounts:406 return f"No accounts found matching '{account_name}'."407 lines = [f"- {a['name']} (Revenue: ${a.get('revenue', 0):,.0f})" for a in accounts]408 return f"Found {len(accounts)} account(s):\n" + "\n".join(lines)409410def get_pipeline_summary() -> str:411 """Get a summary of the open sales pipeline."""412 client = Dynamics365Client(TENANT_ID, CLIENT_ID, CLIENT_SECRET, CRM_URL)413 opps = client.get("opportunities", params={414 "$select": "name,estimatedvalue,closeprobability",415 "$filter": "statecode eq 0",416 "$orderby": "estimatedvalue desc",417 }).get("value", [])418 total = sum(o.get("estimatedvalue", 0) for o in opps)419 weighted = sum(o.get("estimatedvalue", 0) * o.get("closeprobability", 0) / 100 for o in opps)420 return (f"Pipeline: {len(opps)} open opportunities\n"421 f"Total value: ${total:,.0f}\n"422 f"Weighted value: ${weighted:,.0f}")423```424425## Dynamics 365 Copilot Features426427| Module | Copilot Capabilities |428|---|---|429| **Sales** | Record summarization, email drafting, meeting prep, lead research, pipeline insights |430| **Service** | Case summarization, KB article generation, similar case suggestions, AI routing |431| **Finance** | Account reconciliation agent, collections drafting, cash flow forecasting |432| **Supply Chain** | Demand forecasting, intelligent order management, inventory anomaly detection |433434## Anti-Patterns435436- Not using `$select` -- always specify fields to reduce payload and improve performance437- Ignoring `@odata.nextLink` -- results are capped at 5000 per page by default438- Using OData `$filter` for complex joins -- use FetchXML instead439- Hardcoding GUIDs -- use alternate keys where available (e.g., `accounts(accountnumber='A001')`)440- Skipping Application User setup -- client credentials flow requires a D365 Application User with security roles441- Sending raw D365 data to LLMs without field selection -- filter sensitive fields before AI processing442- Not handling F&O `dataAreaId` -- Finance & Operations requires legal entity on most write operations443444## References445446- [Dataverse Web API Reference](https://learn.microsoft.com/en-us/power-apps/developer/data-platform/webapi/reference/about)447- [Dynamics 365 F&O Data Entities](https://learn.microsoft.com/en-us/dynamics365/fin-ops-core/dev-itpro/data-entities/data-entities)448- [MSAL Python Documentation](https://learn.microsoft.com/en-us/entra/msal/python/)449- [FetchXML Reference](https://learn.microsoft.com/en-us/power-apps/developer/data-platform/use-fetchxml-construct-query)450- [Dynamics 365 Copilot](https://learn.microsoft.com/en-us/dynamics365/copilot/ai-get-started)451452<!-- Source: .faos/custom/skills/integrations/dynamics-365/SKILL.md -->