From 5c964fc171df9928cd7412e111aeac4efa9914a3 Mon Sep 17 00:00:00 2001 From: Max Wang Date: Tue, 20 Jan 2026 10:52:48 -0800 Subject: [PATCH 1/9] add claude skill for the sdk --- .claude/skills/dataverse-sdk/SKILL.md | 281 ++++++++++++++++++ README.md | 32 +- pyproject.toml | 4 + .../Dataverse/_skill_installer.py | 224 ++++++++++++++ .../Dataverse/claude_skill/SKILL.md | 281 ++++++++++++++++++ .../Dataverse/claude_skill/__init__.py | 9 + src/PowerPlatform/Dataverse/client.py | 4 +- 7 files changed, 829 insertions(+), 6 deletions(-) create mode 100644 .claude/skills/dataverse-sdk/SKILL.md create mode 100644 src/PowerPlatform/Dataverse/_skill_installer.py create mode 100644 src/PowerPlatform/Dataverse/claude_skill/SKILL.md create mode 100644 src/PowerPlatform/Dataverse/claude_skill/__init__.py diff --git a/.claude/skills/dataverse-sdk/SKILL.md b/.claude/skills/dataverse-sdk/SKILL.md new file mode 100644 index 0000000..a8e844f --- /dev/null +++ b/.claude/skills/dataverse-sdk/SKILL.md @@ -0,0 +1,281 @@ +--- +name: powerplatform-dataverseclient-python +description: Guidance for using the PowerPlatform Dataverse Client Python SDK. Use when calling the SDK like creating CRUD operations, SQL queries, table metadata management, and upload files. +--- + +# PowerPlatform Dataverse SDK Guide + +## Overview + +Use the PowerPlatform Dataverse Client Python SDK to interact with Microsoft Dataverse. + +## Key Concepts + +### Schema Names vs Display Names +- Standard tables: lowercase (e.g., `"account"`, `"contact"`) +- Custom tables: include customization prefix (e.g., `"new_Product"`, `"cr123_Invoice"`) +- Custom columns: include customization prefix (e.g., `"new_Price"`, `"cr123_Status"`) +- ALWAYS use **schema names** (logical names), NOT display names + +### Bulk Operations +The SDK supports Dataverse's native bulk operations: Pass lists to `create()`, `update()` for automatic bulk processing, for `delete()`, set `use_bulk_delete` when passing lists to use bulk operation + +### Paging +- Control page size with `page_size` parameter +- Use `top` parameter to limit total records returned + +## Common Operations + +### Import +```python +from azure.identity import ( + InteractiveBrowserCredential, + ClientSecretCredential, + ClientCertificateCredential, + AzureCliCredential +) +from PowerPlatform.Dataverse.client import DataverseClient +``` + +### Client Initialization +```python +# Development options +credential = InteractiveBrowserCredential() +credential = AzureCliCredential() + +# Production options +credential = ClientSecretCredential(tenant_id, client_id, client_secret) +credential = ClientCertificateCredential(tenant_id, client_id, cert_path) + +# Create client (no trailing slash on URL!) +client = DataverseClient("https://yourorg.crm.dynamics.com", credential) +``` + +### CRUD Operations + +#### Create Records +```python +# Single record +account_ids = client.create("account", {"name": "Contoso Ltd", "telephone1": "555-0100"}) +account_id = account_ids[0] + +# Bulk create (uses CreateMultiple API automatically) +contacts = [ + {"firstname": "John", "lastname": "Doe"}, + {"firstname": "Jane", "lastname": "Smith"} +] +contact_ids = client.create("contact", contacts) +``` + +#### Read Records +```python +# Get single record by ID +account = client.get("account", account_id, select=["name", "telephone1"]) + +# Query with filter +pages = client.get( + "account", + select=["accountid", "name"], # select is case-insensitive (automatically lowercased) + filter="statecode eq 0", # filter must use lowercase logical names (not transformed) + top=100 +) +for page in pages: + for record in page: + print(record["name"]) + +# Query with navigation property expansion (case-sensitive!) +pages = client.get( + "account", + select=["name"], + expand=["primarycontactid"], # Navigation properties are case-sensitive! + filter="statecode eq 0" # Column names must be lowercase logical names +) +for page in pages: + for account in page: + contact = account.get("primarycontactid", {}) + print(f"{account['name']} - {contact.get('fullname', 'N/A')}") +``` + +#### Update Records +```python +# Single update +client.update("account", account_id, {"telephone1": "555-0200"}) + +# Bulk update (broadcast same change to multiple records) +client.update("account", [id1, id2, id3], {"industry": "Technology"}) +``` + +#### Delete Records +```python +# Single delete +client.delete("account", account_id) + +# Bulk delete (uses BulkDelete API) +client.delete("account", [id1, id2, id3], use_bulk_delete=True) +``` + +### SQL Queries + +SQL queries are **read-only** and support limited SQL syntax. A single SELECT statement with optional WHERE, TOP (integer literal), ORDER BY (column names only), and a simple table alias after FROM is supported. But JOIN and subqueries may not be. Refer to the Dataverse documentation for the current feature set. + +```python +# Basic SQL query +results = client.query_sql( + "SELECT TOP 10 accountid, name FROM account WHERE statecode = 0" +) +for record in results: + print(record["name"]) +``` + +### Table Management + +#### Create Custom Tables +```python +# Create table with columns (include customization prefix!) +table_info = client.create_table( + table_schema_name="new_Product", + columns={ + "new_Code": "string", + "new_Price": "decimal", + "new_Active": "bool", + "new_Quantity": "int" + } +) + +# With solution assignment and custom primary column +table_info = client.create_table( + table_schema_name="new_Product", + columns={"new_Code": "string", "new_Price": "decimal"}, + solution_unique_name="MyPublisher", + primary_column_schema_name="new_ProductCode" +) +``` + +#### Supported Column Types +Types on the same line map to the same exact format under the hood +- `"string"` or `"text"` - Single line of text +- `"int"` or `"integer"` - Whole number +- `"decimal"` or `"money"` - Decimal number +- `"float"` or `"double"` - Floating point number +- `"bool"` or `"boolean"` - Yes/No +- `"datetime"` or `"date"` - Date +- Enum subclass - Local option set (picklist) + +#### Manage Columns +```python +# Add columns to existing table (must include customization prefix!) +client.create_columns("new_Product", { + "new_Category": "string", + "new_InStock": "bool" +}) + +# Remove columns +client.delete_columns("new_Product", ["new_Category"]) +``` + +#### Inspect Tables +```python +# Get single table information +table_info = client.get_table_info("new_Product") +print(f"Logical name: {table_info['table_logical_name']}") +print(f"Entity set: {table_info['entity_set_name']}") + +# List all tables +tables = client.list_tables() +for table in tables: + print(table) +``` + +#### Delete Tables +```python +# Delete custom table +client.delete_table("new_Product") +``` + +### File Operations + +```python +# Upload file to a file column +client.upload_file( + table_schema_name="account", + record_id=account_id, + file_name_attribute="new_document", + path="/path/to/document.pdf" +) +``` + +## Error Handling + +The SDK provides structured exceptions with detailed error information: + +```python +from PowerPlatform.Dataverse.core.errors import ( + DataverseError, + HttpError, + ValidationError, + MetadataError, + SQLParseError +) +from PowerPlatform.Dataverse.client import DataverseClient + +try: + client.get("account", "invalid-id") +except HttpError as e: + print(f"HTTP {e.status_code}: {e.message}") + print(f"Error code: {e.code}") + print(f"Subcode: {e.subcode}") + if e.is_transient: + print("This error may be retryable") +except ValidationError as e: + print(f"Validation error: {e.message}") +``` + +### Common Error Patterns + +**Authentication failures:** +- Check environment URL format (no trailing slash) +- Verify credentials have Dataverse permissions +- Ensure app registration is properly configured + +**404 Not Found:** +- Verify table schema name is correct (lowercase for standard tables) +- Check record ID exists +- Ensure using schema names, not display names +- Cache issue could happen, so retry might help, especially for metadata creation + +**400 Bad Request:** +- Check filter/expand parameters use correct case +- Verify column names exist and are spelled correctly +- Ensure custom columns include customization prefix + +## Best Practices + +### Performance Optimization + +1. **Use bulk operations** - Pass lists to create/update/delete for automatic optimization +2. **Specify select fields** - Limit returned columns to reduce payload size +3. **Control page size** - Use `top` and `page_size` parameters appropriately +4. **Reuse client instances** - Don't create new clients for each operation +5. **Use production credentials** - ClientSecretCredential or ClientCertificateCredential for unattended operations +6. **Error handling** - Implement retry logic for transient errors (`e.is_transient`) +7. **Always include customization prefix** for custom tables/columns +8. **Use lowercase** - Generally using lower cased input won't go wrong, exception would be custom tables/columns naming +9. **Test in non-production environments** first + +## Additional Resources + +Load these resources as needed during development: + +- [API Reference](https://learn.microsoft.com/python/api/dataverse-sdk-docs-python/dataverse-overview) +- [Product Documentation](https://learn.microsoft.com/power-apps/developer/data-platform/sdk-python/) +- [Dataverse Web API](https://learn.microsoft.com/power-apps/developer/data-platform/webapi/) +- [Azure Identity](https://learn.microsoft.com/python/api/overview/azure/identity-readme) + +## Key Reminders + +1. **Schema names are required** - Never use display names +2. **Custom tables need prefixes** - Include customization prefix (e.g., "new_") +3. **Filter is case-sensitive** - Use lowercase logical names +4. **Bulk operations are encouraged** - Pass lists for optimization +5. **No trailing slashes in URLs** - Format: `https://org.crm.dynamics.com` +6. **Structured errors** - Check `is_transient` for retry logic diff --git a/README.md b/README.md index f281896..803fbf5 100644 --- a/README.md +++ b/README.md @@ -57,7 +57,21 @@ Install the PowerPlatform Dataverse Client using [pip](https://pypi.org/project/ pip install PowerPlatform-Dataverse-Client ``` -For development from source: +(Optional) Install Claude Skill globally with the Client: + +```bash +pip install PowerPlatform-Dataverse-Client && dataverse-install-claude-skill +``` + +This installs a Claude Skill that enables Claude Code to: +- Apply SDK best practices automatically +- Provide context-aware code suggestions +- Help with error handling and troubleshooting +- Guide you through common patterns + +The skill works with both the Claude Code CLI and VSCode extension. Once installed, Claude will automatically use it when working with Dataverse operations. For more information on Claude Skill see https://platform.claude.com/docs/en/agents-and-tools/agent-skills/overview. See skill definition here .claude\skills\dataverse-sdk\SKILL.md. + +For development from source (Claude Skill auto loaded): ```bash git clone https://github.com/microsoft/PowerPlatform-DataverseClient-Python.git @@ -225,6 +239,16 @@ table_info = client.create_table( primary_column_schema_name="new_ProductName" # Optional: custom primary column (default is "{customization prefix value}_Name") ) +# Get table information +info = client.get_table_info("new_Product") +print(f"Logical name: {info['table_logical_name']}") +print(f"Entity set: {info['entity_set_name']}") + +# List all tables +tables = client.list_tables() +for table in tables: + print(table) + # Add columns to existing table (columns must include customization prefix value) client.create_columns("new_Product", {"new_Category": "string"}) @@ -302,9 +326,9 @@ except ValidationError as e: ### Authentication issues -**Common fixes:** +**Common fixes:** - Verify environment URL format: `https://yourorg.crm.dynamics.com` (no trailing slash) -- Ensure Azure Identity credentials have proper Dataverse permissions +- Ensure Azure Identity credentials have proper Dataverse permissions - Check app registration permissions are granted and admin-consented ### Performance considerations @@ -313,7 +337,7 @@ For optimal performance in production environments: | Best Practice | Description | |---------------|-------------| -| **Bulk Operations** | Pass lists to `create()`, `update()`, and `delete()` for automatic bulk processing | +| **Bulk Operations** | Pass lists to `create()`, `update()` for automatic bulk processing, for `delete()`, set `use_bulk_delete` when passing lists to use bulk operation | | **Select Fields** | Specify `select` parameter to limit returned columns and reduce payload size | | **Page Size Control** | Use `top` and `page_size` parameters to control memory usage | | **Connection Reuse** | Reuse `DataverseClient` instances across operations | diff --git a/pyproject.toml b/pyproject.toml index f4f8737..9cbcab4 100644 --- a/pyproject.toml +++ b/pyproject.toml @@ -37,6 +37,9 @@ dependencies = [ "Issues" = "https://github.com/microsoft/PowerPlatform-DataverseClient-Python/issues" "Documentation" = "https://github.com/microsoft/PowerPlatform-DataverseClient-Python#readme" +[project.scripts] +dataverse-install-claude-skill = "PowerPlatform.Dataverse._skill_installer:main" + [project.optional-dependencies] dev = [ "pytest>=7.0.0", @@ -58,6 +61,7 @@ namespaces = false [tool.setuptools.package-data] "*" = ["py.typed"] +"PowerPlatform.Dataverse.claude_skill" = ["SKILL.md"] # Microsoft Python Standards - Linting & Formatting [tool.black] diff --git a/src/PowerPlatform/Dataverse/_skill_installer.py b/src/PowerPlatform/Dataverse/_skill_installer.py new file mode 100644 index 0000000..974f7d0 --- /dev/null +++ b/src/PowerPlatform/Dataverse/_skill_installer.py @@ -0,0 +1,224 @@ +# Copyright (c) Microsoft Corporation. +# Licensed under the MIT license. + +""" +Claude Code skill installer for the PowerPlatform Dataverse Client SDK. + +This module provides a CLI command to install the Dataverse SDK Claude Skill +for Claude Code +""" + +import shutil +import sys +from pathlib import Path +from typing import Optional + +# Ensure UTF-8 output for emoji support on Windows +if sys.platform == "win32": + import codecs + if sys.stdout.encoding != 'utf-8': + sys.stdout = codecs.getwriter('utf-8')(sys.stdout.buffer, 'strict') + if sys.stderr.encoding != 'utf-8': + sys.stderr = codecs.getwriter('utf-8')(sys.stderr.buffer, 'strict') + + +def get_skill_source_path() -> Path: + """Get the path to the skill source directory in the package.""" + # Two locations for the skill: + # 1. .claude/skills/dataverse-sdk/ (repo root, for development) + # 2. claude_skill/ (in package, for PyPI distribution) + + package_dir = Path(__file__).parent # PowerPlatform/Dataverse/ + + # Try development/repo location first (for pip install -e .) + # Go up to repo root: Dataverse -> PowerPlatform -> src -> repo root + repo_root = package_dir.parent.parent.parent + repo_claude_path = repo_root / ".claude" / "skills" / "dataverse-sdk" + if repo_claude_path.exists(): + return repo_claude_path + + # Try packaged location (for pip install from wheel/sdist) + # The skill is packaged in PowerPlatform/Dataverse/claude_skill/ + packaged_skill_path = package_dir / "claude_skill" + if packaged_skill_path.exists(): + return packaged_skill_path + + # Fallback: return repo path even if it doesn't exist + # (will be caught by validation in install_skill) + return repo_claude_path + + +def get_skill_destination_path() -> Path: + """Get the destination path for installing the skill globally.""" + return Path.home() / ".claude" / "skills" / "dataverse-sdk" + + +def install_skill(force: bool = False) -> bool: + """ + Install the Dataverse SDK skill for Claude Code. + + Args: + force: If True, overwrite existing skill without prompting. + + Returns: + True if installation succeeded, False otherwise. + """ + skill_source = get_skill_source_path() + skill_dest = get_skill_destination_path() + + # Validate source exists + if not skill_source.exists(): + print(f"❌ Error: Skill source not found at {skill_source}") + print(" This may indicate a packaging issue.") + return False + + skill_md = skill_source / "SKILL.md" + if not skill_md.exists(): + print(f"❌ Error: SKILL.md not found at {skill_md}") + return False + + # Check if skill already exists + if skill_dest.exists(): + if not force: + print(f"⚠️ Skill already exists at {skill_dest}") + response = input(" Overwrite existing skill? (y/n): ").strip().lower() + if response not in ["y", "yes"]: + print(" Installation cancelled.") + return False + print(f" Updating existing skill...") + + # Create destination directory + skill_dest.parent.mkdir(parents=True, exist_ok=True) + + # Copy skill files + try: + if skill_dest.exists(): + shutil.rmtree(skill_dest) + shutil.copytree(skill_source, skill_dest) + print(f"✅ Dataverse SDK skill installed successfully!") + print(f" Location: {skill_dest}") + print() + print(" Claude Code will now automatically use this skill when working") + print(" with the PowerPlatform Dataverse Client SDK.") + print() + print("💡 Next steps:") + print(" • Start Claude Code in your project directory") + print(" • Ask Claude for help with Dataverse operations") + print(" • Claude will automatically apply SDK best practices") + return True + except Exception as e: + print(f"❌ Error installing skill: {e}") + return False + + +def uninstall_skill() -> bool: + """ + Uninstall the Dataverse SDK skill from Claude Code. + + Returns: + True if uninstallation succeeded, False otherwise. + """ + skill_dest = get_skill_destination_path() + + if not skill_dest.exists(): + print(f"ℹ️ Skill not found at {skill_dest}") + print(" Nothing to uninstall.") + return True + + try: + shutil.rmtree(skill_dest) + print(f"✅ Dataverse SDK skill uninstalled successfully!") + print(f" Removed from: {skill_dest}") + return True + except Exception as e: + print(f"❌ Error uninstalling skill: {e}") + return False + + +def check_skill_status() -> None: + """Check and display the current skill installation status.""" + skill_dest = get_skill_destination_path() + + print("🔍 Dataverse SDK Skill Status") + print("=" * 60) + + if skill_dest.exists(): + skill_md = skill_dest / "SKILL.md" + if skill_md.exists(): + print(f"✅ Status: Installed") + print(f" Location: {skill_dest}") + print(f" Skill file: {skill_md}") + print() + print(" The skill is ready to use with Claude Code.") + else: + print(f"⚠️ Status: Partially installed (SKILL.md missing)") + print(f" Location: {skill_dest}") + print() + print(" Consider reinstalling: dataverse-install-claude-skill --force") + else: + print(f"❌ Status: Not installed") + print(f" Expected location: {skill_dest}") + print() + print(" To install: dataverse-install-claude-skill") + + +def main() -> None: + """Main entry point for the skill installer CLI.""" + import argparse + + parser = argparse.ArgumentParser( + description="Install the Dataverse SDK skill for Claude Code", + formatter_class=argparse.RawDescriptionHelpFormatter, + epilog=""" +Examples: + # Install the skill (will prompt if exists) + dataverse-install-claude-skill + + # Force install (overwrite without prompting) + dataverse-install-claude-skill --force + + # Check installation status + dataverse-install-claude-skill --status + + # Uninstall the skill + dataverse-install-claude-skill --uninstall + +About: + This command installs a Claude Code skill that provides expert guidance + for using the PowerPlatform Dataverse Client Python SDK. Once installed, + Claude Code will automatically apply SDK best practices and provide + intelligent assistance when working with Dataverse. + """, + ) + + parser.add_argument( + "--force", "-f", action="store_true", help="Force install without prompting (overwrite existing)" + ) + + parser.add_argument("--status", "-s", action="store_true", help="Check skill installation status") + + parser.add_argument("--uninstall", "-u", action="store_true", help="Uninstall the skill") + + args = parser.parse_args() + + print() + print("🚀 PowerPlatform Dataverse SDK - Claude Code Skill Installer") + print("=" * 60) + print() + + # Handle different modes + if args.status: + check_skill_status() + sys.exit(0) + + if args.uninstall: + success = uninstall_skill() + sys.exit(0 if success else 1) + + # Default: Install + success = install_skill(force=args.force) + sys.exit(0 if success else 1) + + +if __name__ == "__main__": + main() diff --git a/src/PowerPlatform/Dataverse/claude_skill/SKILL.md b/src/PowerPlatform/Dataverse/claude_skill/SKILL.md new file mode 100644 index 0000000..a8e844f --- /dev/null +++ b/src/PowerPlatform/Dataverse/claude_skill/SKILL.md @@ -0,0 +1,281 @@ +--- +name: powerplatform-dataverseclient-python +description: Guidance for using the PowerPlatform Dataverse Client Python SDK. Use when calling the SDK like creating CRUD operations, SQL queries, table metadata management, and upload files. +--- + +# PowerPlatform Dataverse SDK Guide + +## Overview + +Use the PowerPlatform Dataverse Client Python SDK to interact with Microsoft Dataverse. + +## Key Concepts + +### Schema Names vs Display Names +- Standard tables: lowercase (e.g., `"account"`, `"contact"`) +- Custom tables: include customization prefix (e.g., `"new_Product"`, `"cr123_Invoice"`) +- Custom columns: include customization prefix (e.g., `"new_Price"`, `"cr123_Status"`) +- ALWAYS use **schema names** (logical names), NOT display names + +### Bulk Operations +The SDK supports Dataverse's native bulk operations: Pass lists to `create()`, `update()` for automatic bulk processing, for `delete()`, set `use_bulk_delete` when passing lists to use bulk operation + +### Paging +- Control page size with `page_size` parameter +- Use `top` parameter to limit total records returned + +## Common Operations + +### Import +```python +from azure.identity import ( + InteractiveBrowserCredential, + ClientSecretCredential, + ClientCertificateCredential, + AzureCliCredential +) +from PowerPlatform.Dataverse.client import DataverseClient +``` + +### Client Initialization +```python +# Development options +credential = InteractiveBrowserCredential() +credential = AzureCliCredential() + +# Production options +credential = ClientSecretCredential(tenant_id, client_id, client_secret) +credential = ClientCertificateCredential(tenant_id, client_id, cert_path) + +# Create client (no trailing slash on URL!) +client = DataverseClient("https://yourorg.crm.dynamics.com", credential) +``` + +### CRUD Operations + +#### Create Records +```python +# Single record +account_ids = client.create("account", {"name": "Contoso Ltd", "telephone1": "555-0100"}) +account_id = account_ids[0] + +# Bulk create (uses CreateMultiple API automatically) +contacts = [ + {"firstname": "John", "lastname": "Doe"}, + {"firstname": "Jane", "lastname": "Smith"} +] +contact_ids = client.create("contact", contacts) +``` + +#### Read Records +```python +# Get single record by ID +account = client.get("account", account_id, select=["name", "telephone1"]) + +# Query with filter +pages = client.get( + "account", + select=["accountid", "name"], # select is case-insensitive (automatically lowercased) + filter="statecode eq 0", # filter must use lowercase logical names (not transformed) + top=100 +) +for page in pages: + for record in page: + print(record["name"]) + +# Query with navigation property expansion (case-sensitive!) +pages = client.get( + "account", + select=["name"], + expand=["primarycontactid"], # Navigation properties are case-sensitive! + filter="statecode eq 0" # Column names must be lowercase logical names +) +for page in pages: + for account in page: + contact = account.get("primarycontactid", {}) + print(f"{account['name']} - {contact.get('fullname', 'N/A')}") +``` + +#### Update Records +```python +# Single update +client.update("account", account_id, {"telephone1": "555-0200"}) + +# Bulk update (broadcast same change to multiple records) +client.update("account", [id1, id2, id3], {"industry": "Technology"}) +``` + +#### Delete Records +```python +# Single delete +client.delete("account", account_id) + +# Bulk delete (uses BulkDelete API) +client.delete("account", [id1, id2, id3], use_bulk_delete=True) +``` + +### SQL Queries + +SQL queries are **read-only** and support limited SQL syntax. A single SELECT statement with optional WHERE, TOP (integer literal), ORDER BY (column names only), and a simple table alias after FROM is supported. But JOIN and subqueries may not be. Refer to the Dataverse documentation for the current feature set. + +```python +# Basic SQL query +results = client.query_sql( + "SELECT TOP 10 accountid, name FROM account WHERE statecode = 0" +) +for record in results: + print(record["name"]) +``` + +### Table Management + +#### Create Custom Tables +```python +# Create table with columns (include customization prefix!) +table_info = client.create_table( + table_schema_name="new_Product", + columns={ + "new_Code": "string", + "new_Price": "decimal", + "new_Active": "bool", + "new_Quantity": "int" + } +) + +# With solution assignment and custom primary column +table_info = client.create_table( + table_schema_name="new_Product", + columns={"new_Code": "string", "new_Price": "decimal"}, + solution_unique_name="MyPublisher", + primary_column_schema_name="new_ProductCode" +) +``` + +#### Supported Column Types +Types on the same line map to the same exact format under the hood +- `"string"` or `"text"` - Single line of text +- `"int"` or `"integer"` - Whole number +- `"decimal"` or `"money"` - Decimal number +- `"float"` or `"double"` - Floating point number +- `"bool"` or `"boolean"` - Yes/No +- `"datetime"` or `"date"` - Date +- Enum subclass - Local option set (picklist) + +#### Manage Columns +```python +# Add columns to existing table (must include customization prefix!) +client.create_columns("new_Product", { + "new_Category": "string", + "new_InStock": "bool" +}) + +# Remove columns +client.delete_columns("new_Product", ["new_Category"]) +``` + +#### Inspect Tables +```python +# Get single table information +table_info = client.get_table_info("new_Product") +print(f"Logical name: {table_info['table_logical_name']}") +print(f"Entity set: {table_info['entity_set_name']}") + +# List all tables +tables = client.list_tables() +for table in tables: + print(table) +``` + +#### Delete Tables +```python +# Delete custom table +client.delete_table("new_Product") +``` + +### File Operations + +```python +# Upload file to a file column +client.upload_file( + table_schema_name="account", + record_id=account_id, + file_name_attribute="new_document", + path="/path/to/document.pdf" +) +``` + +## Error Handling + +The SDK provides structured exceptions with detailed error information: + +```python +from PowerPlatform.Dataverse.core.errors import ( + DataverseError, + HttpError, + ValidationError, + MetadataError, + SQLParseError +) +from PowerPlatform.Dataverse.client import DataverseClient + +try: + client.get("account", "invalid-id") +except HttpError as e: + print(f"HTTP {e.status_code}: {e.message}") + print(f"Error code: {e.code}") + print(f"Subcode: {e.subcode}") + if e.is_transient: + print("This error may be retryable") +except ValidationError as e: + print(f"Validation error: {e.message}") +``` + +### Common Error Patterns + +**Authentication failures:** +- Check environment URL format (no trailing slash) +- Verify credentials have Dataverse permissions +- Ensure app registration is properly configured + +**404 Not Found:** +- Verify table schema name is correct (lowercase for standard tables) +- Check record ID exists +- Ensure using schema names, not display names +- Cache issue could happen, so retry might help, especially for metadata creation + +**400 Bad Request:** +- Check filter/expand parameters use correct case +- Verify column names exist and are spelled correctly +- Ensure custom columns include customization prefix + +## Best Practices + +### Performance Optimization + +1. **Use bulk operations** - Pass lists to create/update/delete for automatic optimization +2. **Specify select fields** - Limit returned columns to reduce payload size +3. **Control page size** - Use `top` and `page_size` parameters appropriately +4. **Reuse client instances** - Don't create new clients for each operation +5. **Use production credentials** - ClientSecretCredential or ClientCertificateCredential for unattended operations +6. **Error handling** - Implement retry logic for transient errors (`e.is_transient`) +7. **Always include customization prefix** for custom tables/columns +8. **Use lowercase** - Generally using lower cased input won't go wrong, exception would be custom tables/columns naming +9. **Test in non-production environments** first + +## Additional Resources + +Load these resources as needed during development: + +- [API Reference](https://learn.microsoft.com/python/api/dataverse-sdk-docs-python/dataverse-overview) +- [Product Documentation](https://learn.microsoft.com/power-apps/developer/data-platform/sdk-python/) +- [Dataverse Web API](https://learn.microsoft.com/power-apps/developer/data-platform/webapi/) +- [Azure Identity](https://learn.microsoft.com/python/api/overview/azure/identity-readme) + +## Key Reminders + +1. **Schema names are required** - Never use display names +2. **Custom tables need prefixes** - Include customization prefix (e.g., "new_") +3. **Filter is case-sensitive** - Use lowercase logical names +4. **Bulk operations are encouraged** - Pass lists for optimization +5. **No trailing slashes in URLs** - Format: `https://org.crm.dynamics.com` +6. **Structured errors** - Check `is_transient` for retry logic diff --git a/src/PowerPlatform/Dataverse/claude_skill/__init__.py b/src/PowerPlatform/Dataverse/claude_skill/__init__.py new file mode 100644 index 0000000..a9a5c3c --- /dev/null +++ b/src/PowerPlatform/Dataverse/claude_skill/__init__.py @@ -0,0 +1,9 @@ +# Copyright (c) Microsoft Corporation. +# Licensed under the MIT license. + +""" +Claude Code skill package for the PowerPlatform Dataverse Client SDK. + +This package contains the SKILL.md file that provides guidance to Claude Code +when working with the Dataverse SDK. +""" diff --git a/src/PowerPlatform/Dataverse/client.py b/src/PowerPlatform/Dataverse/client.py index e59ad26..84bd5d4 100644 --- a/src/PowerPlatform/Dataverse/client.py +++ b/src/PowerPlatform/Dataverse/client.py @@ -436,7 +436,7 @@ def create_table( :param columns: Dictionary mapping column names (with customization prefix value) to their types. All custom column names must include the customization prefix value (e.g. ``"new_Title"``). Supported types: - - Primitive types: ``"string"``, ``"int"``, ``"decimal"``, ``"float"``, ``"datetime"``, ``"bool"`` + - Primitive types: ``"string"`` (alias: ``"text"``), ``"int"`` (alias: ``"integer"``), ``"decimal"`` (alias: ``"money"``), ``"float"`` (alias: ``"double"``), ``"datetime"`` (alias: ``"date"``), ``"bool"`` (alias: ``"boolean"``) - Enum subclass (IntEnum preferred): Creates a local option set. Optional multilingual labels can be provided via ``__labels__`` class attribute, defined inside the Enum subclass:: @@ -546,7 +546,7 @@ def create_columns( :param table_schema_name: Schema name of the table (e.g. ``"new_MyTestTable"``). :type table_schema_name: :class:`str` :param columns: Mapping of column schema names (with customization prefix value) to supported types. All custom column names must include the customization prefix value** (e.g. ``"new_Notes"``). Primitive types include - ``string``, ``int``, ``decimal``, ``float``, ``datetime``, and ``bool``. Enum subclasses (IntEnum preferred) + ``"string"`` (alias: ``"text"``), ``"int"`` (alias: ``"integer"``), ``"decimal"`` (alias: ``"money"``), ``"float"`` (alias: ``"double"``), ``"datetime"`` (alias: ``"date"``), and ``"bool"`` (alias: ``"boolean"``). Enum subclasses (IntEnum preferred) generate a local option set and can specify localized labels via ``__labels__``. :type columns: :class:`dict` mapping :class:`str` to :class:`typing.Any` :returns: Schema names for the columns that were created. From 8f51f6f9bd2c532f62199e0bcef99bea77484899 Mon Sep 17 00:00:00 2001 From: zhaodongwang-msft Date: Tue, 20 Jan 2026 11:31:33 -0800 Subject: [PATCH 2/9] Update README.md Co-authored-by: Copilot <175728472+Copilot@users.noreply.github.com> --- README.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/README.md b/README.md index 803fbf5..1406b7a 100644 --- a/README.md +++ b/README.md @@ -69,7 +69,7 @@ This installs a Claude Skill that enables Claude Code to: - Help with error handling and troubleshooting - Guide you through common patterns -The skill works with both the Claude Code CLI and VSCode extension. Once installed, Claude will automatically use it when working with Dataverse operations. For more information on Claude Skill see https://platform.claude.com/docs/en/agents-and-tools/agent-skills/overview. See skill definition here .claude\skills\dataverse-sdk\SKILL.md. +The skill works with both the Claude Code CLI and VSCode extension. Once installed, Claude will automatically use it when working with Dataverse operations. For more information on Claude Skill see https://platform.claude.com/docs/en/agents-and-tools/agent-skills/overview. See skill definition here .claude/skills/dataverse-sdk/SKILL.md. For development from source (Claude Skill auto loaded): From 4d96a1db4eedb9d5a22d79bfa21d746e8bf2a7cb Mon Sep 17 00:00:00 2001 From: Max Wang Date: Tue, 20 Jan 2026 11:35:01 -0800 Subject: [PATCH 3/9] formatting --- README.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/README.md b/README.md index 1406b7a..cd959f1 100644 --- a/README.md +++ b/README.md @@ -69,7 +69,7 @@ This installs a Claude Skill that enables Claude Code to: - Help with error handling and troubleshooting - Guide you through common patterns -The skill works with both the Claude Code CLI and VSCode extension. Once installed, Claude will automatically use it when working with Dataverse operations. For more information on Claude Skill see https://platform.claude.com/docs/en/agents-and-tools/agent-skills/overview. See skill definition here .claude/skills/dataverse-sdk/SKILL.md. +The skill works with both the Claude Code CLI and VSCode extension. Once installed, Claude will automatically use it when working with Dataverse operations. For more information on Claude Skill see https://platform.claude.com/docs/en/agents-and-tools/agent-skills/overview. See skill definition here: `.claude/skills/dataverse-sdk/SKILL.md`. For development from source (Claude Skill auto loaded): From ddf72dc1ba24a037757fceec1cf7ecb7cebacbc6 Mon Sep 17 00:00:00 2001 From: zhaodongwang-msft Date: Tue, 20 Jan 2026 11:35:24 -0800 Subject: [PATCH 4/9] Update src/PowerPlatform/Dataverse/claude_skill/SKILL.md Co-authored-by: Copilot <175728472+Copilot@users.noreply.github.com> --- src/PowerPlatform/Dataverse/claude_skill/SKILL.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/src/PowerPlatform/Dataverse/claude_skill/SKILL.md b/src/PowerPlatform/Dataverse/claude_skill/SKILL.md index a8e844f..9653aa0 100644 --- a/src/PowerPlatform/Dataverse/claude_skill/SKILL.md +++ b/src/PowerPlatform/Dataverse/claude_skill/SKILL.md @@ -259,7 +259,7 @@ except ValidationError as e: 5. **Use production credentials** - ClientSecretCredential or ClientCertificateCredential for unattended operations 6. **Error handling** - Implement retry logic for transient errors (`e.is_transient`) 7. **Always include customization prefix** for custom tables/columns -8. **Use lowercase** - Generally using lower cased input won't go wrong, exception would be custom tables/columns naming +8. **Use lowercase** - Generally using lowercase input won't go wrong, exception would be custom tables/columns naming 9. **Test in non-production environments** first ## Additional Resources From 75aa4a4e329278b2874f072e3f2e0b04e3efdd36 Mon Sep 17 00:00:00 2001 From: zhaodongwang-msft Date: Tue, 20 Jan 2026 11:35:33 -0800 Subject: [PATCH 5/9] Update .claude/skills/dataverse-sdk/SKILL.md Co-authored-by: Copilot <175728472+Copilot@users.noreply.github.com> --- .claude/skills/dataverse-sdk/SKILL.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/.claude/skills/dataverse-sdk/SKILL.md b/.claude/skills/dataverse-sdk/SKILL.md index a8e844f..9653aa0 100644 --- a/.claude/skills/dataverse-sdk/SKILL.md +++ b/.claude/skills/dataverse-sdk/SKILL.md @@ -259,7 +259,7 @@ except ValidationError as e: 5. **Use production credentials** - ClientSecretCredential or ClientCertificateCredential for unattended operations 6. **Error handling** - Implement retry logic for transient errors (`e.is_transient`) 7. **Always include customization prefix** for custom tables/columns -8. **Use lowercase** - Generally using lower cased input won't go wrong, exception would be custom tables/columns naming +8. **Use lowercase** - Generally using lowercase input won't go wrong, exception would be custom tables/columns naming 9. **Test in non-production environments** first ## Additional Resources From 46b14a63242685604f14ea170a65a2ff8e99f6e3 Mon Sep 17 00:00:00 2001 From: Max Wang Date: Tue, 20 Jan 2026 11:37:30 -0800 Subject: [PATCH 6/9] formatting --- .claude/skills/dataverse-sdk/SKILL.md | 2 +- src/PowerPlatform/Dataverse/claude_skill/SKILL.md | 2 +- 2 files changed, 2 insertions(+), 2 deletions(-) diff --git a/.claude/skills/dataverse-sdk/SKILL.md b/.claude/skills/dataverse-sdk/SKILL.md index 9653aa0..142f452 100644 --- a/.claude/skills/dataverse-sdk/SKILL.md +++ b/.claude/skills/dataverse-sdk/SKILL.md @@ -259,7 +259,7 @@ except ValidationError as e: 5. **Use production credentials** - ClientSecretCredential or ClientCertificateCredential for unattended operations 6. **Error handling** - Implement retry logic for transient errors (`e.is_transient`) 7. **Always include customization prefix** for custom tables/columns -8. **Use lowercase** - Generally using lowercase input won't go wrong, exception would be custom tables/columns naming +8. **Use lowercase** - Generally using lowercase input won't go wrong, except for custom table/column naming 9. **Test in non-production environments** first ## Additional Resources diff --git a/src/PowerPlatform/Dataverse/claude_skill/SKILL.md b/src/PowerPlatform/Dataverse/claude_skill/SKILL.md index 9653aa0..142f452 100644 --- a/src/PowerPlatform/Dataverse/claude_skill/SKILL.md +++ b/src/PowerPlatform/Dataverse/claude_skill/SKILL.md @@ -259,7 +259,7 @@ except ValidationError as e: 5. **Use production credentials** - ClientSecretCredential or ClientCertificateCredential for unattended operations 6. **Error handling** - Implement retry logic for transient errors (`e.is_transient`) 7. **Always include customization prefix** for custom tables/columns -8. **Use lowercase** - Generally using lowercase input won't go wrong, exception would be custom tables/columns naming +8. **Use lowercase** - Generally using lowercase input won't go wrong, except for custom table/column naming 9. **Test in non-production environments** first ## Additional Resources From f147bbf5fd3498933d058bc48a04550dee54199f Mon Sep 17 00:00:00 2001 From: zhaodongwang-msft Date: Tue, 20 Jan 2026 11:38:20 -0800 Subject: [PATCH 7/9] Update src/PowerPlatform/Dataverse/_skill_installer.py Co-authored-by: Copilot <175728472+Copilot@users.noreply.github.com> --- src/PowerPlatform/Dataverse/_skill_installer.py | 1 - 1 file changed, 1 deletion(-) diff --git a/src/PowerPlatform/Dataverse/_skill_installer.py b/src/PowerPlatform/Dataverse/_skill_installer.py index 974f7d0..8a720af 100644 --- a/src/PowerPlatform/Dataverse/_skill_installer.py +++ b/src/PowerPlatform/Dataverse/_skill_installer.py @@ -11,7 +11,6 @@ import shutil import sys from pathlib import Path -from typing import Optional # Ensure UTF-8 output for emoji support on Windows if sys.platform == "win32": From 686bae991959b197e6dadb17d911b8e3c8899236 Mon Sep 17 00:00:00 2001 From: Max Wang Date: Tue, 20 Jan 2026 11:40:19 -0800 Subject: [PATCH 8/9] black formatting --- src/PowerPlatform/Dataverse/_skill_installer.py | 9 +++++---- src/PowerPlatform/Dataverse/data/_odata.py | 1 - 2 files changed, 5 insertions(+), 5 deletions(-) diff --git a/src/PowerPlatform/Dataverse/_skill_installer.py b/src/PowerPlatform/Dataverse/_skill_installer.py index 974f7d0..427e7a6 100644 --- a/src/PowerPlatform/Dataverse/_skill_installer.py +++ b/src/PowerPlatform/Dataverse/_skill_installer.py @@ -16,10 +16,11 @@ # Ensure UTF-8 output for emoji support on Windows if sys.platform == "win32": import codecs - if sys.stdout.encoding != 'utf-8': - sys.stdout = codecs.getwriter('utf-8')(sys.stdout.buffer, 'strict') - if sys.stderr.encoding != 'utf-8': - sys.stderr = codecs.getwriter('utf-8')(sys.stderr.buffer, 'strict') + + if sys.stdout.encoding != "utf-8": + sys.stdout = codecs.getwriter("utf-8")(sys.stdout.buffer, "strict") + if sys.stderr.encoding != "utf-8": + sys.stderr = codecs.getwriter("utf-8")(sys.stderr.buffer, "strict") def get_skill_source_path() -> Path: diff --git a/src/PowerPlatform/Dataverse/data/_odata.py b/src/PowerPlatform/Dataverse/data/_odata.py index df78185..7c5fc6c 100644 --- a/src/PowerPlatform/Dataverse/data/_odata.py +++ b/src/PowerPlatform/Dataverse/data/_odata.py @@ -36,7 +36,6 @@ from ..__version__ import __version__ as _SDK_VERSION - _USER_AGENT = f"DataverseSvcPythonClient:{_SDK_VERSION}" _GUID_RE = re.compile(r"[0-9a-fA-F]{8}-[0-9a-fA-F]{4}-[0-9a-fA-F]{4}-[0-9a-fA-F]{4}-[0-9a-fA-F]{12}") _CALL_SCOPE_CORRELATION_ID: ContextVar[Optional[str]] = ContextVar("_CALL_SCOPE_CORRELATION_ID", default=None) From 3bc9622090a7b0f0f722fdf53a7a7acb0dcaba93 Mon Sep 17 00:00:00 2001 From: Max Wang Date: Tue, 20 Jan 2026 13:21:57 -0800 Subject: [PATCH 9/9] remove unicode --- .../Dataverse/_skill_installer.py | 75 ++++++++----------- 1 file changed, 33 insertions(+), 42 deletions(-) diff --git a/src/PowerPlatform/Dataverse/_skill_installer.py b/src/PowerPlatform/Dataverse/_skill_installer.py index 4cada36..ad49c38 100644 --- a/src/PowerPlatform/Dataverse/_skill_installer.py +++ b/src/PowerPlatform/Dataverse/_skill_installer.py @@ -12,15 +12,6 @@ import sys from pathlib import Path -# Ensure UTF-8 output for emoji support on Windows -if sys.platform == "win32": - import codecs - - if sys.stdout.encoding != "utf-8": - sys.stdout = codecs.getwriter("utf-8")(sys.stdout.buffer, "strict") - if sys.stderr.encoding != "utf-8": - sys.stderr = codecs.getwriter("utf-8")(sys.stderr.buffer, "strict") - def get_skill_source_path() -> Path: """Get the path to the skill source directory in the package.""" @@ -68,24 +59,24 @@ def install_skill(force: bool = False) -> bool: # Validate source exists if not skill_source.exists(): - print(f"❌ Error: Skill source not found at {skill_source}") - print(" This may indicate a packaging issue.") + print(f"[ERROR] Skill source not found at {skill_source}") + print(" This may indicate a packaging issue.") return False skill_md = skill_source / "SKILL.md" if not skill_md.exists(): - print(f"❌ Error: SKILL.md not found at {skill_md}") + print(f"[ERROR] SKILL.md not found at {skill_md}") return False # Check if skill already exists if skill_dest.exists(): if not force: - print(f"⚠️ Skill already exists at {skill_dest}") - response = input(" Overwrite existing skill? (y/n): ").strip().lower() + print(f"[WARN] Skill already exists at {skill_dest}") + response = input(" Overwrite existing skill? (y/n): ").strip().lower() if response not in ["y", "yes"]: - print(" Installation cancelled.") + print(" Installation cancelled.") return False - print(f" Updating existing skill...") + print(f" Updating existing skill...") # Create destination directory skill_dest.parent.mkdir(parents=True, exist_ok=True) @@ -95,19 +86,19 @@ def install_skill(force: bool = False) -> bool: if skill_dest.exists(): shutil.rmtree(skill_dest) shutil.copytree(skill_source, skill_dest) - print(f"✅ Dataverse SDK skill installed successfully!") - print(f" Location: {skill_dest}") + print(f"[OK] Dataverse SDK skill installed successfully!") + print(f" Location: {skill_dest}") print() - print(" Claude Code will now automatically use this skill when working") - print(" with the PowerPlatform Dataverse Client SDK.") + print(" Claude Code will now automatically use this skill when working") + print(" with the PowerPlatform Dataverse Client SDK.") print() - print("💡 Next steps:") - print(" • Start Claude Code in your project directory") - print(" • Ask Claude for help with Dataverse operations") - print(" • Claude will automatically apply SDK best practices") + print("[INFO] Next steps:") + print(" * Start Claude Code in your project directory") + print(" * Ask Claude for help with Dataverse operations") + print(" * Claude will automatically apply SDK best practices") return True except Exception as e: - print(f"❌ Error installing skill: {e}") + print(f"[ERROR] Error installing skill: {e}") return False @@ -121,17 +112,17 @@ def uninstall_skill() -> bool: skill_dest = get_skill_destination_path() if not skill_dest.exists(): - print(f"ℹ️ Skill not found at {skill_dest}") - print(" Nothing to uninstall.") + print(f"[INFO] Skill not found at {skill_dest}") + print(" Nothing to uninstall.") return True try: shutil.rmtree(skill_dest) - print(f"✅ Dataverse SDK skill uninstalled successfully!") - print(f" Removed from: {skill_dest}") + print(f"[OK] Dataverse SDK skill uninstalled successfully!") + print(f" Removed from: {skill_dest}") return True except Exception as e: - print(f"❌ Error uninstalling skill: {e}") + print(f"[ERROR] Error uninstalling skill: {e}") return False @@ -139,27 +130,27 @@ def check_skill_status() -> None: """Check and display the current skill installation status.""" skill_dest = get_skill_destination_path() - print("🔍 Dataverse SDK Skill Status") + print("[INFO] Dataverse SDK Skill Status") print("=" * 60) if skill_dest.exists(): skill_md = skill_dest / "SKILL.md" if skill_md.exists(): - print(f"✅ Status: Installed") - print(f" Location: {skill_dest}") - print(f" Skill file: {skill_md}") + print(f"[OK] Status: Installed") + print(f" Location: {skill_dest}") + print(f" Skill file: {skill_md}") print() - print(" The skill is ready to use with Claude Code.") + print(" The skill is ready to use with Claude Code.") else: - print(f"⚠️ Status: Partially installed (SKILL.md missing)") - print(f" Location: {skill_dest}") + print(f"[WARN] Status: Partially installed (SKILL.md missing)") + print(f" Location: {skill_dest}") print() - print(" Consider reinstalling: dataverse-install-claude-skill --force") + print(" Consider reinstalling: dataverse-install-claude-skill --force") else: - print(f"❌ Status: Not installed") - print(f" Expected location: {skill_dest}") + print(f"[ERROR] Status: Not installed") + print(f" Expected location: {skill_dest}") print() - print(" To install: dataverse-install-claude-skill") + print(" To install: dataverse-install-claude-skill") def main() -> None: @@ -202,7 +193,7 @@ def main() -> None: args = parser.parse_args() print() - print("🚀 PowerPlatform Dataverse SDK - Claude Code Skill Installer") + print("PowerPlatform Dataverse SDK - Claude Code Skill Installer") print("=" * 60) print()