Initial Commit
This commit is contained in:
Submodule
+1
Submodule example/MCP-Doc added at 377d05f0a9
@@ -0,0 +1,492 @@
|
||||
# Advanced DOCX MCP Server Usage Examples
|
||||
|
||||
This document demonstrates the advanced capabilities of the DOCX MCP server with real-world examples.
|
||||
|
||||
## Professional Document Templates
|
||||
|
||||
### Creating a Business Report
|
||||
|
||||
```javascript
|
||||
// Ask your AI: "Create a professional quarterly report with our sales data"
|
||||
|
||||
// 1. Create from report template
|
||||
const doc = await mcp.call("create_from_template", {
|
||||
template: "Report"
|
||||
});
|
||||
|
||||
// 2. Set document properties
|
||||
await mcp.call("set_document_properties", {
|
||||
document_id: doc.document_id,
|
||||
properties: {
|
||||
title: "Q3 2024 Sales Report",
|
||||
subject: "Quarterly Business Review",
|
||||
author: "Sales Team",
|
||||
company: "TechCorp Inc",
|
||||
keywords: ["sales", "quarterly", "2024", "revenue"]
|
||||
}
|
||||
});
|
||||
|
||||
// 3. Add custom sections with advanced formatting
|
||||
await mcp.call("add_section", {
|
||||
document_id: doc.document_id,
|
||||
section_config: {
|
||||
page_size: "Letter",
|
||||
landscape: false,
|
||||
margins: {
|
||||
top: 25.4,
|
||||
bottom: 25.4,
|
||||
left: 31.8,
|
||||
right: 25.4
|
||||
},
|
||||
columns: 1
|
||||
}
|
||||
});
|
||||
|
||||
// 4. Add charts and data visualization
|
||||
await mcp.call("add_chart", {
|
||||
document_id: doc.document_id,
|
||||
chart_type: "Column",
|
||||
data: {
|
||||
title: "Quarterly Revenue Growth",
|
||||
categories: ["Q1", "Q2", "Q3"],
|
||||
series: [{
|
||||
name: "Revenue ($M)",
|
||||
values: [1.2, 1.5, 1.8]
|
||||
}]
|
||||
}
|
||||
});
|
||||
```
|
||||
|
||||
### Advanced Mail Merge Campaign
|
||||
|
||||
```javascript
|
||||
// Ask your AI: "Create personalized letters for our client list with custom fields"
|
||||
|
||||
// 1. Create template with merge fields
|
||||
const template = await mcp.call("create_from_template", {
|
||||
template: "BusinessLetter"
|
||||
});
|
||||
|
||||
await mcp.call("prepare_mail_merge_template", {
|
||||
document_id: template.document_id,
|
||||
fields: ["ClientName", "Company", "LastOrderDate", "AccountManager", "SpecialOffer"]
|
||||
});
|
||||
|
||||
// 2. Process each recipient
|
||||
const recipients = [
|
||||
{
|
||||
ClientName: "John Smith",
|
||||
Company: "ABC Corp",
|
||||
LastOrderDate: "2024-02-15",
|
||||
AccountManager: "Sarah Johnson",
|
||||
SpecialOffer: "20% off next order"
|
||||
}
|
||||
// ... more recipients
|
||||
];
|
||||
|
||||
for (const recipient of recipients) {
|
||||
// Create personalized document
|
||||
const personalDoc = await mcp.call("merge_template", {
|
||||
template_id: template.document_id,
|
||||
data: recipient
|
||||
});
|
||||
|
||||
// Add watermark for draft review
|
||||
await mcp.call("add_watermark", {
|
||||
document_id: personalDoc.document_id,
|
||||
text: "CONFIDENTIAL",
|
||||
style: "Diagonal"
|
||||
});
|
||||
}
|
||||
```
|
||||
|
||||
## Document Analysis & Review
|
||||
|
||||
### Comprehensive Document Analysis
|
||||
|
||||
```javascript
|
||||
// Ask your AI: "Analyze this contract for structure, formatting, and key terms"
|
||||
|
||||
const doc = await mcp.call("open_document", {
|
||||
path: "./contracts/service_agreement.docx"
|
||||
});
|
||||
|
||||
// 1. Get document structure
|
||||
const structure = await mcp.call("get_document_structure", {
|
||||
document_id: doc.document_id
|
||||
});
|
||||
|
||||
// 2. Analyze formatting consistency
|
||||
const formatting = await mcp.call("analyze_formatting", {
|
||||
document_id: doc.document_id
|
||||
});
|
||||
|
||||
// 3. Get detailed statistics
|
||||
const stats = await mcp.call("get_word_count", {
|
||||
document_id: doc.document_id
|
||||
});
|
||||
|
||||
// 4. Search for key legal terms
|
||||
const terms = ["liability", "indemnification", "termination", "confidential"];
|
||||
for (const term of terms) {
|
||||
const results = await mcp.call("search_text", {
|
||||
document_id: doc.document_id,
|
||||
search_term: term,
|
||||
case_sensitive: false,
|
||||
whole_word: true
|
||||
});
|
||||
|
||||
console.log(`Found "${term}" ${results.total_matches} times`);
|
||||
}
|
||||
|
||||
// 5. Export analysis to Markdown
|
||||
await mcp.call("export_to_markdown", {
|
||||
document_id: doc.document_id,
|
||||
output_path: "./analysis/contract_analysis.md"
|
||||
});
|
||||
```
|
||||
|
||||
### Collaborative Review Process
|
||||
|
||||
```javascript
|
||||
// Ask your AI: "Set up this document for review with comments and track changes"
|
||||
|
||||
// 1. Enable track changes
|
||||
await mcp.call("enable_track_changes", {
|
||||
document_id: doc.document_id,
|
||||
author: "Legal Review Team"
|
||||
});
|
||||
|
||||
// 2. Add review comments
|
||||
await mcp.call("add_comment", {
|
||||
document_id: doc.document_id,
|
||||
text: "Payment terms in section 3.2",
|
||||
comment: "Consider reducing payment terms from 60 to 30 days",
|
||||
author: "Finance Team"
|
||||
});
|
||||
|
||||
// 3. Add footnotes for clarification
|
||||
await mcp.call("add_footnote", {
|
||||
document_id: doc.document_id,
|
||||
reference_text: "governing law",
|
||||
footnote_text: "This clause should specify the state jurisdiction for legal disputes"
|
||||
});
|
||||
|
||||
// 4. Create bookmarks for easy navigation
|
||||
await mcp.call("add_bookmark", {
|
||||
document_id: doc.document_id,
|
||||
bookmark_name: "payment_terms",
|
||||
text: "3.2 Payment Terms"
|
||||
});
|
||||
|
||||
// 5. Add cross-references
|
||||
await mcp.call("add_cross_reference", {
|
||||
document_id: doc.document_id,
|
||||
bookmark_name: "payment_terms",
|
||||
display_text: "See Payment Terms section"
|
||||
});
|
||||
```
|
||||
|
||||
## Security & Compliance Examples
|
||||
|
||||
### Readonly Document Review
|
||||
|
||||
```bash
|
||||
# Start server in readonly mode for document review only
|
||||
export DOCX_MCP_READONLY=true
|
||||
./target/release/docx-mcp
|
||||
```
|
||||
|
||||
```javascript
|
||||
// In readonly mode, these operations are available:
|
||||
const doc = await mcp.call("open_document", {
|
||||
path: "./confidential/annual_report.docx"
|
||||
});
|
||||
|
||||
// ✅ Allowed: Extract and analyze content
|
||||
const text = await mcp.call("extract_text", {
|
||||
document_id: doc.document_id
|
||||
});
|
||||
|
||||
const structure = await mcp.call("get_document_structure", {
|
||||
document_id: doc.document_id
|
||||
});
|
||||
|
||||
// ✅ Allowed: Export for analysis
|
||||
await mcp.call("export_to_markdown", {
|
||||
document_id: doc.document_id,
|
||||
output_path: "./analysis/report_content.md"
|
||||
});
|
||||
|
||||
// ❌ Blocked: Any modification attempts
|
||||
// These would return security errors:
|
||||
// - add_paragraph
|
||||
// - save_document
|
||||
// - find_and_replace
|
||||
```
|
||||
|
||||
### Sandboxed Environment
|
||||
|
||||
```bash
|
||||
# Run in sandbox mode - restricts file operations to temp directory
|
||||
export DOCX_MCP_SANDBOX=true
|
||||
export DOCX_MCP_NO_EXTERNAL_TOOLS=true
|
||||
./target/release/docx-mcp
|
||||
```
|
||||
|
||||
```javascript
|
||||
// All file operations restricted to temporary directory
|
||||
// Perfect for untrusted document processing
|
||||
|
||||
const doc = await mcp.call("create_document", {});
|
||||
|
||||
// ✅ Allowed: Operations in temp directory
|
||||
await mcp.call("save_document", {
|
||||
document_id: doc.document_id,
|
||||
output_path: "/tmp/docx-mcp/safe_output.docx"
|
||||
});
|
||||
|
||||
// ❌ Blocked: Operations outside temp directory
|
||||
// This would return a security error:
|
||||
await mcp.call("save_document", {
|
||||
document_id: doc.document_id,
|
||||
output_path: "/home/user/documents/output.docx" // BLOCKED
|
||||
});
|
||||
```
|
||||
|
||||
## Advanced Automation Workflows
|
||||
|
||||
### Automated Report Generation Pipeline
|
||||
|
||||
```javascript
|
||||
// Ask your AI: "Create an automated monthly report generation system"
|
||||
|
||||
class ReportGenerator {
|
||||
async generateMonthlyReport(month, year, data) {
|
||||
// 1. Create from template
|
||||
const doc = await mcp.call("create_from_template", {
|
||||
template: "Report"
|
||||
});
|
||||
|
||||
// 2. Set up custom styles
|
||||
await mcp.call("add_custom_style", {
|
||||
document_id: doc.document_id,
|
||||
style: {
|
||||
id: "CompanyHeading",
|
||||
name: "Company Heading",
|
||||
font: "Arial",
|
||||
size: 18,
|
||||
bold: true,
|
||||
color: "#2E86C1",
|
||||
spacing: {
|
||||
before: 12,
|
||||
after: 6,
|
||||
line: 1.15
|
||||
}
|
||||
}
|
||||
});
|
||||
|
||||
// 3. Add dynamic content with bookmarks
|
||||
await mcp.call("add_bookmark", {
|
||||
document_id: doc.document_id,
|
||||
bookmark_name: "executive_summary",
|
||||
text: "Executive Summary"
|
||||
});
|
||||
|
||||
// 4. Insert data charts
|
||||
for (const metric of data.metrics) {
|
||||
await mcp.call("add_chart", {
|
||||
document_id: doc.document_id,
|
||||
chart_type: metric.type,
|
||||
data: {
|
||||
title: metric.title,
|
||||
categories: metric.categories,
|
||||
series: metric.series
|
||||
}
|
||||
});
|
||||
}
|
||||
|
||||
// 5. Add table of contents
|
||||
await mcp.call("add_table_of_contents", {
|
||||
document_id: doc.document_id
|
||||
});
|
||||
|
||||
// 6. Apply watermark
|
||||
await mcp.call("add_watermark", {
|
||||
document_id: doc.document_id,
|
||||
text: "INTERNAL USE ONLY",
|
||||
style: "Horizontal"
|
||||
});
|
||||
|
||||
// 7. Generate multiple formats
|
||||
const filename = `monthly_report_${year}_${month}`;
|
||||
|
||||
// Save DOCX
|
||||
await mcp.call("save_document", {
|
||||
document_id: doc.document_id,
|
||||
output_path: `./reports/${filename}.docx`
|
||||
});
|
||||
|
||||
// Convert to PDF
|
||||
await mcp.call("convert_to_pdf", {
|
||||
document_id: doc.document_id,
|
||||
output_path: `./reports/${filename}.pdf`
|
||||
});
|
||||
|
||||
// Generate preview images
|
||||
await mcp.call("convert_to_images", {
|
||||
document_id: doc.document_id,
|
||||
output_dir: `./reports/previews/`,
|
||||
format: "png",
|
||||
dpi: 150
|
||||
});
|
||||
|
||||
return {
|
||||
docx: `./reports/${filename}.docx`,
|
||||
pdf: `./reports/${filename}.pdf`,
|
||||
preview: `./reports/previews/`
|
||||
};
|
||||
}
|
||||
}
|
||||
```
|
||||
|
||||
### Document Quality Assurance
|
||||
|
||||
```javascript
|
||||
// Ask your AI: "Create a document QA system that checks formatting and compliance"
|
||||
|
||||
class DocumentQA {
|
||||
async auditDocument(documentPath) {
|
||||
const doc = await mcp.call("open_document", {
|
||||
path: documentPath
|
||||
});
|
||||
|
||||
const audit = {
|
||||
document: documentPath,
|
||||
timestamp: new Date().toISOString(),
|
||||
issues: [],
|
||||
recommendations: []
|
||||
};
|
||||
|
||||
// 1. Check document structure
|
||||
const structure = await mcp.call("get_document_structure", {
|
||||
document_id: doc.document_id
|
||||
});
|
||||
|
||||
if (structure.structure.filter(s => s.type === "heading").length < 2) {
|
||||
audit.issues.push("Document lacks proper heading structure");
|
||||
}
|
||||
|
||||
// 2. Analyze formatting consistency
|
||||
const formatting = await mcp.call("analyze_formatting", {
|
||||
document_id: doc.document_id
|
||||
});
|
||||
|
||||
if (formatting.formatting_analysis.fonts_detected.length > 3) {
|
||||
audit.issues.push("Too many fonts used - limit to 2-3 for consistency");
|
||||
}
|
||||
|
||||
// 3. Check for required content
|
||||
const requiredTerms = ["confidential", "copyright", "contact"];
|
||||
for (const term of requiredTerms) {
|
||||
const search = await mcp.call("search_text", {
|
||||
document_id: doc.document_id,
|
||||
search_term: term,
|
||||
case_sensitive: false
|
||||
});
|
||||
|
||||
if (search.total_matches === 0) {
|
||||
audit.recommendations.push(`Consider adding ${term} information`);
|
||||
}
|
||||
}
|
||||
|
||||
// 4. Check document statistics
|
||||
const stats = await mcp.call("get_word_count", {
|
||||
document_id: doc.document_id
|
||||
});
|
||||
|
||||
if (stats.statistics.words < 500) {
|
||||
audit.issues.push("Document may be too short for professional standards");
|
||||
}
|
||||
|
||||
// 5. Generate audit report
|
||||
const auditDoc = await mcp.call("create_document", {});
|
||||
|
||||
await mcp.call("add_heading", {
|
||||
document_id: auditDoc.document_id,
|
||||
text: "Document Quality Audit Report",
|
||||
level: 1
|
||||
});
|
||||
|
||||
await mcp.call("add_paragraph", {
|
||||
document_id: auditDoc.document_id,
|
||||
text: `Audit completed for: ${documentPath}`
|
||||
});
|
||||
|
||||
// Add issues table
|
||||
const issuesData = audit.issues.map(issue => ["Issue", issue]);
|
||||
await mcp.call("add_table", {
|
||||
document_id: auditDoc.document_id,
|
||||
rows: [["Type", "Description"], ...issuesData]
|
||||
});
|
||||
|
||||
await mcp.call("save_document", {
|
||||
document_id: auditDoc.document_id,
|
||||
output_path: `./qa/audit_${Date.now()}.docx`
|
||||
});
|
||||
|
||||
return audit;
|
||||
}
|
||||
}
|
||||
```
|
||||
|
||||
## Security Configuration Examples
|
||||
|
||||
### Enterprise Security Setup
|
||||
|
||||
```bash
|
||||
#!/bin/bash
|
||||
# Enterprise security configuration script
|
||||
|
||||
# Readonly mode for document review workstations
|
||||
export DOCX_MCP_READONLY=true
|
||||
|
||||
# Whitelist only analysis and export commands
|
||||
export DOCX_MCP_WHITELIST="open_document,extract_text,get_metadata,get_document_structure,analyze_formatting,get_word_count,search_text,export_to_markdown,export_to_html,list_documents,get_security_info"
|
||||
|
||||
# Sandbox mode for processing untrusted documents
|
||||
export DOCX_MCP_SANDBOX=true
|
||||
|
||||
# Resource limits
|
||||
export DOCX_MCP_MAX_SIZE=10485760 # 10MB max file size
|
||||
export DOCX_MCP_MAX_DOCS=5 # Max 5 open documents
|
||||
|
||||
# Disable external tools and network
|
||||
export DOCX_MCP_NO_EXTERNAL_TOOLS=true
|
||||
export DOCX_MCP_NO_NETWORK=true
|
||||
|
||||
echo "🔒 Starting DOCX MCP Server in Enterprise Security Mode"
|
||||
./target/release/docx-mcp
|
||||
```
|
||||
|
||||
### Development Environment Setup
|
||||
|
||||
```bash
|
||||
#!/bin/bash
|
||||
# Development environment with full features
|
||||
|
||||
# Allow all operations but with reasonable limits
|
||||
export DOCX_MCP_MAX_SIZE=104857600 # 100MB max file size
|
||||
export DOCX_MCP_MAX_DOCS=25 # Max 25 open documents
|
||||
|
||||
# Enable all features
|
||||
unset DOCX_MCP_READONLY
|
||||
unset DOCX_MCP_SANDBOX
|
||||
unset DOCX_MCP_WHITELIST
|
||||
unset DOCX_MCP_BLACKLIST
|
||||
|
||||
echo "🚀 Starting DOCX MCP Server in Development Mode"
|
||||
./target/release/docx-mcp
|
||||
```
|
||||
|
||||
These examples demonstrate the full power and flexibility of the DOCX MCP server for professional document workflows, from simple document creation to complex enterprise automation systems.
|
||||
@@ -0,0 +1,503 @@
|
||||
#!/usr/bin/env python3
|
||||
"""
|
||||
Advanced automation example using the DOCX MCP Server.
|
||||
This demonstrates how to build document automation workflows.
|
||||
"""
|
||||
|
||||
import json
|
||||
import asyncio
|
||||
import csv
|
||||
from datetime import datetime
|
||||
from pathlib import Path
|
||||
from typing import List, Dict, Any
|
||||
|
||||
# This would normally be your MCP client library
|
||||
# For demonstration, we're showing the structure
|
||||
class MCPClient:
|
||||
"""Mock MCP Client for demonstration"""
|
||||
|
||||
async def call(self, tool_name: str, arguments: Dict[str, Any]) -> Dict[str, Any]:
|
||||
"""Call an MCP tool"""
|
||||
# In reality, this would communicate with the MCP server
|
||||
print(f"Calling {tool_name} with {arguments}")
|
||||
return {"success": True, "result": {}}
|
||||
|
||||
# Initialize client
|
||||
mcp = MCPClient()
|
||||
|
||||
# === Example 1: Generate Monthly Reports ===
|
||||
async def generate_monthly_report(month: int, year: int, data: Dict[str, Any]):
|
||||
"""Generate a comprehensive monthly report"""
|
||||
|
||||
# Create new document
|
||||
doc = await mcp.call("create_document", {})
|
||||
doc_id = doc["result"]["document_id"]
|
||||
|
||||
# Add title page
|
||||
await mcp.call("add_heading", {
|
||||
"document_id": doc_id,
|
||||
"text": f"{data['company_name']}",
|
||||
"level": 1
|
||||
})
|
||||
|
||||
await mcp.call("add_heading", {
|
||||
"document_id": doc_id,
|
||||
"text": f"Monthly Report - {datetime(year, month, 1).strftime('%B %Y')}",
|
||||
"level": 2
|
||||
})
|
||||
|
||||
await mcp.call("add_page_break", {"document_id": doc_id})
|
||||
|
||||
# Executive Summary
|
||||
await mcp.call("add_heading", {
|
||||
"document_id": doc_id,
|
||||
"text": "Executive Summary",
|
||||
"level": 1
|
||||
})
|
||||
|
||||
await mcp.call("add_paragraph", {
|
||||
"document_id": doc_id,
|
||||
"text": data["executive_summary"],
|
||||
"style": {
|
||||
"font_size": 12,
|
||||
"alignment": "justify"
|
||||
}
|
||||
})
|
||||
|
||||
# Key Metrics Table
|
||||
await mcp.call("add_heading", {
|
||||
"document_id": doc_id,
|
||||
"text": "Key Performance Indicators",
|
||||
"level": 2
|
||||
})
|
||||
|
||||
await mcp.call("add_table", {
|
||||
"document_id": doc_id,
|
||||
"rows": [
|
||||
["Metric", "Target", "Actual", "Variance"],
|
||||
["Revenue", f"${data['targets']['revenue']:,}", f"${data['actuals']['revenue']:,}",
|
||||
f"{((data['actuals']['revenue'] / data['targets']['revenue'] - 1) * 100):.1f}%"],
|
||||
["New Customers", str(data['targets']['customers']), str(data['actuals']['customers']),
|
||||
f"{data['actuals']['customers'] - data['targets']['customers']:+d}"],
|
||||
["Satisfaction Score", f"{data['targets']['satisfaction']}%", f"{data['actuals']['satisfaction']}%",
|
||||
f"{data['actuals']['satisfaction'] - data['targets']['satisfaction']:+.1f}%"]
|
||||
]
|
||||
})
|
||||
|
||||
# Department Reports
|
||||
for dept in data['departments']:
|
||||
await mcp.call("add_heading", {
|
||||
"document_id": doc_id,
|
||||
"text": f"{dept['name']} Department",
|
||||
"level": 2
|
||||
})
|
||||
|
||||
await mcp.call("add_paragraph", {
|
||||
"document_id": doc_id,
|
||||
"text": dept['summary']
|
||||
})
|
||||
|
||||
if dept.get('achievements'):
|
||||
await mcp.call("add_list", {
|
||||
"document_id": doc_id,
|
||||
"items": dept['achievements'],
|
||||
"ordered": False
|
||||
})
|
||||
|
||||
# Action Items
|
||||
await mcp.call("add_heading", {
|
||||
"document_id": doc_id,
|
||||
"text": "Action Items for Next Month",
|
||||
"level": 2
|
||||
})
|
||||
|
||||
await mcp.call("add_table", {
|
||||
"document_id": doc_id,
|
||||
"rows": [
|
||||
["Action", "Owner", "Due Date", "Priority"],
|
||||
*[[item['action'], item['owner'], item['due_date'], item['priority']]
|
||||
for item in data['action_items']]
|
||||
]
|
||||
})
|
||||
|
||||
# Add footer
|
||||
await mcp.call("set_footer", {
|
||||
"document_id": doc_id,
|
||||
"text": f"Confidential - {data['company_name']} - Page"
|
||||
})
|
||||
|
||||
# Save as DOCX
|
||||
filename = f"monthly_report_{year}_{month:02d}.docx"
|
||||
await mcp.call("save_document", {
|
||||
"document_id": doc_id,
|
||||
"output_path": f"./reports/{filename}"
|
||||
})
|
||||
|
||||
# Convert to PDF
|
||||
await mcp.call("convert_to_pdf", {
|
||||
"document_id": doc_id,
|
||||
"output_path": f"./reports/{filename.replace('.docx', '.pdf')}"
|
||||
})
|
||||
|
||||
# Generate thumbnail
|
||||
await mcp.call("convert_to_images", {
|
||||
"document_id": doc_id,
|
||||
"output_dir": "./reports/thumbnails/",
|
||||
"format": "png",
|
||||
"dpi": 72
|
||||
})
|
||||
|
||||
await mcp.call("close_document", {"document_id": doc_id})
|
||||
|
||||
return filename
|
||||
|
||||
# === Example 2: Mail Merge ===
|
||||
async def mail_merge(template_path: str, csv_path: str, output_dir: str):
|
||||
"""Perform mail merge with CSV data"""
|
||||
|
||||
# Read CSV data
|
||||
with open(csv_path, 'r') as f:
|
||||
reader = csv.DictReader(f)
|
||||
recipients = list(reader)
|
||||
|
||||
generated_files = []
|
||||
|
||||
for recipient in recipients:
|
||||
# Open template
|
||||
template = await mcp.call("open_document", {"path": template_path})
|
||||
doc_id = template["result"]["document_id"]
|
||||
|
||||
# Extract template text
|
||||
text_result = await mcp.call("extract_text", {"document_id": doc_id})
|
||||
text = text_result["result"]["text"]
|
||||
|
||||
# Replace placeholders
|
||||
for field, value in recipient.items():
|
||||
placeholder = f"{{{{{field}}}}}"
|
||||
if placeholder in text:
|
||||
await mcp.call("find_and_replace", {
|
||||
"document_id": doc_id,
|
||||
"find_text": placeholder,
|
||||
"replace_text": value
|
||||
})
|
||||
|
||||
# Save personalized document
|
||||
output_filename = f"{recipient.get('name', 'document').replace(' ', '_')}.docx"
|
||||
output_path = f"{output_dir}/{output_filename}"
|
||||
|
||||
await mcp.call("save_document", {
|
||||
"document_id": doc_id,
|
||||
"output_path": output_path
|
||||
})
|
||||
|
||||
# Convert to PDF
|
||||
pdf_path = output_path.replace('.docx', '.pdf')
|
||||
await mcp.call("convert_to_pdf", {
|
||||
"document_id": doc_id,
|
||||
"output_path": pdf_path
|
||||
})
|
||||
|
||||
generated_files.append({
|
||||
"recipient": recipient['name'],
|
||||
"docx": output_path,
|
||||
"pdf": pdf_path
|
||||
})
|
||||
|
||||
await mcp.call("close_document", {"document_id": doc_id})
|
||||
|
||||
# Create summary document
|
||||
summary = await mcp.call("create_document", {})
|
||||
summary_id = summary["result"]["document_id"]
|
||||
|
||||
await mcp.call("add_heading", {
|
||||
"document_id": summary_id,
|
||||
"text": "Mail Merge Summary",
|
||||
"level": 1
|
||||
})
|
||||
|
||||
await mcp.call("add_paragraph", {
|
||||
"document_id": summary_id,
|
||||
"text": f"Generated {len(generated_files)} documents on {datetime.now().strftime('%Y-%m-%d %H:%M')}"
|
||||
})
|
||||
|
||||
# Add summary table
|
||||
rows = [["Recipient", "DOCX File", "PDF File"]]
|
||||
for file_info in generated_files:
|
||||
rows.append([
|
||||
file_info['recipient'],
|
||||
file_info['docx'],
|
||||
file_info['pdf']
|
||||
])
|
||||
|
||||
await mcp.call("add_table", {
|
||||
"document_id": summary_id,
|
||||
"rows": rows
|
||||
})
|
||||
|
||||
await mcp.call("save_document", {
|
||||
"document_id": summary_id,
|
||||
"output_path": f"{output_dir}/merge_summary.docx"
|
||||
})
|
||||
|
||||
await mcp.call("close_document", {"document_id": summary_id})
|
||||
|
||||
return generated_files
|
||||
|
||||
# === Example 3: Document Pipeline ===
|
||||
async def document_processing_pipeline(input_dir: str):
|
||||
"""Process multiple documents through a pipeline"""
|
||||
|
||||
input_path = Path(input_dir)
|
||||
docx_files = list(input_path.glob("*.docx"))
|
||||
|
||||
results = []
|
||||
|
||||
for docx_file in docx_files:
|
||||
print(f"Processing {docx_file.name}...")
|
||||
|
||||
# Open document
|
||||
doc = await mcp.call("open_document", {"path": str(docx_file)})
|
||||
doc_id = doc["result"]["document_id"]
|
||||
|
||||
# Add watermark (header)
|
||||
await mcp.call("set_header", {
|
||||
"document_id": doc_id,
|
||||
"text": "DRAFT - CONFIDENTIAL"
|
||||
})
|
||||
|
||||
# Add footer with date
|
||||
await mcp.call("set_footer", {
|
||||
"document_id": doc_id,
|
||||
"text": f"Processed on {datetime.now().strftime('%Y-%m-%d')}"
|
||||
})
|
||||
|
||||
# Extract text for indexing
|
||||
text_result = await mcp.call("extract_text", {"document_id": doc_id})
|
||||
text = text_result["result"]["text"]
|
||||
word_count = len(text.split())
|
||||
|
||||
# Save modified document
|
||||
output_docx = f"./processed/{docx_file.stem}_processed.docx"
|
||||
await mcp.call("save_document", {
|
||||
"document_id": doc_id,
|
||||
"output_path": output_docx
|
||||
})
|
||||
|
||||
# Convert to PDF
|
||||
output_pdf = output_docx.replace('.docx', '.pdf')
|
||||
await mcp.call("convert_to_pdf", {
|
||||
"document_id": doc_id,
|
||||
"output_path": output_pdf
|
||||
})
|
||||
|
||||
# Generate thumbnail
|
||||
await mcp.call("convert_to_images", {
|
||||
"document_id": doc_id,
|
||||
"output_dir": "./processed/thumbnails/",
|
||||
"format": "jpg",
|
||||
"dpi": 96
|
||||
})
|
||||
|
||||
results.append({
|
||||
"original": docx_file.name,
|
||||
"word_count": word_count,
|
||||
"docx": output_docx,
|
||||
"pdf": output_pdf
|
||||
})
|
||||
|
||||
await mcp.call("close_document", {"document_id": doc_id})
|
||||
|
||||
# Create index document
|
||||
index = await mcp.call("create_document", {})
|
||||
index_id = index["result"]["document_id"]
|
||||
|
||||
await mcp.call("add_heading", {
|
||||
"document_id": index_id,
|
||||
"text": "Document Processing Report",
|
||||
"level": 1
|
||||
})
|
||||
|
||||
await mcp.call("add_paragraph", {
|
||||
"document_id": index_id,
|
||||
"text": f"Processed {len(results)} documents"
|
||||
})
|
||||
|
||||
# Statistics table
|
||||
rows = [["Original File", "Word Count", "Output DOCX", "Output PDF"]]
|
||||
for result in results:
|
||||
rows.append([
|
||||
result['original'],
|
||||
str(result['word_count']),
|
||||
result['docx'],
|
||||
result['pdf']
|
||||
])
|
||||
|
||||
await mcp.call("add_table", {
|
||||
"document_id": index_id,
|
||||
"rows": rows
|
||||
})
|
||||
|
||||
await mcp.call("save_document", {
|
||||
"document_id": index_id,
|
||||
"output_path": "./processed/index.docx"
|
||||
})
|
||||
|
||||
await mcp.call("close_document", {"document_id": index_id})
|
||||
|
||||
return results
|
||||
|
||||
# === Example 4: Contract Generator ===
|
||||
async def generate_contract(contract_type: str, parties: Dict[str, Any], terms: Dict[str, Any]):
|
||||
"""Generate a legal contract based on type and terms"""
|
||||
|
||||
doc = await mcp.call("create_document", {})
|
||||
doc_id = doc["result"]["document_id"]
|
||||
|
||||
# Title
|
||||
await mcp.call("add_heading", {
|
||||
"document_id": doc_id,
|
||||
"text": f"{contract_type.upper()} AGREEMENT",
|
||||
"level": 1
|
||||
})
|
||||
|
||||
# Date and parties
|
||||
await mcp.call("add_paragraph", {
|
||||
"document_id": doc_id,
|
||||
"text": f"This Agreement is entered into as of {terms['date']} between:"
|
||||
})
|
||||
|
||||
await mcp.call("add_list", {
|
||||
"document_id": doc_id,
|
||||
"items": [
|
||||
f"{parties['party1']['name']}, a {parties['party1']['type']} (\"Party 1\")",
|
||||
f"{parties['party2']['name']}, a {parties['party2']['type']} (\"Party 2\")"
|
||||
],
|
||||
"ordered": False
|
||||
})
|
||||
|
||||
# Terms sections
|
||||
section_num = 1
|
||||
for section_title, section_content in terms['sections'].items():
|
||||
await mcp.call("add_heading", {
|
||||
"document_id": doc_id,
|
||||
"text": f"{section_num}. {section_title}",
|
||||
"level": 2
|
||||
})
|
||||
|
||||
if isinstance(section_content, list):
|
||||
await mcp.call("add_list", {
|
||||
"document_id": doc_id,
|
||||
"items": section_content,
|
||||
"ordered": True
|
||||
})
|
||||
else:
|
||||
await mcp.call("add_paragraph", {
|
||||
"document_id": doc_id,
|
||||
"text": section_content
|
||||
})
|
||||
|
||||
section_num += 1
|
||||
|
||||
# Signature block
|
||||
await mcp.call("add_page_break", {"document_id": doc_id})
|
||||
await mcp.call("add_heading", {
|
||||
"document_id": doc_id,
|
||||
"text": "SIGNATURES",
|
||||
"level": 2
|
||||
})
|
||||
|
||||
signature_table = [
|
||||
["Party 1:", "", "Party 2:", ""],
|
||||
["", "", "", ""],
|
||||
["_" * 30, "", "_" * 30, ""],
|
||||
["Name:", parties['party1']['signatory'], "Name:", parties['party2']['signatory']],
|
||||
["Title:", parties['party1']['title'], "Title:", parties['party2']['title']],
|
||||
["Date:", "_" * 20, "Date:", "_" * 20]
|
||||
]
|
||||
|
||||
await mcp.call("add_table", {
|
||||
"document_id": doc_id,
|
||||
"rows": signature_table
|
||||
})
|
||||
|
||||
# Save and convert
|
||||
filename = f"{contract_type.lower().replace(' ', '_')}_{datetime.now().strftime('%Y%m%d')}"
|
||||
await mcp.call("save_document", {
|
||||
"document_id": doc_id,
|
||||
"output_path": f"./contracts/{filename}.docx"
|
||||
})
|
||||
|
||||
await mcp.call("convert_to_pdf", {
|
||||
"document_id": doc_id,
|
||||
"output_path": f"./contracts/{filename}.pdf"
|
||||
})
|
||||
|
||||
await mcp.call("close_document", {"document_id": doc_id})
|
||||
|
||||
return filename
|
||||
|
||||
# === Main execution ===
|
||||
async def main():
|
||||
"""Run example automations"""
|
||||
|
||||
print("Document Automation Examples")
|
||||
print("=" * 40)
|
||||
|
||||
# Example data for monthly report
|
||||
report_data = {
|
||||
"company_name": "TechCorp Industries",
|
||||
"executive_summary": "This month showed strong growth across all departments...",
|
||||
"targets": {"revenue": 1000000, "customers": 50, "satisfaction": 85},
|
||||
"actuals": {"revenue": 1150000, "customers": 62, "satisfaction": 88.5},
|
||||
"departments": [
|
||||
{
|
||||
"name": "Sales",
|
||||
"summary": "Sales exceeded targets by 15%",
|
||||
"achievements": ["Closed 3 enterprise deals", "Expanded into new market"]
|
||||
},
|
||||
{
|
||||
"name": "Engineering",
|
||||
"summary": "Delivered 2 major features on schedule",
|
||||
"achievements": ["Reduced bug count by 30%", "Improved performance by 25%"]
|
||||
}
|
||||
],
|
||||
"action_items": [
|
||||
{"action": "Hire 2 senior developers", "owner": "HR", "due_date": "2024-02-15", "priority": "High"},
|
||||
{"action": "Launch marketing campaign", "owner": "Marketing", "due_date": "2024-02-01", "priority": "Medium"}
|
||||
]
|
||||
}
|
||||
|
||||
# Generate monthly report
|
||||
print("\n1. Generating monthly report...")
|
||||
report_file = await generate_monthly_report(1, 2024, report_data)
|
||||
print(f" ✓ Generated: {report_file}")
|
||||
|
||||
# Contract generation
|
||||
print("\n2. Generating service agreement...")
|
||||
contract_file = await generate_contract(
|
||||
"Service Agreement",
|
||||
{
|
||||
"party1": {"name": "ABC Corp", "type": "corporation", "signatory": "John Smith", "title": "CEO"},
|
||||
"party2": {"name": "XYZ Ltd", "type": "limited company", "signatory": "Jane Doe", "title": "Director"}
|
||||
},
|
||||
{
|
||||
"date": "January 15, 2024",
|
||||
"sections": {
|
||||
"Scope of Services": "Party 2 agrees to provide consulting services...",
|
||||
"Payment Terms": ["Monthly fee of $10,000", "Payment due within 30 days", "Late fee of 1.5% per month"],
|
||||
"Term and Termination": "This agreement shall commence on the date first written above...",
|
||||
"Confidentiality": "Both parties agree to maintain strict confidentiality..."
|
||||
}
|
||||
}
|
||||
)
|
||||
print(f" ✓ Generated: {contract_file}")
|
||||
|
||||
print("\n✅ All automation examples completed!")
|
||||
|
||||
if __name__ == "__main__":
|
||||
# Create necessary directories
|
||||
for dir_path in ["./reports", "./reports/thumbnails", "./contracts", "./processed", "./processed/thumbnails"]:
|
||||
Path(dir_path).mkdir(parents=True, exist_ok=True)
|
||||
|
||||
# Run examples
|
||||
asyncio.run(main())
|
||||
@@ -0,0 +1,166 @@
|
||||
# Claude Desktop Examples
|
||||
|
||||
These are real examples you can use with Claude Desktop once the DOCX MCP server is configured.
|
||||
|
||||
## Basic Document Creation
|
||||
|
||||
```
|
||||
You: Create a new Word document with a professional letterhead for "Acme Corp" and save it as letterhead.docx
|
||||
```
|
||||
|
||||
Claude will create a document with:
|
||||
- Company name as heading
|
||||
- Address and contact details
|
||||
- Professional formatting
|
||||
- Save to the specified file
|
||||
|
||||
## Invoice Generation
|
||||
|
||||
```
|
||||
You: Generate an invoice for client "TechStart Inc" with these items:
|
||||
- 10 hours consulting at $150/hour
|
||||
- 1 software license at $500
|
||||
- Add 10% tax
|
||||
Save as invoice_2024_001.docx and convert to PDF
|
||||
```
|
||||
|
||||
## Batch Processing
|
||||
|
||||
```
|
||||
You: I have 5 DOCX files in the ./reports folder. Please:
|
||||
1. Add page numbers to each
|
||||
2. Set the header to "Confidential - Internal Use Only"
|
||||
3. Convert all to PDF
|
||||
4. Create a summary document listing all reports
|
||||
```
|
||||
|
||||
## Data-Driven Documents
|
||||
|
||||
```
|
||||
You: Create a sales report from this data:
|
||||
Q1: $1.2M (15% growth)
|
||||
Q2: $1.5M (25% growth)
|
||||
Q3: $1.3M (8% growth)
|
||||
Q4: $1.8M (38% growth)
|
||||
|
||||
Include:
|
||||
- Executive summary
|
||||
- Quarterly breakdown table
|
||||
- Year-over-year comparison
|
||||
- Recommendations section
|
||||
Convert to PDF when done
|
||||
```
|
||||
|
||||
## Template Operations
|
||||
|
||||
```
|
||||
You: Open template.docx and replace these placeholders:
|
||||
- {{CLIENT_NAME}} with "John Smith"
|
||||
- {{DATE}} with today's date
|
||||
- {{PROJECT}} with "Website Redesign"
|
||||
- {{AMOUNT}} with "$5,000"
|
||||
Save as contract_john_smith.docx
|
||||
```
|
||||
|
||||
## Document Merging
|
||||
|
||||
```
|
||||
You: Merge these documents in order:
|
||||
1. cover_page.docx
|
||||
2. executive_summary.docx
|
||||
3. main_report.docx
|
||||
4. appendix.docx
|
||||
|
||||
Add page numbers and a table of contents, then save as final_report.docx
|
||||
```
|
||||
|
||||
## Text Extraction and Analysis
|
||||
|
||||
```
|
||||
You: Extract all text from the documents in ./legal folder and:
|
||||
1. Find all mentions of "liability"
|
||||
2. Create a summary document with each mention and its context
|
||||
3. Add a table showing which document contains which terms
|
||||
```
|
||||
|
||||
## Report Formatting
|
||||
|
||||
```
|
||||
You: Format this markdown content as a professional Word document:
|
||||
|
||||
# Project Status Report
|
||||
## Overview
|
||||
Project is on track...
|
||||
## Milestones
|
||||
- [x] Phase 1 complete
|
||||
- [ ] Phase 2 in progress
|
||||
## Budget
|
||||
Current spend: $45,000 of $100,000
|
||||
|
||||
Add proper styling, convert checkboxes to a status table, and export as PDF.
|
||||
```
|
||||
|
||||
## Document Comparison
|
||||
|
||||
```
|
||||
You: Open contract_v1.docx and contract_v2.docx, then:
|
||||
1. Extract text from both
|
||||
2. Create a new document highlighting the differences
|
||||
3. Add a summary table of all changes
|
||||
4. Save as contract_comparison.docx
|
||||
```
|
||||
|
||||
## Automated Documentation
|
||||
|
||||
```
|
||||
You: Create API documentation from this OpenAPI spec file (api.yaml):
|
||||
1. Generate a Word document with proper formatting
|
||||
2. Include endpoint descriptions in a table
|
||||
3. Add request/response examples
|
||||
4. Create a PDF version for distribution
|
||||
```
|
||||
|
||||
## Meeting Minutes Template
|
||||
|
||||
```
|
||||
You: Create a meeting minutes template with:
|
||||
- Company header
|
||||
- Date, time, attendees fields
|
||||
- Agenda items section
|
||||
- Action items table with owner and due date columns
|
||||
- Next meeting section
|
||||
Save as meeting_template.docx
|
||||
```
|
||||
|
||||
## Bulk Conversion
|
||||
|
||||
```
|
||||
You: Convert all Word documents in my Downloads folder to:
|
||||
1. PDF files in ./pdfs folder
|
||||
2. PNG images (first page only) in ./thumbnails folder
|
||||
3. Create an index.docx with links to all documents
|
||||
```
|
||||
|
||||
## Complex Formatting
|
||||
|
||||
```
|
||||
You: Create a technical specification document with:
|
||||
1. Title page with document version and date
|
||||
2. Table of contents (auto-generated)
|
||||
3. Multiple heading levels
|
||||
4. Code blocks with syntax highlighting effect
|
||||
5. Diagrams placeholder sections
|
||||
6. Numbered requirements list
|
||||
7. Glossary table at the end
|
||||
8. Footer with page numbers
|
||||
```
|
||||
|
||||
## Mail Merge Simulation
|
||||
|
||||
```
|
||||
You: I have a CSV with client data (clients.csv). For each client:
|
||||
1. Create a personalized letter using template.docx
|
||||
2. Replace all placeholders with client data
|
||||
3. Save as PDF with client name in filename
|
||||
4. Create a summary document listing all generated files
|
||||
```
|
||||
@@ -0,0 +1,144 @@
|
||||
{
|
||||
"claude_desktop": {
|
||||
"description": "Claude Desktop configuration",
|
||||
"file_location_macos": "~/Library/Application Support/Claude/claude_desktop_config.json",
|
||||
"file_location_windows": "%APPDATA%\\Claude\\claude_desktop_config.json",
|
||||
"config": {
|
||||
"mcpServers": {
|
||||
"docx": {
|
||||
"command": "/absolute/path/to/docx-mcp/target/release/docx-mcp",
|
||||
"args": [],
|
||||
"env": {
|
||||
"RUST_LOG": "info"
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
},
|
||||
"cursor": {
|
||||
"description": "Cursor IDE configuration",
|
||||
"file_location": "~/.cursor/config.json or Settings UI",
|
||||
"config": {
|
||||
"mcp": {
|
||||
"servers": {
|
||||
"docx": {
|
||||
"command": "/absolute/path/to/docx-mcp/target/release/docx-mcp",
|
||||
"args": [],
|
||||
"env": {
|
||||
"RUST_LOG": "info"
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
},
|
||||
"windsurf": {
|
||||
"description": "Windsurf (Codeium) configuration",
|
||||
"file_location": "~/.windsurf/config.json",
|
||||
"config": {
|
||||
"mcp": {
|
||||
"servers": {
|
||||
"docx": {
|
||||
"command": "/absolute/path/to/docx-mcp/target/release/docx-mcp",
|
||||
"args": [],
|
||||
"env": {
|
||||
"RUST_LOG": "info"
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
},
|
||||
"continue_dev": {
|
||||
"description": "Continue.dev configuration",
|
||||
"file_location": "~/.continue/config.json",
|
||||
"config": {
|
||||
"models": [
|
||||
{
|
||||
"title": "Claude 3.5 Sonnet",
|
||||
"provider": "anthropic",
|
||||
"model": "claude-3-5-sonnet-20241022",
|
||||
"apiKey": "your-api-key",
|
||||
"mcp_servers": {
|
||||
"docx": {
|
||||
"command": "/absolute/path/to/docx-mcp/target/release/docx-mcp",
|
||||
"args": []
|
||||
}
|
||||
}
|
||||
}
|
||||
]
|
||||
}
|
||||
},
|
||||
"vscode_mcp": {
|
||||
"description": "VS Code with MCP Extension",
|
||||
"file_location": ".vscode/settings.json",
|
||||
"config": {
|
||||
"mcp.servers": {
|
||||
"docx": {
|
||||
"command": "/absolute/path/to/docx-mcp/target/release/docx-mcp",
|
||||
"args": [],
|
||||
"env": {
|
||||
"RUST_LOG": "info"
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
},
|
||||
"zed": {
|
||||
"description": "Zed editor configuration",
|
||||
"file_location": "~/.config/zed/settings.json",
|
||||
"config": {
|
||||
"assistant": {
|
||||
"mcp_servers": {
|
||||
"docx": {
|
||||
"command": "/absolute/path/to/docx-mcp/target/release/docx-mcp",
|
||||
"args": [],
|
||||
"env": {
|
||||
"RUST_LOG": "info"
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
},
|
||||
"neovim": {
|
||||
"description": "Neovim with MCP support",
|
||||
"file_location": "~/.config/nvim/mcp.json",
|
||||
"config": {
|
||||
"servers": {
|
||||
"docx": {
|
||||
"command": "/absolute/path/to/docx-mcp/target/release/docx-mcp",
|
||||
"args": [],
|
||||
"env": {
|
||||
"RUST_LOG": "info"
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
},
|
||||
"multiple_servers_example": {
|
||||
"description": "Example with multiple MCP servers",
|
||||
"config": {
|
||||
"mcpServers": {
|
||||
"docx": {
|
||||
"command": "/path/to/docx-mcp/target/release/docx-mcp",
|
||||
"args": [],
|
||||
"env": {
|
||||
"RUST_LOG": "info"
|
||||
}
|
||||
},
|
||||
"filesystem": {
|
||||
"command": "/path/to/filesystem-mcp",
|
||||
"args": ["--root", "/home/user/documents"]
|
||||
},
|
||||
"github": {
|
||||
"command": "/path/to/github-mcp",
|
||||
"args": [],
|
||||
"env": {
|
||||
"GITHUB_TOKEN": "ghp_..."
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
Executable
+160
@@ -0,0 +1,160 @@
|
||||
#!/usr/bin/env python3
|
||||
"""
|
||||
Example client to test the DOCX MCP Server.
|
||||
This demonstrates how to interact with the server using JSON-RPC.
|
||||
"""
|
||||
|
||||
import json
|
||||
import sys
|
||||
import asyncio
|
||||
import websockets
|
||||
|
||||
async def call_tool(websocket, tool_name, arguments):
|
||||
"""Call a tool on the MCP server"""
|
||||
request = {
|
||||
"jsonrpc": "2.0",
|
||||
"method": "tools/call",
|
||||
"params": {
|
||||
"name": tool_name,
|
||||
"arguments": arguments
|
||||
},
|
||||
"id": 1
|
||||
}
|
||||
|
||||
await websocket.send(json.dumps(request))
|
||||
response = await websocket.recv()
|
||||
return json.loads(response)
|
||||
|
||||
async def main():
|
||||
# Connect to the MCP server (adjust the URI as needed)
|
||||
uri = "ws://localhost:3000" # Default MCP server port
|
||||
|
||||
async with websockets.connect(uri) as websocket:
|
||||
print("Connected to DOCX MCP Server")
|
||||
|
||||
# Example 1: Create a new document
|
||||
print("\n1. Creating new document...")
|
||||
result = await call_tool(websocket, "create_document", {})
|
||||
doc_id = result["result"]["document_id"]
|
||||
print(f" Document created with ID: {doc_id}")
|
||||
|
||||
# Example 2: Add a heading
|
||||
print("\n2. Adding heading...")
|
||||
result = await call_tool(websocket, "add_heading", {
|
||||
"document_id": doc_id,
|
||||
"text": "Sample Document",
|
||||
"level": 1
|
||||
})
|
||||
print(" Heading added")
|
||||
|
||||
# Example 3: Add a paragraph with styling
|
||||
print("\n3. Adding styled paragraph...")
|
||||
result = await call_tool(websocket, "add_paragraph", {
|
||||
"document_id": doc_id,
|
||||
"text": "This is a sample paragraph with custom styling.",
|
||||
"style": {
|
||||
"font_size": 14,
|
||||
"bold": True,
|
||||
"color": "#0066CC",
|
||||
"alignment": "center"
|
||||
}
|
||||
})
|
||||
print(" Styled paragraph added")
|
||||
|
||||
# Example 4: Add a table
|
||||
print("\n4. Adding table...")
|
||||
result = await call_tool(websocket, "add_table", {
|
||||
"document_id": doc_id,
|
||||
"rows": [
|
||||
["Product", "Price", "Quantity"],
|
||||
["Widget A", "$10.99", "100"],
|
||||
["Widget B", "$15.99", "75"],
|
||||
["Widget C", "$8.99", "150"]
|
||||
]
|
||||
})
|
||||
print(" Table added")
|
||||
|
||||
# Example 5: Add a numbered list
|
||||
print("\n5. Adding numbered list...")
|
||||
result = await call_tool(websocket, "add_list", {
|
||||
"document_id": doc_id,
|
||||
"items": [
|
||||
"First item in the list",
|
||||
"Second item with more text",
|
||||
"Third and final item"
|
||||
],
|
||||
"ordered": True
|
||||
})
|
||||
print(" Numbered list added")
|
||||
|
||||
# Example 6: Set header and footer
|
||||
print("\n6. Setting header and footer...")
|
||||
result = await call_tool(websocket, "set_header", {
|
||||
"document_id": doc_id,
|
||||
"text": "Sample Document Header"
|
||||
})
|
||||
result = await call_tool(websocket, "set_footer", {
|
||||
"document_id": doc_id,
|
||||
"text": "Page 1 | Confidential"
|
||||
})
|
||||
print(" Header and footer set")
|
||||
|
||||
# Example 7: Save the document
|
||||
print("\n7. Saving document...")
|
||||
result = await call_tool(websocket, "save_document", {
|
||||
"document_id": doc_id,
|
||||
"output_path": "./sample_output.docx"
|
||||
})
|
||||
print(" Document saved to sample_output.docx")
|
||||
|
||||
# Example 8: Convert to PDF
|
||||
print("\n8. Converting to PDF...")
|
||||
result = await call_tool(websocket, "convert_to_pdf", {
|
||||
"document_id": doc_id,
|
||||
"output_path": "./sample_output.pdf"
|
||||
})
|
||||
if result["result"]["success"]:
|
||||
print(" Document converted to PDF")
|
||||
else:
|
||||
print(f" PDF conversion failed: {result['result'].get('error', 'Unknown error')}")
|
||||
|
||||
# Example 9: Convert to images
|
||||
print("\n9. Converting to images...")
|
||||
result = await call_tool(websocket, "convert_to_images", {
|
||||
"document_id": doc_id,
|
||||
"output_dir": "./images/",
|
||||
"format": "png",
|
||||
"dpi": 150
|
||||
})
|
||||
if result["result"]["success"]:
|
||||
print(f" Document converted to images: {result['result']['images']}")
|
||||
else:
|
||||
print(f" Image conversion failed: {result['result'].get('error', 'Unknown error')}")
|
||||
|
||||
# Example 10: Extract text
|
||||
print("\n10. Extracting text...")
|
||||
result = await call_tool(websocket, "extract_text", {
|
||||
"document_id": doc_id
|
||||
})
|
||||
text = result["result"]["text"]
|
||||
print(f" Extracted text (first 100 chars): {text[:100]}...")
|
||||
|
||||
# Example 11: Get metadata
|
||||
print("\n11. Getting metadata...")
|
||||
result = await call_tool(websocket, "get_metadata", {
|
||||
"document_id": doc_id
|
||||
})
|
||||
metadata = result["result"]["metadata"]
|
||||
print(f" Document metadata: {json.dumps(metadata, indent=2)}")
|
||||
|
||||
# Example 12: Close the document
|
||||
print("\n12. Closing document...")
|
||||
result = await call_tool(websocket, "close_document", {
|
||||
"document_id": doc_id
|
||||
})
|
||||
print(" Document closed")
|
||||
|
||||
print("\n✅ All tests completed successfully!")
|
||||
|
||||
if __name__ == "__main__":
|
||||
asyncio.run(main())
|
||||
Reference in New Issue
Block a user