MCP Purchase Order Agent
Provides email monitoring and automation: fetches unread Gmail emails with attachments and sends purchase order or custom response emails with attachments to suppliers.
This server does not currently have a deployable release on Glama. Follow the repository's setup instructions to install and configure it for your MCP client, including any required credentials and local dependencies.
MCP Purchase Order Agent
A comprehensive Model Context Protocol (MCP) server for automated purchase order management, processing, and workflow automation. This server provides a complete suite of tools for handling purchase orders from email monitoring to document generation and database management.
π Features
Core Capabilities
π§ Email Monitoring: Automatically fetch and process purchase orders from Gmail
π Document Processing: OCR and AI-powered extraction of purchase order data from PDFs
π Document Generation: Create professional PDF purchase orders using LaTeX
π¦ Inventory Management: Track stock levels and identify restock needs
π° Financial Validation: Automated approval workflows and budget checking
ποΈ Database Management: Store and retrieve purchase order records in MongoDB
βοΈ Email Automation: Send professional purchase order emails with attachments
π Queue Management: Manage purchase request workflows
π Report Generation: Create and save inventory and status reports
Available Tools
generate_purchase_order - Generate PDF purchase order documents
generate_latex_po - Generate LaTeX purchase order documents
validate_po_items - Validate purchase order items format
create_sample_po_data - Create sample purchase order data for testing
fetch_emails - Fetch unread emails with attachments from Gmail
parse_document - Parse documents and extract structured purchase order data
get_financial_data - Get financial data and approval status
manage_purchase_queue - Manage purchase request queue operations
manage_po_records - Execute PO record management actions
generate_po_email - Generate and send purchase order emails to suppliers
analyze_inventory - Analyze inventory and get restock information
save_report - Save data to text files
send_response_email - Send email responses with custom subject and body
Related MCP server: idin9-doc-ocr-mcp
π Prerequisites
Python 3.11+
MongoDB (running on localhost:27017)
LaTeX distribution (for PDF generation)
Gmail account with app-specific password
Google AI API key (for document processing)
π οΈ Installation
1. Clone and Setup
# Clone the repository
git clone <repository-url>
cd MCP_PurchaseOrderFlow
# Create virtual environment (recommended)
python -m venv .venv
# On Windows
.venv\Scripts\activate
# On macOS/Linux
source .venv/bin/activate2. Install Dependencies
# Install with uv (recommended)
uv sync
# Or with pip
pip install -e .3. Environment Configuration
Create a .env file in the project root:
# Gmail Configuration (Buyer/Company Email)
GMAIL_EMAIL=buyer@company.com
GMAIL_APP_PASSWORD=your-16-character-app-password
email=buyer@company.com
password=your-16-character-app-password
# Supplier Email Configuration
supemail=supplier@example.com
suppassword=supplier-app-password
# Google AI Configuration
GOOGLE_API_KEY=your-google-ai-api-key
# MongoDB Configuration (optional, defaults shown)
MONGODB_URI=mongodb://localhost:27017
MONGODB_DATABASE=purchase_orders
# Server Configuration
MCP_SERVER_PORT=8099
TRANSPORT_MODE=stdio # Options: stdio, sse, streamable-http
# Company Information
COMPANY_NAME=Your Company Name
COMPANY_ADDRESS=Your Company Address
COMPANY_EMAIL=company@example.comEnvironment Variables Explained
Email Configuration
GMAIL_EMAIL / email: Your company's buyer email address (Gmail account)
GMAIL_APP_PASSWORD / password: Gmail app-specific password (16-character code)
supemail: Supplier's email address for communications
suppassword: Supplier's email app-specific password (if needed)
API Keys
GOOGLE_API_KEY: Your Google AI/Gemini API key for document processing
How to Get Gmail App Password
Enable 2-Factor Authentication on your Gmail account
Go to Google Account settings β Security β 2-Step Verification
Select "App passwords" at the bottom
Generate a new app password for "Mail"
Use the 16-character code (no spaces) as your app password
How to Get Google AI API Key
Visit Google AI Studio
Sign in with your Google account
Click "Create API Key"
Copy the generated API key
4. External Dependencies
MongoDB Setup
# Install MongoDB Community Edition
# Visit: https://www.mongodb.com/try/download/community
# Start MongoDB service
# Windows: Start as Windows Service
# macOS: brew services start mongodb-community
# Linux: sudo systemctl start mongodLaTeX Setup
# Windows (MiKTeX)
# Download from: https://miktex.org/download
# macOS (MacTeX)
brew install --cask mactex
# Ubuntu/Debian
sudo apt-get install texlive-full
# Arch Linux
sudo pacman -S texlive-mostπ Usage
Running the MCP Server
Option 1: Standard I/O Transport (Default)
python mcppoagent.pyOption 2: SSE Transport (HTTP)
# Set environment variable
export TRANSPORT_MODE=sse
python mcppoagent.pyOption 3: StreamableHTTP Transport
# Set environment variable
export TRANSPORT_MODE=streamable-http
python mcppoagent.pyπ Tool Documentation
Email & Document Processing
fetch_emails()
Fetches unread emails with attachments from Gmail inbox.
# Returns JSON with emails containing attachments
result = await fetch_emails()parse_document(file_path, action="extract_po_data")
Parses documents and extracts structured purchase order data.
# Extract PO data from PDF
result = await parse_document("/path/to/po.pdf", "extract_po_data")Purchase Order Generation
generate_purchase_order(supplier_name, items, **kwargs)
Generates PDF purchase order documents.
items = [
{
"item_code": "ITM001",
"description": "Widget A",
"quantity": 100,
"unit_price": 25.50,
"uom": "pcs",
"urgency": "high"
}
]
result = await generate_purchase_order("ABC Suppliers", items)generate_latex_po(supplier_name, items, **kwargs)
Generates LaTeX purchase order documents.
result = await generate_latex_po(
"ABC Suppliers",
items,
delivery_date="2025-08-15",
contact_email="supplier@example.com"
)Inventory & Financial Management
analyze_inventory(analysis_type, category="", urgency_level="all")
Analyzes inventory and provides restock information.
# Check items needing restock
result = await analyze_inventory("restock_needed", urgency_level="critical")get_financial_data(query_type, amount=0.0)
Gets financial data and approval status.
# Check approval limits
result = await get_financial_data("approval_limits", 5000.0)Queue & Record Management
manage_purchase_queue(action, request_data=None, request_id=None)
Manages purchase request queue operations.
# Add to queue
result = await manage_purchase_queue("add_to_queue", request_data)
# Get pending requests
result = await manage_purchase_queue("get_pending")manage_po_records(action, **kwargs)
Manages PO record database operations.
# Record a single PO
result = await manage_po_records("record_single_po", po_data=po_data)Email Communication
generate_po_email(action, supplier_email, supplier_name, **kwargs)
Generates and sends purchase order emails.
result = await generate_po_email(
"send_po_email",
"supplier@example.com",
"ABC Suppliers",
po_number="PO-001",
po_file_path="/path/to/po.pdf"
)send_response_email(subject, body, recipient_email, **kwargs)
Sends custom email responses.
result = await send_response_email(
"PO Confirmation",
"Your purchase order has been received.",
"supplier@example.com"
)Utilities
validate_po_items(items)
Validates purchase order items format.
result = await validate_po_items(items)create_sample_po_data(item_count=3, supplier_name="ABC Suppliers")
Creates sample purchase order data for testing.
result = await create_sample_po_data(5, "Test Supplier")save_report(file_path, data, **kwargs)
Saves data to text files.
result = await save_report("/path/to/report.txt", report_data, append=True)π§ Configuration Options
Server Configuration
Port: Set via
portparameter in FastMCP constructor (default: 8099)Transport: Configure via
TRANSPORT_MODEenvironment variableDebug: Enable debug mode for development
Email Configuration
Gmail Integration: Requires app-specific password
Email Templates: Customizable email templates for different scenarios
Attachment Handling: Automatic PDF attachment processing
Database Configuration
MongoDB: Default connection to localhost:27017
Collections: Automatic collection creation for PO records
Indexing: Optimized indexes for query performance
Document Processing
OCR Engine: PaddleOCR for text extraction
AI Processing: Google Generative AI for data extraction
LaTeX: Full LaTeX document generation support
π‘οΈ Security Considerations
Environment Variables: Store sensitive data in
.envfileGmail App Passwords: Use app-specific passwords, not account passwords
API Keys: Secure storage of Google AI API keys
Database Access: Configure MongoDB authentication in production
File Permissions: Ensure proper file system permissions
π§ͺ Testing
Sample Data Generation
# Generate test data
result = await create_sample_po_data(3, "Test Supplier")
# Validate generated items
result = await validate_po_items(sample_items)Manual Testing
# Test email fetching
emails = await fetch_emails()
# Test document parsing
parsed = await parse_document("test_po.pdf")
# Test PO generation
po = await generate_purchase_order("Test Corp", sample_items)π Troubleshooting
Common Issues
MongoDB Connection Errors
# Check MongoDB status
mongosh --eval "db.adminCommand('ismaster')"
# Restart MongoDB service
sudo systemctl restart mongodGmail Authentication Errors
Verify app-specific password is correct
Ensure 2FA is enabled on Gmail account
Check GMAIL_EMAIL and GMAIL_APP_PASSWORD environment variables
LaTeX Compilation Errors
# Test LaTeX installation
pdflatex --version
# Install missing packages (MiKTeX)
miktex packages install <package-name>OCR Processing Issues
Ensure sufficient system memory for PaddleOCR
Verify image/PDF file accessibility
Check Google AI API key validity
Debug Mode
# Enable debug logging
import logging
logging.basicConfig(level=logging.DEBUG)π API Reference
Response Format
All tools return JSON-formatted strings with consistent structure:
{
"status": "success|error",
"message": "Descriptive message",
"data": { /* Tool-specific data */ },
"metadata": { /* Additional information */ }
}Error Handling
Validation Errors: Detailed field-level validation messages
System Errors: Graceful error handling with user-friendly messages
Retry Logic: Automatic retries for transient failures
π€ Contributing
Fork the repository
Create a feature branch:
git checkout -b feature/new-featureMake changes and add tests
Commit changes:
git commit -am 'Add new feature'Push to branch:
git push origin feature/new-featureSubmit a pull request
π License
This project is licensed under the MIT License - see the LICENSE file for details.
π Support
For support and questions:
Create an issue on GitHub
Check the troubleshooting section
Review the API documentation
π Version History
v0.1.0: Initial release with core PO management features
Features: Email monitoring, document processing, PO generation, inventory management
Note: This MCP server is designed to work with Model Context Protocol clients. Ensure your client supports MCP specification v0.1.0 or later.
Tool Schema Changelog
Recent tool additions, removals, and schema changes observed during successful MCP inspections.
Loading tool schema changelogβ¦
This server cannot be deployed
Maintenance
Related MCP Connectors
Receipt ingestion, Gmail capture, expense analysis, and reviewed reports for AI-agent workflows.
Quote-to-cash tools: parse invoices and POs, match POs to invoices, collection emails, billing math.
Extract PDFs into structured tables, query records, and configure document inbox workflows.
Invoice and receipt extractor: reads PDF and image invoices/receipts with AI, pulling dateβ¦
Related MCP Servers
- FlicenseNot gradedqualityDmaintenanceProduction-grade Google services integration (Gmail, Calendar, Drive, Sheets, Keep) with intelligent multi-provider LLM fallback system, featuring automated email categorization, calendar management, and job application tracking.-
- AlicenseBqualityDmaintenanceEnables automated OCR and Thai tax invoice processing from PDFs and scanned images, including parsing key invoice fields, three-tier routing, SQLite storage, and human review workflows via MCP tools.9MIT
- FlicenseNot gradedqualityCmaintenanceEnables automated invoice generation from structured orders, PDF creation, and uploads to Google Drive, while also exposing MCP tools for Google Sheets operations and WhatsApp messaging.-
- AlicenseNot gradedqualityCmaintenanceEnables natural-language-driven purchase-to-pay workflows against mock procurement and payment APIs, including invoice matching, exception handling, human approvals, and idempotent payment scheduling with a tamper-evident audit log.MIT