Leopards Courier MCP
# Leopards Courier MCP
An **unofficial, self-hosted Model Context Protocol server** for Leopards Courier Pakistan eCommerce merchant accounts. Use natural language to track consignments, retrieve COD payment records, inspect shipping charges, and (when explicitly enabled) book and manage shipments.
**Status:** v0.2.0 pre-release — offline tests pass; mandatory SDK, package build, dependency audit and live staging validation are not yet complete. Do not deploy for production. Not affiliated with Leopards Courier. No live carrier or MCP client interoperability certification. Each merchant supplies their own credentials; this is not a shared hosted service.
## Features
- 21 typed MCP tools for tracking, booking, invoices, rates, shipper advice and merchant operations.
- Local stdio and private Streamable HTTP (`/mcp`) using the official Python MCP SDK v1.
- Read-only and staging defaults; explicit confirmation and opt-in for mutations, plus separate production write opt-in. Durable local booking reservations prevent repeat bookings through the same journal.
- No automatic retries or redirects; request timeouts and bounded response sizes.
- Optional authenticated, deduplicating status push webhook with SQLite persistence.
- Synthetic tests, CI workflow, MIT license and security policy.
## Quick start
Requirements: Python 3.10–3.13, a Leopards eCommerce merchant account and API credentials. Generate your API key and password under **API Settings → API Management** in the merchant portal. Request separate staging credentials if needed.
After obtaining the source, run:
```bash
cd leopards-courier-mcp
python3 -m venv .venv
source .venv/bin/activate # Windows: .venv\Scripts\activate
python -m pip install -e '.[dev,webhook]'
```
Configure the following in your shell or secret manager. `.env.example` documents the settings but is not automatically loaded. On Windows use PowerShell `$env:NAME = 'value'`. Do not place real credentials in shell history, screenshots, chat messages or repository files.
```bash
read -r -s -p 'Merchant API key: ' LCS_API_KEY; echo
read -r -s -p 'Merchant API password: ' LCS_API_PASSWORD; echo
export LCS_API_KEY LCS_API_PASSWORD
export LCS_ENV=staging
export LCS_ALLOW_WRITES=false
leopards-mcp
```
The command starts an MCP stdio server, not an interactive shell. Configure an MCP client to start that executable with the secret environment inherited from the client or secret manager. Example local client configuration (replace the absolute path; exact config format depends on the client):
```json
{
"mcpServers": {
"leopards-courier": {
"command": "/absolute/path/leopards-courier-mcp/.venv/bin/leopards-mcp",
"args": ["--transport", "stdio"]
}
}
}
```
GUI applications may not inherit terminal variables. Inject secrets using the client's secure environment configuration or a local secret-manager launcher; do not commit the launcher or secret values.
### Connect to ChatGPT
1. Start `leopards-mcp --transport streamable-http` (local endpoint `http://127.0.0.1:8000/mcp`).
2. Use a supported private access mechanism, such as [OpenAI Secure MCP Tunnel](https://developers.openai.com/api/docs/guides/secure-mcp-tunnels), or an authenticated MCP gateway over HTTPS. Do **not** expose the bare HTTP listener publicly. The project does not implement an OAuth authorization server.
3. In a supported ChatGPT account, use Plugins → Add custom MCP server and select the private connection or authenticated server URL. See [OpenAI setup and eligibility](https://help.openai.com/en/articles/12584461-connecting-custom-mcp-servers-in-chatgpt).
4. Test `list_cities`, then `track_shipments` with a known staging CN. Check results against the merchant portal. Enable production only after validating responses.
Full custom MCP write support depends on account/workspace eligibility. Installing this repository alone does not grant ChatGPT plan access or deploy a server.
### Example requests
- “Track these three consignment numbers and summarize their latest statuses.”
- “Find consignments booked against order DEMO-001.”
- “Show COD payment references and billed shipping charges for these CNs.”
- “List invoice records and identify which shipments need reconciliation.”
- “Show the quote for 500g from the selected origin city to the destination city.”
- “Prepare a shipment booking. Show the fields and ask for approval before booking.”
## Tool reference
| Tool | Mode | Merchant API operation |
| --- | --- | --- |
| `list_cities` | Read | getAllCities |
| `track_shipments` | Read | trackBookedPacket |
| `shipment_statuses` | Read | getBookedPacketLastStatus |
| `shipments_by_order_id` | Read | getShipmentDetailsByOrderID |
| `payment_details` | Read | getPaymentDetails |
| `shipping_charges` | Read | getShippingCharges |
| `tariff_quote` | Read | getTariffDetails |
| `list_invoices` | Read | getInvoices |
| `list_banks` | Read | getBankList |
| `shipper_details` | Read | getShipperDetails |
| `proof_of_delivery` | Read | getElectronicProofOfDelivery |
| `load_sheet_details` | Read | downloadLoadSheet (JSON) |
| `shipper_advice_by_date` | Read | shipperAdviceList (older filter schema) |
| `shipper_advice_list` | Read | shipperAdviceList (paginated filter schema) |
| `activity_log` | Read | activityLog |
| `book_shipment` | Write | bookPacket |
| `batch_book_shipments` | Write | configurable batch endpoint |
| `cancel_shipments` | Write | cancelBookedPackets |
| `generate_load_sheet` | Write | generateLoadSheet |
| `create_shipper` | Write | createShipper |
| `update_shipper_advice` | Write | updateShipperAdvice |
## Configuration
| Variable | Default | Meaning |
| --- | --- | --- |
| `LCS_API_KEY` | required | Merchant credential |
| `LCS_API_PASSWORD` | required | Merchant credential |
| `LCS_ENV` | staging | `staging` or `production` |
| `LCS_ALLOW_WRITES` | false | Exact `true` enables write tools; each also requires `confirm=true` |
| `LCS_ALLOW_PRODUCTION_WRITES` | false | Additional explicit `true` required for production writes |
| `LCS_BOOKING_JOURNAL` | unset | Required private persistent SQLite path for single and batch bookings |
| `LCS_BATCH_ENDPOINT` | unset | Exact batch API name confirmed by carrier |
| `LCS_WEBHOOK_SECRET` | required for webhook | Random shared secret, at least 32 characters |
| `LCS_WEBHOOK_HEADER` | X-LCS-Webhook-Secret | Agreed custom authentication header |
| `LCS_WEBHOOK_DB` | events.sqlite3 | Private persistent SQLite file |
For mutations, verify the existing order first, present all consequential details to the operator, and obtain approval. The carrier does not document idempotency keys. The confirmation argument is an extra safety gate, not evidence of approval; use client-level approval controls. After an uncertain response, use `shipments_by_order_id`, tracking or the portal before retrying. Local limits: 50 CNs per request, 25 batch bookings/advice updates, 31 calendar days per date range, 100 paginated advice records. The local booking model requires an order ID to improve reconciliation. Bookings reserve order IDs in a private local SQLite journal before making the request. All workers for the same merchant must share the same persistent file. An order remains reserved even after a timeout, rejection or crash; do not delete the journal, rotate credentials to bypass it, or change order IDs to replay an uncertain write. Reconcile manually with Leopards before deciding how to resolve an exceptional reservation. The guard does not detect earlier portal bookings, bookings through other systems, different API keys, separate journals or different merchant order IDs; always check the portal first. No carrier-wide idempotency is claimed.
## Push webhook (optional)
This is a separate service, not a public MCP endpoint. Install the `webhook` extra, set a strong random `LCS_WEBHOOK_SECRET`, then run:
```bash
leopards-webhook
```
The service listens on `127.0.0.1:8001/webhooks/leopards`. Configure a TLS-enabled, rate-limited reverse proxy for that route only, and share the callback URL plus the agreed secret header with Leopards. The Push API document permits custom headers but does not specify a signing algorithm. Do not expose your MCP listener alongside this callback. The webhook accepts a `data` array of events and returns HTTP 202 with the carrier's documented success shape. It deduplicates CN/status/activity date, stores only these three values, and discards receiver names/reasons. Timestamps are kept without an assumed timezone. No downstream Shopify sync or automatic actions are performed. See [API notes](docs/api-notes.md) and [security](SECURITY.md).
## Development and verification
```bash
python -m pytest -q --cov=leopards_mcp --cov-branch --cov-fail-under=90
python -m compileall -q src tests
python -m build
python -m pip_audit --strict
```
Tests use synthetic data and mocked HTTP transport. CI installs the declared SDK and requires registration, stdio, and Streamable HTTP checks. A missing SDK fails collection; skips and expected failures fail the test gate. See [release audit](docs/release-audit.md) for the actual local results and open blockers. Before production, validate every needed endpoint in staging with your own merchant account, including permission and partial failure behavior. Native PDF load-sheet downloads are not implemented; JSON details and booking slip links are supported. Do not infer a successful bank deposit from a courier invoice status.
## Troubleshooting
- **Credentials missing:** set both environment variables in the MCP process, not only in a shell the client never reads.
- **Carrier rejected request:** confirm account environment, API access, field values and portal status. Errors are intentionally sanitized to avoid leaking credentials or customer data.
- **Batch booking blocked:** verify the exact endpoint with Leopards; no automatic fallback is used.
- **HTTP redirect or timeout:** inspect the carrier portal. Never replay an uncertain write blindly.
- **Large responses:** narrow dates or CNs; full invoice responses may require carrier-side support if they exceed the local response cap.
## License and attribution
MIT for this project's original code and documentation. Leopards trademarks and merchant API documentation belong to their respective owners. The original vendor PDFs are intentionally not distributed. This independent project is not endorsed by the carrier. Users are responsible for complying with merchant API terms, customer privacy requirements and appropriate authorization.
TDQS
Scored across 21 tools
Most tools map to a distinct resource (invoices, banks, POD, load sheets, booking, cancellation), but there are clear overlaps: track_shipments vs shipment_statuses vs activity_log all report consignment status, and shipper_advice_by_date vs shipper_advice_list are explicitly two request variants of the same operation. The descriptions do help resolve these (date-range vs paginated variant, activity history vs last-status), but an agent must read carefully to pick correctly.
All names are snake_case, which is good, but the verb convention is split: write operations use verb_noun (book_shipment, cancel_shipments, create_shipper, update_shipper_advice) while most reads are bare noun phrases (payment_details, shipping_charges, shipper_details, load_sheet_details, activity_log) and others prefix list_ (list_cities, list_invoices, list_banks). The read/write split has some internal logic, but list-like operations are unpredictable in naming.
21 tools is on the heavy end for a courier integration surface, and a few slots are spent on redundancy (shipper_advice_by_date vs shipper_advice_list, track_shipments vs shipment_statuses) rather than new capability. The breadth of the underlying domain (booking, tracking, finance, shipper management, load sheets) makes the size defensible, but it sits at the borderline.
Core lifecycle is well covered: quote, book (single and batch), track, status, cancel, load sheet generation and retrieval, POD, charges, invoices, payments, shipper creation and shipper advice. Gaps are minor but real: there is no update/delete for shipments or shippers (create only), no label/waybill retrieval, and no pickup or return-shipment operations.