Compare commits
25 Commits
v2.5.0
...
c37ae2f441
| Author | SHA1 | Date | |
|---|---|---|---|
| c37ae2f441 | |||
| 30127d970b | |||
| ed3c3ed0ec | |||
| 11774267ac | |||
| f496a5316e | |||
| b4396770c0 | |||
| 8ef2963524 | |||
| 889a2f5921 | |||
| 72f9d5b4d9 | |||
| ae9c19ac63 | |||
| 2234543c2b | |||
| 93b5d78a03 | |||
| 40b56b21ec | |||
| 07d43dfae2 | |||
| c174a60b82 | |||
| b3fec955cc | |||
| c47d78f3a7 | |||
| 970cfce7a5 | |||
| 5385410977 | |||
| eb62ee63ca | |||
| cd18359992 | |||
| 3d76af542a | |||
| ec52dc6708 | |||
| 15e34ef0ef | |||
| 1a61e8022a |
@@ -0,0 +1,2 @@
|
|||||||
|
*.html linguist-documentation
|
||||||
|
assets/** linguist-Generated
|
||||||
@@ -0,0 +1,7 @@
|
|||||||
|
version: 2
|
||||||
|
updates:
|
||||||
|
- package-ecosystem: "npm"
|
||||||
|
directory: "/"
|
||||||
|
schedule:
|
||||||
|
interval: "monthly"
|
||||||
|
open-pull-requests-limit: 0
|
||||||
@@ -0,0 +1,215 @@
|
|||||||
|
# AGENTS.md — aura-courier-mcp v2.5.4 → v2.6.0 hardening
|
||||||
|
|
||||||
|
> Works for any coding agent (Claude Code, Codex, Antigravity/Gemini, Cursor).
|
||||||
|
> Save as `AGENTS.md` in the repo root (Claude Code: also copy/symlink to `CLAUDE.md`; Antigravity/Gemini: `GEMINI.md` if it does not read `AGENTS.md`). Then prompt: **"Read AGENTS.md and execute it end to end."**
|
||||||
|
|
||||||
|
Repo: https://github.com/auraajenticai/aura-courier-mcp (Apache-2.0, Node, Streamable-HTTP MCP, protocol 2024-11-05)
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
## 0. Ground rules (read first, obey always)
|
||||||
|
|
||||||
|
1. **Discover before editing.** Read the repo (entrypoint, tool registry, courier adapters, webhook handlers, config, existing tests, package.json) and write a 10-line "repo map" at the start of your report. Do not assume file names; the ones used below are placeholders.
|
||||||
|
2. **Never invent facts.** Anything marked `OBSERVED` below was seen in live behavior. Anything marked `UNVERIFIED` you must confirm from code or by running it, then state the result. If you cannot confirm, say so; do not guess.
|
||||||
|
3. **Never create real shipments or move money.** Do not call real courier booking, cancel, or payout endpoints. Use mocks/nock/fixtures for upstream APIs. No real customer phone numbers in tests; use `01700000000`-style synthetic values only.
|
||||||
|
4. **No secrets in code, logs, tests, or the report.** Redact API keys, tokens, and merchant IDs.
|
||||||
|
5. **Backward compatibility.** Do not rename or remove existing tools or existing response fields. Add new fields. Deprecate loudly in descriptions.
|
||||||
|
6. **Small, reviewable commits** (one per task ID). Run the full test suite before each commit.
|
||||||
|
7. **Stop and ask** (end your turn with a question) only if a decision cannot be derived from code or this file, e.g. choosing a hosting secret store. Otherwise decide, document in the report, and continue.
|
||||||
|
8. **Honest reporting.** If a task is partly done, say exactly which acceptance tests pass and which fail.
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
## 1. Global response envelope (all tools)
|
||||||
|
|
||||||
|
```json
|
||||||
|
{
|
||||||
|
"ok": true,
|
||||||
|
"data": {},
|
||||||
|
"error": null,
|
||||||
|
"meta": {
|
||||||
|
"request_id": "uuid",
|
||||||
|
"source": "live_api | static_tariff | cache | validator",
|
||||||
|
"as_of": "ISO-8601"
|
||||||
|
}
|
||||||
|
}
|
||||||
|
```
|
||||||
|
|
||||||
|
On failure: `ok:false`, `data:null`, `error:{code,message,retryable,courier?}`.
|
||||||
|
|
||||||
|
Error codes: `UNAUTHORIZED`, `INVALID_INPUT`, `CONSIGNMENT_NOT_FOUND`, `COURIER_NOT_CONFIGURED`, `COURIER_UPSTREAM_ERROR`, `UNSUPPORTED_BY_PROVIDER`, `DUPLICATE_INVOICE`.
|
||||||
|
|
||||||
|
Never leak raw axios/HTTP error text. Existing top-level fields (e.g. `success`) stay in place alongside the envelope.
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
## 2. Tasks
|
||||||
|
|
||||||
|
### T1 — Authentication on `/mcp` and webhooks (P0)
|
||||||
|
|
||||||
|
- **Status:** `UNVERIFIED`. The published client config contains only a URL with no credential. First determine from code whether `/mcp` enforces auth. Write the answer into your report.
|
||||||
|
- **Required:**
|
||||||
|
- `Authorization: Bearer <key>` required on `/mcp`. Missing/invalid → HTTP 401 + `UNAUTHORIZED`.
|
||||||
|
- Key → tenant → that tenant's courier credentials (no shared global credentials across tenants).
|
||||||
|
- Scopes: `read` (track, compare, fraud, geocode, zone, list, balance), `write` (create_parcel, resolve_ndr_issue, and any new write tool).
|
||||||
|
- Per-key rate limiting and an audit log (tool, tenant, hash of args, outcome). Do not log raw phone numbers or addresses; hash or mask them.
|
||||||
|
- Webhooks `/webhooks/{steadfast,pathao,redx,paperfly}`: verify each courier's secret/signature per its documented scheme; reject unsigned/invalid with 401/403. If a courier does not offer signatures, require a per-tenant secret token in the URL or header and document the limitation.
|
||||||
|
- Update README, homepage config snippet, and `/guide` to show the header.
|
||||||
|
- **Acceptance:** unauthenticated `POST /mcp tools/list` → 401; valid key → tool list; unsigned webhook → rejected.
|
||||||
|
|
||||||
|
### T2 — `resolve_ndr_issue` must not claim actions it did not take (P0)
|
||||||
|
|
||||||
|
- **OBSERVED:** the tool is documented as generation-only (sends nothing). For input `{consignment_id:"TEST-0000", courier:"steadfast", issue_type:"customer_phone_off"}` it returned `resolution_status:"CUSTOMER_REENGAGED"`, an action text saying a WhatsApp message "has been sent" (`পাঠানো হয়েছে`), and `carrier_instruction:"HOLD_FOR_CONTACT: Reached customer via messaging… on hold at local hub. Do not RTO."` Nothing was sent, and the consignment does not exist (no validation).
|
||||||
|
- **Required:** verify the consignment exists using the same logic as `track_parcel` (`CONSIGNMENT_NOT_FOUND` if not). Response `data`:
|
||||||
|
|
||||||
|
```json
|
||||||
|
{
|
||||||
|
"status": "DRAFT_GENERATED",
|
||||||
|
"consignment_verified": true,
|
||||||
|
"actions_executed": [],
|
||||||
|
"whatsapp_draft": { "language": "bn", "text": "..." },
|
||||||
|
"courier_ticket_draft": { "subject": "...", "body": "..." },
|
||||||
|
"recommended_carrier_action": "HOLD | RESCHEDULE | CORRECT_ADDRESS | RETURN",
|
||||||
|
"requires_manual_execution": true
|
||||||
|
}
|
||||||
|
```
|
||||||
|
|
||||||
|
- Remove `CUSTOMER_REENGAGED` and any past-tense claims ("sent", "reached", "on hold"). Use suggestive wording only ("প্রস্তাবিত" / "Suggested"). `actions_executed` is non-empty only if a real upstream API call was actually made.
|
||||||
|
- **Acceptance:** unknown ID → `CONSIGNMENT_NOT_FOUND`; valid ID → `actions_executed == []`, no `CUSTOMER_REENGAGED` anywhere in output.
|
||||||
|
|
||||||
|
### T3 — `get_balance` must not return fake zero (P0)
|
||||||
|
|
||||||
|
- **OBSERVED:** `get_balance(courier:"pathao")` → `success:true, current_balance:0, raw_response.message:"Pathao payout balance managed via merchant portal"`.
|
||||||
|
- **Required:** if the provider has no balance API, return:
|
||||||
|
|
||||||
|
```json
|
||||||
|
{ "courier": "pathao", "amount_bdt": null, "pending_bdt": null,
|
||||||
|
"status": "UNSUPPORTED_BY_PROVIDER", "hint": "Use Pathao merchant portal" }
|
||||||
|
```
|
||||||
|
|
||||||
|
Keep `current_balance` only when it is a real number (otherwise `null`). Steadfast returns real numbers plus `as_of`.
|
||||||
|
- **Acceptance:** Pathao → `amount_bdt: null` and `status: UNSUPPORTED_BY_PROVIDER`.
|
||||||
|
|
||||||
|
### T4 — Single pricing source of truth (P1)
|
||||||
|
|
||||||
|
- **OBSERVED:**
|
||||||
|
- `calculate_delivery_zone_and_fee` uses flat zone fees (Dhaka ≤22 km ৳80, 22–45 km ৳100, >45 km ৳150).
|
||||||
|
- `compare_courier_rates` returns per-courier fees (Dhanmondi 0.5 kg: Steadfast 70, Pathao 60, RedX 80, Paperfly 80 + COD 15/15/15/23).
|
||||||
|
- SLA inconsistencies: homepage "24–48h"; tool description "24–72h"; Sylhet (236 km) and Chattogram (255 km) return "৭২–৯৬ ঘণ্টা"; Savar returns "৪৮–৭২ ঘণ্টা".
|
||||||
|
- Weight surcharges (+20 at 2 kg etc.) match the homepage static table; Chattogram Pathao quote carries a Dhaka-only coverage note.
|
||||||
|
- **UNVERIFIED (inference):** rates come from a hardcoded table, not live courier rate APIs. Confirm in code.
|
||||||
|
- **Required:**
|
||||||
|
- Create one tariff module (courier × zone × weight slab × COD% × SLA hours). Both tools read it. Generate homepage tables and tool descriptions from it.
|
||||||
|
- `meta.source = "static_tariff"` unless a live courier rate API is genuinely called. Remove "real-time rate" wording where false.
|
||||||
|
- Use consistent, realistic SLA ranges per zone/courier (propose: inside Dhaka 12–48h, sub-Dhaka 24–72h, outside 48–96h; adjust if courier docs say otherwise and cite the source).
|
||||||
|
- `coverage_notes` must be route-specific.
|
||||||
|
- `calculate_delivery_zone_and_fee` data: `{zone, distance_km, standard_fee_bdt, cod_percent, sla_hours:{min,max}, route_summary}` (keep old fields too).
|
||||||
|
- **Acceptance:** for the same address, both tools report the same `zone` and `sla_hours`; Chattogram quote has no Dhaka-only note.
|
||||||
|
|
||||||
|
### T5 — `validate_and_geocode_address` quality flags (P1)
|
||||||
|
|
||||||
|
- **OBSERVED:**
|
||||||
|
- Input `"Road 11, House 24, Dhanmondi, Dhaka"` → `formatted_address:"11, house, 24 Dhanmondi Bridge, Dhaka 1209"`, `location_type:"RANGE_INTERPOLATED"`, `thana:""`, `confidence_score:85`, `is_deliverable:true`.
|
||||||
|
- Input with `thana:"Uttara"` returned `thana:"Uttara"` (echo of the input), `ROOFTOP`, confidence 98.
|
||||||
|
- So `thana` appears to be echoed, not resolved.
|
||||||
|
- **Required** response data:
|
||||||
|
|
||||||
|
```json
|
||||||
|
{
|
||||||
|
"formatted_address": "...",
|
||||||
|
"thana_input": "Uttara|null",
|
||||||
|
"thana_resolved": "string|null",
|
||||||
|
"district": "...", "division": "...",
|
||||||
|
"coordinates": {"lat": 0, "lng": 0},
|
||||||
|
"location_type": "ROOFTOP|RANGE_INTERPOLATED|GEOMETRIC_CENTER|APPROXIMATE",
|
||||||
|
"confidence_score": 0,
|
||||||
|
"match_quality": {"road": true, "house": true, "area": true},
|
||||||
|
"needs_review": false,
|
||||||
|
"warnings": []
|
||||||
|
}
|
||||||
|
```
|
||||||
|
|
||||||
|
- Derive `thana_resolved` from Google `address_components` (sublocality / administrative_area_level_3 or equivalent); `null` if absent. Never copy `thana_input` into `thana_resolved`.
|
||||||
|
- Cap `confidence_score` at 60 when `location_type != ROOFTOP`.
|
||||||
|
- `needs_review = true` when confidence < 70, `thana_resolved` is null, or road/house tokens from the input are missing in `formatted_address`; add a human-readable `warnings` entry.
|
||||||
|
- Keep legacy `thana` field but populate it from `thana_resolved` (or `thana_input` marked in `warnings` as unverified).
|
||||||
|
- **Acceptance:** the Dhanmondi example → `needs_review:true`, `confidence_score <= 60`; thana never equals input unless Google also resolved it.
|
||||||
|
|
||||||
|
### T6 — `check_fraud_risk` semantics (P1)
|
||||||
|
|
||||||
|
- **OBSERVED:** `check_fraud_risk("01000000000")` → `risk_level:"CRITICAL"`, `delivery_success_rate:"0% (অবৈধ নম্বর / Invalid BD Number)"`, `cancellation_rate:"100%"`, `carrier_source:"operator_prefix_validator"`. `/health` reports `fraud_engine: "Steadfast Nationwide API + BD Prefix Validator"` while the tool description claims "millions of historical consignments nationwide".
|
||||||
|
- **Required:**
|
||||||
|
- `risk_level` enum: `INVALID_NUMBER | NO_HISTORY | LOW | MEDIUM | HIGH | CRITICAL`.
|
||||||
|
- Invalid prefix/length → `INVALID_NUMBER`, `delivery_success_rate: null`, `cancellation_rate: null` (not 0%/100%).
|
||||||
|
- Add `data_sources: ["steadfast_nationwide","prefix_validator"]` (reflecting what was actually queried), `sample_size`, `coverage_note`.
|
||||||
|
- Correct the tool description to match the real data sources (confirm in code which providers are queried).
|
||||||
|
- Never log the full phone number; mask as `017****1234` in logs.
|
||||||
|
- **Acceptance:** invalid number → `INVALID_NUMBER` with null rates; valid number with no history → `NO_HISTORY`.
|
||||||
|
|
||||||
|
### T7 — `track_parcel` and uniform error mapping (P1)
|
||||||
|
|
||||||
|
- **OBSERVED:** `track_parcel("SF00000000")` → `Aura Courier MCP Error: Request failed with status code 404`.
|
||||||
|
- **Required:** if `courier` omitted, auto-detect by prefix, then try all configured couriers. If none match → `ok:false`, `error.code:"CONSIGNMENT_NOT_FOUND"`, plus `couriers_checked:[...]`. Map upstream 401 → `COURIER_UPSTREAM_ERROR` (credential issue, non-retryable), 429/5xx/timeout → `COURIER_UPSTREAM_ERROR` with `retryable:true`. Add timeouts and bounded retry with backoff for GETs only (never auto-retry `create_parcel`).
|
||||||
|
- **Acceptance:** no raw axios text in any tool output.
|
||||||
|
|
||||||
|
### T8 — `create_parcel` safety + missing tools (P2)
|
||||||
|
|
||||||
|
- **Required:**
|
||||||
|
- `dry_run` (default false) returns `{would_book_with, estimated_cost_bdt, validation:{phone_ok,address_ok,needs_review}}` without any upstream booking call.
|
||||||
|
- Idempotency by `invoice` (per tenant): repeat call returns the existing consignment with `idempotent_replay:true`; never books twice. Persist the mapping.
|
||||||
|
- Real response data: `{consignment_id, tracking_code, courier, routing_reason, cost_estimate_bdt, cancellable_via_api}`.
|
||||||
|
- Auto routing (`courier:"auto"`) must record why a courier was chosen.
|
||||||
|
- New tools (additive): `cancel_parcel(courier, consignment_id)` where the provider API supports it, else `UNSUPPORTED_BY_PROVIDER`; `bulk_create_parcels(items[], dry_run)` with per-item results; `get_webhook_events(consignment_id?, since?)` over stored webhook events.
|
||||||
|
- Update the tool count in `/health`, homepage and README.
|
||||||
|
- **Acceptance (mocked upstream only):** two identical invoices → one upstream call, second returns `idempotent_replay:true`; `dry_run` makes zero upstream booking calls.
|
||||||
|
|
||||||
|
### T9 — `/health` exposure (P2)
|
||||||
|
|
||||||
|
- **OBSERVED:** `/health` publicly returns heap/rss/uptime, active sessions, engine names, webhook paths.
|
||||||
|
- **Required:** public `GET /health` → `{ok, version}` only. Detailed telemetry only with an admin key.
|
||||||
|
- **Acceptance:** unauthenticated `/health` has no heap/session/engine fields.
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
## 3. Test plan (all must pass in CI; mock every upstream)
|
||||||
|
|
||||||
|
| # | Test |
|
||||||
|
|---|---|
|
||||||
|
| 1 | No/invalid bearer → 401 on `/mcp`; unsigned webhook rejected |
|
||||||
|
| 2 | `resolve_ndr_issue` unknown id → `CONSIGNMENT_NOT_FOUND`; valid id → `actions_executed == []` and no `CUSTOMER_REENGAGED` |
|
||||||
|
| 3 | `get_balance` pathao → `amount_bdt:null`, `UNSUPPORTED_BY_PROVIDER` |
|
||||||
|
| 4 | Same address: zone-fee tool and compare tool agree on `zone` and `sla_hours` |
|
||||||
|
| 5 | Geocode Dhanmondi example → `needs_review:true`, confidence ≤ 60 when not ROOFTOP; thana not echoed as resolved |
|
||||||
|
| 6 | `check_fraud_risk("01000000000")` → `INVALID_NUMBER`, null rates |
|
||||||
|
| 7 | `track_parcel("SF00000000")` → `CONSIGNMENT_NOT_FOUND`, no raw axios text |
|
||||||
|
| 8 | `create_parcel` same invoice twice → one upstream call; second `idempotent_replay:true` |
|
||||||
|
| 9 | Chattogram 2 kg quote has no Dhaka-only coverage note |
|
||||||
|
| 10 | Public `/health` exposes only `ok` and `version` |
|
||||||
|
| 11 | Snapshot test: every tool response validates against the envelope schema |
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
## 4. Order of work
|
||||||
|
|
||||||
|
T1 → T2 → T3 → (T4, T5, T6, T7 in any order) → T8 → T9 → tests green → bump to **v2.6.0** → CHANGELOG.md → update README, homepage, `/guide`, tool descriptions.
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
## 5. Out of scope
|
||||||
|
|
||||||
|
- Adding new couriers or changing business pricing numbers (only unify and cite them).
|
||||||
|
- Touching production credentials or running anything against live courier production APIs.
|
||||||
|
- Rewriting the project in another language/framework.
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
## 6. Final report format (required)
|
||||||
|
|
||||||
|
1. **Repo map** (≤10 lines).
|
||||||
|
2. **Per task:** status (done / partial / blocked), files changed, commit hash, which acceptance tests pass.
|
||||||
|
3. **Resolved UNVERIFIED items:** T1 auth status before your change (enforced or not), whether rates were static or live, which providers the fraud engine really queries.
|
||||||
|
4. **Breaking or behavioral changes** a client must know about.
|
||||||
|
5. **Manual follow-ups** for the owner (key rotation, secret store, courier webhook reconfiguration).
|
||||||
|
6. **Test output summary** (counts, failures).
|
||||||
|
|
||||||
|
If any of the above could not be done, state it plainly instead of omitting it.
|
||||||
@@ -0,0 +1,62 @@
|
|||||||
|
# Changelog
|
||||||
|
|
||||||
|
## [2.6.0] - 2026-11-10
|
||||||
|
|
||||||
|
### Added
|
||||||
|
- **Global Response Envelope (`src/envelope.ts`)**: All 12 MCP tools now return a normalized `{ ok, data, error, meta: { request_id, source, as_of } }` envelope alongside existing top-level backward-compatible fields. Raw Axios error strings (`"Request failed with status code ..."`) are strictly sanitized and replaced with typed `EnvelopeErrorCode` entries (`UNAUTHORIZED`, `INVALID_INPUT`, `CONSIGNMENT_NOT_FOUND`, `COURIER_NOT_CONFIGURED`, `COURIER_UPSTREAM_ERROR`, `UNSUPPORTED_BY_PROVIDER`, `DUPLICATE_INVOICE`).
|
||||||
|
- **Task T1 — Authentication, Scopes, Per-Key Rate Limits & Webhook Verification (`src/middleware/auth.ts`)**:
|
||||||
|
- `POST /mcp` now strictly requires `Authorization: Bearer <key>` (`HTTP 401` + `UNAUTHORIZED` envelope when missing/invalid).
|
||||||
|
- Supports `read` (`aura_ro_*`) and `write` (`aura_rw_*` / master) scopes, per-key sliding-window rate limits, tenant credential isolation (`keysFromRequest`), and privacy-safe audit logs (`maskPhone` as `017****1234`, `[REDACTED_ADDRESS]`).
|
||||||
|
- `/webhooks/{steadfast,pathao,redx,paperfly}` verify inbound webhook signatures/tokens (`HTTP 401` on unsigned requests).
|
||||||
|
- **Task T2 — Verified Draft-Only `resolve_ndr_issue`**: Verifies `consignment_id` via `track_parcel` first (returning `CONSIGNMENT_NOT_FOUND` on bogus IDs), and returns `status: "DRAFT_GENERATED"`, `actions_executed: []`, `requires_manual_execution: true`, and conditional Bengali copy prefixed with `"প্রস্তাবিত মেসেজ:"`.
|
||||||
|
- **Task T3 — Honest `get_balance` Semantics**: `Steadfast` returns live `amount_bdt` and `status: "OK"`; `Pathao`, `RedX`, and `Paperfly` return `amount_bdt: null, pending_bdt: null, status: "UNSUPPORTED_BY_PROVIDER"` with merchant portal hints (never a misleading numeric `0`).
|
||||||
|
- **Task T4 — Single Tariff Source of Truth (`src/tariffs.ts`)**: Unified `ZONE_DEFINITIONS` and `CARRIER_TARIFF_TABLE` (`meta.source: "static_tariff"`) across `calculate_delivery_zone_and_fee` and `compare_courier_rates` with structured `sla_hours: { min, max }` and route-specific `coverage_notes`.
|
||||||
|
- **Task T5 — Geocoding Accuracy & Thana Verification (`src/adapters/google_maps.ts`)**: `validate_and_geocode_address` derives `thana_resolved` strictly from geocoder components (never echoing `thana_input`), caps `confidence_score` at `60` when `location_type !== "ROOFTOP"`, and returns `match_quality: { road, house, area }`, `needs_review`, and `warnings[]`.
|
||||||
|
- **Task T6 — Honest `check_fraud_risk` Taxonomy (`src/adapters/fraud_engine.ts`)**: Returns `risk_level: "INVALID_NUMBER"` with `delivery_success_rate: null` for invalid prefixes (`01000000000`), `risk_level: "NO_HISTORY"` with `null` rates when `sample_size === 0`, and `data_sources`, `sample_size`, and `coverage_note`.
|
||||||
|
- **Task T7 — Multi-Courier `track_parcel` & Bounded GET Retry**: Auto-detects prefix, checks all configured couriers (`couriers_checked`), retries transient `429/5xx/timeout` GETs via `withGetRetry`, and returns `CONSIGNMENT_NOT_FOUND` without raw Axios strings.
|
||||||
|
- **Task T8 — `create_parcel` Dry-Run, Invoice Idempotency & 3 New Tools (12 Total Tools)**:
|
||||||
|
- `create_parcel` supports `dry_run: true` (zero upstream calls, returns `would_book_with` and `estimated_cost_bdt`) and per-tenant `invoice` idempotency (`idempotent_replay: true/false`).
|
||||||
|
- Added `cancel_parcel(courier, consignment_id)`, `bulk_create_parcels(items[], dry_run?)`, and `get_webhook_events(consignment_id?, since?)`.
|
||||||
|
- **Task T9 — Hardened `/health` Endpoint**: Unauthenticated `GET /health` returns `{ ok: true, version: "2.6.0" }` only; full telemetry requires an admin Bearer token.
|
||||||
|
- **Automated CI Acceptance Suite (`test/v260.test.mjs`)**: Added 12 mocked unit & acceptance tests covering all `AGENTS.md` criteria (`npm test`).
|
||||||
|
|
||||||
|
## [2.5.5] - 2026-11-10
|
||||||
|
|
||||||
|
### Added
|
||||||
|
- **Live 4-Courier Balance, Settlement & Store Verification (`get_balance`)**: Upgraded `get_balance` to support `steadfast`, `pathao`, `redx`, `paperfly`, and `all` simultaneously—querying live Packzy wallet balances (`Steadfast`), live OAuth 2.0 order/COD settlement ledgers & active stores (`Pathao`), live OpenAPI pickup stores (`RedX`), and live Basic Auth + `paperflykey` merchant status (`Paperfly`).
|
||||||
|
- **Dual-Carrier Nationwide Fraud Shield (`check_fraud_risk`)**: Integrated Pathao's live `/aladdin/api/v1/user/success` nationwide customer delivery history API alongside Steadfast's `/fraud_check/{phone}` API for 100% live `total_parcels`, `total_delivered`, `total_cancelled`, and `delivery_success_rate` telemetry.
|
||||||
|
- **Stateless + Stateful Dual-Mode `POST /mcp` Gateway**: Added direct single-request JSON-RPC 2.0 execution for `tools/call` and `tools/list` on `POST /mcp` without requiring a prior `mcp-session-id` handshake, while preserving full stateful `StreamableHTTPServerTransport` sessions for MCP clients.
|
||||||
|
- **Dual Subscription & Per-Message Pricing Architecture (`/guide#pricing`)**: Structured two distinct Google Cloud Startup–aligned subscription tracks: **Track A (`Aura Courier MCP Only` — Free Trial `$0`, Starter `$9 / ৳499`, Pro `$19 / ৳999`)** and **Track B (`Aura Main Omnichannel AI + WhatsApp/Messenger + Per-Message Quota` — Starter `$19 / ৳1,999`, Growth `$49 / ৳4,999`, Enterprise `$149 / ৳14,999` + Meta WABA Per-Message Rate Card)**.
|
||||||
|
|
||||||
|
## [2.5.4] - 2026-11-10
|
||||||
|
|
||||||
|
### Added
|
||||||
|
- **Standalone Courier MCP vs. Full Aura Client Dashboard Architecture Guide (`/guide#architecture`)**: Added a comprehensive bilingual comparison and module breakdown explaining how merchants can use **Aura Courier MCP Standalone** inside WooCommerce/Shopify/Custom stores or upgrade to the full **Aura Client Dashboard Suite** (`client.auraajenticai.cloud`) with 6-Pillar WhatsApp/Messenger AI Bots, 3-Column Omnichannel Inbox (`#view-inbox`), and Logistics Profit Guard (`#view-risk`).
|
||||||
|
- **4-Platform Interactive Simulator (`/guide#simulator`)**: Upgraded the live simulator with a 4th interactive tab (**🌐 Aura Client Dashboard**) and dynamic **Delivery Zone Switcher** (`Inside Dhaka`, `Sub-Dhaka`, `Outside Dhaka`).
|
||||||
|
- **Bangladesh (`৳ BDT`) & Global (`$ USD`) Pricing Structure + 15-Day Free Trial (`/guide#pricing`)**: Bound transparent 4-tier pricing (**15-Day Free Trial `৳0`**, **Courier MCP Starter `৳499/mo`**, **Courier MCP Pro `৳999/mo`**, and **Aura Ecosystem Suite `৳2,499/mo`**) with interactive BDT/USD and Monthly/Yearly toggles.
|
||||||
|
- **Clean Single-Line Navigation UI**: Removed cluttering diagonal arrows (`↗`) across the landing page and guide navigation bars.
|
||||||
|
|
||||||
|
## [2.5.3] - 2026-11-10
|
||||||
|
|
||||||
|
### Added
|
||||||
|
- **Interactive In-Dashboard Store Simulator (`/guide`)**: Added a full interactive store admin simulator directly inside `https://courier.auraajenticai.cloud/guide` allowing merchants to switch between **WooCommerce (WP Admin)**, **Shopify Admin**, and **Custom Website (Supabase)**, toggle **Safe vs. High-Risk Fraud Customer** telemetry, select any of the **4 Couriers (Steadfast, Pathao, RedX, Paperfly)**, book parcels with 1 click, and preview **4x6 Thermal Barcode Shipping Labels**.
|
||||||
|
- **Official High-Res Brand Icon (`/assets/courier-logo.jpg`)**: Integrated the official Aura Courier MCP brand icon across `/guide` and static assets.
|
||||||
|
- **GitHub Linguist Configuration (`.gitattributes`)**: Marked static HTML documentation pages as `linguist-documentation` so GitHub and Glama AI classify the repository language accurately as `TypeScript`.
|
||||||
|
|
||||||
|
All notable changes to **Aura Courier MCP** are documented in this file.
|
||||||
|
|
||||||
|
## [2.5.2] - 2026-11-10
|
||||||
|
### Added
|
||||||
|
- **Bilingual User Guide & Business Benefits Hub (`GET /guide`)**: Interactive Bengali & English guide (`https://courier.auraajenticai.cloud/guide`) covering 3-in-1 WooCommerce/Shopify integration, 6-Pillar WhatsApp/Messenger AI Bot harmony, Multi-Tenant Isolation, and MCP AI Agent setup.
|
||||||
|
- **Bilingual Real-Time Fraud Risk Output (`🇧🇩 বাংলা | 🇬🇧 English`)**: Upgraded `FraudRiskEngine.evaluateRisk` and In-Dashboard Quick-Ship widget (`/api/courier/quick-ship`) with bilingual recommendations and 1-click language switching.
|
||||||
|
- **Repository Governance & Security Documentation**: Added `SECURITY.md`, `CONTRIBUTING.md`, and `CHANGELOG.md`.
|
||||||
|
|
||||||
|
## [2.5.1] - 2026-11-10
|
||||||
|
### Added
|
||||||
|
- **Zero-Knowledge AES-256 Cryptographic Vault Policy (`/privacy`)**: Documented strict Zero Admin Visibility guarantee for client courier API keys.
|
||||||
|
- **3-in-1 Store Connection & In-Dashboard Quick-Ship Bridge**: Added support for 1-Click WooCommerce Auto-Connect, Pre-Connected `.zip` Plugin, and Shopify/Custom Store widgets.
|
||||||
|
|
||||||
|
## [2.5.0] - 2026-11-09
|
||||||
|
### Changed
|
||||||
|
- **Glama TDQS 5.0 Compliance**: Enhanced all 9 MCP tool descriptions with explicit side-effect declarations, disambiguation rules, and parameter constraints.
|
||||||
|
- **Credential Isolation**: Removed all fallback merchant credentials from source files in favor of runtime environment and header injection.
|
||||||
@@ -0,0 +1,215 @@
|
|||||||
|
# AGENTS.md — aura-courier-mcp v2.5.4 → v2.6.0 hardening
|
||||||
|
|
||||||
|
> Works for any coding agent (Claude Code, Codex, Antigravity/Gemini, Cursor).
|
||||||
|
> Save as `AGENTS.md` in the repo root (Claude Code: also copy/symlink to `CLAUDE.md`; Antigravity/Gemini: `GEMINI.md` if it does not read `AGENTS.md`). Then prompt: **"Read AGENTS.md and execute it end to end."**
|
||||||
|
|
||||||
|
Repo: https://github.com/auraajenticai/aura-courier-mcp (Apache-2.0, Node, Streamable-HTTP MCP, protocol 2024-11-05)
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
## 0. Ground rules (read first, obey always)
|
||||||
|
|
||||||
|
1. **Discover before editing.** Read the repo (entrypoint, tool registry, courier adapters, webhook handlers, config, existing tests, package.json) and write a 10-line "repo map" at the start of your report. Do not assume file names; the ones used below are placeholders.
|
||||||
|
2. **Never invent facts.** Anything marked `OBSERVED` below was seen in live behavior. Anything marked `UNVERIFIED` you must confirm from code or by running it, then state the result. If you cannot confirm, say so; do not guess.
|
||||||
|
3. **Never create real shipments or move money.** Do not call real courier booking, cancel, or payout endpoints. Use mocks/nock/fixtures for upstream APIs. No real customer phone numbers in tests; use `01700000000`-style synthetic values only.
|
||||||
|
4. **No secrets in code, logs, tests, or the report.** Redact API keys, tokens, and merchant IDs.
|
||||||
|
5. **Backward compatibility.** Do not rename or remove existing tools or existing response fields. Add new fields. Deprecate loudly in descriptions.
|
||||||
|
6. **Small, reviewable commits** (one per task ID). Run the full test suite before each commit.
|
||||||
|
7. **Stop and ask** (end your turn with a question) only if a decision cannot be derived from code or this file, e.g. choosing a hosting secret store. Otherwise decide, document in the report, and continue.
|
||||||
|
8. **Honest reporting.** If a task is partly done, say exactly which acceptance tests pass and which fail.
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
## 1. Global response envelope (all tools)
|
||||||
|
|
||||||
|
```json
|
||||||
|
{
|
||||||
|
"ok": true,
|
||||||
|
"data": {},
|
||||||
|
"error": null,
|
||||||
|
"meta": {
|
||||||
|
"request_id": "uuid",
|
||||||
|
"source": "live_api | static_tariff | cache | validator",
|
||||||
|
"as_of": "ISO-8601"
|
||||||
|
}
|
||||||
|
}
|
||||||
|
```
|
||||||
|
|
||||||
|
On failure: `ok:false`, `data:null`, `error:{code,message,retryable,courier?}`.
|
||||||
|
|
||||||
|
Error codes: `UNAUTHORIZED`, `INVALID_INPUT`, `CONSIGNMENT_NOT_FOUND`, `COURIER_NOT_CONFIGURED`, `COURIER_UPSTREAM_ERROR`, `UNSUPPORTED_BY_PROVIDER`, `DUPLICATE_INVOICE`.
|
||||||
|
|
||||||
|
Never leak raw axios/HTTP error text. Existing top-level fields (e.g. `success`) stay in place alongside the envelope.
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
## 2. Tasks
|
||||||
|
|
||||||
|
### T1 — Authentication on `/mcp` and webhooks (P0)
|
||||||
|
|
||||||
|
- **Status:** `UNVERIFIED`. The published client config contains only a URL with no credential. First determine from code whether `/mcp` enforces auth. Write the answer into your report.
|
||||||
|
- **Required:**
|
||||||
|
- `Authorization: Bearer <key>` required on `/mcp`. Missing/invalid → HTTP 401 + `UNAUTHORIZED`.
|
||||||
|
- Key → tenant → that tenant's courier credentials (no shared global credentials across tenants).
|
||||||
|
- Scopes: `read` (track, compare, fraud, geocode, zone, list, balance), `write` (create_parcel, resolve_ndr_issue, and any new write tool).
|
||||||
|
- Per-key rate limiting and an audit log (tool, tenant, hash of args, outcome). Do not log raw phone numbers or addresses; hash or mask them.
|
||||||
|
- Webhooks `/webhooks/{steadfast,pathao,redx,paperfly}`: verify each courier's secret/signature per its documented scheme; reject unsigned/invalid with 401/403. If a courier does not offer signatures, require a per-tenant secret token in the URL or header and document the limitation.
|
||||||
|
- Update README, homepage config snippet, and `/guide` to show the header.
|
||||||
|
- **Acceptance:** unauthenticated `POST /mcp tools/list` → 401; valid key → tool list; unsigned webhook → rejected.
|
||||||
|
|
||||||
|
### T2 — `resolve_ndr_issue` must not claim actions it did not take (P0)
|
||||||
|
|
||||||
|
- **OBSERVED:** the tool is documented as generation-only (sends nothing). For input `{consignment_id:"TEST-0000", courier:"steadfast", issue_type:"customer_phone_off"}` it returned `resolution_status:"CUSTOMER_REENGAGED"`, an action text saying a WhatsApp message "has been sent" (`পাঠানো হয়েছে`), and `carrier_instruction:"HOLD_FOR_CONTACT: Reached customer via messaging… on hold at local hub. Do not RTO."` Nothing was sent, and the consignment does not exist (no validation).
|
||||||
|
- **Required:** verify the consignment exists using the same logic as `track_parcel` (`CONSIGNMENT_NOT_FOUND` if not). Response `data`:
|
||||||
|
|
||||||
|
```json
|
||||||
|
{
|
||||||
|
"status": "DRAFT_GENERATED",
|
||||||
|
"consignment_verified": true,
|
||||||
|
"actions_executed": [],
|
||||||
|
"whatsapp_draft": { "language": "bn", "text": "..." },
|
||||||
|
"courier_ticket_draft": { "subject": "...", "body": "..." },
|
||||||
|
"recommended_carrier_action": "HOLD | RESCHEDULE | CORRECT_ADDRESS | RETURN",
|
||||||
|
"requires_manual_execution": true
|
||||||
|
}
|
||||||
|
```
|
||||||
|
|
||||||
|
- Remove `CUSTOMER_REENGAGED` and any past-tense claims ("sent", "reached", "on hold"). Use suggestive wording only ("প্রস্তাবিত" / "Suggested"). `actions_executed` is non-empty only if a real upstream API call was actually made.
|
||||||
|
- **Acceptance:** unknown ID → `CONSIGNMENT_NOT_FOUND`; valid ID → `actions_executed == []`, no `CUSTOMER_REENGAGED` anywhere in output.
|
||||||
|
|
||||||
|
### T3 — `get_balance` must not return fake zero (P0)
|
||||||
|
|
||||||
|
- **OBSERVED:** `get_balance(courier:"pathao")` → `success:true, current_balance:0, raw_response.message:"Pathao payout balance managed via merchant portal"`.
|
||||||
|
- **Required:** if the provider has no balance API, return:
|
||||||
|
|
||||||
|
```json
|
||||||
|
{ "courier": "pathao", "amount_bdt": null, "pending_bdt": null,
|
||||||
|
"status": "UNSUPPORTED_BY_PROVIDER", "hint": "Use Pathao merchant portal" }
|
||||||
|
```
|
||||||
|
|
||||||
|
Keep `current_balance` only when it is a real number (otherwise `null`). Steadfast returns real numbers plus `as_of`.
|
||||||
|
- **Acceptance:** Pathao → `amount_bdt: null` and `status: UNSUPPORTED_BY_PROVIDER`.
|
||||||
|
|
||||||
|
### T4 — Single pricing source of truth (P1)
|
||||||
|
|
||||||
|
- **OBSERVED:**
|
||||||
|
- `calculate_delivery_zone_and_fee` uses flat zone fees (Dhaka ≤22 km ৳80, 22–45 km ৳100, >45 km ৳150).
|
||||||
|
- `compare_courier_rates` returns per-courier fees (Dhanmondi 0.5 kg: Steadfast 70, Pathao 60, RedX 80, Paperfly 80 + COD 15/15/15/23).
|
||||||
|
- SLA inconsistencies: homepage "24–48h"; tool description "24–72h"; Sylhet (236 km) and Chattogram (255 km) return "৭২–৯৬ ঘণ্টা"; Savar returns "৪৮–৭২ ঘণ্টা".
|
||||||
|
- Weight surcharges (+20 at 2 kg etc.) match the homepage static table; Chattogram Pathao quote carries a Dhaka-only coverage note.
|
||||||
|
- **UNVERIFIED (inference):** rates come from a hardcoded table, not live courier rate APIs. Confirm in code.
|
||||||
|
- **Required:**
|
||||||
|
- Create one tariff module (courier × zone × weight slab × COD% × SLA hours). Both tools read it. Generate homepage tables and tool descriptions from it.
|
||||||
|
- `meta.source = "static_tariff"` unless a live courier rate API is genuinely called. Remove "real-time rate" wording where false.
|
||||||
|
- Use consistent, realistic SLA ranges per zone/courier (propose: inside Dhaka 12–48h, sub-Dhaka 24–72h, outside 48–96h; adjust if courier docs say otherwise and cite the source).
|
||||||
|
- `coverage_notes` must be route-specific.
|
||||||
|
- `calculate_delivery_zone_and_fee` data: `{zone, distance_km, standard_fee_bdt, cod_percent, sla_hours:{min,max}, route_summary}` (keep old fields too).
|
||||||
|
- **Acceptance:** for the same address, both tools report the same `zone` and `sla_hours`; Chattogram quote has no Dhaka-only note.
|
||||||
|
|
||||||
|
### T5 — `validate_and_geocode_address` quality flags (P1)
|
||||||
|
|
||||||
|
- **OBSERVED:**
|
||||||
|
- Input `"Road 11, House 24, Dhanmondi, Dhaka"` → `formatted_address:"11, house, 24 Dhanmondi Bridge, Dhaka 1209"`, `location_type:"RANGE_INTERPOLATED"`, `thana:""`, `confidence_score:85`, `is_deliverable:true`.
|
||||||
|
- Input with `thana:"Uttara"` returned `thana:"Uttara"` (echo of the input), `ROOFTOP`, confidence 98.
|
||||||
|
- So `thana` appears to be echoed, not resolved.
|
||||||
|
- **Required** response data:
|
||||||
|
|
||||||
|
```json
|
||||||
|
{
|
||||||
|
"formatted_address": "...",
|
||||||
|
"thana_input": "Uttara|null",
|
||||||
|
"thana_resolved": "string|null",
|
||||||
|
"district": "...", "division": "...",
|
||||||
|
"coordinates": {"lat": 0, "lng": 0},
|
||||||
|
"location_type": "ROOFTOP|RANGE_INTERPOLATED|GEOMETRIC_CENTER|APPROXIMATE",
|
||||||
|
"confidence_score": 0,
|
||||||
|
"match_quality": {"road": true, "house": true, "area": true},
|
||||||
|
"needs_review": false,
|
||||||
|
"warnings": []
|
||||||
|
}
|
||||||
|
```
|
||||||
|
|
||||||
|
- Derive `thana_resolved` from Google `address_components` (sublocality / administrative_area_level_3 or equivalent); `null` if absent. Never copy `thana_input` into `thana_resolved`.
|
||||||
|
- Cap `confidence_score` at 60 when `location_type != ROOFTOP`.
|
||||||
|
- `needs_review = true` when confidence < 70, `thana_resolved` is null, or road/house tokens from the input are missing in `formatted_address`; add a human-readable `warnings` entry.
|
||||||
|
- Keep legacy `thana` field but populate it from `thana_resolved` (or `thana_input` marked in `warnings` as unverified).
|
||||||
|
- **Acceptance:** the Dhanmondi example → `needs_review:true`, `confidence_score <= 60`; thana never equals input unless Google also resolved it.
|
||||||
|
|
||||||
|
### T6 — `check_fraud_risk` semantics (P1)
|
||||||
|
|
||||||
|
- **OBSERVED:** `check_fraud_risk("01000000000")` → `risk_level:"CRITICAL"`, `delivery_success_rate:"0% (অবৈধ নম্বর / Invalid BD Number)"`, `cancellation_rate:"100%"`, `carrier_source:"operator_prefix_validator"`. `/health` reports `fraud_engine: "Steadfast Nationwide API + BD Prefix Validator"` while the tool description claims "millions of historical consignments nationwide".
|
||||||
|
- **Required:**
|
||||||
|
- `risk_level` enum: `INVALID_NUMBER | NO_HISTORY | LOW | MEDIUM | HIGH | CRITICAL`.
|
||||||
|
- Invalid prefix/length → `INVALID_NUMBER`, `delivery_success_rate: null`, `cancellation_rate: null` (not 0%/100%).
|
||||||
|
- Add `data_sources: ["steadfast_nationwide","prefix_validator"]` (reflecting what was actually queried), `sample_size`, `coverage_note`.
|
||||||
|
- Correct the tool description to match the real data sources (confirm in code which providers are queried).
|
||||||
|
- Never log the full phone number; mask as `017****1234` in logs.
|
||||||
|
- **Acceptance:** invalid number → `INVALID_NUMBER` with null rates; valid number with no history → `NO_HISTORY`.
|
||||||
|
|
||||||
|
### T7 — `track_parcel` and uniform error mapping (P1)
|
||||||
|
|
||||||
|
- **OBSERVED:** `track_parcel("SF00000000")` → `Aura Courier MCP Error: Request failed with status code 404`.
|
||||||
|
- **Required:** if `courier` omitted, auto-detect by prefix, then try all configured couriers. If none match → `ok:false`, `error.code:"CONSIGNMENT_NOT_FOUND"`, plus `couriers_checked:[...]`. Map upstream 401 → `COURIER_UPSTREAM_ERROR` (credential issue, non-retryable), 429/5xx/timeout → `COURIER_UPSTREAM_ERROR` with `retryable:true`. Add timeouts and bounded retry with backoff for GETs only (never auto-retry `create_parcel`).
|
||||||
|
- **Acceptance:** no raw axios text in any tool output.
|
||||||
|
|
||||||
|
### T8 — `create_parcel` safety + missing tools (P2)
|
||||||
|
|
||||||
|
- **Required:**
|
||||||
|
- `dry_run` (default false) returns `{would_book_with, estimated_cost_bdt, validation:{phone_ok,address_ok,needs_review}}` without any upstream booking call.
|
||||||
|
- Idempotency by `invoice` (per tenant): repeat call returns the existing consignment with `idempotent_replay:true`; never books twice. Persist the mapping.
|
||||||
|
- Real response data: `{consignment_id, tracking_code, courier, routing_reason, cost_estimate_bdt, cancellable_via_api}`.
|
||||||
|
- Auto routing (`courier:"auto"`) must record why a courier was chosen.
|
||||||
|
- New tools (additive): `cancel_parcel(courier, consignment_id)` where the provider API supports it, else `UNSUPPORTED_BY_PROVIDER`; `bulk_create_parcels(items[], dry_run)` with per-item results; `get_webhook_events(consignment_id?, since?)` over stored webhook events.
|
||||||
|
- Update the tool count in `/health`, homepage and README.
|
||||||
|
- **Acceptance (mocked upstream only):** two identical invoices → one upstream call, second returns `idempotent_replay:true`; `dry_run` makes zero upstream booking calls.
|
||||||
|
|
||||||
|
### T9 — `/health` exposure (P2)
|
||||||
|
|
||||||
|
- **OBSERVED:** `/health` publicly returns heap/rss/uptime, active sessions, engine names, webhook paths.
|
||||||
|
- **Required:** public `GET /health` → `{ok, version}` only. Detailed telemetry only with an admin key.
|
||||||
|
- **Acceptance:** unauthenticated `/health` has no heap/session/engine fields.
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
## 3. Test plan (all must pass in CI; mock every upstream)
|
||||||
|
|
||||||
|
| # | Test |
|
||||||
|
|---|---|
|
||||||
|
| 1 | No/invalid bearer → 401 on `/mcp`; unsigned webhook rejected |
|
||||||
|
| 2 | `resolve_ndr_issue` unknown id → `CONSIGNMENT_NOT_FOUND`; valid id → `actions_executed == []` and no `CUSTOMER_REENGAGED` |
|
||||||
|
| 3 | `get_balance` pathao → `amount_bdt:null`, `UNSUPPORTED_BY_PROVIDER` |
|
||||||
|
| 4 | Same address: zone-fee tool and compare tool agree on `zone` and `sla_hours` |
|
||||||
|
| 5 | Geocode Dhanmondi example → `needs_review:true`, confidence ≤ 60 when not ROOFTOP; thana not echoed as resolved |
|
||||||
|
| 6 | `check_fraud_risk("01000000000")` → `INVALID_NUMBER`, null rates |
|
||||||
|
| 7 | `track_parcel("SF00000000")` → `CONSIGNMENT_NOT_FOUND`, no raw axios text |
|
||||||
|
| 8 | `create_parcel` same invoice twice → one upstream call; second `idempotent_replay:true` |
|
||||||
|
| 9 | Chattogram 2 kg quote has no Dhaka-only coverage note |
|
||||||
|
| 10 | Public `/health` exposes only `ok` and `version` |
|
||||||
|
| 11 | Snapshot test: every tool response validates against the envelope schema |
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
## 4. Order of work
|
||||||
|
|
||||||
|
T1 → T2 → T3 → (T4, T5, T6, T7 in any order) → T8 → T9 → tests green → bump to **v2.6.0** → CHANGELOG.md → update README, homepage, `/guide`, tool descriptions.
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
## 5. Out of scope
|
||||||
|
|
||||||
|
- Adding new couriers or changing business pricing numbers (only unify and cite them).
|
||||||
|
- Touching production credentials or running anything against live courier production APIs.
|
||||||
|
- Rewriting the project in another language/framework.
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
## 6. Final report format (required)
|
||||||
|
|
||||||
|
1. **Repo map** (≤10 lines).
|
||||||
|
2. **Per task:** status (done / partial / blocked), files changed, commit hash, which acceptance tests pass.
|
||||||
|
3. **Resolved UNVERIFIED items:** T1 auth status before your change (enforced or not), whether rates were static or live, which providers the fraud engine really queries.
|
||||||
|
4. **Breaking or behavioral changes** a client must know about.
|
||||||
|
5. **Manual follow-ups** for the owner (key rotation, secret store, courier webhook reconfiguration).
|
||||||
|
6. **Test output summary** (counts, failures).
|
||||||
|
|
||||||
|
If any of the above could not be done, state it plainly instead of omitting it.
|
||||||
@@ -0,0 +1,24 @@
|
|||||||
|
# Contributing to Aura Courier MCP
|
||||||
|
|
||||||
|
Thank you for your interest in contributing to **Aura Courier MCP** — the Universal Bangladesh Courier & Spatial Intelligence Model Context Protocol (MCP) Server.
|
||||||
|
|
||||||
|
## Development Workflow
|
||||||
|
|
||||||
|
1. **Install Dependencies**:
|
||||||
|
```bash
|
||||||
|
npm install
|
||||||
|
```
|
||||||
|
2. **Build TypeScript**:
|
||||||
|
```bash
|
||||||
|
npm run build
|
||||||
|
```
|
||||||
|
3. **Run Structural & TDQS Validation**:
|
||||||
|
```bash
|
||||||
|
node validate_plugin.js
|
||||||
|
```
|
||||||
|
|
||||||
|
## Engineering Mandates
|
||||||
|
|
||||||
|
- **Zero Mock Data**: Never introduce hardcoded fallback metrics or fabricated carrier responses. All tools must query live carrier APIs or return transparent operational status codes.
|
||||||
|
- **Bilingual Support (`🇧🇩 বাংলা | 🇬🇧 English`)**: User-facing recommendations and guides must support both Bengali and English.
|
||||||
|
- **Zero Hardcoded Secrets**: Never commit API keys, tokens, or merchant credentials.
|
||||||
@@ -0,0 +1,215 @@
|
|||||||
|
# AGENTS.md — aura-courier-mcp v2.5.4 → v2.6.0 hardening
|
||||||
|
|
||||||
|
> Works for any coding agent (Claude Code, Codex, Antigravity/Gemini, Cursor).
|
||||||
|
> Save as `AGENTS.md` in the repo root (Claude Code: also copy/symlink to `CLAUDE.md`; Antigravity/Gemini: `GEMINI.md` if it does not read `AGENTS.md`). Then prompt: **"Read AGENTS.md and execute it end to end."**
|
||||||
|
|
||||||
|
Repo: https://github.com/auraajenticai/aura-courier-mcp (Apache-2.0, Node, Streamable-HTTP MCP, protocol 2024-11-05)
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
## 0. Ground rules (read first, obey always)
|
||||||
|
|
||||||
|
1. **Discover before editing.** Read the repo (entrypoint, tool registry, courier adapters, webhook handlers, config, existing tests, package.json) and write a 10-line "repo map" at the start of your report. Do not assume file names; the ones used below are placeholders.
|
||||||
|
2. **Never invent facts.** Anything marked `OBSERVED` below was seen in live behavior. Anything marked `UNVERIFIED` you must confirm from code or by running it, then state the result. If you cannot confirm, say so; do not guess.
|
||||||
|
3. **Never create real shipments or move money.** Do not call real courier booking, cancel, or payout endpoints. Use mocks/nock/fixtures for upstream APIs. No real customer phone numbers in tests; use `01700000000`-style synthetic values only.
|
||||||
|
4. **No secrets in code, logs, tests, or the report.** Redact API keys, tokens, and merchant IDs.
|
||||||
|
5. **Backward compatibility.** Do not rename or remove existing tools or existing response fields. Add new fields. Deprecate loudly in descriptions.
|
||||||
|
6. **Small, reviewable commits** (one per task ID). Run the full test suite before each commit.
|
||||||
|
7. **Stop and ask** (end your turn with a question) only if a decision cannot be derived from code or this file, e.g. choosing a hosting secret store. Otherwise decide, document in the report, and continue.
|
||||||
|
8. **Honest reporting.** If a task is partly done, say exactly which acceptance tests pass and which fail.
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
## 1. Global response envelope (all tools)
|
||||||
|
|
||||||
|
```json
|
||||||
|
{
|
||||||
|
"ok": true,
|
||||||
|
"data": {},
|
||||||
|
"error": null,
|
||||||
|
"meta": {
|
||||||
|
"request_id": "uuid",
|
||||||
|
"source": "live_api | static_tariff | cache | validator",
|
||||||
|
"as_of": "ISO-8601"
|
||||||
|
}
|
||||||
|
}
|
||||||
|
```
|
||||||
|
|
||||||
|
On failure: `ok:false`, `data:null`, `error:{code,message,retryable,courier?}`.
|
||||||
|
|
||||||
|
Error codes: `UNAUTHORIZED`, `INVALID_INPUT`, `CONSIGNMENT_NOT_FOUND`, `COURIER_NOT_CONFIGURED`, `COURIER_UPSTREAM_ERROR`, `UNSUPPORTED_BY_PROVIDER`, `DUPLICATE_INVOICE`.
|
||||||
|
|
||||||
|
Never leak raw axios/HTTP error text. Existing top-level fields (e.g. `success`) stay in place alongside the envelope.
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
## 2. Tasks
|
||||||
|
|
||||||
|
### T1 — Authentication on `/mcp` and webhooks (P0)
|
||||||
|
|
||||||
|
- **Status:** `UNVERIFIED`. The published client config contains only a URL with no credential. First determine from code whether `/mcp` enforces auth. Write the answer into your report.
|
||||||
|
- **Required:**
|
||||||
|
- `Authorization: Bearer <key>` required on `/mcp`. Missing/invalid → HTTP 401 + `UNAUTHORIZED`.
|
||||||
|
- Key → tenant → that tenant's courier credentials (no shared global credentials across tenants).
|
||||||
|
- Scopes: `read` (track, compare, fraud, geocode, zone, list, balance), `write` (create_parcel, resolve_ndr_issue, and any new write tool).
|
||||||
|
- Per-key rate limiting and an audit log (tool, tenant, hash of args, outcome). Do not log raw phone numbers or addresses; hash or mask them.
|
||||||
|
- Webhooks `/webhooks/{steadfast,pathao,redx,paperfly}`: verify each courier's secret/signature per its documented scheme; reject unsigned/invalid with 401/403. If a courier does not offer signatures, require a per-tenant secret token in the URL or header and document the limitation.
|
||||||
|
- Update README, homepage config snippet, and `/guide` to show the header.
|
||||||
|
- **Acceptance:** unauthenticated `POST /mcp tools/list` → 401; valid key → tool list; unsigned webhook → rejected.
|
||||||
|
|
||||||
|
### T2 — `resolve_ndr_issue` must not claim actions it did not take (P0)
|
||||||
|
|
||||||
|
- **OBSERVED:** the tool is documented as generation-only (sends nothing). For input `{consignment_id:"TEST-0000", courier:"steadfast", issue_type:"customer_phone_off"}` it returned `resolution_status:"CUSTOMER_REENGAGED"`, an action text saying a WhatsApp message "has been sent" (`পাঠানো হয়েছে`), and `carrier_instruction:"HOLD_FOR_CONTACT: Reached customer via messaging… on hold at local hub. Do not RTO."` Nothing was sent, and the consignment does not exist (no validation).
|
||||||
|
- **Required:** verify the consignment exists using the same logic as `track_parcel` (`CONSIGNMENT_NOT_FOUND` if not). Response `data`:
|
||||||
|
|
||||||
|
```json
|
||||||
|
{
|
||||||
|
"status": "DRAFT_GENERATED",
|
||||||
|
"consignment_verified": true,
|
||||||
|
"actions_executed": [],
|
||||||
|
"whatsapp_draft": { "language": "bn", "text": "..." },
|
||||||
|
"courier_ticket_draft": { "subject": "...", "body": "..." },
|
||||||
|
"recommended_carrier_action": "HOLD | RESCHEDULE | CORRECT_ADDRESS | RETURN",
|
||||||
|
"requires_manual_execution": true
|
||||||
|
}
|
||||||
|
```
|
||||||
|
|
||||||
|
- Remove `CUSTOMER_REENGAGED` and any past-tense claims ("sent", "reached", "on hold"). Use suggestive wording only ("প্রস্তাবিত" / "Suggested"). `actions_executed` is non-empty only if a real upstream API call was actually made.
|
||||||
|
- **Acceptance:** unknown ID → `CONSIGNMENT_NOT_FOUND`; valid ID → `actions_executed == []`, no `CUSTOMER_REENGAGED` anywhere in output.
|
||||||
|
|
||||||
|
### T3 — `get_balance` must not return fake zero (P0)
|
||||||
|
|
||||||
|
- **OBSERVED:** `get_balance(courier:"pathao")` → `success:true, current_balance:0, raw_response.message:"Pathao payout balance managed via merchant portal"`.
|
||||||
|
- **Required:** if the provider has no balance API, return:
|
||||||
|
|
||||||
|
```json
|
||||||
|
{ "courier": "pathao", "amount_bdt": null, "pending_bdt": null,
|
||||||
|
"status": "UNSUPPORTED_BY_PROVIDER", "hint": "Use Pathao merchant portal" }
|
||||||
|
```
|
||||||
|
|
||||||
|
Keep `current_balance` only when it is a real number (otherwise `null`). Steadfast returns real numbers plus `as_of`.
|
||||||
|
- **Acceptance:** Pathao → `amount_bdt: null` and `status: UNSUPPORTED_BY_PROVIDER`.
|
||||||
|
|
||||||
|
### T4 — Single pricing source of truth (P1)
|
||||||
|
|
||||||
|
- **OBSERVED:**
|
||||||
|
- `calculate_delivery_zone_and_fee` uses flat zone fees (Dhaka ≤22 km ৳80, 22–45 km ৳100, >45 km ৳150).
|
||||||
|
- `compare_courier_rates` returns per-courier fees (Dhanmondi 0.5 kg: Steadfast 70, Pathao 60, RedX 80, Paperfly 80 + COD 15/15/15/23).
|
||||||
|
- SLA inconsistencies: homepage "24–48h"; tool description "24–72h"; Sylhet (236 km) and Chattogram (255 km) return "৭২–৯৬ ঘণ্টা"; Savar returns "৪৮–৭২ ঘণ্টা".
|
||||||
|
- Weight surcharges (+20 at 2 kg etc.) match the homepage static table; Chattogram Pathao quote carries a Dhaka-only coverage note.
|
||||||
|
- **UNVERIFIED (inference):** rates come from a hardcoded table, not live courier rate APIs. Confirm in code.
|
||||||
|
- **Required:**
|
||||||
|
- Create one tariff module (courier × zone × weight slab × COD% × SLA hours). Both tools read it. Generate homepage tables and tool descriptions from it.
|
||||||
|
- `meta.source = "static_tariff"` unless a live courier rate API is genuinely called. Remove "real-time rate" wording where false.
|
||||||
|
- Use consistent, realistic SLA ranges per zone/courier (propose: inside Dhaka 12–48h, sub-Dhaka 24–72h, outside 48–96h; adjust if courier docs say otherwise and cite the source).
|
||||||
|
- `coverage_notes` must be route-specific.
|
||||||
|
- `calculate_delivery_zone_and_fee` data: `{zone, distance_km, standard_fee_bdt, cod_percent, sla_hours:{min,max}, route_summary}` (keep old fields too).
|
||||||
|
- **Acceptance:** for the same address, both tools report the same `zone` and `sla_hours`; Chattogram quote has no Dhaka-only note.
|
||||||
|
|
||||||
|
### T5 — `validate_and_geocode_address` quality flags (P1)
|
||||||
|
|
||||||
|
- **OBSERVED:**
|
||||||
|
- Input `"Road 11, House 24, Dhanmondi, Dhaka"` → `formatted_address:"11, house, 24 Dhanmondi Bridge, Dhaka 1209"`, `location_type:"RANGE_INTERPOLATED"`, `thana:""`, `confidence_score:85`, `is_deliverable:true`.
|
||||||
|
- Input with `thana:"Uttara"` returned `thana:"Uttara"` (echo of the input), `ROOFTOP`, confidence 98.
|
||||||
|
- So `thana` appears to be echoed, not resolved.
|
||||||
|
- **Required** response data:
|
||||||
|
|
||||||
|
```json
|
||||||
|
{
|
||||||
|
"formatted_address": "...",
|
||||||
|
"thana_input": "Uttara|null",
|
||||||
|
"thana_resolved": "string|null",
|
||||||
|
"district": "...", "division": "...",
|
||||||
|
"coordinates": {"lat": 0, "lng": 0},
|
||||||
|
"location_type": "ROOFTOP|RANGE_INTERPOLATED|GEOMETRIC_CENTER|APPROXIMATE",
|
||||||
|
"confidence_score": 0,
|
||||||
|
"match_quality": {"road": true, "house": true, "area": true},
|
||||||
|
"needs_review": false,
|
||||||
|
"warnings": []
|
||||||
|
}
|
||||||
|
```
|
||||||
|
|
||||||
|
- Derive `thana_resolved` from Google `address_components` (sublocality / administrative_area_level_3 or equivalent); `null` if absent. Never copy `thana_input` into `thana_resolved`.
|
||||||
|
- Cap `confidence_score` at 60 when `location_type != ROOFTOP`.
|
||||||
|
- `needs_review = true` when confidence < 70, `thana_resolved` is null, or road/house tokens from the input are missing in `formatted_address`; add a human-readable `warnings` entry.
|
||||||
|
- Keep legacy `thana` field but populate it from `thana_resolved` (or `thana_input` marked in `warnings` as unverified).
|
||||||
|
- **Acceptance:** the Dhanmondi example → `needs_review:true`, `confidence_score <= 60`; thana never equals input unless Google also resolved it.
|
||||||
|
|
||||||
|
### T6 — `check_fraud_risk` semantics (P1)
|
||||||
|
|
||||||
|
- **OBSERVED:** `check_fraud_risk("01000000000")` → `risk_level:"CRITICAL"`, `delivery_success_rate:"0% (অবৈধ নম্বর / Invalid BD Number)"`, `cancellation_rate:"100%"`, `carrier_source:"operator_prefix_validator"`. `/health` reports `fraud_engine: "Steadfast Nationwide API + BD Prefix Validator"` while the tool description claims "millions of historical consignments nationwide".
|
||||||
|
- **Required:**
|
||||||
|
- `risk_level` enum: `INVALID_NUMBER | NO_HISTORY | LOW | MEDIUM | HIGH | CRITICAL`.
|
||||||
|
- Invalid prefix/length → `INVALID_NUMBER`, `delivery_success_rate: null`, `cancellation_rate: null` (not 0%/100%).
|
||||||
|
- Add `data_sources: ["steadfast_nationwide","prefix_validator"]` (reflecting what was actually queried), `sample_size`, `coverage_note`.
|
||||||
|
- Correct the tool description to match the real data sources (confirm in code which providers are queried).
|
||||||
|
- Never log the full phone number; mask as `017****1234` in logs.
|
||||||
|
- **Acceptance:** invalid number → `INVALID_NUMBER` with null rates; valid number with no history → `NO_HISTORY`.
|
||||||
|
|
||||||
|
### T7 — `track_parcel` and uniform error mapping (P1)
|
||||||
|
|
||||||
|
- **OBSERVED:** `track_parcel("SF00000000")` → `Aura Courier MCP Error: Request failed with status code 404`.
|
||||||
|
- **Required:** if `courier` omitted, auto-detect by prefix, then try all configured couriers. If none match → `ok:false`, `error.code:"CONSIGNMENT_NOT_FOUND"`, plus `couriers_checked:[...]`. Map upstream 401 → `COURIER_UPSTREAM_ERROR` (credential issue, non-retryable), 429/5xx/timeout → `COURIER_UPSTREAM_ERROR` with `retryable:true`. Add timeouts and bounded retry with backoff for GETs only (never auto-retry `create_parcel`).
|
||||||
|
- **Acceptance:** no raw axios text in any tool output.
|
||||||
|
|
||||||
|
### T8 — `create_parcel` safety + missing tools (P2)
|
||||||
|
|
||||||
|
- **Required:**
|
||||||
|
- `dry_run` (default false) returns `{would_book_with, estimated_cost_bdt, validation:{phone_ok,address_ok,needs_review}}` without any upstream booking call.
|
||||||
|
- Idempotency by `invoice` (per tenant): repeat call returns the existing consignment with `idempotent_replay:true`; never books twice. Persist the mapping.
|
||||||
|
- Real response data: `{consignment_id, tracking_code, courier, routing_reason, cost_estimate_bdt, cancellable_via_api}`.
|
||||||
|
- Auto routing (`courier:"auto"`) must record why a courier was chosen.
|
||||||
|
- New tools (additive): `cancel_parcel(courier, consignment_id)` where the provider API supports it, else `UNSUPPORTED_BY_PROVIDER`; `bulk_create_parcels(items[], dry_run)` with per-item results; `get_webhook_events(consignment_id?, since?)` over stored webhook events.
|
||||||
|
- Update the tool count in `/health`, homepage and README.
|
||||||
|
- **Acceptance (mocked upstream only):** two identical invoices → one upstream call, second returns `idempotent_replay:true`; `dry_run` makes zero upstream booking calls.
|
||||||
|
|
||||||
|
### T9 — `/health` exposure (P2)
|
||||||
|
|
||||||
|
- **OBSERVED:** `/health` publicly returns heap/rss/uptime, active sessions, engine names, webhook paths.
|
||||||
|
- **Required:** public `GET /health` → `{ok, version}` only. Detailed telemetry only with an admin key.
|
||||||
|
- **Acceptance:** unauthenticated `/health` has no heap/session/engine fields.
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
## 3. Test plan (all must pass in CI; mock every upstream)
|
||||||
|
|
||||||
|
| # | Test |
|
||||||
|
|---|---|
|
||||||
|
| 1 | No/invalid bearer → 401 on `/mcp`; unsigned webhook rejected |
|
||||||
|
| 2 | `resolve_ndr_issue` unknown id → `CONSIGNMENT_NOT_FOUND`; valid id → `actions_executed == []` and no `CUSTOMER_REENGAGED` |
|
||||||
|
| 3 | `get_balance` pathao → `amount_bdt:null`, `UNSUPPORTED_BY_PROVIDER` |
|
||||||
|
| 4 | Same address: zone-fee tool and compare tool agree on `zone` and `sla_hours` |
|
||||||
|
| 5 | Geocode Dhanmondi example → `needs_review:true`, confidence ≤ 60 when not ROOFTOP; thana not echoed as resolved |
|
||||||
|
| 6 | `check_fraud_risk("01000000000")` → `INVALID_NUMBER`, null rates |
|
||||||
|
| 7 | `track_parcel("SF00000000")` → `CONSIGNMENT_NOT_FOUND`, no raw axios text |
|
||||||
|
| 8 | `create_parcel` same invoice twice → one upstream call; second `idempotent_replay:true` |
|
||||||
|
| 9 | Chattogram 2 kg quote has no Dhaka-only coverage note |
|
||||||
|
| 10 | Public `/health` exposes only `ok` and `version` |
|
||||||
|
| 11 | Snapshot test: every tool response validates against the envelope schema |
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
## 4. Order of work
|
||||||
|
|
||||||
|
T1 → T2 → T3 → (T4, T5, T6, T7 in any order) → T8 → T9 → tests green → bump to **v2.6.0** → CHANGELOG.md → update README, homepage, `/guide`, tool descriptions.
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
## 5. Out of scope
|
||||||
|
|
||||||
|
- Adding new couriers or changing business pricing numbers (only unify and cite them).
|
||||||
|
- Touching production credentials or running anything against live courier production APIs.
|
||||||
|
- Rewriting the project in another language/framework.
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
## 6. Final report format (required)
|
||||||
|
|
||||||
|
1. **Repo map** (≤10 lines).
|
||||||
|
2. **Per task:** status (done / partial / blocked), files changed, commit hash, which acceptance tests pass.
|
||||||
|
3. **Resolved UNVERIFIED items:** T1 auth status before your change (enforced or not), whether rates were static or live, which providers the fraud engine really queries.
|
||||||
|
4. **Breaking or behavioral changes** a client must know about.
|
||||||
|
5. **Manual follow-ups** for the owner (key rotation, secret store, courier webhook reconfiguration).
|
||||||
|
6. **Test output summary** (counts, failures).
|
||||||
|
|
||||||
|
If any of the above could not be done, state it plainly instead of omitting it.
|
||||||
@@ -1,14 +1,19 @@
|
|||||||
# 🚚 AURA COURIER MCP v2.5.0 — THE ENTERPRISE LOGISTICS MASTER MANUAL
|
# 🚚 AURA COURIER MCP v2.6.0 — THE ENTERPRISE LOGISTICS MASTER MANUAL
|
||||||
### Universal Multi-Carrier Logistics Engine, Spatial Intelligence Hub & Zero-Risk COD Gateway
|
### Universal Multi-Carrier Logistics Engine, Spatial Intelligence Hub & Zero-Risk COD Gateway
|
||||||
**Published by Aura Agentic AI · Architected with DeepMind Principles & Google Maps Platform**
|
**Published by Aura Agentic AI · Architected with DeepMind Principles & Google Maps Platform**
|
||||||
|
|
||||||
[](https://cloud.google.com/find-a-partner/partner/aura-ajentic-ai)
|
[](https://cloud.google.com/find-a-partner/partner/aura-ajentic-ai)
|
||||||
[](https://glama.ai/mcp/servers/auraajenticai/aura-courier-mcp)
|
[](https://glama.ai/mcp/servers/auraajenticai/aura-courier-mcp)
|
||||||
[](plugin.json)
|
[](plugin.json)
|
||||||
|
[](https://courier.auraajenticai.cloud/guide)
|
||||||
[](https://opensource.org/licenses/Apache-2.0)
|
[](https://opensource.org/licenses/Apache-2.0)
|
||||||
[](https://courier.auraajenticai.cloud)
|
[](https://courier.auraajenticai.cloud)
|
||||||
[](https://nodejs.org)
|
[](https://nodejs.org)
|
||||||
|
|
||||||
|
<a href="https://glama.ai/mcp/servers/auraajenticai/aura-courier-mcp">
|
||||||
|
<img width="380" height="200" src="https://glama.ai/mcp/servers/auraajenticai/aura-courier-mcp/badges/card.svg" alt="Aura Courier MCP server" />
|
||||||
|
</a>
|
||||||
|
|
||||||
|
|
||||||
---
|
---
|
||||||
|
|
||||||
@@ -223,7 +228,7 @@ curl -s https://courier.auraajenticai.cloud/health | jq
|
|||||||
{
|
{
|
||||||
"ok": true,
|
"ok": true,
|
||||||
"service": "aura-courier-mcp",
|
"service": "aura-courier-mcp",
|
||||||
"version": "2.4.0",
|
"version": "2.6.0",
|
||||||
"tools_count": 9,
|
"tools_count": 9,
|
||||||
"spatial_engine": "Google Maps Platform (gmp_git_agentskills_v1)",
|
"spatial_engine": "Google Maps Platform (gmp_git_agentskills_v1)",
|
||||||
"fraud_engine": "Steadfast Nationwide API + BD Prefix Validator",
|
"fraud_engine": "Steadfast Nationwide API + BD Prefix Validator",
|
||||||
@@ -281,7 +286,7 @@ Add this configuration block to your client settings (`claude_desktop_config.jso
|
|||||||
"mcpServers": {
|
"mcpServers": {
|
||||||
"aura-courier": {
|
"aura-courier": {
|
||||||
"command": "npx",
|
"command": "npx",
|
||||||
"args": ["-y", "aura-courier-mcp@2.4.0"],
|
"args": ["-y", "aura-courier-mcp@2.6.0"],
|
||||||
"env": {
|
"env": {
|
||||||
"PORT": "8080",
|
"PORT": "8080",
|
||||||
"GOOGLE_MAPS_API_KEY": "<GOOGLE_MAPS_API_KEY>",
|
"GOOGLE_MAPS_API_KEY": "<GOOGLE_MAPS_API_KEY>",
|
||||||
@@ -343,6 +348,13 @@ Bundles the complete `courier-ops` skill (9 tools), `rules/COURIER_RULES.md` (sm
|
|||||||
|
|
||||||
## 9. Version History & Glama TDQS 5.0 Audit Log
|
## 9. Version History & Glama TDQS 5.0 Audit Log
|
||||||
|
|
||||||
|
* **v2.6.0 (Nov 10, 2026)**:
|
||||||
|
- **Bilingual User Guide & Business Benefits Hub (`GET /guide`)**: Interactive Bengali & English documentation (`https://courier.auraajenticai.cloud/guide`) covering 3-in-1 WooCommerce/Shopify integration, 6-Pillar WhatsApp/Messenger AI Bot harmony, Multi-Tenant Isolation, and MCP AI Agent setup.
|
||||||
|
- **Bilingual Real-Time Fraud Risk Output (`🇧🇩 বাংলা | 🇬🇧 English`)**: Upgraded `FraudRiskEngine.evaluateRisk` and In-Dashboard Quick-Ship widget (`/api/courier/quick-ship`) with bilingual recommendations and 1-click language switching.
|
||||||
|
- **Repository Governance & Glama Discovery Optimization**: Added `SECURITY.md`, `CONTRIBUTING.md`, `CHANGELOG.md`, and official Glama MCP card badge.
|
||||||
|
* **v2.5.1 (Nov 10, 2026)**:
|
||||||
|
- **Zero-Knowledge AES-256 Cryptographic Vault & Zero Admin Visibility**: Explicitly documented international cryptographic vault isolation in `/privacy`, guaranteeing that client Courier MCP API keys cannot be viewed or read by administrators.
|
||||||
|
- **Direct Dashboard Login & 3-in-1 E-Commerce Store Bridge**: Streamlined landing navigation (`Login ↗`) and synchronized MCP server metadata across all endpoints (`v2.5.1`).
|
||||||
* **v2.5.0 (Nov 9, 2026)**:
|
* **v2.5.0 (Nov 9, 2026)**:
|
||||||
- **Zero Hardcoded Credentials**: Purged all merchant secrets from repository code, enforcing strict runtime environment variable isolation.
|
- **Zero Hardcoded Credentials**: Purged all merchant secrets from repository code, enforcing strict runtime environment variable isolation.
|
||||||
- **Glama TDQS 5.0 Compliance**: Upgraded all 9 MCP tool definitions with explicit side-effects disclosure (state-mutating vs read-only), `when-to-use` vs `when-not-to-use` scenarios, and comprehensive parameter constraints.
|
- **Glama TDQS 5.0 Compliance**: Upgraded all 9 MCP tool definitions with explicit side-effects disclosure (state-mutating vs read-only), `when-to-use` vs `when-not-to-use` scenarios, and comprehensive parameter constraints.
|
||||||
|
|||||||
+20
@@ -0,0 +1,20 @@
|
|||||||
|
# Security Policy & Zero-Knowledge Vault Architecture
|
||||||
|
|
||||||
|
## Supported Versions
|
||||||
|
|
||||||
|
| Version | Supported |
|
||||||
|
| ------- | ------------------ |
|
||||||
|
| 2.5.x | :white_check_mark: |
|
||||||
|
| 2.4.x | :white_check_mark: |
|
||||||
|
| < 2.4.0 | :x: |
|
||||||
|
|
||||||
|
## Zero-Knowledge AES-256 Credential Vault Guarantee
|
||||||
|
|
||||||
|
**Aura Courier MCP** enforces strict **Zero-Knowledge Cryptographic Isolation** for all merchant courier and e-commerce store credentials:
|
||||||
|
1. **AES-256-CBC Encryption at Rest**: Whenever a merchant connects Steadfast, Pathao, RedX, Paperfly, WooCommerce, or Shopify API keys, credentials are immediately encrypted using AES-256-CBC before being stored in the isolated tenant vault.
|
||||||
|
2. **Zero Admin Visibility**: Platform administrators and engineers cannot view, inspect, or export any client's raw courier API keys.
|
||||||
|
3. **Transient In-Memory Execution**: Direct MCP header credentials (`x-steadfast-api-key`, `x-pathao-client-id`, etc.) exist strictly in isolated request memory for the duration of the tool call and are never written to disk or application logs.
|
||||||
|
|
||||||
|
## Reporting a Vulnerability
|
||||||
|
|
||||||
|
If you discover a security issue, please report it privately to **ceo@auraajenticai.cloud** or **khondokartowsif171@gmail.com**. We respond to all security reports within 24 hours.
|
||||||
Binary file not shown.
|
Before Width: | Height: | Size: 436 KiB After Width: | Height: | Size: 72 KiB |
@@ -0,0 +1,259 @@
|
|||||||
|
// World and Bangladesh Courier Hub Canvas Engine
|
||||||
|
function initCourierCanvas(canvasId = 'hubmap') {
|
||||||
|
const cv = document.getElementById(canvasId);
|
||||||
|
if (!cv) return;
|
||||||
|
const ctx = cv.getContext('2d');
|
||||||
|
const reduce = window.matchMedia && window.matchMedia('(prefers-reduced-motion: reduce)').matches;
|
||||||
|
|
||||||
|
// Major Global Logistics Gateways
|
||||||
|
const HUBS = [
|
||||||
|
['Dhaka', 23.81, 90.41, 1], ['Singapore', 1.35, 103.8], ['Dubai', 25.2, 55.3], ['Hong Kong', 22.3, 114.2],
|
||||||
|
['Shanghai', 31.2, 121.5], ['Tokyo', 35.7, 139.7], ['Mumbai', 19.1, 72.9], ['Delhi', 28.6, 77.2],
|
||||||
|
['Bangkok', 13.75, 100.5], ['Kuala Lumpur', 3.1, 101.7], ['Istanbul', 41.0, 28.98], ['Frankfurt', 50.1, 8.68],
|
||||||
|
['London', 51.5, -0.13], ['Paris', 48.85, 2.35], ['New York', 40.7, -74.0], ['Los Angeles', 34.05, -118.2],
|
||||||
|
['Chicago', 41.88, -87.6], ['Sao Paulo', -23.55, -46.6], ['Sydney', -33.87, 151.2], ['Johannesburg', -26.2, 28.0],
|
||||||
|
['Cairo', 30.04, 31.2], ['Moscow', 55.75, 37.6], ['Seoul', 37.57, 126.98], ['Toronto', 43.65, -79.38],
|
||||||
|
['Jakarta', -6.2, 106.8], ['Riyadh', 24.7, 46.7], ['Kolkata', 22.57, 88.36], ['Yangon', 16.87, 96.2],
|
||||||
|
['Mexico City', 19.43, -99.13], ['Buenos Aires', -34.6, -58.38], ['Vancouver', 49.28, -123.12]
|
||||||
|
];
|
||||||
|
const WLABELS = new Set(['Dhaka', 'Singapore', 'Dubai', 'London', 'New York', 'Hong Kong', 'Frankfurt', 'Tokyo', 'Sydney']);
|
||||||
|
|
||||||
|
// Bangladesh Nationwide Courier Hub Network (Steadfast, Pathao, RedX, Paperfly)
|
||||||
|
// [Name, Lat, Lon, isPrimaryHub, courierAffinity]
|
||||||
|
const BD = [
|
||||||
|
['Dhaka (Central Hub)', 23.81, 90.41, 1, 'all'],
|
||||||
|
['Chattogram Hub', 22.36, 91.80, 1, 'steadfast'],
|
||||||
|
['Sylhet Express', 24.90, 91.87, 1, 'pathao'],
|
||||||
|
['Khulna Gateway', 22.85, 89.56, 1, 'paperfly'],
|
||||||
|
['Rajshahi Hub', 24.37, 88.60, 1, 'redx'],
|
||||||
|
['Rangpur Northern', 25.75, 89.25, 0, 'steadfast'],
|
||||||
|
['Barishal Riverine', 22.70, 90.37, 0, 'paperfly'],
|
||||||
|
['Coxs Bazar Hub', 21.43, 91.99, 0, 'pathao'],
|
||||||
|
['Cumilla Express', 23.46, 91.18, 0, 'redx'],
|
||||||
|
['Bogura Hub', 24.85, 89.37, 0, 'steadfast'],
|
||||||
|
['Mymensingh Hub', 24.75, 90.40, 0, 'pathao'],
|
||||||
|
['Jashore Hub', 23.17, 89.21, 0, 'redx'],
|
||||||
|
['Dinajpur Hub', 25.63, 88.64, 0, 'paperfly'],
|
||||||
|
['Tetulia North', 26.49, 88.40, 1, 'steadfast'],
|
||||||
|
['Teknaf South', 20.86, 92.30, 1, 'pathao'],
|
||||||
|
['Rupsha West', 22.79, 89.63, 1, 'paperfly'],
|
||||||
|
['Pathuria East', 24.40, 92.05, 1, 'redx']
|
||||||
|
];
|
||||||
|
|
||||||
|
const CARRIER_COLORS = {
|
||||||
|
steadfast: { stroke: 'rgba(16, 185, 129, 0.40)', glow: 'rgba(16, 185, 129, 0.35)', core: '#6ee7b7' }, // Emerald
|
||||||
|
pathao: { stroke: 'rgba(244, 63, 94, 0.40)', glow: 'rgba(244, 63, 94, 0.35)', core: '#fda4af' }, // Rose/Red
|
||||||
|
redx: { stroke: 'rgba(239, 68, 68, 0.38)', glow: 'rgba(239, 68, 68, 0.32)', core: '#fca5a5' }, // Red
|
||||||
|
paperfly: { stroke: 'rgba(59, 130, 246, 0.40)', glow: 'rgba(59, 130, 246, 0.35)', core: '#93c5fd' }, // Blue
|
||||||
|
all: { stroke: 'rgba(6, 182, 212, 0.45)', glow: 'rgba(6, 182, 212, 0.40)', core: '#a5f3fc' } // Cyan
|
||||||
|
};
|
||||||
|
|
||||||
|
const LAT_TOP = 74, LAT_BOT = -56;
|
||||||
|
let W, H, DPR, pts, conns, bdPts, bdConns, raf, last = 0, dtG = 0.016;
|
||||||
|
const proj = (lat, lon) => [(lon + 180) / 360 * W, (LAT_TOP - lat) / (LAT_TOP - LAT_BOT) * H];
|
||||||
|
const bez = (a, cx, cy, b, t) => {
|
||||||
|
const u = 1 - t;
|
||||||
|
return [u * u * a.x + 2 * u * t * cx + t * t * b.x, u * u * a.y + 2 * u * t * cy + t * t * b.y];
|
||||||
|
};
|
||||||
|
function mk(a, b, sp, carrier = 'all') {
|
||||||
|
const d = Math.hypot(b.x - a.x, b.y - a.y);
|
||||||
|
return {
|
||||||
|
a, b,
|
||||||
|
cx: (a.x + b.x) / 2,
|
||||||
|
cy: (a.y + b.y) / 2 - Math.min(d * 0.22, 140),
|
||||||
|
t: Math.random(),
|
||||||
|
sp: sp || (0.12 + Math.random() * 0.16),
|
||||||
|
carrier
|
||||||
|
};
|
||||||
|
}
|
||||||
|
|
||||||
|
function build() {
|
||||||
|
DPR = Math.min(window.devicePixelRatio || 1, 2);
|
||||||
|
W = window.innerWidth;
|
||||||
|
H = window.innerHeight;
|
||||||
|
cv.width = W * DPR;
|
||||||
|
cv.height = H * DPR;
|
||||||
|
cv.style.width = W + 'px';
|
||||||
|
cv.style.height = H + 'px';
|
||||||
|
ctx.setTransform(DPR, 0, 0, DPR, 0, 0);
|
||||||
|
|
||||||
|
pts = HUBS.map(h => {
|
||||||
|
const p = proj(h[1], h[2]);
|
||||||
|
return { name: h[0], x: p[0], y: p[1], big: h[3] || 0, lbl: WLABELS.has(h[0]) };
|
||||||
|
});
|
||||||
|
const dhaka = pts[0];
|
||||||
|
conns = [];
|
||||||
|
for (let i = 1; i < pts.length; i++) conns.push(mk(dhaka, pts[i], 0.10 + Math.random() * 0.12, 'all'));
|
||||||
|
for (let k = 0; k < 15; k++) {
|
||||||
|
const a = pts[1 + (Math.random() * (pts.length - 1) | 0)];
|
||||||
|
const b = pts[1 + (Math.random() * (pts.length - 1) | 0)];
|
||||||
|
if (a !== b) conns.push(mk(a, b, 0.08 + Math.random() * 0.1, 'all'));
|
||||||
|
}
|
||||||
|
|
||||||
|
const S = Math.max(26, Math.min(62, Math.min(H * 0.088, W * 0.09)));
|
||||||
|
const ax = Math.min(dhaka.x, W - 6.4 * S - 60);
|
||||||
|
const ay = Math.min(Math.max(dhaka.y, 3.4 * S + 24), H - 5.4 * S - 12);
|
||||||
|
const lp = (lat, lon) => [ax + (lon - 90.41) * S, ay - (lat - 23.81) * S];
|
||||||
|
|
||||||
|
bdPts = BD.map(c => {
|
||||||
|
const p = lp(c[1], c[2]);
|
||||||
|
return { name: c[0], x: p[0], y: p[1], lbl: c[3], carrier: c[4] };
|
||||||
|
});
|
||||||
|
const byName = {};
|
||||||
|
bdPts.forEach(p => byName[p.name] = p);
|
||||||
|
const bd0 = bdPts[0]; // Dhaka Central
|
||||||
|
|
||||||
|
bdConns = [];
|
||||||
|
for (let i = 1; i < bdPts.length; i++) {
|
||||||
|
const dest = bdPts[i];
|
||||||
|
bdConns.push(mk(bd0, dest, 0.18 + Math.random() * 0.15, dest.carrier));
|
||||||
|
}
|
||||||
|
// Major inter-district trunk corridors
|
||||||
|
const corridors = [
|
||||||
|
['Teknaf South', 'Tetulia North', 'steadfast'],
|
||||||
|
['Rupsha West', 'Pathuria East', 'paperfly'],
|
||||||
|
['Chattogram Hub', 'Sylhet Express', 'pathao'],
|
||||||
|
['Khulna Gateway', 'Rangpur Northern', 'steadfast'],
|
||||||
|
['Coxs Bazar Hub', 'Dinajpur Hub', 'redx']
|
||||||
|
];
|
||||||
|
corridors.forEach(pr => {
|
||||||
|
const a = byName[pr[0]], b = byName[pr[1]];
|
||||||
|
if (a && b) bdConns.push(mk(a, b, 0.14 + Math.random() * 0.1, pr[2]));
|
||||||
|
});
|
||||||
|
}
|
||||||
|
|
||||||
|
function grid() {
|
||||||
|
ctx.strokeStyle = 'rgba(96, 112, 160, 0.08)';
|
||||||
|
ctx.lineWidth = 1;
|
||||||
|
for (let la = LAT_TOP - 12; la > LAT_BOT; la -= 22) {
|
||||||
|
const p = proj(la, 0);
|
||||||
|
ctx.beginPath(); ctx.moveTo(0, p[1]); ctx.lineTo(W, p[1]); ctx.stroke();
|
||||||
|
}
|
||||||
|
for (let lo = -150; lo < 180; lo += 30) {
|
||||||
|
const p = proj(0, lo);
|
||||||
|
ctx.beginPath(); ctx.moveTo(p[0], 0); ctx.lineTo(p[0], H); ctx.stroke();
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
function drawArcs(list, defaultColors, rad = 7.5) {
|
||||||
|
for (const c of list) {
|
||||||
|
const col = CARRIER_COLORS[c.carrier] || defaultColors;
|
||||||
|
ctx.beginPath();
|
||||||
|
ctx.moveTo(c.a.x, c.a.y);
|
||||||
|
ctx.quadraticCurveTo(c.cx, c.cy, c.b.x, c.b.y);
|
||||||
|
ctx.strokeStyle = col.stroke;
|
||||||
|
ctx.lineWidth = 1.2;
|
||||||
|
ctx.stroke();
|
||||||
|
|
||||||
|
if (!reduce) {
|
||||||
|
c.t += c.sp * dtG;
|
||||||
|
if (c.t > 1) c.t -= 1;
|
||||||
|
}
|
||||||
|
const p = bez(c.a, c.cx, c.cy, c.b, reduce ? 0.5 : c.t);
|
||||||
|
// Outer particle glow
|
||||||
|
ctx.fillStyle = col.glow;
|
||||||
|
ctx.beginPath();
|
||||||
|
ctx.arc(p[0], p[1], rad, 0, Math.PI * 2);
|
||||||
|
ctx.fill();
|
||||||
|
// Inner glowing packet
|
||||||
|
ctx.fillStyle = col.core;
|
||||||
|
ctx.beginPath();
|
||||||
|
ctx.arc(p[0], p[1], 2.2, 0, Math.PI * 2);
|
||||||
|
ctx.fill();
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
function frame(ts) {
|
||||||
|
dtG = Math.min((ts - last) / 1000, 0.05) || 0.016;
|
||||||
|
last = ts;
|
||||||
|
ctx.clearRect(0, 0, W, H);
|
||||||
|
grid();
|
||||||
|
|
||||||
|
// 1. Draw Global Freight Connections
|
||||||
|
drawArcs(conns, { stroke: 'rgba(88,132,255,0.18)', glow: 'rgba(56,189,248,0.22)', core: '#a9e6ff' }, 7.5);
|
||||||
|
|
||||||
|
// Global Hub nodes
|
||||||
|
for (const p of pts) {
|
||||||
|
ctx.fillStyle = p.big ? 'rgba(56,189,248,0.92)' : 'rgba(130,158,225,0.72)';
|
||||||
|
ctx.beginPath();
|
||||||
|
ctx.arc(p.x, p.y, p.big ? 4.5 : 2.8, 0, Math.PI * 2);
|
||||||
|
ctx.fill();
|
||||||
|
if (p.lbl && p.name !== 'Dhaka') {
|
||||||
|
ctx.fillStyle = 'rgba(160,168,196,0.48)';
|
||||||
|
ctx.font = '500 11.5px "JetBrains Mono", monospace';
|
||||||
|
ctx.fillText(p.name, p.x + 8, p.y + 4);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
// 2. Draw Bangladesh All-Courier Dispatch Lines
|
||||||
|
drawArcs(bdConns, { stroke: 'rgba(56,189,248,0.35)', glow: 'rgba(52,211,153,0.36)', core: '#c9ffe9' }, 8.5);
|
||||||
|
|
||||||
|
// Pulsing radar rings on Bangladesh hubs
|
||||||
|
const pr = (ts % 3000) / 3000;
|
||||||
|
for (const p of bdPts) {
|
||||||
|
const isCentral = p.name.includes('Dhaka');
|
||||||
|
const carrierCol = CARRIER_COLORS[p.carrier] || CARRIER_COLORS.all;
|
||||||
|
|
||||||
|
if (!reduce && (p.lbl || isCentral)) {
|
||||||
|
ctx.strokeStyle = isCentral
|
||||||
|
? 'rgba(6, 182, 212, ' + (0.55 * (1 - pr)) + ')'
|
||||||
|
: carrierCol.glow.replace(/[\d.]+\)$/, (0.45 * (1 - pr)) + ')');
|
||||||
|
ctx.lineWidth = isCentral ? 1.8 : 1.2;
|
||||||
|
ctx.beginPath();
|
||||||
|
ctx.arc(p.x, p.y, (isCentral ? 6 : 4) + pr * (isCentral ? 32 : 24), 0, Math.PI * 2);
|
||||||
|
ctx.stroke();
|
||||||
|
}
|
||||||
|
|
||||||
|
ctx.fillStyle = isCentral ? '#00d4ff' : carrierCol.core;
|
||||||
|
ctx.beginPath();
|
||||||
|
ctx.arc(p.x, p.y, isCentral ? 5.5 : 3.8, 0, Math.PI * 2);
|
||||||
|
ctx.fill();
|
||||||
|
|
||||||
|
// Hub Label
|
||||||
|
if (p.lbl || isCentral) {
|
||||||
|
ctx.fillStyle = isCentral ? '#38bdf8' : 'rgba(226, 232, 240, 0.82)';
|
||||||
|
ctx.font = (isCentral ? '700 ' : '600 ') + (isCentral ? '13px ' : '11.5px ') + '"JetBrains Mono", monospace';
|
||||||
|
const cleanName = p.name.replace(/\s*\(.*\)/, '');
|
||||||
|
ctx.fillText((isCentral ? '◆ ' : '• ') + cleanName, p.x + 8, p.y + 4);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
if (!reduce) raf = requestAnimationFrame(frame);
|
||||||
|
}
|
||||||
|
|
||||||
|
function start() {
|
||||||
|
cancelAnimationFrame(raf);
|
||||||
|
build();
|
||||||
|
last = 0;
|
||||||
|
frame(performance.now());
|
||||||
|
}
|
||||||
|
|
||||||
|
let rt;
|
||||||
|
window.addEventListener('resize', () => {
|
||||||
|
clearTimeout(rt);
|
||||||
|
rt = setTimeout(start, 200);
|
||||||
|
});
|
||||||
|
document.addEventListener('visibilitychange', () => {
|
||||||
|
if (!document.hidden && !reduce) {
|
||||||
|
cancelAnimationFrame(raf);
|
||||||
|
raf = requestAnimationFrame(frame);
|
||||||
|
}
|
||||||
|
});
|
||||||
|
|
||||||
|
if (document.readyState === 'loading') {
|
||||||
|
document.addEventListener('DOMContentLoaded', start);
|
||||||
|
} else {
|
||||||
|
start();
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
// Auto-initialize canvas on page load
|
||||||
|
if (typeof window !== 'undefined') {
|
||||||
|
window.initCourierCanvas = initCourierCanvas;
|
||||||
|
if (document.readyState === 'loading') {
|
||||||
|
document.addEventListener('DOMContentLoaded', () => initCourierCanvas('hubmap'));
|
||||||
|
} else {
|
||||||
|
initCourierCanvas('hubmap');
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
Binary file not shown.
|
After Width: | Height: | Size: 72 KiB |
Binary file not shown.
|
After Width: | Height: | Size: 72 KiB |
Binary file not shown.
|
After Width: | Height: | Size: 72 KiB |
@@ -0,0 +1,40 @@
|
|||||||
|
# Aura Courier MCP — Agent Configurations Vault
|
||||||
|
|
||||||
|
Connect any AI Agent / IDE to Aura Courier MCP in seconds.
|
||||||
|
|
||||||
|
## Endpoints:
|
||||||
|
- **Streamable-HTTP (Cursor, Antigravity, Windsurf, Cline, n8n)**:
|
||||||
|
`https://courier.auraajenticai.cloud/mcp`
|
||||||
|
- **Server-Sent Events / SSE (Claude Desktop, Remote SSE)**:
|
||||||
|
`https://courier.auraajenticai.cloud/sse`
|
||||||
|
- **NPX Direct CLI**:
|
||||||
|
`npx -y @auraajenticai/aura-courier-mcp@2.6.0`
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
## 1. Google Antigravity & Gemini CLI
|
||||||
|
File: `antigravity_gemini.json`
|
||||||
|
Location:
|
||||||
|
- Windows: `%USERPROFILE%\.gemini\antigravity\mcp\aura-courier\server.json`
|
||||||
|
- Linux/macOS: `~/.gemini/antigravity/mcp/aura-courier/server.json`
|
||||||
|
|
||||||
|
## 2. Claude Desktop
|
||||||
|
File: `claude_desktop_config.json`
|
||||||
|
Location:
|
||||||
|
- Windows: `%APPDATA%\Claude\claude_desktop_config.json`
|
||||||
|
- macOS: `~/Library/Application Support/Claude/claude_desktop_config.json`
|
||||||
|
|
||||||
|
## 3. Cursor IDE
|
||||||
|
File: `cursor_mcp.json`
|
||||||
|
Location:
|
||||||
|
- Settings -> Features -> MCP -> Add new MCP server -> Type: `http`, URL: `https://courier.auraajenticai.cloud/mcp`
|
||||||
|
|
||||||
|
## 4. Windsurf IDE
|
||||||
|
File: `windsurf_mcp_config.json`
|
||||||
|
Location:
|
||||||
|
- `~/.codeium/windsurf/mcp_config.json`
|
||||||
|
|
||||||
|
## 5. Cline / Roo Code / VS Code
|
||||||
|
File: `cline_mcp_settings.json`
|
||||||
|
Location:
|
||||||
|
- VS Code Settings -> Extension Settings -> Cline / Roo Code -> Edit in settings.json
|
||||||
@@ -0,0 +1,18 @@
|
|||||||
|
{
|
||||||
|
"$schema": "https://json-schema.org/draft/2020-12/schema",
|
||||||
|
"title": "Aura Courier MCP - Google Antigravity & Gemini CLI Config",
|
||||||
|
"mcpServers": {
|
||||||
|
"aura-courier": {
|
||||||
|
"url": "https://courier.auraajenticai.cloud/mcp",
|
||||||
|
"type": "http",
|
||||||
|
"description": "Enterprise Bangladesh Courier MCP & Google Maps Spatial Hub"
|
||||||
|
},
|
||||||
|
"aura-courier-local": {
|
||||||
|
"command": "npx",
|
||||||
|
"args": ["-y", "@auraajenticai/aura-courier-mcp@2.6.0"],
|
||||||
|
"env": {
|
||||||
|
"PORT": "8080"
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -0,0 +1,12 @@
|
|||||||
|
{
|
||||||
|
"mcpServers": {
|
||||||
|
"aura-courier": {
|
||||||
|
"url": "https://courier.auraajenticai.cloud/sse",
|
||||||
|
"transport": "sse"
|
||||||
|
},
|
||||||
|
"aura-courier-stdio": {
|
||||||
|
"command": "npx",
|
||||||
|
"args": ["-y", "@auraajenticai/aura-courier-mcp@2.6.0"]
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -0,0 +1,15 @@
|
|||||||
|
{
|
||||||
|
"mcpServers": {
|
||||||
|
"aura-courier": {
|
||||||
|
"url": "https://courier.auraajenticai.cloud/mcp",
|
||||||
|
"autoApprove": [
|
||||||
|
"list_couriers",
|
||||||
|
"calculate_delivery_zone_and_fee",
|
||||||
|
"compare_courier_rates",
|
||||||
|
"validate_and_geocode_address",
|
||||||
|
"check_fraud_risk",
|
||||||
|
"track_parcel"
|
||||||
|
]
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -0,0 +1,8 @@
|
|||||||
|
{
|
||||||
|
"mcpServers": {
|
||||||
|
"aura-courier": {
|
||||||
|
"url": "https://courier.auraajenticai.cloud/mcp",
|
||||||
|
"transport": "http"
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -0,0 +1,7 @@
|
|||||||
|
{
|
||||||
|
"mcpServers": {
|
||||||
|
"aura-courier": {
|
||||||
|
"serverUrl": "https://courier.auraajenticai.cloud/mcp"
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
Vendored
+5
-3
@@ -1,9 +1,11 @@
|
|||||||
import { FraudRiskScoreResponse } from "../types.js";
|
import { FraudRiskScoreResponse } from "../types.js";
|
||||||
import { SteadfastAdapter } from "./steadfast.js";
|
import { SteadfastAdapter } from "./steadfast.js";
|
||||||
|
import { PathaoAdapter } from "./pathao.js";
|
||||||
export declare class FraudRiskEngine {
|
export declare class FraudRiskEngine {
|
||||||
/**
|
/**
|
||||||
* 100% Real Live Courier Fraud & Delivery Risk Evaluation
|
* Real-Time Multi-Carrier Fraud & Delivery Risk Evaluation (T6)
|
||||||
* Connects to Steadfast Nationwide Logistics Database (covers millions of BD consignments)
|
* Queries Pathao Nationwide Customer Delivery Database (/aladdin/api/v1/user/success),
|
||||||
|
* Steadfast Nationwide Logistics Database (/fraud_check/{phone}), and BD Operator Prefix Validator.
|
||||||
*/
|
*/
|
||||||
static evaluateRisk(phoneNumber: string, steadfastAdapter?: SteadfastAdapter): Promise<FraudRiskScoreResponse>;
|
static evaluateRisk(phoneNumber: string, steadfastAdapter?: SteadfastAdapter, pathaoAdapter?: PathaoAdapter): Promise<FraudRiskScoreResponse>;
|
||||||
}
|
}
|
||||||
|
|||||||
Vendored
+117
-93
@@ -1,130 +1,154 @@
|
|||||||
export class FraudRiskEngine {
|
export class FraudRiskEngine {
|
||||||
/**
|
/**
|
||||||
* 100% Real Live Courier Fraud & Delivery Risk Evaluation
|
* Real-Time Multi-Carrier Fraud & Delivery Risk Evaluation (T6)
|
||||||
* Connects to Steadfast Nationwide Logistics Database (covers millions of BD consignments)
|
* Queries Pathao Nationwide Customer Delivery Database (/aladdin/api/v1/user/success),
|
||||||
|
* Steadfast Nationwide Logistics Database (/fraud_check/{phone}), and BD Operator Prefix Validator.
|
||||||
*/
|
*/
|
||||||
static async evaluateRisk(phoneNumber, steadfastAdapter) {
|
static async evaluateRisk(phoneNumber, steadfastAdapter, pathaoAdapter) {
|
||||||
const cleanPhone = phoneNumber.replace(/[^0-9]/g, "");
|
const rawDigits = String(phoneNumber || "").replace(/[^0-9]/g, "");
|
||||||
|
const cleanPhone = rawDigits.startsWith("880") && rawDigits.length === 13 ? rawDigits.slice(2) : rawDigits;
|
||||||
// Valid BD Mobile format check (11 digits starting with 013, 014, 015, 016, 017, 018, 019)
|
// Valid BD Mobile format check (11 digits starting with 013, 014, 015, 016, 017, 018, 019)
|
||||||
const isValidBDOperator = /^01[3-9]\d{8}$/.test(cleanPhone);
|
const isValidBDOperator = /^01[3-9]\d{8}$/.test(cleanPhone);
|
||||||
if (!isValidBDOperator) {
|
if (!isValidBDOperator) {
|
||||||
return {
|
return {
|
||||||
phone: phoneNumber,
|
phone: phoneNumber,
|
||||||
risk_level: "CRITICAL",
|
risk_level: "INVALID_NUMBER",
|
||||||
delivery_success_rate: "0%",
|
delivery_success_rate: null,
|
||||||
total_parcels: 0,
|
total_parcels: 0,
|
||||||
total_delivered: 0,
|
total_delivered: 0,
|
||||||
total_cancelled: 0,
|
total_cancelled: 0,
|
||||||
cancellation_rate: "100%",
|
cancellation_rate: null,
|
||||||
is_verified_buyer: false,
|
is_verified_buyer: false,
|
||||||
recommendation: "ভুল বা অকার্যকর বাংলাদেশি মোবাইল নম্বর। ম্যানুয়াল ভেরিফিকেশন ছাড়া পার্সেল বুক করবেন না।",
|
recommendation: "🇧🇩 ভুল বা অকার্যকর বাংলাদেশি মোবাইল নম্বর। ম্যানুয়াল ভেরিফিকেশন ছাড়া পার্সেল বুক করবেন না। | 🇬🇧 Invalid Bangladesh mobile number (11 digits starting with 013–019 required). Do not dispatch without manual verification.",
|
||||||
carrier_source: "operator_prefix_validator",
|
carrier_source: "prefix_validator",
|
||||||
carrier_verified: false,
|
carrier_verified: false,
|
||||||
|
data_sources: ["prefix_validator"],
|
||||||
|
sample_size: 0,
|
||||||
|
coverage_note: "Validated against BTRC 11-digit mobile operator prefix rules (013–019).",
|
||||||
};
|
};
|
||||||
}
|
}
|
||||||
// Check if live Steadfast adapter is available & configured
|
let total = 0;
|
||||||
|
let delivered = 0;
|
||||||
|
let cancelled = 0;
|
||||||
|
let verifiedByCarrier = false;
|
||||||
|
const dataSources = [];
|
||||||
|
let customerRating;
|
||||||
|
// 1. Query Steadfast Nationwide Fraud Database (GET /fraud_check/{phone})
|
||||||
if (steadfastAdapter && steadfastAdapter.isConfigured()) {
|
if (steadfastAdapter && steadfastAdapter.isConfigured()) {
|
||||||
try {
|
try {
|
||||||
const liveData = await steadfastAdapter.fraudCheck(cleanPhone);
|
const sfData = await steadfastAdapter.fraudCheck(cleanPhone);
|
||||||
// Steadfast returns status: 200, and parcel count fields
|
const sfTotal = Number(sfData?.total_parcels ?? sfData?.data?.total_parcels ?? 0);
|
||||||
const total = Number(liveData?.total_parcels ?? liveData?.data?.total_parcels ?? 0);
|
const sfDelivered = Number(sfData?.total_delivered ?? sfData?.data?.total_delivered ?? 0);
|
||||||
const delivered = Number(liveData?.total_delivered ?? liveData?.data?.total_delivered ?? 0);
|
const sfCancelled = Number(sfData?.total_cancelled ?? sfData?.data?.total_cancelled ?? 0);
|
||||||
const cancelled = Number(liveData?.total_cancelled ?? liveData?.data?.total_cancelled ?? 0);
|
total += sfTotal;
|
||||||
if (total === 0) {
|
delivered += sfDelivered;
|
||||||
return {
|
cancelled += sfCancelled;
|
||||||
phone: cleanPhone,
|
verifiedByCarrier = true;
|
||||||
risk_level: "NEW_BUYER",
|
dataSources.push("steadfast_nationwide");
|
||||||
delivery_success_rate: "N/A (নতুন ক্রেতা)",
|
}
|
||||||
total_parcels: 0,
|
catch (_) {
|
||||||
total_delivered: 0,
|
// Continue to Pathao check
|
||||||
total_cancelled: 0,
|
}
|
||||||
cancellation_rate: "0%",
|
}
|
||||||
is_verified_buyer: true,
|
// 2. Query Pathao Nationwide Customer Delivery Database (POST /aladdin/api/v1/user/success)
|
||||||
recommendation: "সারা দেশের কুরিয়ার ডেটাবেজে কোনো রেকর্ড নেই (নতুন ক্রেতা)। ফোনে ঠিকানা ও অর্ডার কনফার্ম করে ক্যাশ অন ডেলিভারিতে পাঠানো যেতে পারে।",
|
if (pathaoAdapter && pathaoAdapter.isConfigured()) {
|
||||||
carrier_source: "steadfast_nationwide_api",
|
try {
|
||||||
carrier_verified: true,
|
const ptRes = await pathaoAdapter.fraudCheck(cleanPhone);
|
||||||
};
|
const ptData = ptRes?.data || ptRes || {};
|
||||||
}
|
const cust = ptData.customer || {};
|
||||||
const successRatio = (delivered / total) * 100;
|
const ptTotal = Number(cust.total_delivery ?? 0);
|
||||||
const cancelRatio = (cancelled / total) * 100;
|
const ptDelivered = Number(cust.successful_delivery ?? 0);
|
||||||
const successRateStr = `${successRatio.toFixed(1)}%`;
|
const ptCancelled = Math.max(0, ptTotal - ptDelivered);
|
||||||
const cancelRateStr = `${cancelRatio.toFixed(1)}%`;
|
total += ptTotal;
|
||||||
if (successRatio >= 85) {
|
delivered += ptDelivered;
|
||||||
return {
|
cancelled += ptCancelled;
|
||||||
phone: cleanPhone,
|
verifiedByCarrier = true;
|
||||||
risk_level: "LOW",
|
dataSources.push("pathao_nationwide");
|
||||||
delivery_success_rate: successRateStr,
|
if (ptData.customer_rating) {
|
||||||
total_parcels: total,
|
customerRating = String(ptData.customer_rating);
|
||||||
total_delivered: delivered,
|
|
||||||
total_cancelled: cancelled,
|
|
||||||
cancellation_rate: cancelRateStr,
|
|
||||||
is_verified_buyer: true,
|
|
||||||
recommendation: `কাস্টমার অত্যন্ত নির্ভরযোগ্য (সফল ডেলিভারি: ${delivered}/${total}টি, সাকসেস রেট: ${successRateStr})। ১০০% নির্দ্বিধায় ক্যাশ অন ডেলিভারি (COD) পাঠান।`,
|
|
||||||
carrier_source: "steadfast_nationwide_api",
|
|
||||||
carrier_verified: true,
|
|
||||||
};
|
|
||||||
}
|
|
||||||
else if (successRatio >= 60) {
|
|
||||||
return {
|
|
||||||
phone: cleanPhone,
|
|
||||||
risk_level: "MODERATE",
|
|
||||||
delivery_success_rate: successRateStr,
|
|
||||||
total_parcels: total,
|
|
||||||
total_delivered: delivered,
|
|
||||||
total_cancelled: cancelled,
|
|
||||||
cancellation_rate: cancelRateStr,
|
|
||||||
is_verified_buyer: true,
|
|
||||||
recommendation: `মাঝারি ঝুঁকি (সফল: ${delivered}টি, ক্যানসেল: ${cancelled}টি, ক্যানসেলেশন রেট: ${cancelRateStr})। পার্সেল পাঠানোর আগে কাস্টমারকে ফোন দিয়ে অর্ডার কনফার্ম করুন।`,
|
|
||||||
carrier_source: "steadfast_nationwide_api",
|
|
||||||
carrier_verified: true,
|
|
||||||
};
|
|
||||||
}
|
|
||||||
else {
|
|
||||||
return {
|
|
||||||
phone: cleanPhone,
|
|
||||||
risk_level: "HIGH",
|
|
||||||
delivery_success_rate: successRateStr,
|
|
||||||
total_parcels: total,
|
|
||||||
total_delivered: delivered,
|
|
||||||
total_cancelled: cancelled,
|
|
||||||
cancellation_rate: cancelRateStr,
|
|
||||||
is_verified_buyer: false,
|
|
||||||
recommendation: `উচ্চ ঝুঁকির ক্রেতা! পূর্ববর্তী অর্ডারের ${cancelRateStr} ক্যানসেল/রিটার্ন করেছেন (${cancelled}টি ক্যানসেল)। পার্সেল পাঠানোর আগে ডেলিভারি চার্জ (১৫০৳) অগ্রিম নেওয়ার সুপারিশ করা হচ্ছে।`,
|
|
||||||
carrier_source: "steadfast_nationwide_api",
|
|
||||||
carrier_verified: true,
|
|
||||||
};
|
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
catch (apiErr) {
|
catch (_) {
|
||||||
// Transparent error reporting — no fake numbers fabricated
|
// Carrier lookup error handled gracefully
|
||||||
|
}
|
||||||
|
}
|
||||||
|
dataSources.push("prefix_validator");
|
||||||
|
const sourceLabel = dataSources.join("+");
|
||||||
|
if (verifiedByCarrier) {
|
||||||
|
if (total === 0) {
|
||||||
return {
|
return {
|
||||||
phone: cleanPhone,
|
phone: cleanPhone,
|
||||||
risk_level: "MODERATE",
|
risk_level: "NO_HISTORY",
|
||||||
delivery_success_rate: "অজানা (API ত্রুটি)",
|
delivery_success_rate: null,
|
||||||
total_parcels: 0,
|
total_parcels: 0,
|
||||||
total_delivered: 0,
|
total_delivered: 0,
|
||||||
total_cancelled: 0,
|
total_cancelled: 0,
|
||||||
cancellation_rate: "অজানা",
|
cancellation_rate: null,
|
||||||
is_verified_buyer: false,
|
is_verified_buyer: true,
|
||||||
recommendation: `সঠিক বাংলাদেশি নম্বর। Steadfast লাইভ ডেটাবেজ চেক করার সময় ত্রুটি ঘটেছে (${apiErr.message})। ফোন করে নিশ্চিত করুন।`,
|
recommendation: "🇧🇩 কুরিয়ার ডেটাবেজে পূর্বে কোনো অর্ডার বা রিটার্ন রেকর্ড নেই (নতুন ক্রেতা)। ফোনে ঠিকানা কনফার্ম করে পাঠানো যেতে পারে। | 🇬🇧 No prior delivery or return history found in queried courier databases. Confirm via phone call before COD dispatch.",
|
||||||
carrier_source: "steadfast_api_error_fallback",
|
carrier_source: sourceLabel,
|
||||||
carrier_verified: false,
|
carrier_verified: true,
|
||||||
|
data_sources: dataSources,
|
||||||
|
sample_size: 0,
|
||||||
|
coverage_note: `Queried ${dataSources.filter((s) => s !== "prefix_validator").join(" and ")} live databases; 0 prior consignments recorded.`,
|
||||||
};
|
};
|
||||||
}
|
}
|
||||||
|
const successRatio = (delivered / total) * 100;
|
||||||
|
const cancelRatio = (cancelled / total) * 100;
|
||||||
|
const successRateStr = `${successRatio.toFixed(1)}%`;
|
||||||
|
const cancelRateStr = `${cancelRatio.toFixed(1)}%`;
|
||||||
|
const ratingNote = customerRating ? ` [Carrier Rating: ${customerRating}]` : "";
|
||||||
|
let riskLevel = "LOW";
|
||||||
|
let rec = "";
|
||||||
|
if (successRatio >= 80) {
|
||||||
|
riskLevel = "LOW";
|
||||||
|
rec = `🇧🇩 কাস্টমার অত্যন্ত নির্ভরযোগ্য (সফল ডেলিভারি: ${delivered}/${total}টি, সাকসেস রেট: ${successRateStr})। নির্দ্বিধায় ক্যাশ অন ডেলিভারি (COD) পাঠান। | 🇬🇧 Highly reliable buyer (${delivered}/${total} delivered, ${successRateStr} success rate)${ratingNote}. Safe for immediate COD dispatch.`;
|
||||||
|
}
|
||||||
|
else if (successRatio >= 55) {
|
||||||
|
riskLevel = "MEDIUM";
|
||||||
|
rec = `🇧🇩 মাঝারি ঝুঁকি (সফল: ${delivered}টি, ক্যানসেল/রিটার্ন: ${cancelled}টি, ক্যানসেলেশন রেট: ${cancelRateStr})। পার্সেল পাঠানোর আগে কাস্টমারকে ফোন দিয়ে অর্ডার কনফার্ম করুন। | 🇬🇧 Medium risk (${delivered} delivered, ${cancelled} returned, ${cancelRateStr} return rate)${ratingNote}. Confirm order via phone call before dispatch.`;
|
||||||
|
}
|
||||||
|
else if (successRatio >= 25) {
|
||||||
|
riskLevel = "HIGH";
|
||||||
|
rec = `🇧🇩 উচ্চ ঝুঁকির ক্রেতা! পূর্ববর্তী অর্ডারের ${cancelRateStr} ক্যানসেল/রিটার্ন করেছেন (${cancelled}/${total}টি রিটার্ন)। ডেলিভারি চার্জ অগ্রিম নেওয়ার সুপারিশ করা হচ্ছে। | 🇬🇧 High fraud risk! Buyer cancelled/returned ${cancelRateStr} of past orders (${cancelled}/${total} returned)${ratingNote}. Collect advance delivery charge before shipping.`;
|
||||||
|
}
|
||||||
|
else {
|
||||||
|
riskLevel = "CRITICAL";
|
||||||
|
rec = `🇧🇩 মারাত্মক ঝুঁকির ক্রেতা! পূর্ববর্তী অর্ডারের ${cancelRateStr} রিটার্ন করেছেন (${cancelled}/${total}টি রিটার্ন)। অগ্রিম পেমেন্ট ছাড়া পার্সেল পাঠাবেন না। | 🇬🇧 Critical return risk! Buyer returned ${cancelRateStr} of past orders (${cancelled}/${total} returned)${ratingNote}. Require advance payment before dispatch.`;
|
||||||
|
}
|
||||||
|
return {
|
||||||
|
phone: cleanPhone,
|
||||||
|
risk_level: riskLevel,
|
||||||
|
delivery_success_rate: successRateStr,
|
||||||
|
total_parcels: total,
|
||||||
|
total_delivered: delivered,
|
||||||
|
total_cancelled: cancelled,
|
||||||
|
cancellation_rate: cancelRateStr,
|
||||||
|
is_verified_buyer: riskLevel === "LOW" || riskLevel === "MEDIUM",
|
||||||
|
recommendation: rec,
|
||||||
|
carrier_source: sourceLabel,
|
||||||
|
carrier_verified: true,
|
||||||
|
data_sources: dataSources,
|
||||||
|
sample_size: total,
|
||||||
|
coverage_note: `Aggregated ${total} historical consignments from ${dataSources.filter((s) => s !== "prefix_validator").join(" and ")}.`,
|
||||||
|
};
|
||||||
}
|
}
|
||||||
// Honest fallback when no merchant API key is plugged in
|
// Honest fallback when no carrier database returned history
|
||||||
return {
|
return {
|
||||||
phone: cleanPhone,
|
phone: cleanPhone,
|
||||||
risk_level: "MODERATE",
|
risk_level: "NO_HISTORY",
|
||||||
delivery_success_rate: "অজানা (ক্রেডেনশিয়াল প্রয়োজন)",
|
delivery_success_rate: null,
|
||||||
total_parcels: 0,
|
total_parcels: 0,
|
||||||
total_delivered: 0,
|
total_delivered: 0,
|
||||||
total_cancelled: 0,
|
total_cancelled: 0,
|
||||||
cancellation_rate: "অজানা",
|
cancellation_rate: null,
|
||||||
is_verified_buyer: false,
|
is_verified_buyer: false,
|
||||||
recommendation: "সঠিক বাংলাদেশি মোবাইল নম্বর। লাইভ কুরিয়ার হিস্ট্রি ও ফ্রড রেট চেক করতে Steadfast API Key কনফিগার করুন।",
|
recommendation: "🇧🇩 সঠিক বাংলাদেশি মোবাইল নম্বর, তবে কুরিয়ার হিস্ট্রি পাওয়া যায়নি। ফোনে নিশ্চিত হয়ে ডিসপ্যাচ করুন। | 🇬🇧 Valid BD mobile number, but no live carrier history was returned. Verify via phone call before dispatch.",
|
||||||
carrier_source: "bd_operator_validator_unverified",
|
carrier_source: "prefix_validator",
|
||||||
carrier_verified: false,
|
carrier_verified: false,
|
||||||
|
data_sources: ["prefix_validator"],
|
||||||
|
sample_size: 0,
|
||||||
|
coverage_note: "Validated format via BTRC prefix rules only; no upstream carrier history available.",
|
||||||
};
|
};
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|||||||
Vendored
+7
-3
@@ -5,15 +5,19 @@ export declare class GoogleMapsAdapter {
|
|||||||
constructor(apiKey?: string);
|
constructor(apiKey?: string);
|
||||||
isConfigured(): boolean;
|
isConfigured(): boolean;
|
||||||
/**
|
/**
|
||||||
* Validate and Geocode Bangladesh Address using Google Maps Geocoding API
|
* Evaluate road/house/area token match quality and review warnings (T5)
|
||||||
|
*/
|
||||||
|
private buildQualityAssessment;
|
||||||
|
/**
|
||||||
|
* Validate and Geocode Bangladesh Address using Google Maps Geocoding API (T5)
|
||||||
*/
|
*/
|
||||||
validateAndGeocode(req: AddressValidationRequest): Promise<AddressValidationResponse>;
|
validateAndGeocode(req: AddressValidationRequest): Promise<AddressValidationResponse>;
|
||||||
/**
|
/**
|
||||||
* Compute Road Distance & Classify Delivery Zone via Google Routes API
|
* Compute Road Distance & Classify Delivery Zone from Single Tariff Source of Truth (T4)
|
||||||
*/
|
*/
|
||||||
calculateDeliveryZoneAndFee(req: ZoneRateRequest): Promise<ZoneRateResponse>;
|
calculateDeliveryZoneAndFee(req: ZoneRateRequest): Promise<ZoneRateResponse>;
|
||||||
/**
|
/**
|
||||||
* Enterprise Multi-Carrier Rate Comparison (Steadfast vs Pathao vs RedX vs Paperfly)
|
* Multi-Carrier Rate Comparison backed by Single Tariff Source of Truth (T4)
|
||||||
*/
|
*/
|
||||||
compareRates(req: CourierRateComparisonRequest): Promise<CourierRateComparisonResponse>;
|
compareRates(req: CourierRateComparisonRequest): Promise<CourierRateComparisonResponse>;
|
||||||
private fallbackAddressParse;
|
private fallbackAddressParse;
|
||||||
|
|||||||
Vendored
+167
-233
@@ -1,11 +1,9 @@
|
|||||||
import axios from "axios";
|
import axios from "axios";
|
||||||
// Google Maps Platform Skill Attribution & Governance
|
import { withGetRetry } from "../envelope.js";
|
||||||
// Attribution ID: gmp_git_agentskills_v1
|
import { classifyZoneFromAddressAndDistance, computeCourierQuote, } from "../tariffs.js";
|
||||||
const GMP_ATTRIBUTION_ID = "gmp_git_agentskills_v1";
|
|
||||||
export class GoogleMapsAdapter {
|
export class GoogleMapsAdapter {
|
||||||
apiKey;
|
apiKey;
|
||||||
defaultHub = {
|
defaultHub = {
|
||||||
// Dhaka Central Logistics Hub (Tejgaon / Mirpur axis)
|
|
||||||
lat: 23.7925,
|
lat: 23.7925,
|
||||||
lng: 90.4078,
|
lng: 90.4078,
|
||||||
name: "Aura Central Sorting Hub, Dhaka",
|
name: "Aura Central Sorting Hub, Dhaka",
|
||||||
@@ -17,9 +15,76 @@ export class GoogleMapsAdapter {
|
|||||||
return Boolean(this.apiKey);
|
return Boolean(this.apiKey);
|
||||||
}
|
}
|
||||||
/**
|
/**
|
||||||
* Validate and Geocode Bangladesh Address using Google Maps Geocoding API
|
* Evaluate road/house/area token match quality and review warnings (T5)
|
||||||
|
*/
|
||||||
|
buildQualityAssessment(req, formattedAddress, locType, rawConfidence, thanaResolved) {
|
||||||
|
const addrIn = String(req.address || "");
|
||||||
|
const fmtLower = String(formattedAddress || "").toLowerCase();
|
||||||
|
// Check road token
|
||||||
|
const roadMatch = addrIn.match(/road\s*#?\s*(\d+[a-z]?)/i);
|
||||||
|
let roadOk = true;
|
||||||
|
if (roadMatch) {
|
||||||
|
const roadNum = roadMatch[1].toLowerCase();
|
||||||
|
roadOk =
|
||||||
|
fmtLower.includes(`road ${roadNum}`) ||
|
||||||
|
fmtLower.includes(`rd ${roadNum}`) ||
|
||||||
|
fmtLower.includes(`road-${roadNum}`) ||
|
||||||
|
fmtLower.includes(`road #${roadNum}`);
|
||||||
|
}
|
||||||
|
// Check house token
|
||||||
|
const houseMatch = addrIn.match(/house\s*#?\s*(\d+[a-z]?)/i);
|
||||||
|
let houseOk = true;
|
||||||
|
if (houseMatch) {
|
||||||
|
const houseNum = houseMatch[1].toLowerCase();
|
||||||
|
houseOk =
|
||||||
|
fmtLower.includes(`house ${houseNum}`) ||
|
||||||
|
fmtLower.includes(`house-${houseNum}`) ||
|
||||||
|
fmtLower.includes(`house #${houseNum}`) ||
|
||||||
|
(locType === "ROOFTOP" && fmtLower.includes(houseNum));
|
||||||
|
}
|
||||||
|
// Check area token
|
||||||
|
const areaTokens = addrIn
|
||||||
|
.toLowerCase()
|
||||||
|
.replace(/road\s*#?\s*\d+[a-z]?/gi, "")
|
||||||
|
.replace(/house\s*#?\s*\d+[a-z]?/gi, "")
|
||||||
|
.split(/[,.-]+/)
|
||||||
|
.map((s) => s.trim())
|
||||||
|
.filter((s) => s.length >= 4 && s !== "dhaka" && s !== "bangladesh");
|
||||||
|
const areaOk = areaTokens.length === 0 || areaTokens.some((tok) => fmtLower.includes(tok));
|
||||||
|
// Cap confidence at 60 whenever location_type !== "ROOFTOP" (T5)
|
||||||
|
let confidence = locType === "ROOFTOP" ? rawConfidence : Math.min(60, rawConfidence);
|
||||||
|
if (!roadOk || !houseOk) {
|
||||||
|
confidence = Math.min(confidence, 55);
|
||||||
|
}
|
||||||
|
const warnings = [];
|
||||||
|
if (locType !== "ROOFTOP") {
|
||||||
|
warnings.push(`Geocode precision is ${locType} (not ROOFTOP); confidence capped at 60.`);
|
||||||
|
}
|
||||||
|
if (thanaResolved === null) {
|
||||||
|
warnings.push("Thana/sublocality could not be resolved from geocoder components.");
|
||||||
|
}
|
||||||
|
if (req.thana && thanaResolved === null) {
|
||||||
|
warnings.push(`Input thana '${req.thana}' was not independently verified by geocoder.`);
|
||||||
|
}
|
||||||
|
if (!roadOk) {
|
||||||
|
warnings.push("Input road number was not cleanly matched in formatted address.");
|
||||||
|
}
|
||||||
|
if (!houseOk) {
|
||||||
|
warnings.push("Input house number was not cleanly matched as a rooftop premise in formatted address.");
|
||||||
|
}
|
||||||
|
const needsReview = confidence < 70 || thanaResolved === null || !roadOk || !houseOk;
|
||||||
|
return {
|
||||||
|
confidence,
|
||||||
|
matchQuality: { road: roadOk, house: houseOk, area: areaOk },
|
||||||
|
needsReview,
|
||||||
|
warnings,
|
||||||
|
};
|
||||||
|
}
|
||||||
|
/**
|
||||||
|
* Validate and Geocode Bangladesh Address using Google Maps Geocoding API (T5)
|
||||||
*/
|
*/
|
||||||
async validateAndGeocode(req) {
|
async validateAndGeocode(req) {
|
||||||
|
const thanaInput = req.thana ? String(req.thana) : null;
|
||||||
const fullQuery = [req.address, req.thana, req.district, "Bangladesh"]
|
const fullQuery = [req.address, req.thana, req.district, "Bangladesh"]
|
||||||
.filter(Boolean)
|
.filter(Boolean)
|
||||||
.join(", ");
|
.join(", ");
|
||||||
@@ -28,15 +93,15 @@ export class GoogleMapsAdapter {
|
|||||||
}
|
}
|
||||||
try {
|
try {
|
||||||
const url = `https://maps.googleapis.com/maps/api/geocode/json`;
|
const url = `https://maps.googleapis.com/maps/api/geocode/json`;
|
||||||
const res = await axios.get(url, {
|
const res = await withGetRetry(() => axios.get(url, {
|
||||||
params: {
|
params: {
|
||||||
address: fullQuery,
|
address: fullQuery,
|
||||||
components: "country:BD",
|
components: "country:BD",
|
||||||
language: "bn,en",
|
language: "en",
|
||||||
key: this.apiKey,
|
key: this.apiKey,
|
||||||
},
|
},
|
||||||
timeout: 8000,
|
timeout: 8000,
|
||||||
});
|
}));
|
||||||
const data = res.data;
|
const data = res.data;
|
||||||
if (data.status !== "OK" || !data.results || !data.results.length) {
|
if (data.status !== "OK" || !data.results || !data.results.length) {
|
||||||
return this.fallbackAddressParse(req);
|
return this.fallbackAddressParse(req);
|
||||||
@@ -44,14 +109,20 @@ export class GoogleMapsAdapter {
|
|||||||
const result = data.results[0];
|
const result = data.results[0];
|
||||||
const components = result.address_components || [];
|
const components = result.address_components || [];
|
||||||
const location = result.geometry?.location || { lat: 23.8103, lng: 90.4125 };
|
const location = result.geometry?.location || { lat: 23.8103, lng: 90.4125 };
|
||||||
const locType = result.geometry?.location_type || "APPROXIMATE";
|
const locType = String(result.geometry?.location_type || "APPROXIMATE");
|
||||||
let thana = "";
|
// Derive thana_resolved strictly from Google address_components; NEVER echo thana_input!
|
||||||
|
let thanaResolved = null;
|
||||||
let district = "";
|
let district = "";
|
||||||
let division = "";
|
let division = "";
|
||||||
for (const c of components) {
|
for (const c of components) {
|
||||||
const types = c.types || [];
|
const types = c.types || [];
|
||||||
if (types.includes("sublocality") || types.includes("sublocality_level_1") || types.includes("neighborhood")) {
|
if (types.includes("sublocality") ||
|
||||||
thana = c.long_name;
|
types.includes("sublocality_level_1") ||
|
||||||
|
types.includes("administrative_area_level_3") ||
|
||||||
|
types.includes("neighborhood")) {
|
||||||
|
if (!thanaResolved && c.long_name) {
|
||||||
|
thanaResolved = String(c.long_name);
|
||||||
|
}
|
||||||
}
|
}
|
||||||
else if (types.includes("administrative_area_level_2")) {
|
else if (types.includes("administrative_area_level_2")) {
|
||||||
district = c.long_name;
|
district = c.long_name;
|
||||||
@@ -60,17 +131,20 @@ export class GoogleMapsAdapter {
|
|||||||
division = c.long_name;
|
division = c.long_name;
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
let confidence = 50;
|
let rawConf = 50;
|
||||||
if (locType === "ROOFTOP")
|
if (locType === "ROOFTOP")
|
||||||
confidence = 98;
|
rawConf = 95;
|
||||||
else if (locType === "RANGE_INTERPOLATED")
|
else if (locType === "RANGE_INTERPOLATED")
|
||||||
confidence = 85;
|
rawConf = 60;
|
||||||
else if (locType === "GEOMETRIC_CENTER")
|
else if (locType === "GEOMETRIC_CENTER")
|
||||||
confidence = 70;
|
rawConf = 55;
|
||||||
|
const qa = this.buildQualityAssessment(req, result.formatted_address, locType, rawConf, thanaResolved);
|
||||||
return {
|
return {
|
||||||
success: true,
|
success: true,
|
||||||
formatted_address: result.formatted_address,
|
formatted_address: result.formatted_address,
|
||||||
thana: thana || req.thana || "",
|
thana_input: thanaInput,
|
||||||
|
thana_resolved: thanaResolved,
|
||||||
|
thana: thanaResolved || "",
|
||||||
district: district || req.district || "Dhaka",
|
district: district || req.district || "Dhaka",
|
||||||
division: division || "Dhaka Division",
|
division: division || "Dhaka Division",
|
||||||
coordinates: {
|
coordinates: {
|
||||||
@@ -78,17 +152,20 @@ export class GoogleMapsAdapter {
|
|||||||
lng: location.lng,
|
lng: location.lng,
|
||||||
},
|
},
|
||||||
location_type: locType,
|
location_type: locType,
|
||||||
is_deliverable: confidence >= 60,
|
is_deliverable: qa.confidence >= 50,
|
||||||
confidence_score: confidence,
|
confidence_score: qa.confidence,
|
||||||
|
match_quality: qa.matchQuality,
|
||||||
|
needs_review: qa.needsReview,
|
||||||
|
warnings: qa.warnings,
|
||||||
place_id: result.place_id,
|
place_id: result.place_id,
|
||||||
};
|
};
|
||||||
}
|
}
|
||||||
catch (err) {
|
catch (_) {
|
||||||
return this.fallbackAddressParse(req);
|
return this.fallbackAddressParse(req);
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
/**
|
/**
|
||||||
* Compute Road Distance & Classify Delivery Zone via Google Routes API
|
* Compute Road Distance & Classify Delivery Zone from Single Tariff Source of Truth (T4)
|
||||||
*/
|
*/
|
||||||
async calculateDeliveryZoneAndFee(req) {
|
async calculateDeliveryZoneAndFee(req) {
|
||||||
let destLat = req.destination_coords?.lat;
|
let destLat = req.destination_coords?.lat;
|
||||||
@@ -124,44 +201,31 @@ export class GoogleMapsAdapter {
|
|||||||
roadDistanceKm = this.haversineDistance(this.defaultHub.lat, this.defaultHub.lng, destLat, destLng);
|
roadDistanceKm = this.haversineDistance(this.defaultHub.lat, this.defaultHub.lng, destLat, destLng);
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
catch (routesErr) {
|
catch (_) {
|
||||||
roadDistanceKm = this.haversineDistance(this.defaultHub.lat, this.defaultHub.lng, destLat, destLng);
|
roadDistanceKm = this.haversineDistance(this.defaultHub.lat, this.defaultHub.lng, destLat, destLng);
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
else if (destLat && destLng) {
|
else if (destLat && destLng) {
|
||||||
roadDistanceKm = this.haversineDistance(this.defaultHub.lat, this.defaultHub.lng, destLat, destLng);
|
roadDistanceKm = this.haversineDistance(this.defaultHub.lat, this.defaultHub.lng, destLat, destLng);
|
||||||
}
|
}
|
||||||
const addr = req.recipient_address.toLowerCase();
|
const zoneDef = classifyZoneFromAddressAndDistance(req.recipient_address, roadDistanceKm);
|
||||||
const isSubDhakaArea = /savar|gazipur|keraniganj|narayanganj|সাভার|গাজীপুর|কেরানীগঞ্জ|নারায়ণগঞ্জ/i.test(addr);
|
|
||||||
let zone = "outside_dhaka";
|
|
||||||
let zoneTitle = "ঢাকার বাইরে (সারা বাংলাদেশ)";
|
|
||||||
let fee = 150;
|
|
||||||
let hours = "৭২–৯৬ ঘণ্টা";
|
|
||||||
if (roadDistanceKm > 0 && roadDistanceKm <= 22 && !isSubDhakaArea) {
|
|
||||||
zone = "inside_dhaka";
|
|
||||||
zoneTitle = "ঢাকার ভেতরে (মেট্রোপলিটন)";
|
|
||||||
fee = 80;
|
|
||||||
hours = "২৪–৪৮ ঘণ্টা (সরাসরি হোম ডেলিভারি)";
|
|
||||||
}
|
|
||||||
else if ((roadDistanceKm > 22 && roadDistanceKm <= 45) || isSubDhakaArea) {
|
|
||||||
zone = "sub_dhaka";
|
|
||||||
zoneTitle = "সাব-ঢাকা (আশপাশের অঞ্চল)";
|
|
||||||
fee = 100;
|
|
||||||
hours = "৪৮–৭২ ঘণ্টা";
|
|
||||||
}
|
|
||||||
return {
|
return {
|
||||||
success: true,
|
success: true,
|
||||||
zone,
|
zone: zoneDef.zone,
|
||||||
zone_title: zoneTitle,
|
zone_title: zoneDef.zone_title,
|
||||||
|
distance_km: roadDistanceKm,
|
||||||
road_distance_km: roadDistanceKm,
|
road_distance_km: roadDistanceKm,
|
||||||
estimated_delivery_hours: hours,
|
sla_hours: zoneDef.sla_hours,
|
||||||
standard_delivery_fee: fee,
|
estimated_delivery_hours: zoneDef.sla_label,
|
||||||
cod_charge_percentage: 1.0,
|
standard_fee_bdt: zoneDef.standard_fee_bdt,
|
||||||
|
standard_delivery_fee: zoneDef.standard_fee_bdt,
|
||||||
|
cod_percent: zoneDef.cod_percent,
|
||||||
|
cod_charge_percentage: zoneDef.cod_percent,
|
||||||
route_summary: routeSummary || `Hub to Destination (~${roadDistanceKm} km)`,
|
route_summary: routeSummary || `Hub to Destination (~${roadDistanceKm} km)`,
|
||||||
};
|
};
|
||||||
}
|
}
|
||||||
/**
|
/**
|
||||||
* Enterprise Multi-Carrier Rate Comparison (Steadfast vs Pathao vs RedX vs Paperfly)
|
* Multi-Carrier Rate Comparison backed by Single Tariff Source of Truth (T4)
|
||||||
*/
|
*/
|
||||||
async compareRates(req) {
|
async compareRates(req) {
|
||||||
const zoneInfo = await this.calculateDeliveryZoneAndFee({
|
const zoneInfo = await this.calculateDeliveryZoneAndFee({
|
||||||
@@ -170,116 +234,34 @@ export class GoogleMapsAdapter {
|
|||||||
});
|
});
|
||||||
const weight = req.weight_kg || 0.5;
|
const weight = req.weight_kg || 0.5;
|
||||||
const cod = req.cod_amount || 0;
|
const cod = req.cod_amount || 0;
|
||||||
const extraKg = Math.max(0, Math.ceil(weight - 1.0));
|
const couriers = ["steadfast", "pathao", "redx", "paperfly"];
|
||||||
// Base rates per carrier based on real BD logistics market tariffs
|
const rawQuotes = couriers.map((c) => computeCourierQuote(c, zoneInfo.zone, weight, cod));
|
||||||
let sfBase = 70, ptBase = 60, rxBase = 80, pfBase = 80;
|
|
||||||
let sfExtra = 20, ptExtra = 25, rxExtra = 20, pfExtra = 25;
|
|
||||||
let sfHours = "২৪–৪৮ ঘণ্টা", ptHours = "১২–২৪ ঘণ্টা (Same-Day)", rxHours = "২৪–৪৮ ঘণ্টা", pfHours = "২৪–৪৮ ঘণ্টা";
|
|
||||||
if (zoneInfo.zone === "sub_dhaka") {
|
|
||||||
sfBase = 100;
|
|
||||||
ptBase = 110;
|
|
||||||
rxBase = 110;
|
|
||||||
pfBase = 110;
|
|
||||||
sfHours = "৪৮–৭২ ঘণ্টা";
|
|
||||||
ptHours = "২৪–৪৮ ঘণ্টা";
|
|
||||||
rxHours = "৪৮–৭২ ঘণ্টা";
|
|
||||||
pfHours = "৪৮–৭২ ঘণ্টা";
|
|
||||||
}
|
|
||||||
else if (zoneInfo.zone === "outside_dhaka") {
|
|
||||||
sfBase = 140;
|
|
||||||
ptBase = 150;
|
|
||||||
rxBase = 160;
|
|
||||||
pfBase = 170;
|
|
||||||
sfHours = "৭২–৯৬ ঘণ্টা";
|
|
||||||
ptHours = "৪৮–৭২ ঘণ্টা";
|
|
||||||
rxHours = "৭২–৯৬ ঘণ্টা";
|
|
||||||
pfHours = "৭২–৯৬ ঘণ্টা";
|
|
||||||
}
|
|
||||||
const sfCod = Math.round(cod * 0.01);
|
|
||||||
const ptCod = Math.round(cod * 0.01);
|
|
||||||
const rxCod = Math.round(cod * 0.01);
|
|
||||||
const pfCod = Math.round(cod * 0.015);
|
|
||||||
const sfTotal = sfBase + (extraKg * sfExtra) + sfCod;
|
|
||||||
const ptTotal = ptBase + (extraKg * ptExtra) + ptCod;
|
|
||||||
const rxTotal = rxBase + (extraKg * rxExtra) + rxCod;
|
|
||||||
const pfTotal = pfBase + (extraKg * pfExtra) + pfCod;
|
|
||||||
const carrierQuotes = [
|
|
||||||
{
|
|
||||||
courier: "steadfast",
|
|
||||||
name: "Steadfast Courier",
|
|
||||||
base: sfBase,
|
|
||||||
extra: extraKg * sfExtra,
|
|
||||||
cod: sfCod,
|
|
||||||
total: sfTotal,
|
|
||||||
hours: sfHours,
|
|
||||||
notes: "৬৪ জেলা ও সকল থানায় সরাসরি ক্যাশ অন ডেলিভারি হাব নেটওয়ার্ক।",
|
|
||||||
},
|
|
||||||
{
|
|
||||||
courier: "pathao",
|
|
||||||
name: "Pathao Express",
|
|
||||||
base: ptBase,
|
|
||||||
extra: extraKg * ptExtra,
|
|
||||||
cod: ptCod,
|
|
||||||
total: ptTotal,
|
|
||||||
hours: ptHours,
|
|
||||||
notes: "ঢাকা ও প্রধান মেট্রোপলিটন সিটিতে দ্রুততম অন-ডিমান্ড রাইডার পিকআপ।",
|
|
||||||
},
|
|
||||||
{
|
|
||||||
courier: "redx",
|
|
||||||
name: "RedX Delivery",
|
|
||||||
base: rxBase,
|
|
||||||
extra: extraKg * rxExtra,
|
|
||||||
cod: rxCod,
|
|
||||||
total: rxTotal,
|
|
||||||
hours: rxHours,
|
|
||||||
notes: "শক্তিশালী সাব-ডিস্ট্রিক্ট হাব ও বৃহৎ পার্সেল হ্যান্ডলিং নেটওয়ার্ক।",
|
|
||||||
},
|
|
||||||
{
|
|
||||||
courier: "paperfly",
|
|
||||||
name: "Paperfly Go",
|
|
||||||
base: pfBase,
|
|
||||||
extra: extraKg * pfExtra,
|
|
||||||
cod: pfCod,
|
|
||||||
total: pfTotal,
|
|
||||||
hours: pfHours,
|
|
||||||
notes: "প্রত্যন্ত ইউনিয়ন ও ডোরস্টেপ ডেলিভারি কভারেজ।",
|
|
||||||
},
|
|
||||||
];
|
|
||||||
let recommended = "steadfast";
|
let recommended = "steadfast";
|
||||||
let reason = "সর্বনিম্ন খরচ ও ৬৪ জেলায় ৯৯.৮% সফল ডেলিভারি নেটওয়ার্ক";
|
let reason = "Balanced nationwide coverage and cost efficiency.";
|
||||||
if (zoneInfo.zone === "inside_dhaka" && req.priority === "fastest") {
|
if (req.priority === "cheapest") {
|
||||||
recommended = "pathao";
|
const sorted = [...rawQuotes].sort((a, b) => a.total_cost - b.total_cost);
|
||||||
reason = "ঢাকা মেট্রোপলিটনে দ্রুততম সেম-ডে এক্সপ্রেস ডেলিভারি";
|
|
||||||
}
|
|
||||||
else if (req.priority === "cheapest") {
|
|
||||||
const sorted = [...carrierQuotes].sort((a, b) => a.total - b.total);
|
|
||||||
recommended = sorted[0].courier;
|
recommended = sorted[0].courier;
|
||||||
reason = `${sorted[0].name} এই রুটে সর্বনিম্ন খরচে ডেলিভারি প্রদান করে (৳${sorted[0].total})।`;
|
reason = `${sorted[0].courier_name} offers the lowest total tariff on this route (৳${sorted[0].total_cost}).`;
|
||||||
}
|
}
|
||||||
else if (zoneInfo.zone === "inside_dhaka") {
|
else if (zoneInfo.zone === "inside_dhaka") {
|
||||||
recommended = ptTotal <= sfTotal ? "pathao" : "steadfast";
|
recommended = "pathao";
|
||||||
reason = "ঢাকা মেট্রোপলিটনে সাশ্রয়ী ডেলিভারি ও দ্রুত পিকআপ";
|
reason = "Lowest base rate and high-density rider pickup within Inside Dhaka.";
|
||||||
}
|
}
|
||||||
else {
|
else {
|
||||||
recommended = "steadfast";
|
recommended = "steadfast";
|
||||||
reason = "ঢাকার বাইরে সারা বাংলাদেশের ৬৪ জেলায় সর্বোচ্চ কভারেজ ও সর্বনিম্ন রিটার্ন রেট";
|
reason = "Lowest inter-district base tariff and 64-district doorstep COD coverage.";
|
||||||
}
|
}
|
||||||
const quotes = carrierQuotes.map((cq) => ({
|
const quotes = rawQuotes.map((rq) => ({
|
||||||
courier: cq.courier,
|
...rq,
|
||||||
courier_name: cq.name,
|
is_recommended: rq.courier === recommended,
|
||||||
base_delivery_fee: cq.base,
|
|
||||||
weight_surcharge: cq.extra,
|
|
||||||
cod_charge: cq.cod,
|
|
||||||
total_cost: cq.total,
|
|
||||||
estimated_hours: cq.hours,
|
|
||||||
coverage_notes: cq.notes,
|
|
||||||
is_recommended: cq.courier === recommended,
|
|
||||||
}));
|
}));
|
||||||
return {
|
return {
|
||||||
success: true,
|
success: true,
|
||||||
zone: zoneInfo.zone,
|
zone: zoneInfo.zone,
|
||||||
zone_title: zoneInfo.zone_title,
|
zone_title: zoneInfo.zone_title,
|
||||||
|
distance_km: zoneInfo.distance_km,
|
||||||
road_distance_km: zoneInfo.road_distance_km,
|
road_distance_km: zoneInfo.road_distance_km,
|
||||||
|
sla_hours: zoneInfo.sla_hours,
|
||||||
weight_kg: weight,
|
weight_kg: weight,
|
||||||
cod_amount: cod,
|
cod_amount: cod,
|
||||||
recommended_courier: recommended,
|
recommended_courier: recommended,
|
||||||
@@ -288,101 +270,53 @@ export class GoogleMapsAdapter {
|
|||||||
};
|
};
|
||||||
}
|
}
|
||||||
async fallbackAddressParse(req) {
|
async fallbackAddressParse(req) {
|
||||||
|
const thanaInput = req.thana ? String(req.thana) : null;
|
||||||
const fullQuery = [req.address, req.thana, req.district, "Bangladesh"].filter(Boolean).join(", ");
|
const fullQuery = [req.address, req.thana, req.district, "Bangladesh"].filter(Boolean).join(", ");
|
||||||
// Tier 2: Live OpenStreetMap Nominatim Geocoding (Zero-Billing Fallback)
|
const lower = fullQuery.toLowerCase();
|
||||||
try {
|
const BD_DISTRICTS = [
|
||||||
const nomRes = await axios.get("https://nominatim.openstreetmap.org/search", {
|
{ match: /chattogram|chittagong|চট্টগ্রাম/, district: "Chattogram", division: "Chattogram Division", lat: 22.3569, lng: 91.7832 },
|
||||||
params: {
|
{ match: /sylhet|সিলেট/, district: "Sylhet", division: "Sylhet Division", lat: 24.8949, lng: 91.8687 },
|
||||||
q: fullQuery,
|
{ match: /rajshahi|রাজশাহী/, district: "Rajshahi", division: "Rajshahi Division", lat: 24.3745, lng: 88.6042 },
|
||||||
countrycodes: "bd",
|
{ match: /khulna|খুলনা/, district: "Khulna", division: "Khulna Division", lat: 22.8456, lng: 89.5403 },
|
||||||
format: "json",
|
{ match: /barishal|barisal|বরিশাল/, district: "Barishal", division: "Barishal Division", lat: 22.7010, lng: 90.3535 },
|
||||||
addressdetails: 1,
|
{ match: /rangpur|রংপুর/, district: "Rangpur", division: "Rangpur Division", lat: 25.7439, lng: 89.2752 },
|
||||||
limit: 1,
|
{ match: /mymensingh|ময়মনসিংহ/, district: "Mymensingh", division: "Mymensingh Division", lat: 24.7471, lng: 90.4203 },
|
||||||
},
|
{ match: /cumilla|comilla|কুমিল্লা/, district: "Cumilla", division: "Chattogram Division", lat: 23.4607, lng: 91.1809 },
|
||||||
headers: { "User-Agent": "AuraCourierMCP/2.5 (https://courier.auraajenticai.cloud)" },
|
{ match: /gazipur|গাজীপুর|tongi|টঙ্গী/, district: "Gazipur", division: "Dhaka Division", lat: 23.9999, lng: 90.4203 },
|
||||||
timeout: 5500,
|
{ match: /narayanganj|নারায়ণগঞ্জ/, district: "Narayanganj", division: "Dhaka Division", lat: 23.6238, lng: 90.5000 },
|
||||||
});
|
{ match: /savar|সাভার|ashulia|আশুলিয়া/, district: "Dhaka", division: "Dhaka Division", lat: 23.8583, lng: 90.2667 },
|
||||||
if (Array.isArray(nomRes.data) && nomRes.data.length > 0) {
|
{ match: /keraniganj|কেরানীগঞ্জ|ati bazar|atibazar/, district: "Dhaka", division: "Dhaka Division", lat: 23.7196, lng: 90.3125 },
|
||||||
const hit = nomRes.data[0];
|
{ match: /uttara|উত্তরা/, district: "Dhaka", division: "Dhaka Division", lat: 23.8759, lng: 90.3795 },
|
||||||
const addr = hit.address || {};
|
{ match: /mirpur|মিরপুর/, district: "Dhaka", division: "Dhaka Division", lat: 23.8042, lng: 90.3667 },
|
||||||
const lat = parseFloat(hit.lat);
|
{ match: /dhanmondi|ধানমন্ডি/, district: "Dhaka", division: "Dhaka Division", lat: 23.7461, lng: 90.3742 },
|
||||||
const lng = parseFloat(hit.lon);
|
{ match: /gulshan|গুলশান|banani|বনানী/, district: "Dhaka", division: "Dhaka Division", lat: 23.7925, lng: 90.4078 },
|
||||||
const thana = addr.suburb || addr.neighbourhood || addr.town || addr.municipality || addr.city_district || req.thana || "";
|
|
||||||
const district = (addr.county || addr.city || addr.state_district || req.district || "Dhaka").replace(/\s*District$/i, "");
|
|
||||||
const division = addr.state || "Dhaka Division";
|
|
||||||
return {
|
|
||||||
success: true,
|
|
||||||
formatted_address: hit.display_name || fullQuery,
|
|
||||||
thana,
|
|
||||||
district,
|
|
||||||
division,
|
|
||||||
coordinates: { lat, lng },
|
|
||||||
location_type: "GEOMETRIC_CENTER",
|
|
||||||
is_deliverable: true,
|
|
||||||
confidence_score: 88,
|
|
||||||
place_id: `osm_${hit.place_id || Date.now()}`,
|
|
||||||
};
|
|
||||||
}
|
|
||||||
}
|
|
||||||
catch (_) {
|
|
||||||
// Proceed to Tier 3 Spatial Gazetteer
|
|
||||||
}
|
|
||||||
// Tier 3: Bangladesh 64-District & Dhaka Thana Spatial Gazetteer
|
|
||||||
const raw = [req.address, req.thana, req.district].filter(Boolean).join(" ").toLowerCase();
|
|
||||||
const gazetteer = [
|
|
||||||
{ rx: /mirpur|মিরপুর|pallabi|পল্লবী|kazipara|shewrapara|কাজীপাড়া|শেওড়াপাড়া/, thana: "Mirpur", district: "Dhaka", division: "Dhaka Division", lat: 23.8042, lng: 90.3667 },
|
|
||||||
{ rx: /uttara|উত্তরা|airport|বিমানবন্দর|sector|সেক্টর|dakshin khan|uttar khan/, thana: "Uttara", district: "Dhaka", division: "Dhaka Division", lat: 23.8759, lng: 90.3795 },
|
|
||||||
{ rx: /dhanmondi|ধানমন্ডি|kalabagan|কলাবাগান|jigatola|জিগাতলা|shankar/, thana: "Dhanmondi", district: "Dhaka", division: "Dhaka Division", lat: 23.7461, lng: 90.3742 },
|
|
||||||
{ rx: /gulshan|গুলশান|banani|বনানী|baridhara|বারিধারা|niketan|নিকেতন/, thana: "Gulshan", district: "Dhaka", division: "Dhaka Division", lat: 23.7925, lng: 90.4078 },
|
|
||||||
{ rx: /mohammadpur|মোহাম্মদপুর|adabor|আদাবর|lalmatia|লালমাটিয়া|bosila|বসিলা/, thana: "Mohammadpur", district: "Dhaka", division: "Dhaka Division", lat: 23.7662, lng: 90.3589 },
|
|
||||||
{ rx: /badda|বাড্ডা|rampura|রামপুরা|banasree|বনশ্রী|aftabnagar|আফতাবনগর|hatirjheel/, thana: "Badda", district: "Dhaka", division: "Dhaka Division", lat: 23.7805, lng: 90.4267 },
|
|
||||||
{ rx: /bashundhara|বসুন্ধরা|vatara|ভাটারা|kuril|কুড়িল|nikunja|নিকুঞ্জ|khilkhet|খিলক্ষেত/, thana: "Vatara", district: "Dhaka", division: "Dhaka Division", lat: 23.8191, lng: 90.4526 },
|
|
||||||
{ rx: /motijheel|মতিঝিল|paltan|পল্টন|kakrail|কাকরাইল|shantinagar|শান্তিনগর|malibagh|মালিবাগ|mogbazar|মগবাজার/, thana: "Motijheel", district: "Dhaka", division: "Dhaka Division", lat: 23.7330, lng: 90.4172 },
|
|
||||||
{ rx: /shahbag|শাহবাগ|hatirpool|হাতিরপুল|motaleb|মোতালেব|eleph|এলিফ্যান্ট|new market|নিউ মার্কেট|farmgate|ফার্মগেট|tejgaon|তেজগাঁও|karwan|কারওয়ান/, thana: "Shahbagh", district: "Dhaka", division: "Dhaka Division", lat: 23.7415, lng: 90.3918 },
|
|
||||||
{ rx: /jatrabari|যাত্রাবাড়ী|demra|ডেমরা|kadamtali|কদমতলী|shanir akhra|শনির আখড়া|wari|ওয়ারী|old dhaka|পুরান ঢাকা|lalbagh|লালবাগ|kotwali/, thana: "Jatrabari", district: "Dhaka", division: "Dhaka Division", lat: 23.7104, lng: 90.4348 },
|
|
||||||
{ rx: /keraniganj|কেরানীগঞ্জ|ati bazar|আটি বাজার|atibazar|hasnabad/, thana: "Keraniganj", district: "Dhaka", division: "Dhaka Division", lat: 23.6942, lng: 90.3475 },
|
|
||||||
{ rx: /savar|সাভার|ashulia|আশুলিয়া|hemayetpur|হেমায়েতপুর|dhamrai|ধামরাই/, thana: "Savar", district: "Dhaka", division: "Dhaka Division", lat: 23.8583, lng: 90.2667 },
|
|
||||||
{ rx: /gazipur|গাজীপুর|tongi|টঙ্গী|board bazar|বোর্ড বাজার|joydebpur|জয়দেবপুর|konabari/, thana: "Tongi", district: "Gazipur", division: "Dhaka Division", lat: 23.9889, lng: 90.3950 },
|
|
||||||
{ rx: /narayanganj|নারায়ণগঞ্জ|siddhirganj|সিদ্ধিরগঞ্জ|fatullah|ফতুল্লা|chashara|চাষাড়া|sonargaon|rupganj/, thana: "Narayanganj Sadar", district: "Narayanganj", division: "Dhaka Division", lat: 23.6238, lng: 90.5000 },
|
|
||||||
{ rx: /chattogram|chittagong|চট্টগ্রাম|agrabad|আগ্রাবাদ|nasirabad|নাসিরাবাদ|halishahar|হালিশহর|panchlaish|gec|জিইসি|kotwali/, thana: "Panchlaish", district: "Chattogram", division: "Chattogram Division", lat: 22.3569, lng: 91.7832 },
|
|
||||||
{ rx: /cox.?s?s*bazar|কক্সবাজার|chakaria|teknaf|ukhiya/, thana: "Cox's Bazar Sadar", district: "Cox's Bazar", division: "Chattogram Division", lat: 21.4272, lng: 92.0058 },
|
|
||||||
{ rx: /cumilla|comilla|কুমিল্লা|kandirpar|কান্দিরপাড়|laksam|daudkandi/, thana: "Cumilla Sadar", district: "Cumilla", division: "Chattogram Division", lat: 23.4607, lng: 91.1809 },
|
|
||||||
{ rx: /feni|ফেনী|noakhali|নোয়াখালী|maijdee|চৌমুহনী|lakshmipur|লক্ষ্মীপুর|chandpur|চাঁদপুর|brahmanbaria|ব্রাহ্মণবাড়িয়া/, thana: "Sadar", district: "Noakhali", division: "Chattogram Division", lat: 22.8724, lng: 91.0973 },
|
|
||||||
{ rx: /sylhet|সিলেট|zindabazar|জিন্দাবাজার|amberkhana|আম্বরখানা|upashahar|উপশহর|moulvibazar|মৌলভীবাজার|sreemangal|habiganj|হবিগঞ্জ|sunamganj|সুনামগঞ্জ/, thana: "Sylhet Sadar", district: "Sylhet", division: "Sylhet Division", lat: 24.8949, lng: 91.8687 },
|
|
||||||
{ rx: /rajshahi|রাজশাহী|boalia|বোয়ালিয়া|shaheb bazar|সাহেব বাজার|motihar|নাটোর|natore|naogaon|নওগাঁ|chapainawabganj|চাঁপাইনবাবগঞ্জ|pabna|পাবনা|sirajganj|সিরাজগঞ্জ/, thana: "Boalia", district: "Rajshahi", division: "Rajshahi Division", lat: 24.3745, lng: 88.6042 },
|
|
||||||
{ rx: /bogura|bogra|বগুড়া|sherpur|শেরপুর|joypurhat|জয়পুরহাট/, thana: "Bogura Sadar", district: "Bogura", division: "Rajshahi Division", lat: 24.8481, lng: 89.3730 },
|
|
||||||
{ rx: /khulna|খুলনা|sonadanga|সোনাডাঙ্গা|khalishpur|খালিশপুর|daulatpur|jashore|jessore|যশোর|kushtia|কুষ্টিয়া|satkhira|সাতক্ষীরা|bagerhat|বাগেরহাট|jhenaidah|ঝিনাইদহ/, thana: "Sonadanga", district: "Khulna", division: "Khulna Division", lat: 22.8456, lng: 89.5403 },
|
|
||||||
{ rx: /barishal|barisal|বরিশাল|patukhali|পটুয়াখালী|bhola|ভোলা|pirojpur|পিরোজপুর|jhalokati|barguna/, thana: "Barishal Sadar", district: "Barishal", division: "Barishal Division", lat: 22.7010, lng: 90.3535 },
|
|
||||||
{ rx: /rangpur|রংপুর|dinajpur|দিনাজপুর|thakurgaon|ঠাকুরগাঁও|panchagarh|পঞ্চগড়|nilphamari|নীলফামারী|saidpur|সৈয়দপুর|kurigram|কুড়িগ্রাম|gaibandha|গাইবান্ধা|lalmonirhat/, thana: "Rangpur Sadar", district: "Rangpur", division: "Rangpur Division", lat: 25.7439, lng: 89.2752 },
|
|
||||||
{ rx: /mymensingh|ময়মনসিংহ|jamalpur|জামালপুর|netrokona|নেত্রকোনা|tangail|টাঙ্গাইল|kishoreganj|কিশোরগঞ্জ|faridpur|ফরিদপুর|madaripur|মাদারীপুর|gopalganj|গোপালগঞ্জ|shariatpur|শরীয়তপুর|rajbari|রাজবাড়ী|manikganj|মানিকগঞ্জ|munshiganj|মুন্সিগঞ্জ|narsingdi|নরসিংদী/, thana: "Mymensingh Sadar", district: "Mymensingh", division: "Mymensingh Division", lat: 24.7471, lng: 90.4203 },
|
|
||||||
];
|
];
|
||||||
for (const g of gazetteer) {
|
const matched = BD_DISTRICTS.find((d) => d.match.test(lower)) || {
|
||||||
if (g.rx.test(raw)) {
|
district: req.district || "Dhaka",
|
||||||
return {
|
division: "Dhaka Division",
|
||||||
success: true,
|
lat: 23.7805,
|
||||||
formatted_address: `${req.address}, ${req.thana || g.thana}, ${req.district || g.district}, Bangladesh`,
|
lng: 90.4078,
|
||||||
thana: req.thana || g.thana,
|
};
|
||||||
district: req.district || g.district,
|
// Never echo thana_input into thana_resolved in fallback mode
|
||||||
division: g.division,
|
const thanaResolved = null;
|
||||||
coordinates: { lat: g.lat, lng: g.lng },
|
const locType = "APPROXIMATE";
|
||||||
location_type: "GEOMETRIC_CENTER",
|
const qa = this.buildQualityAssessment(req, fullQuery, locType, 55, thanaResolved);
|
||||||
is_deliverable: true,
|
|
||||||
confidence_score: 84,
|
|
||||||
place_id: `bd_gazetteer_${g.district.toLowerCase().replace(/\s+/g, "_")}`,
|
|
||||||
};
|
|
||||||
}
|
|
||||||
}
|
|
||||||
const isDhaka = /dhaka|ঢাকা/i.test(raw);
|
|
||||||
return {
|
return {
|
||||||
success: true,
|
success: true,
|
||||||
formatted_address: req.address,
|
formatted_address: fullQuery,
|
||||||
thana: req.thana || (isDhaka ? "Dhaka Metro" : "Sadar"),
|
thana_input: thanaInput,
|
||||||
district: req.district || (isDhaka ? "Dhaka" : "Outside Dhaka"),
|
thana_resolved: thanaResolved,
|
||||||
division: isDhaka ? "Dhaka Division" : "Bangladesh",
|
thana: "",
|
||||||
coordinates: isDhaka ? { lat: 23.8103, lng: 90.4125 } : { lat: 24.0000, lng: 90.0000 },
|
district: matched.district,
|
||||||
location_type: "APPROXIMATE",
|
division: matched.division,
|
||||||
|
coordinates: { lat: matched.lat, lng: matched.lng },
|
||||||
|
location_type: locType,
|
||||||
is_deliverable: true,
|
is_deliverable: true,
|
||||||
confidence_score: 72,
|
confidence_score: qa.confidence,
|
||||||
|
match_quality: qa.matchQuality,
|
||||||
|
needs_review: true,
|
||||||
|
warnings: qa.warnings,
|
||||||
|
place_id: `bd_gazetteer_${matched.district.toLowerCase()}`,
|
||||||
};
|
};
|
||||||
}
|
}
|
||||||
haversineDistance(lat1, lon1, lat2, lon2) {
|
haversineDistance(lat1, lon1, lat2, lon2) {
|
||||||
@@ -395,6 +329,6 @@ export class GoogleMapsAdapter {
|
|||||||
Math.sin(dLon / 2) *
|
Math.sin(dLon / 2) *
|
||||||
Math.sin(dLon / 2);
|
Math.sin(dLon / 2);
|
||||||
const c = 2 * Math.atan2(Math.sqrt(a), Math.sqrt(1 - a));
|
const c = 2 * Math.atan2(Math.sqrt(a), Math.sqrt(1 - a));
|
||||||
return Math.round(R * c * 1.2 * 10) / 10;
|
return Math.round(R * c * 1.25 * 10) / 10;
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|||||||
Vendored
+3
@@ -12,5 +12,8 @@ export declare class PaperflyAdapter implements CourierAdapter {
|
|||||||
isConfigured(): boolean;
|
isConfigured(): boolean;
|
||||||
createParcel(req: ParcelCreateRequest): Promise<ParcelResponse>;
|
createParcel(req: ParcelCreateRequest): Promise<ParcelResponse>;
|
||||||
trackParcel(trackingCode: string): Promise<TrackingResponse>;
|
trackParcel(trackingCode: string): Promise<TrackingResponse>;
|
||||||
|
/**
|
||||||
|
* Paperfly does not expose a live wallet balance API endpoint (T3).
|
||||||
|
*/
|
||||||
getBalance(): Promise<BalanceResponse>;
|
getBalance(): Promise<BalanceResponse>;
|
||||||
}
|
}
|
||||||
|
|||||||
Vendored
+65
-23
@@ -1,4 +1,5 @@
|
|||||||
import axios from "axios";
|
import axios from "axios";
|
||||||
|
import { McpToolError } from "../envelope.js";
|
||||||
export class PaperflyAdapter {
|
export class PaperflyAdapter {
|
||||||
courierName = "paperfly";
|
courierName = "paperfly";
|
||||||
apiKey;
|
apiKey;
|
||||||
@@ -62,35 +63,76 @@ export class PaperflyAdapter {
|
|||||||
}
|
}
|
||||||
async trackParcel(trackingCode) {
|
async trackParcel(trackingCode) {
|
||||||
if (!this.enabled) {
|
if (!this.enabled) {
|
||||||
throw new Error("Paperfly credentials are not configured.");
|
throw new McpToolError({
|
||||||
|
code: "COURIER_NOT_CONFIGURED",
|
||||||
|
message: "Paperfly credentials are not configured.",
|
||||||
|
courier: "paperfly",
|
||||||
|
});
|
||||||
}
|
}
|
||||||
if (!this.username || !this.password) {
|
if (!this.username || !this.password) {
|
||||||
throw new Error("Paperfly tracking needs your merchant-panel username & password (Basic Auth). Add them to use track_parcel.");
|
throw new McpToolError({
|
||||||
|
code: "COURIER_NOT_CONFIGURED",
|
||||||
|
message: "Paperfly tracking requires merchant-panel username and password.",
|
||||||
|
courier: "paperfly",
|
||||||
|
});
|
||||||
}
|
}
|
||||||
// Paperfly tracks by your merchant order reference (merchantOrderReference), not its tracking number.
|
try {
|
||||||
const response = await this.client.post("/API-Order-Tracking", { ReferenceNumber: trackingCode }, { headers: { paperflykey: this.apiKey }, auth: { username: this.username, password: this.password } });
|
const response = await this.client.post("/API-Order-Tracking", { ReferenceNumber: trackingCode }, { headers: { paperflykey: this.apiKey }, auth: { username: this.username, password: this.password } });
|
||||||
const data = response.data;
|
const data = response.data;
|
||||||
const st = data?.success?.trackingStatus?.[0] || {};
|
if (data?.error) {
|
||||||
const stages = [
|
throw new McpToolError({
|
||||||
[st.Delivered, "delivered"],
|
code: "CONSIGNMENT_NOT_FOUND",
|
||||||
[st.Partial, "partial-delivery"],
|
message: `Consignment '${trackingCode}' was not found in Paperfly.`,
|
||||||
[st.Returned, "returned"],
|
retryable: false,
|
||||||
[st.PickedForDelivery, "out-for-delivery"],
|
courier: "paperfly",
|
||||||
[st.inTransit, "in-transit"],
|
});
|
||||||
[st.ReceivedAtPoint, "received-at-point"],
|
}
|
||||||
[st.Pick, "picked-up"],
|
const st = data?.success?.trackingStatus?.[0] || {};
|
||||||
];
|
const stages = [
|
||||||
const status = stages.find(([v]) => v && String(v).trim())?.[1] || data?.success?.message || "pending";
|
[st.Delivered, "delivered"],
|
||||||
|
[st.Partial, "partial-delivery"],
|
||||||
|
[st.Returned, "returned"],
|
||||||
|
[st.PickedForDelivery, "out-for-delivery"],
|
||||||
|
[st.inTransit, "in-transit"],
|
||||||
|
[st.ReceivedAtPoint, "received-at-point"],
|
||||||
|
[st.Pick, "picked-up"],
|
||||||
|
];
|
||||||
|
const status = stages.find(([v]) => v && String(v).trim())?.[1] || data?.success?.message || "pending";
|
||||||
|
return {
|
||||||
|
success: true,
|
||||||
|
courier: "paperfly",
|
||||||
|
tracking_code: trackingCode,
|
||||||
|
status,
|
||||||
|
updated_at: new Date().toISOString(),
|
||||||
|
raw_response: data,
|
||||||
|
};
|
||||||
|
}
|
||||||
|
catch (err) {
|
||||||
|
if (err instanceof McpToolError)
|
||||||
|
throw err;
|
||||||
|
if (err?.response?.status === 400 || err?.response?.status === 404) {
|
||||||
|
throw new McpToolError({
|
||||||
|
code: "CONSIGNMENT_NOT_FOUND",
|
||||||
|
message: `Consignment '${trackingCode}' was not found in Paperfly.`,
|
||||||
|
retryable: false,
|
||||||
|
courier: "paperfly",
|
||||||
|
});
|
||||||
|
}
|
||||||
|
throw err;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
/**
|
||||||
|
* Paperfly does not expose a live wallet balance API endpoint (T3).
|
||||||
|
*/
|
||||||
|
async getBalance() {
|
||||||
return {
|
return {
|
||||||
success: true,
|
success: true,
|
||||||
courier: "paperfly",
|
courier: "paperfly",
|
||||||
tracking_code: trackingCode,
|
amount_bdt: null,
|
||||||
status,
|
pending_bdt: null,
|
||||||
updated_at: new Date().toISOString(),
|
current_balance: null,
|
||||||
raw_response: data,
|
status: "UNSUPPORTED_BY_PROVIDER",
|
||||||
|
hint: "Use Paperfly merchant portal",
|
||||||
};
|
};
|
||||||
}
|
}
|
||||||
async getBalance() {
|
|
||||||
throw new Error("Paperfly does not expose a merchant balance endpoint via its public API — check the Paperfly merchant panel.");
|
|
||||||
}
|
|
||||||
}
|
}
|
||||||
|
|||||||
Vendored
+9
@@ -32,6 +32,15 @@ export declare class PathaoAdapter implements CourierAdapter {
|
|||||||
}>;
|
}>;
|
||||||
createParcel(req: ParcelCreateRequest): Promise<ParcelResponse>;
|
createParcel(req: ParcelCreateRequest): Promise<ParcelResponse>;
|
||||||
trackParcel(trackingCode: string): Promise<TrackingResponse>;
|
trackParcel(trackingCode: string): Promise<TrackingResponse>;
|
||||||
|
/**
|
||||||
|
* Pathao does not expose a live wallet balance API endpoint (T3).
|
||||||
|
* Returns amount_bdt: null, current_balance: null, status: UNSUPPORTED_BY_PROVIDER.
|
||||||
|
*/
|
||||||
getBalance(): Promise<BalanceResponse>;
|
getBalance(): Promise<BalanceResponse>;
|
||||||
|
/**
|
||||||
|
* 100% Real Live Pathao Nationwide Customer Delivery Success API
|
||||||
|
* Endpoint: POST /aladdin/api/v1/user/success
|
||||||
|
*/
|
||||||
|
fraudCheck(phone: string): Promise<any>;
|
||||||
getLocations(cityName?: string): Promise<LocationResolutionResponse>;
|
getLocations(cityName?: string): Promise<LocationResolutionResponse>;
|
||||||
}
|
}
|
||||||
|
|||||||
Vendored
+57
-14
@@ -1,4 +1,5 @@
|
|||||||
import axios from "axios";
|
import axios from "axios";
|
||||||
|
import { McpToolError, withGetRetry } from "../envelope.js";
|
||||||
export class PathaoAdapter {
|
export class PathaoAdapter {
|
||||||
courierName = "pathao";
|
courierName = "pathao";
|
||||||
clientId;
|
clientId;
|
||||||
@@ -226,28 +227,70 @@ export class PathaoAdapter {
|
|||||||
}
|
}
|
||||||
async trackParcel(trackingCode) {
|
async trackParcel(trackingCode) {
|
||||||
if (!this.isConfigured()) {
|
if (!this.isConfigured()) {
|
||||||
throw new Error("Pathao credentials are not configured.");
|
throw new McpToolError({
|
||||||
|
code: "COURIER_NOT_CONFIGURED",
|
||||||
|
message: "Pathao credentials are not configured.",
|
||||||
|
courier: "pathao",
|
||||||
|
});
|
||||||
|
}
|
||||||
|
try {
|
||||||
|
const client = await this.getClient();
|
||||||
|
const response = await withGetRetry(() => client.get(`/aladdin/api/v1/orders/${encodeURIComponent(trackingCode)}/info`));
|
||||||
|
const data = response.data?.data || {};
|
||||||
|
return {
|
||||||
|
success: true,
|
||||||
|
courier: "pathao",
|
||||||
|
tracking_code: trackingCode,
|
||||||
|
status: data.order_status || data.order_status_slug || "unknown",
|
||||||
|
updated_at: data.updated_at || new Date().toISOString(),
|
||||||
|
raw_response: response.data,
|
||||||
|
};
|
||||||
|
}
|
||||||
|
catch (err) {
|
||||||
|
const status = err?.response?.status;
|
||||||
|
if (status === 404 || status === 400 || status === 422) {
|
||||||
|
throw new McpToolError({
|
||||||
|
code: "CONSIGNMENT_NOT_FOUND",
|
||||||
|
message: `Consignment '${trackingCode}' was not found in Pathao.`,
|
||||||
|
retryable: false,
|
||||||
|
courier: "pathao",
|
||||||
|
});
|
||||||
|
}
|
||||||
|
throw err;
|
||||||
}
|
}
|
||||||
const client = await this.getClient();
|
|
||||||
const response = await client.get(`/aladdin/api/v1/orders/${encodeURIComponent(trackingCode)}/info`);
|
|
||||||
const data = response.data.data;
|
|
||||||
return {
|
|
||||||
success: true,
|
|
||||||
courier: "pathao",
|
|
||||||
tracking_code: trackingCode,
|
|
||||||
status: data.order_status || "unknown",
|
|
||||||
updated_at: data.updated_at || new Date().toISOString(),
|
|
||||||
raw_response: response.data,
|
|
||||||
};
|
|
||||||
}
|
}
|
||||||
|
/**
|
||||||
|
* Pathao does not expose a live wallet balance API endpoint (T3).
|
||||||
|
* Returns amount_bdt: null, current_balance: null, status: UNSUPPORTED_BY_PROVIDER.
|
||||||
|
*/
|
||||||
async getBalance() {
|
async getBalance() {
|
||||||
return {
|
return {
|
||||||
success: true,
|
success: true,
|
||||||
courier: "pathao",
|
courier: "pathao",
|
||||||
current_balance: 0,
|
amount_bdt: null,
|
||||||
raw_response: { message: "Pathao payout balance managed via merchant portal" },
|
pending_bdt: null,
|
||||||
|
current_balance: null,
|
||||||
|
status: "UNSUPPORTED_BY_PROVIDER",
|
||||||
|
hint: "Use Pathao merchant portal",
|
||||||
};
|
};
|
||||||
}
|
}
|
||||||
|
/**
|
||||||
|
* 100% Real Live Pathao Nationwide Customer Delivery Success API
|
||||||
|
* Endpoint: POST /aladdin/api/v1/user/success
|
||||||
|
*/
|
||||||
|
async fraudCheck(phone) {
|
||||||
|
if (!this.isConfigured()) {
|
||||||
|
throw new McpToolError({
|
||||||
|
code: "COURIER_NOT_CONFIGURED",
|
||||||
|
message: "Pathao credentials are not configured.",
|
||||||
|
courier: "pathao",
|
||||||
|
});
|
||||||
|
}
|
||||||
|
const cleanPhone = phone.replace(/\D/g, "").replace(/^88/, "");
|
||||||
|
const client = await this.getClient();
|
||||||
|
const response = await client.post("/aladdin/api/v1/user/success", { phone: cleanPhone });
|
||||||
|
return response.data;
|
||||||
|
}
|
||||||
async getLocations(cityName) {
|
async getLocations(cityName) {
|
||||||
const client = await this.getClient();
|
const client = await this.getClient();
|
||||||
const response = await client.get("/aladdin/api/v1/cities");
|
const response = await client.get("/aladdin/api/v1/cities");
|
||||||
|
|||||||
Vendored
+3
@@ -10,5 +10,8 @@ export declare class RedxAdapter implements CourierAdapter {
|
|||||||
private resolveDeliveryArea;
|
private resolveDeliveryArea;
|
||||||
createParcel(req: ParcelCreateRequest): Promise<ParcelResponse>;
|
createParcel(req: ParcelCreateRequest): Promise<ParcelResponse>;
|
||||||
trackParcel(trackingCode: string): Promise<TrackingResponse>;
|
trackParcel(trackingCode: string): Promise<TrackingResponse>;
|
||||||
|
/**
|
||||||
|
* RedX does not expose a live wallet balance API endpoint (T3).
|
||||||
|
*/
|
||||||
getBalance(): Promise<BalanceResponse>;
|
getBalance(): Promise<BalanceResponse>;
|
||||||
}
|
}
|
||||||
|
|||||||
Vendored
+42
-13
@@ -1,4 +1,5 @@
|
|||||||
import axios from "axios";
|
import axios from "axios";
|
||||||
|
import { McpToolError, withGetRetry } from "../envelope.js";
|
||||||
export class RedxAdapter {
|
export class RedxAdapter {
|
||||||
courierName = "redx";
|
courierName = "redx";
|
||||||
client;
|
client;
|
||||||
@@ -89,23 +90,51 @@ export class RedxAdapter {
|
|||||||
}
|
}
|
||||||
async trackParcel(trackingCode) {
|
async trackParcel(trackingCode) {
|
||||||
if (!this.enabled) {
|
if (!this.enabled) {
|
||||||
throw new Error("RedX credentials are not configured.");
|
throw new McpToolError({
|
||||||
|
code: "COURIER_NOT_CONFIGURED",
|
||||||
|
message: "RedX credentials are not configured.",
|
||||||
|
courier: "redx",
|
||||||
|
});
|
||||||
}
|
}
|
||||||
const response = await this.client.get(`/parcel/track/${encodeURIComponent(trackingCode)}`);
|
try {
|
||||||
const data = response.data;
|
const response = await withGetRetry(() => this.client.get(`/parcel/track/${encodeURIComponent(trackingCode)}`));
|
||||||
const events = data?.tracking || [];
|
const data = response.data;
|
||||||
const latest = events[events.length - 1];
|
const events = data?.tracking || [];
|
||||||
|
const latest = events[events.length - 1];
|
||||||
|
return {
|
||||||
|
success: true,
|
||||||
|
courier: "redx",
|
||||||
|
tracking_code: trackingCode,
|
||||||
|
status: latest?.message_en || "in-transit",
|
||||||
|
updated_at: latest?.time || new Date().toISOString(),
|
||||||
|
timeline: events.map((e) => ({ status: e.message_en || "", time: e.time || "", note: e.message_bn })),
|
||||||
|
raw_response: data,
|
||||||
|
};
|
||||||
|
}
|
||||||
|
catch (err) {
|
||||||
|
if (err?.response?.status === 404 || err?.response?.status === 400) {
|
||||||
|
throw new McpToolError({
|
||||||
|
code: "CONSIGNMENT_NOT_FOUND",
|
||||||
|
message: `Consignment '${trackingCode}' was not found in RedX.`,
|
||||||
|
retryable: false,
|
||||||
|
courier: "redx",
|
||||||
|
});
|
||||||
|
}
|
||||||
|
throw err;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
/**
|
||||||
|
* RedX does not expose a live wallet balance API endpoint (T3).
|
||||||
|
*/
|
||||||
|
async getBalance() {
|
||||||
return {
|
return {
|
||||||
success: true,
|
success: true,
|
||||||
courier: "redx",
|
courier: "redx",
|
||||||
tracking_code: trackingCode,
|
amount_bdt: null,
|
||||||
status: latest?.message_en || "unknown",
|
pending_bdt: null,
|
||||||
updated_at: latest?.time || new Date().toISOString(),
|
current_balance: null,
|
||||||
timeline: events.map((e) => ({ status: e.message_en || "", time: e.time || "", note: e.message_bn })),
|
status: "UNSUPPORTED_BY_PROVIDER",
|
||||||
raw_response: data,
|
hint: "Use RedX merchant portal",
|
||||||
};
|
};
|
||||||
}
|
}
|
||||||
async getBalance() {
|
|
||||||
throw new Error("RedX does not expose a merchant balance endpoint via its public API — check your balance in the RedX merchant panel.");
|
|
||||||
}
|
|
||||||
}
|
}
|
||||||
|
|||||||
Vendored
-1
@@ -12,7 +12,6 @@ export declare class SteadfastAdapter implements CourierAdapter {
|
|||||||
/**
|
/**
|
||||||
* 100% Real Live Steadfast Fraud Check API
|
* 100% Real Live Steadfast Fraud Check API
|
||||||
* Endpoint: GET /fraud_check/{phone}
|
* Endpoint: GET /fraud_check/{phone}
|
||||||
* Returns nationwide parcel history across Bangladesh: total_parcels, total_delivered, total_cancelled
|
|
||||||
*/
|
*/
|
||||||
fraudCheck(phone: string): Promise<any>;
|
fraudCheck(phone: string): Promise<any>;
|
||||||
}
|
}
|
||||||
|
|||||||
Vendored
+72
-17
@@ -1,11 +1,12 @@
|
|||||||
import axios from "axios";
|
import axios from "axios";
|
||||||
|
import { McpToolError, withGetRetry } from "../envelope.js";
|
||||||
export class SteadfastAdapter {
|
export class SteadfastAdapter {
|
||||||
courierName = "steadfast";
|
courierName = "steadfast";
|
||||||
client;
|
client;
|
||||||
enabled;
|
enabled;
|
||||||
constructor(apiKey, secretKey, baseUrl) {
|
constructor(apiKey, secretKey, baseUrl) {
|
||||||
this.enabled = Boolean(apiKey && secretKey);
|
this.enabled = Boolean(apiKey && secretKey);
|
||||||
const resolvedBase = baseUrl || "https://portal.steadfast.com.bd/api/v1";
|
const resolvedBase = baseUrl || "https://portal.packzy.com/api/v1";
|
||||||
this.client = axios.create({
|
this.client = axios.create({
|
||||||
baseURL: resolvedBase,
|
baseURL: resolvedBase,
|
||||||
headers: {
|
headers: {
|
||||||
@@ -52,43 +53,97 @@ export class SteadfastAdapter {
|
|||||||
}
|
}
|
||||||
async trackParcel(trackingCode) {
|
async trackParcel(trackingCode) {
|
||||||
if (!this.enabled) {
|
if (!this.enabled) {
|
||||||
throw new Error("Steadfast Courier credentials are not configured.");
|
throw new McpToolError({
|
||||||
|
code: "COURIER_NOT_CONFIGURED",
|
||||||
|
message: "Steadfast Courier credentials are not configured.",
|
||||||
|
courier: "steadfast",
|
||||||
|
});
|
||||||
}
|
}
|
||||||
const response = await this.client.get(`/status_by_trackingcode/${encodeURIComponent(trackingCode)}`);
|
const endpoints = [
|
||||||
const data = response.data;
|
`/status_by_trackingcode/${encodeURIComponent(trackingCode)}`,
|
||||||
return {
|
`/status_by_cid/${encodeURIComponent(trackingCode)}`,
|
||||||
success: true,
|
`/status_by_invoice/${encodeURIComponent(trackingCode)}`,
|
||||||
|
];
|
||||||
|
let lastErr = null;
|
||||||
|
for (const ep of endpoints) {
|
||||||
|
try {
|
||||||
|
const response = await withGetRetry(() => this.client.get(ep));
|
||||||
|
const data = response.data;
|
||||||
|
if (data && (data.status === 200 || data.delivery_status)) {
|
||||||
|
return {
|
||||||
|
success: true,
|
||||||
|
courier: "steadfast",
|
||||||
|
tracking_code: trackingCode,
|
||||||
|
status: data.delivery_status || "in_review",
|
||||||
|
updated_at: data.updated_at || new Date().toISOString(),
|
||||||
|
raw_response: data,
|
||||||
|
};
|
||||||
|
}
|
||||||
|
}
|
||||||
|
catch (err) {
|
||||||
|
lastErr = err;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
const status = lastErr?.response?.status;
|
||||||
|
if (status === 404 || status === 400) {
|
||||||
|
throw new McpToolError({
|
||||||
|
code: "CONSIGNMENT_NOT_FOUND",
|
||||||
|
message: `Consignment '${trackingCode}' was not found in Steadfast.`,
|
||||||
|
retryable: false,
|
||||||
|
courier: "steadfast",
|
||||||
|
});
|
||||||
|
}
|
||||||
|
if (status === 401 || status === 403) {
|
||||||
|
throw new McpToolError({
|
||||||
|
code: "COURIER_UPSTREAM_ERROR",
|
||||||
|
message: "Steadfast upstream authentication or consignment ownership check failed.",
|
||||||
|
retryable: false,
|
||||||
|
courier: "steadfast",
|
||||||
|
});
|
||||||
|
}
|
||||||
|
throw lastErr || new McpToolError({
|
||||||
|
code: "CONSIGNMENT_NOT_FOUND",
|
||||||
|
message: `Consignment '${trackingCode}' was not found in Steadfast.`,
|
||||||
|
retryable: false,
|
||||||
courier: "steadfast",
|
courier: "steadfast",
|
||||||
tracking_code: trackingCode,
|
});
|
||||||
status: data.delivery_status || "unknown",
|
|
||||||
updated_at: data.updated_at || new Date().toISOString(),
|
|
||||||
raw_response: data,
|
|
||||||
};
|
|
||||||
}
|
}
|
||||||
async getBalance() {
|
async getBalance() {
|
||||||
if (!this.enabled) {
|
if (!this.enabled) {
|
||||||
throw new Error("Steadfast Courier credentials are not configured.");
|
throw new McpToolError({
|
||||||
|
code: "COURIER_NOT_CONFIGURED",
|
||||||
|
message: "Steadfast Courier credentials are not configured.",
|
||||||
|
courier: "steadfast",
|
||||||
|
});
|
||||||
}
|
}
|
||||||
const response = await this.client.get("/get_balance");
|
const response = await withGetRetry(() => this.client.get("/get_balance"));
|
||||||
const data = response.data;
|
const data = response.data;
|
||||||
|
const bal = typeof data?.current_balance === "number" ? data.current_balance : Number(data?.current_balance ?? 0);
|
||||||
return {
|
return {
|
||||||
success: true,
|
success: true,
|
||||||
courier: "steadfast",
|
courier: "steadfast",
|
||||||
current_balance: Number(data.current_balance || 0),
|
amount_bdt: bal,
|
||||||
|
pending_bdt: 0,
|
||||||
|
current_balance: bal,
|
||||||
|
status: "OK",
|
||||||
|
as_of: new Date().toISOString(),
|
||||||
raw_response: data,
|
raw_response: data,
|
||||||
};
|
};
|
||||||
}
|
}
|
||||||
/**
|
/**
|
||||||
* 100% Real Live Steadfast Fraud Check API
|
* 100% Real Live Steadfast Fraud Check API
|
||||||
* Endpoint: GET /fraud_check/{phone}
|
* Endpoint: GET /fraud_check/{phone}
|
||||||
* Returns nationwide parcel history across Bangladesh: total_parcels, total_delivered, total_cancelled
|
|
||||||
*/
|
*/
|
||||||
async fraudCheck(phone) {
|
async fraudCheck(phone) {
|
||||||
if (!this.enabled) {
|
if (!this.enabled) {
|
||||||
throw new Error("Steadfast Courier credentials are not configured.");
|
throw new McpToolError({
|
||||||
|
code: "COURIER_NOT_CONFIGURED",
|
||||||
|
message: "Steadfast Courier credentials are not configured.",
|
||||||
|
courier: "steadfast",
|
||||||
|
});
|
||||||
}
|
}
|
||||||
const cleanPhone = phone.replace(/\D/g, "");
|
const cleanPhone = phone.replace(/\D/g, "");
|
||||||
const response = await this.client.get(`/fraud_check/${encodeURIComponent(cleanPhone)}`);
|
const response = await withGetRetry(() => this.client.get(`/fraud_check/${encodeURIComponent(cleanPhone)}`));
|
||||||
return response.data;
|
return response.data;
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|||||||
Vendored
+10
-1
@@ -1,5 +1,14 @@
|
|||||||
import dotenv from "dotenv";
|
import dotenv from "dotenv";
|
||||||
dotenv.config();
|
if (process.env.NODE_ENV !== "test") {
|
||||||
|
const runtimePort = process.env.PORT;
|
||||||
|
dotenv.config({ override: true });
|
||||||
|
if (runtimePort) {
|
||||||
|
process.env.PORT = runtimePort;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
else {
|
||||||
|
dotenv.config();
|
||||||
|
}
|
||||||
/**
|
/**
|
||||||
* Build a CourierConfig from a key/value source.
|
* Build a CourierConfig from a key/value source.
|
||||||
* Defaults to process.env (used by the STDIO/npx entrypoint); the HTTP
|
* Defaults to process.env (used by the STDIO/npx entrypoint); the HTTP
|
||||||
|
|||||||
Vendored
+55
@@ -0,0 +1,55 @@
|
|||||||
|
export type EnvelopeSource = "live_api" | "static_tariff" | "cache" | "validator";
|
||||||
|
export type EnvelopeErrorCode = "UNAUTHORIZED" | "INVALID_INPUT" | "CONSIGNMENT_NOT_FOUND" | "COURIER_NOT_CONFIGURED" | "COURIER_UPSTREAM_ERROR" | "UNSUPPORTED_BY_PROVIDER" | "DUPLICATE_INVOICE";
|
||||||
|
export interface EnvelopeError {
|
||||||
|
code: EnvelopeErrorCode;
|
||||||
|
message: string;
|
||||||
|
retryable: boolean;
|
||||||
|
courier?: string;
|
||||||
|
}
|
||||||
|
export interface EnvelopeMeta {
|
||||||
|
request_id: string;
|
||||||
|
source: EnvelopeSource;
|
||||||
|
as_of: string;
|
||||||
|
}
|
||||||
|
export interface GlobalEnvelope<T = any> {
|
||||||
|
ok: boolean;
|
||||||
|
data: T | null;
|
||||||
|
error: EnvelopeError | null;
|
||||||
|
meta: EnvelopeMeta;
|
||||||
|
[key: string]: any;
|
||||||
|
}
|
||||||
|
export declare class McpToolError extends Error {
|
||||||
|
readonly code: EnvelopeErrorCode;
|
||||||
|
readonly retryable: boolean;
|
||||||
|
readonly courier?: string;
|
||||||
|
readonly source: EnvelopeSource;
|
||||||
|
readonly extraFields?: Record<string, any>;
|
||||||
|
constructor(opts: {
|
||||||
|
code: EnvelopeErrorCode;
|
||||||
|
message: string;
|
||||||
|
retryable?: boolean;
|
||||||
|
courier?: string;
|
||||||
|
source?: EnvelopeSource;
|
||||||
|
extraFields?: Record<string, any>;
|
||||||
|
});
|
||||||
|
}
|
||||||
|
/**
|
||||||
|
* Wrap a successful tool payload in the global response envelope while keeping
|
||||||
|
* existing top-level fields intact alongside the envelope for backward compatibility.
|
||||||
|
*/
|
||||||
|
export declare function wrapSuccess<T>(payload: T, source?: EnvelopeSource): GlobalEnvelope<T>;
|
||||||
|
/**
|
||||||
|
* Sanitize any error (including raw Axios errors) into a structured GlobalEnvelope
|
||||||
|
* that NEVER leaks raw Axios/HTTP error strings ("Request failed with status code ...").
|
||||||
|
*/
|
||||||
|
export declare function wrapError(err: any, defaultSource?: EnvelopeSource, defaultCourier?: string): GlobalEnvelope<null>;
|
||||||
|
export declare function sanitizeMessage(msg: string): string;
|
||||||
|
/**
|
||||||
|
* Bounded retry with exponential backoff for read-only GET operations.
|
||||||
|
* Retries only on 429, 5xx, or network timeouts.
|
||||||
|
*/
|
||||||
|
export declare function withGetRetry<T>(fn: () => Promise<T>, maxRetries?: number, baseDelayMs?: number): Promise<T>;
|
||||||
|
/**
|
||||||
|
* Mask Bangladeshi phone numbers for privacy-safe audit logging (e.g., 017****1234).
|
||||||
|
*/
|
||||||
|
export declare function maskPhone(phone: string): string;
|
||||||
Vendored
+159
@@ -0,0 +1,159 @@
|
|||||||
|
import { randomUUID } from "node:crypto";
|
||||||
|
export class McpToolError extends Error {
|
||||||
|
code;
|
||||||
|
retryable;
|
||||||
|
courier;
|
||||||
|
source;
|
||||||
|
extraFields;
|
||||||
|
constructor(opts) {
|
||||||
|
super(opts.message);
|
||||||
|
this.name = "McpToolError";
|
||||||
|
this.code = opts.code;
|
||||||
|
this.retryable = Boolean(opts.retryable);
|
||||||
|
this.courier = opts.courier;
|
||||||
|
this.source = opts.source || "live_api";
|
||||||
|
this.extraFields = opts.extraFields;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
/**
|
||||||
|
* Wrap a successful tool payload in the global response envelope while keeping
|
||||||
|
* existing top-level fields intact alongside the envelope for backward compatibility.
|
||||||
|
*/
|
||||||
|
export function wrapSuccess(payload, source = "live_api") {
|
||||||
|
const spread = payload && typeof payload === "object" && !Array.isArray(payload)
|
||||||
|
? payload
|
||||||
|
: { items: payload, success: true };
|
||||||
|
return {
|
||||||
|
...spread,
|
||||||
|
ok: true,
|
||||||
|
data: payload,
|
||||||
|
error: null,
|
||||||
|
meta: {
|
||||||
|
request_id: randomUUID(),
|
||||||
|
source,
|
||||||
|
as_of: new Date().toISOString(),
|
||||||
|
},
|
||||||
|
};
|
||||||
|
}
|
||||||
|
/**
|
||||||
|
* Sanitize any error (including raw Axios errors) into a structured GlobalEnvelope
|
||||||
|
* that NEVER leaks raw Axios/HTTP error strings ("Request failed with status code ...").
|
||||||
|
*/
|
||||||
|
export function wrapError(err, defaultSource = "live_api", defaultCourier) {
|
||||||
|
if (err instanceof McpToolError) {
|
||||||
|
return {
|
||||||
|
...(err.extraFields || {}),
|
||||||
|
success: false,
|
||||||
|
ok: false,
|
||||||
|
data: null,
|
||||||
|
error: {
|
||||||
|
code: err.code,
|
||||||
|
message: sanitizeMessage(err.message),
|
||||||
|
retryable: err.retryable,
|
||||||
|
...(err.courier ? { courier: err.courier } : defaultCourier ? { courier: defaultCourier } : {}),
|
||||||
|
},
|
||||||
|
meta: {
|
||||||
|
request_id: randomUUID(),
|
||||||
|
source: err.source || defaultSource,
|
||||||
|
as_of: new Date().toISOString(),
|
||||||
|
},
|
||||||
|
};
|
||||||
|
}
|
||||||
|
const httpStatus = err?.response?.status;
|
||||||
|
const errCode = String(err?.code || "");
|
||||||
|
const rawMsg = String(err?.message || "Unexpected operational error");
|
||||||
|
let code = "COURIER_UPSTREAM_ERROR";
|
||||||
|
let retryable = false;
|
||||||
|
let cleanMsg = "Upstream courier gateway error.";
|
||||||
|
if (rawMsg.toLowerCase().includes("not configured")) {
|
||||||
|
code = "COURIER_NOT_CONFIGURED";
|
||||||
|
retryable = false;
|
||||||
|
cleanMsg = sanitizeMessage(rawMsg);
|
||||||
|
}
|
||||||
|
else if (httpStatus === 401 || httpStatus === 403) {
|
||||||
|
code = "COURIER_UPSTREAM_ERROR";
|
||||||
|
retryable = false;
|
||||||
|
cleanMsg = "Courier upstream authentication or access rejected by provider.";
|
||||||
|
}
|
||||||
|
else if (httpStatus === 404) {
|
||||||
|
code = "CONSIGNMENT_NOT_FOUND";
|
||||||
|
retryable = false;
|
||||||
|
cleanMsg = "Requested consignment or resource was not found in the courier network.";
|
||||||
|
}
|
||||||
|
else if (httpStatus === 429 ||
|
||||||
|
(httpStatus && httpStatus >= 500) ||
|
||||||
|
errCode === "ECONNABORTED" ||
|
||||||
|
errCode === "ETIMEDOUT" ||
|
||||||
|
errCode === "ECONNRESET" ||
|
||||||
|
rawMsg.toLowerCase().includes("timeout")) {
|
||||||
|
code = "COURIER_UPSTREAM_ERROR";
|
||||||
|
retryable = true;
|
||||||
|
cleanMsg = "Courier upstream service temporarily unavailable or timed out.";
|
||||||
|
}
|
||||||
|
else if (httpStatus === 400 || httpStatus === 422 || rawMsg.toLowerCase().includes("invalid")) {
|
||||||
|
code = "INVALID_INPUT";
|
||||||
|
retryable = false;
|
||||||
|
cleanMsg = sanitizeMessage(rawMsg);
|
||||||
|
}
|
||||||
|
else {
|
||||||
|
cleanMsg = sanitizeMessage(rawMsg);
|
||||||
|
}
|
||||||
|
return {
|
||||||
|
success: false,
|
||||||
|
ok: false,
|
||||||
|
data: null,
|
||||||
|
error: {
|
||||||
|
code,
|
||||||
|
message: cleanMsg,
|
||||||
|
retryable,
|
||||||
|
...(defaultCourier ? { courier: defaultCourier } : {}),
|
||||||
|
},
|
||||||
|
meta: {
|
||||||
|
request_id: randomUUID(),
|
||||||
|
source: defaultSource,
|
||||||
|
as_of: new Date().toISOString(),
|
||||||
|
},
|
||||||
|
};
|
||||||
|
}
|
||||||
|
export function sanitizeMessage(msg) {
|
||||||
|
return String(msg || "Operation failed")
|
||||||
|
.replace(/Request failed with status code \d+/gi, "Upstream provider returned an error status")
|
||||||
|
.replace(/AxiosError:\s*/gi, "")
|
||||||
|
.trim();
|
||||||
|
}
|
||||||
|
/**
|
||||||
|
* Bounded retry with exponential backoff for read-only GET operations.
|
||||||
|
* Retries only on 429, 5xx, or network timeouts.
|
||||||
|
*/
|
||||||
|
export async function withGetRetry(fn, maxRetries = 2, baseDelayMs = 150) {
|
||||||
|
let attempt = 0;
|
||||||
|
while (true) {
|
||||||
|
try {
|
||||||
|
return await fn();
|
||||||
|
}
|
||||||
|
catch (err) {
|
||||||
|
const status = err?.response?.status;
|
||||||
|
const code = String(err?.code || "");
|
||||||
|
const isRetryable = status === 429 ||
|
||||||
|
(typeof status === "number" && status >= 500) ||
|
||||||
|
code === "ECONNABORTED" ||
|
||||||
|
code === "ETIMEDOUT" ||
|
||||||
|
code === "ECONNRESET";
|
||||||
|
if (!isRetryable || attempt >= maxRetries) {
|
||||||
|
throw err;
|
||||||
|
}
|
||||||
|
attempt++;
|
||||||
|
const delay = baseDelayMs * Math.pow(2, attempt - 1);
|
||||||
|
await new Promise((r) => setTimeout(r, delay));
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
/**
|
||||||
|
* Mask Bangladeshi phone numbers for privacy-safe audit logging (e.g., 017****1234).
|
||||||
|
*/
|
||||||
|
export function maskPhone(phone) {
|
||||||
|
const digits = String(phone || "").replace(/\D/g, "");
|
||||||
|
if (digits.length < 7)
|
||||||
|
return "***";
|
||||||
|
return `${digits.slice(0, 3)}****${digits.slice(-4)}`;
|
||||||
|
}
|
||||||
Vendored
+9
-1
@@ -1 +1,9 @@
|
|||||||
export {};
|
import { Request } from "express";
|
||||||
|
import { EnvSource } from "./config.js";
|
||||||
|
/**
|
||||||
|
* Pull this client's courier keys from request headers or query params.
|
||||||
|
* Task T1 Tenant Isolation: Only fall back to master process.env credentials when
|
||||||
|
* the caller authenticated with the master key (tenantId === "master").
|
||||||
|
*/
|
||||||
|
export declare function keysFromRequest(req: Request): EnvSource;
|
||||||
|
export declare const app: import("express-serve-static-core").Express;
|
||||||
|
|||||||
Vendored
+222
-228
@@ -2,22 +2,25 @@ import express from "express";
|
|||||||
import { randomUUID } from "node:crypto";
|
import { randomUUID } from "node:crypto";
|
||||||
import { StreamableHTTPServerTransport } from "@modelcontextprotocol/sdk/server/streamableHttp.js";
|
import { StreamableHTTPServerTransport } from "@modelcontextprotocol/sdk/server/streamableHttp.js";
|
||||||
import { isInitializeRequest } from "@modelcontextprotocol/sdk/types.js";
|
import { isInitializeRequest } from "@modelcontextprotocol/sdk/types.js";
|
||||||
import { CourierRegistry } from "./registry.js";
|
import { CourierRegistry, recordWebhookEvent } from "./registry.js";
|
||||||
import { loadConfig } from "./config.js";
|
import { loadConfig } from "./config.js";
|
||||||
import { buildMcpServer, TOOLS } from "./server.js";
|
import { buildMcpServer, executeToolCall, TOOLS } from "./server.js";
|
||||||
import { createRateLimiter } from "./middleware/rate_limit.js";
|
import { createRateLimiter } from "./middleware/rate_limit.js";
|
||||||
import { optionalAuthMiddleware, isActionPermitted } from "./middleware/auth.js";
|
import { optionalAuthMiddleware, requireMcpAuth, isActionPermitted, resolveAuthContext, verifyWebhookSignature, recordAuditLog, } from "./middleware/auth.js";
|
||||||
|
import { McpToolError, wrapError, wrapSuccess } from "./envelope.js";
|
||||||
import path from "node:path";
|
import path from "node:path";
|
||||||
import { fileURLToPath } from "node:url";
|
import { fileURLToPath } from "node:url";
|
||||||
import pg from "pg";
|
import pg from "pg";
|
||||||
const dbUrl = process.env.DATABASE_URL || "postgresql://postgres:AMeyaNUsvKN9GR4zs33YZFQw2ZjeBXRacp5K09bz4vwDMsLejuO1KxBGIZtDLVCw@ernix50nvuq9ur9jy8na8tgr:5432/aura_auth";
|
const dbUrl = process.env.DATABASE_URL ||
|
||||||
|
"postgresql://postgres:AMeyaNUsvKN9GR4zs33YZFQw2ZjeBXRacp5K09bz4vwDMsLejuO1KxBGIZtDLVCw@ernix50nvuq9ur9jy8na8tgr:5432/aura_auth";
|
||||||
let dbPool = null;
|
let dbPool = null;
|
||||||
try {
|
if (process.env.NODE_ENV !== "test") {
|
||||||
dbPool = new pg.Pool({ connectionString: dbUrl, max: 4, idleTimeoutMillis: 30000 });
|
try {
|
||||||
|
dbPool = new pg.Pool({ connectionString: dbUrl, max: 4, idleTimeoutMillis: 30000 });
|
||||||
|
}
|
||||||
|
catch (_) { }
|
||||||
}
|
}
|
||||||
catch (_) { }
|
|
||||||
// Automated Data Retention Engine (Daily Midnight Sweep)
|
// Automated Data Retention Engine (Daily Midnight Sweep)
|
||||||
// Anonymizes customer PII older than 90 days in accordance with data retention policy
|
|
||||||
setInterval(async () => {
|
setInterval(async () => {
|
||||||
if (dbPool) {
|
if (dbPool) {
|
||||||
try {
|
try {
|
||||||
@@ -28,9 +31,7 @@ setInterval(async () => {
|
|||||||
console.log(`[Data Retention Engine] Anonymized ${pruneRes.rowCount} legacy order records older than 90 days.`);
|
console.log(`[Data Retention Engine] Anonymized ${pruneRes.rowCount} legacy order records older than 90 days.`);
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
catch (err) {
|
catch (_) { }
|
||||||
// Table may not exist in standalone mode; continue safely
|
|
||||||
}
|
|
||||||
}
|
}
|
||||||
}, 24 * 60 * 60 * 1000).unref();
|
}, 24 * 60 * 60 * 1000).unref();
|
||||||
const PORT = Number(process.env.PORT || 8080);
|
const PORT = Number(process.env.PORT || 8080);
|
||||||
@@ -39,52 +40,63 @@ const LANDING = path.join(APP_DIR, "index.html");
|
|||||||
const PRIVACY_HTML = path.join(APP_DIR, "privacy.html");
|
const PRIVACY_HTML = path.join(APP_DIR, "privacy.html");
|
||||||
const HEALTH_HTML = path.join(APP_DIR, "health.html");
|
const HEALTH_HTML = path.join(APP_DIR, "health.html");
|
||||||
const MCP_EXPLORER_HTML = path.join(APP_DIR, "mcp_explorer.html");
|
const MCP_EXPLORER_HTML = path.join(APP_DIR, "mcp_explorer.html");
|
||||||
// Pull this client's courier keys from request headers or query params, with fallback to environment
|
const GUIDE_HTML = path.join(APP_DIR, "guide.html");
|
||||||
function keysFromRequest(req) {
|
/**
|
||||||
|
* Pull this client's courier keys from request headers or query params.
|
||||||
|
* Task T1 Tenant Isolation: Only fall back to master process.env credentials when
|
||||||
|
* the caller authenticated with the master key (tenantId === "master").
|
||||||
|
*/
|
||||||
|
export function keysFromRequest(req) {
|
||||||
const h = req.headers;
|
const h = req.headers;
|
||||||
const q = req.query;
|
const q = req.query;
|
||||||
const pick = (header, query, envVar) => {
|
const allowMasterEnvFallback = req.auraAuth?.tenantId === "master";
|
||||||
|
const pick = (header, query, envVar, allowNonMasterEnv = false) => {
|
||||||
const hv = h[header];
|
const hv = h[header];
|
||||||
const v = (Array.isArray(hv) ? hv[0] : hv) ?? q[query];
|
const v = (Array.isArray(hv) ? hv[0] : hv) ?? q[query];
|
||||||
return v ? String(v) : (envVar ? process.env[envVar] : undefined);
|
if (v)
|
||||||
|
return String(v);
|
||||||
|
if (envVar && (allowMasterEnvFallback || allowNonMasterEnv)) {
|
||||||
|
return process.env[envVar];
|
||||||
|
}
|
||||||
|
return undefined;
|
||||||
};
|
};
|
||||||
return {
|
return {
|
||||||
STEADFAST_API_KEY: pick("x-steadfast-api-key", "steadfast_key", "STEADFAST_API_KEY"),
|
STEADFAST_API_KEY: pick("x-steadfast-api-key", "steadfast_key", "STEADFAST_API_KEY"),
|
||||||
STEADFAST_SECRET_KEY: pick("x-steadfast-secret-key", "steadfast_secret", "STEADFAST_SECRET_KEY"),
|
STEADFAST_SECRET_KEY: pick("x-steadfast-secret-key", "steadfast_secret", "STEADFAST_SECRET_KEY"),
|
||||||
STEADFAST_BASE_URL: pick("x-steadfast-base-url", "steadfast_base_url", "STEADFAST_BASE_URL"),
|
STEADFAST_BASE_URL: pick("x-steadfast-base-url", "steadfast_base_url", "STEADFAST_BASE_URL", true),
|
||||||
PATHAO_CLIENT_ID: pick("x-pathao-client-id", "pathao_client_id", "PATHAO_CLIENT_ID"),
|
PATHAO_CLIENT_ID: pick("x-pathao-client-id", "pathao_client_id", "PATHAO_CLIENT_ID"),
|
||||||
PATHAO_CLIENT_SECRET: pick("x-pathao-client-secret", "pathao_client_secret", "PATHAO_CLIENT_SECRET"),
|
PATHAO_CLIENT_SECRET: pick("x-pathao-client-secret", "pathao_client_secret", "PATHAO_CLIENT_SECRET"),
|
||||||
PATHAO_USERNAME: pick("x-pathao-username", "pathao_username", "PATHAO_USERNAME"),
|
PATHAO_USERNAME: pick("x-pathao-username", "pathao_username", "PATHAO_USERNAME"),
|
||||||
PATHAO_PASSWORD: pick("x-pathao-password", "pathao_password", "PATHAO_PASSWORD"),
|
PATHAO_PASSWORD: pick("x-pathao-password", "pathao_password", "PATHAO_PASSWORD"),
|
||||||
PATHAO_STORE_ID: pick("x-pathao-store-id", "pathao_store_id", "PATHAO_STORE_ID"),
|
PATHAO_STORE_ID: pick("x-pathao-store-id", "pathao_store_id", "PATHAO_STORE_ID"),
|
||||||
PATHAO_BASE_URL: pick("x-pathao-base-url", "pathao_base_url", "PATHAO_BASE_URL"),
|
PATHAO_BASE_URL: pick("x-pathao-base-url", "pathao_base_url", "PATHAO_BASE_URL", true),
|
||||||
REDX_API_TOKEN: pick("x-redx-api-token", "redx_token", "REDX_API_TOKEN"),
|
REDX_API_TOKEN: pick("x-redx-api-token", "redx_token", "REDX_API_TOKEN"),
|
||||||
REDX_BASE_URL: pick("x-redx-base-url", "redx_base_url", "REDX_BASE_URL"),
|
REDX_BASE_URL: pick("x-redx-base-url", "redx_base_url", "REDX_BASE_URL", true),
|
||||||
REDX_PICKUP_STORE_ID: pick("x-redx-pickup-store-id", "redx_pickup_store_id", "REDX_PICKUP_STORE_ID"),
|
REDX_PICKUP_STORE_ID: pick("x-redx-pickup-store-id", "redx_pickup_store_id", "REDX_PICKUP_STORE_ID"),
|
||||||
PAPERFLY_API_KEY: pick("x-paperfly-api-key", "paperfly_key", "PAPERFLY_API_KEY"),
|
PAPERFLY_API_KEY: pick("x-paperfly-api-key", "paperfly_key", "PAPERFLY_API_KEY"),
|
||||||
PAPERFLY_USERNAME: pick("x-paperfly-username", "paperfly_username", "PAPERFLY_USERNAME"),
|
PAPERFLY_USERNAME: pick("x-paperfly-username", "paperfly_username", "PAPERFLY_USERNAME"),
|
||||||
PAPERFLY_PASSWORD: pick("x-paperfly-password", "paperfly_password", "PAPERFLY_PASSWORD"),
|
PAPERFLY_PASSWORD: pick("x-paperfly-password", "paperfly_password", "PAPERFLY_PASSWORD"),
|
||||||
PAPERFLY_STORE_NAME: pick("x-paperfly-store-name", "paperfly_store", "PAPERFLY_STORE_NAME"),
|
PAPERFLY_STORE_NAME: pick("x-paperfly-store-name", "paperfly_store", "PAPERFLY_STORE_NAME"),
|
||||||
GOOGLE_MAPS_API_KEY: pick("x-google-maps-key", "google_maps_key", "GOOGLE_MAPS_API_KEY"),
|
GOOGLE_MAPS_API_KEY: pick("x-google-maps-key", "google_maps_key", "GOOGLE_MAPS_API_KEY", true),
|
||||||
};
|
};
|
||||||
}
|
}
|
||||||
const app = express();
|
export const app = express();
|
||||||
app.use(express.json({ limit: "1mb" }));
|
app.use(express.json({ limit: "1mb" }));
|
||||||
// Robust Malformed JSON Syntax Error Guard
|
// Robust Malformed JSON Syntax Error Guard
|
||||||
app.use((err, req, res, next) => {
|
app.use((err, _req, res, next) => {
|
||||||
if (err && (err.type === "entity.parse.failed" || err.status === 400)) {
|
if (err && (err.type === "entity.parse.failed" || err.status === 400)) {
|
||||||
return res.status(400).json({
|
return res.status(400).json(wrapError(new McpToolError({
|
||||||
error: "Malformed JSON payload in request body",
|
code: "INVALID_INPUT",
|
||||||
details: err.message,
|
message: "Malformed JSON payload in request body.",
|
||||||
timestamp: new Date().toISOString()
|
retryable: false,
|
||||||
});
|
}), "validator"));
|
||||||
}
|
}
|
||||||
next(err);
|
next(err);
|
||||||
});
|
});
|
||||||
// Allow browser-based and cross-origin MCP clients.
|
// Allow browser-based and cross-origin MCP clients.
|
||||||
app.use((req, res, next) => {
|
app.use((req, res, next) => {
|
||||||
res.header("Access-Control-Allow-Origin", "*");
|
res.header("Access-Control-Allow-Origin", "*");
|
||||||
res.header("Access-Control-Allow-Headers", "Content-Type, Accept, Authorization, mcp-session-id, mcp-protocol-version, x-steadfast-api-key, x-steadfast-secret-key, x-steadfast-base-url, x-pathao-client-id, x-pathao-client-secret, x-pathao-username, x-pathao-password, x-pathao-store-id, x-pathao-base-url, x-redx-api-token, x-redx-base-url, x-redx-pickup-store-id, x-paperfly-api-key, x-paperfly-username, x-paperfly-password, x-paperfly-store-name, x-google-maps-key");
|
res.header("Access-Control-Allow-Headers", "Content-Type, Accept, Authorization, mcp-session-id, mcp-protocol-version, x-aura-signature, x-steadfast-signature, x-pathao-signature, x-redx-signature, x-paperfly-signature, x-webhook-secret, x-steadfast-api-key, x-steadfast-secret-key, x-steadfast-base-url, x-pathao-client-id, x-pathao-client-secret, x-pathao-username, x-pathao-password, x-pathao-store-id, x-pathao-base-url, x-redx-api-token, x-redx-base-url, x-redx-pickup-store-id, x-paperfly-api-key, x-paperfly-username, x-paperfly-password, x-paperfly-store-name, x-google-maps-key");
|
||||||
res.header("Access-Control-Allow-Methods", "GET, POST, DELETE, OPTIONS");
|
res.header("Access-Control-Allow-Methods", "GET, POST, DELETE, OPTIONS");
|
||||||
res.header("Access-Control-Expose-Headers", "mcp-session-id");
|
res.header("Access-Control-Expose-Headers", "mcp-session-id");
|
||||||
if (req.method === "OPTIONS") {
|
if (req.method === "OPTIONS") {
|
||||||
@@ -98,19 +110,16 @@ const generalLimiter = createRateLimiter({ windowMs: 60 * 1000, max: 120, name:
|
|||||||
const mcpLimiter = createRateLimiter({ windowMs: 60 * 1000, max: 60, name: "MCP Protocol Gateway" });
|
const mcpLimiter = createRateLimiter({ windowMs: 60 * 1000, max: 60, name: "MCP Protocol Gateway" });
|
||||||
const trackingLimiter = createRateLimiter({ windowMs: 60 * 1000, max: 30, name: "Live Tracking Hub" });
|
const trackingLimiter = createRateLimiter({ windowMs: 60 * 1000, max: 30, name: "Live Tracking Hub" });
|
||||||
const webhookLimiter = createRateLimiter({ windowMs: 60 * 1000, max: 120, name: "Courier Webhook Gateway" });
|
const webhookLimiter = createRateLimiter({ windowMs: 60 * 1000, max: 120, name: "Courier Webhook Gateway" });
|
||||||
// Apply global rate limiting and optional auth context evaluation
|
|
||||||
app.use(generalLimiter);
|
app.use(generalLimiter);
|
||||||
app.use(optionalAuthMiddleware);
|
app.use(optionalAuthMiddleware);
|
||||||
// Static brand assets (app icons, favicons, logos)
|
// Static brand assets (app icons, favicons, logos)
|
||||||
app.use("/assets", express.static(path.join(APP_DIR, "assets")));
|
app.use("/assets", express.static(path.join(APP_DIR, "assets")));
|
||||||
const sessions = new Map();
|
const sessions = new Map();
|
||||||
const SESSION_TTL_MS = 60 * 60 * 1000; // 1-hour idle expiration
|
const SESSION_TTL_MS = 60 * 60 * 1000; // 1-hour idle expiration
|
||||||
// Sweep abandoned sessions every 15 minutes to prevent heap bloat
|
|
||||||
setInterval(() => {
|
setInterval(() => {
|
||||||
const now = Date.now();
|
const now = Date.now();
|
||||||
for (const [sid, entry] of sessions.entries()) {
|
for (const [sid, entry] of sessions.entries()) {
|
||||||
if (now - entry.lastActiveAt > SESSION_TTL_MS) {
|
if (now - entry.lastActiveAt > SESSION_TTL_MS) {
|
||||||
console.log(`[Memory GC] Evicting stale MCP session: ${sid}`);
|
|
||||||
try {
|
try {
|
||||||
entry.transport.close?.();
|
entry.transport.close?.();
|
||||||
}
|
}
|
||||||
@@ -119,8 +128,12 @@ setInterval(() => {
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
}, 15 * 60 * 1000).unref();
|
}, 15 * 60 * 1000).unref();
|
||||||
app.post("/mcp", mcpLimiter, async (req, res) => {
|
/**
|
||||||
|
* Task T1: POST /mcp requires Authorization: Bearer <key>.
|
||||||
|
*/
|
||||||
|
app.post("/mcp", mcpLimiter, requireMcpAuth, async (req, res) => {
|
||||||
const sessionId = req.headers["mcp-session-id"];
|
const sessionId = req.headers["mcp-session-id"];
|
||||||
|
const tenantId = req.auraAuth?.tenantId || "default";
|
||||||
let transport;
|
let transport;
|
||||||
if (sessionId && sessions.has(sessionId)) {
|
if (sessionId && sessions.has(sessionId)) {
|
||||||
const entry = sessions.get(sessionId);
|
const entry = sessions.get(sessionId);
|
||||||
@@ -129,11 +142,9 @@ app.post("/mcp", mcpLimiter, async (req, res) => {
|
|||||||
}
|
}
|
||||||
else if (!sessionId && isInitializeRequest(req.body)) {
|
else if (!sessionId && isInitializeRequest(req.body)) {
|
||||||
const registry = new CourierRegistry(loadConfig(keysFromRequest(req)));
|
const registry = new CourierRegistry(loadConfig(keysFromRequest(req)));
|
||||||
const server = buildMcpServer(registry, (toolName) => isActionPermitted(req, toolName));
|
const server = buildMcpServer(registry, (toolName) => isActionPermitted(req, toolName), tenantId);
|
||||||
transport = new StreamableHTTPServerTransport({
|
transport = new StreamableHTTPServerTransport({
|
||||||
sessionIdGenerator: () => randomUUID(),
|
sessionIdGenerator: () => randomUUID(),
|
||||||
// Return application/json for POST responses instead of SSE — far more compatible with
|
|
||||||
// MCP clients/registries (e.g. Glama's connector test) that don't consume the event stream.
|
|
||||||
enableJsonResponse: true,
|
enableJsonResponse: true,
|
||||||
onsessioninitialized: (sid) => {
|
onsessioninitialized: (sid) => {
|
||||||
sessions.set(sid, { transport, lastActiveAt: Date.now() });
|
sessions.set(sid, { transport, lastActiveAt: Date.now() });
|
||||||
@@ -145,6 +156,45 @@ app.post("/mcp", mcpLimiter, async (req, res) => {
|
|||||||
};
|
};
|
||||||
await server.connect(transport);
|
await server.connect(transport);
|
||||||
}
|
}
|
||||||
|
else if (req.body && (req.body.method === "tools/list" || req.body.method === "tools/call")) {
|
||||||
|
// Stateless JSON-RPC 2.0 Direct Execution Mode
|
||||||
|
const rpcId = req.body.id ?? 1;
|
||||||
|
const registry = new CourierRegistry(loadConfig(keysFromRequest(req)));
|
||||||
|
if (req.body.method === "tools/list") {
|
||||||
|
res.status(200).json({ jsonrpc: "2.0", id: rpcId, result: { tools: TOOLS } });
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
const toolName = String(req.body.params?.name || "");
|
||||||
|
const args = (req.body.params?.arguments || {});
|
||||||
|
const auth = isActionPermitted(req, toolName, args);
|
||||||
|
if (!auth.permitted) {
|
||||||
|
const errEnvelope = wrapError(new McpToolError({
|
||||||
|
code: "UNAUTHORIZED",
|
||||||
|
message: auth.reason || "Unauthorized tool invocation.",
|
||||||
|
retryable: false,
|
||||||
|
}), "validator");
|
||||||
|
res.status(200).json({
|
||||||
|
jsonrpc: "2.0",
|
||||||
|
id: rpcId,
|
||||||
|
result: {
|
||||||
|
isError: true,
|
||||||
|
content: [{ type: "text", text: JSON.stringify(errEnvelope, null, 2) }],
|
||||||
|
},
|
||||||
|
});
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
const { isError, envelope } = await executeToolCall(registry, toolName, args, tenantId);
|
||||||
|
recordAuditLog(tenantId, toolName, args, isError ? "error" : "ok");
|
||||||
|
res.status(200).json({
|
||||||
|
jsonrpc: "2.0",
|
||||||
|
id: rpcId,
|
||||||
|
result: {
|
||||||
|
isError,
|
||||||
|
content: [{ type: "text", text: JSON.stringify(envelope, null, 2) }],
|
||||||
|
},
|
||||||
|
});
|
||||||
|
return;
|
||||||
|
}
|
||||||
else {
|
else {
|
||||||
res.status(400).json({
|
res.status(400).json({
|
||||||
jsonrpc: "2.0",
|
jsonrpc: "2.0",
|
||||||
@@ -170,7 +220,6 @@ app.post("/mcp", mcpLimiter, async (req, res) => {
|
|||||||
app.get("/mcp", mcpLimiter, async (req, res) => {
|
app.get("/mcp", mcpLimiter, async (req, res) => {
|
||||||
const sessionId = req.headers["mcp-session-id"];
|
const sessionId = req.headers["mcp-session-id"];
|
||||||
if (!sessionId || !sessions.has(sessionId)) {
|
if (!sessionId || !sessions.has(sessionId)) {
|
||||||
// If opened directly by a human in a web browser, serve the interactive MCP Protocol Explorer!
|
|
||||||
if (req.headers.accept?.includes("text/html")) {
|
if (req.headers.accept?.includes("text/html")) {
|
||||||
return res.sendFile(MCP_EXPLORER_HTML, (err) => {
|
return res.sendFile(MCP_EXPLORER_HTML, (err) => {
|
||||||
if (err && !res.headersSent) {
|
if (err && !res.headersSent) {
|
||||||
@@ -178,15 +227,27 @@ app.get("/mcp", mcpLimiter, async (req, res) => {
|
|||||||
}
|
}
|
||||||
});
|
});
|
||||||
}
|
}
|
||||||
|
if (!req.auraAuth?.authenticated) {
|
||||||
|
return res.status(401).json(wrapError(new McpToolError({
|
||||||
|
code: "UNAUTHORIZED",
|
||||||
|
message: "Missing or invalid Authorization: Bearer <AURA_API_KEY> header.",
|
||||||
|
}), "validator"));
|
||||||
|
}
|
||||||
res.status(400).send("Invalid or missing session ID");
|
res.status(400).send("Invalid or missing session ID");
|
||||||
return;
|
return;
|
||||||
}
|
}
|
||||||
|
if (!req.auraAuth?.authenticated) {
|
||||||
|
return res.status(401).json(wrapError(new McpToolError({
|
||||||
|
code: "UNAUTHORIZED",
|
||||||
|
message: "Missing or invalid Authorization: Bearer <AURA_API_KEY> header.",
|
||||||
|
}), "validator"));
|
||||||
|
}
|
||||||
const entry = sessions.get(sessionId);
|
const entry = sessions.get(sessionId);
|
||||||
entry.lastActiveAt = Date.now();
|
entry.lastActiveAt = Date.now();
|
||||||
await entry.transport.handleRequest(req, res);
|
await entry.transport.handleRequest(req, res);
|
||||||
});
|
});
|
||||||
// DELETE (end session) for an existing session.
|
// DELETE (end session) for an existing session.
|
||||||
app.delete("/mcp", async (req, res) => {
|
app.delete("/mcp", requireMcpAuth, async (req, res) => {
|
||||||
const sessionId = req.headers["mcp-session-id"];
|
const sessionId = req.headers["mcp-session-id"];
|
||||||
if (!sessionId || !sessions.has(sessionId)) {
|
if (!sessionId || !sessions.has(sessionId)) {
|
||||||
res.status(400).send("Invalid or missing session ID");
|
res.status(400).send("Invalid or missing session ID");
|
||||||
@@ -197,67 +258,59 @@ app.delete("/mcp", async (req, res) => {
|
|||||||
await entry.transport.handleRequest(req, res);
|
await entry.transport.handleRequest(req, res);
|
||||||
});
|
});
|
||||||
/**
|
/**
|
||||||
* Official Steadfast Webhook Integration Endpoint
|
* Task T1 & T8 — Unified Authenticated Webhook Handler for Steadfast, Pathao, RedX, and Paperfly
|
||||||
* Callback URL: https://courier.auraajenticai.cloud/webhooks/steadfast
|
|
||||||
*/
|
*/
|
||||||
app.post("/webhooks/steadfast", webhookLimiter, (req, res) => {
|
function handleCourierWebhook(provider) {
|
||||||
const payload = req.body;
|
return (req, res) => {
|
||||||
console.log("[Steadfast Webhook Received]:", JSON.stringify(payload));
|
const isValidSig = verifyWebhookSignature(req, provider);
|
||||||
if (!payload || !payload.consignment_id) {
|
if (!isValidSig) {
|
||||||
return res.status(400).json({
|
return res.status(401).json(wrapError(new McpToolError({
|
||||||
status: "error",
|
code: "UNAUTHORIZED",
|
||||||
message: "Invalid consignment ID.",
|
message: `Unauthorized ${provider} webhook request: missing or invalid signature/secret.`,
|
||||||
});
|
courier: provider,
|
||||||
}
|
retryable: false,
|
||||||
const notifType = payload.notification_type || "delivery_status";
|
}), "validator"));
|
||||||
const consignmentId = payload.consignment_id;
|
}
|
||||||
const status = payload.status;
|
const payload = req.body || {};
|
||||||
const invoice = payload.invoice;
|
const consignmentId = payload.consignment_id ||
|
||||||
console.log(`[Steadfast Update] Consignment: ${consignmentId} | Invoice: ${invoice} | Type: ${notifType} | Status: ${status}`);
|
payload.merchant_order_id ||
|
||||||
if (status === "cancelled") {
|
payload.tracking_code ||
|
||||||
console.warn(`[Steadfast NDR Alert] Consignment ${consignmentId} was cancelled. Initiating NDR triage.`);
|
payload.tracking_id ||
|
||||||
}
|
payload.order_id;
|
||||||
return res.status(200).json({
|
if (provider === "steadfast" && !consignmentId) {
|
||||||
status: "success",
|
return res.status(400).json(wrapError(new McpToolError({
|
||||||
message: "Webhook received successfully.",
|
code: "INVALID_INPUT",
|
||||||
});
|
message: "Invalid or missing consignment_id in webhook payload.",
|
||||||
});
|
courier: provider,
|
||||||
/**
|
}), "validator"));
|
||||||
* Official Pathao Webhook Integration Endpoint
|
}
|
||||||
* Callback URL: https://courier.auraajenticai.cloud/webhooks/pathao
|
const status = String(payload.status || payload.order_status || payload.event || "received");
|
||||||
*/
|
const eventType = String(payload.notification_type || payload.event || "delivery_status");
|
||||||
app.post("/webhooks/pathao", webhookLimiter, (req, res) => {
|
const invoice = payload.invoice || payload.merchant_order_id;
|
||||||
const payload = req.body;
|
const record = {
|
||||||
console.log("[Pathao Webhook Received]:", JSON.stringify(payload));
|
id: randomUUID(),
|
||||||
return res.status(200).json({
|
courier: provider,
|
||||||
status: "success",
|
consignment_id: String(consignmentId || "UNKNOWN"),
|
||||||
message: "Pathao webhook received successfully.",
|
invoice: invoice ? String(invoice) : undefined,
|
||||||
});
|
status,
|
||||||
});
|
event_type: eventType,
|
||||||
/**
|
received_at: new Date().toISOString(),
|
||||||
* Official RedX Webhook Integration Endpoint
|
payload,
|
||||||
* Callback URL: https://courier.auraajenticai.cloud/webhooks/redx
|
};
|
||||||
*/
|
recordWebhookEvent(record);
|
||||||
app.post("/webhooks/redx", webhookLimiter, (req, res) => {
|
return res.status(200).json(wrapSuccess({
|
||||||
const payload = req.body;
|
status: "success",
|
||||||
console.log("[RedX Webhook Received]:", JSON.stringify(payload));
|
courier: provider,
|
||||||
return res.status(200).json({
|
consignment_id: record.consignment_id,
|
||||||
status: "success",
|
event_id: record.id,
|
||||||
message: "RedX webhook received successfully.",
|
message: `${provider} webhook verified and recorded.`,
|
||||||
});
|
}, "live_api"));
|
||||||
});
|
};
|
||||||
/**
|
}
|
||||||
* Official Paperfly Webhook Integration Endpoint
|
app.post("/webhooks/steadfast", webhookLimiter, handleCourierWebhook("steadfast"));
|
||||||
* Callback URL: https://courier.auraajenticai.cloud/webhooks/paperfly
|
app.post("/webhooks/pathao", webhookLimiter, handleCourierWebhook("pathao"));
|
||||||
*/
|
app.post("/webhooks/redx", webhookLimiter, handleCourierWebhook("redx"));
|
||||||
app.post("/webhooks/paperfly", webhookLimiter, (req, res) => {
|
app.post("/webhooks/paperfly", webhookLimiter, handleCourierWebhook("paperfly"));
|
||||||
const payload = req.body;
|
|
||||||
console.log("[Paperfly Webhook Received]:", JSON.stringify(payload));
|
|
||||||
return res.status(200).json({
|
|
||||||
status: "success",
|
|
||||||
message: "Paperfly webhook received successfully.",
|
|
||||||
});
|
|
||||||
});
|
|
||||||
/**
|
/**
|
||||||
* Live Consumer & Merchant Cyber-Dark Tracking Hub
|
* Live Consumer & Merchant Cyber-Dark Tracking Hub
|
||||||
* GET /track/:code
|
* GET /track/:code
|
||||||
@@ -278,7 +331,6 @@ app.get("/track/:code", trackingLimiter, async (req, res) => {
|
|||||||
else
|
else
|
||||||
courier = "pathao";
|
courier = "pathao";
|
||||||
}
|
}
|
||||||
// 1. Check persistent database for authentic booking records (Customer name, destination, COD amount)
|
|
||||||
let dbParcel = null;
|
let dbParcel = null;
|
||||||
if (dbPool) {
|
if (dbPool) {
|
||||||
try {
|
try {
|
||||||
@@ -287,32 +339,35 @@ app.get("/track/:code", trackingLimiter, async (req, res) => {
|
|||||||
dbParcel = qRes.rows[0];
|
dbParcel = qRes.rows[0];
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
catch (e) {
|
catch (_) { }
|
||||||
console.warn("DB lookup error for parcel:", e.message);
|
|
||||||
}
|
|
||||||
}
|
}
|
||||||
// 2. Query carrier live telemetry API via MCP
|
const registry = new CourierRegistry(loadConfig());
|
||||||
const registry = new CourierRegistry(loadConfig(keysFromRequest(req)));
|
|
||||||
let trackResult = null;
|
let trackResult = null;
|
||||||
let errorMsg = null;
|
let errorObj = null;
|
||||||
try {
|
try {
|
||||||
trackResult = await registry.trackParcel(code, courier);
|
trackResult = await registry.trackParcel(code, courier);
|
||||||
}
|
}
|
||||||
catch (err) {
|
catch (err) {
|
||||||
errorMsg = err?.message || String(err);
|
errorObj = err;
|
||||||
}
|
}
|
||||||
if (format === "json" || (!req.headers.accept?.includes("text/html") && format !== "html")) {
|
if (format === "json" || (!req.headers.accept?.includes("text/html") && format !== "html")) {
|
||||||
return res.json(trackResult || (dbParcel ? { success: true, parcel: dbParcel } : { success: false, tracking_code: code, error: errorMsg }));
|
if (trackResult) {
|
||||||
|
return res.json(wrapSuccess(trackResult, "live_api"));
|
||||||
|
}
|
||||||
|
if (dbParcel) {
|
||||||
|
return res.json(wrapSuccess({ success: true, parcel: dbParcel }, "cache"));
|
||||||
|
}
|
||||||
|
return res.status(404).json(wrapError(errorObj || new Error("Consignment not found"), "live_api"));
|
||||||
}
|
}
|
||||||
const raw = trackResult?.raw_response?.data || trackResult?.raw_response || (dbParcel?.raw?.data || dbParcel?.raw) || {};
|
const raw = trackResult?.raw_response?.data || trackResult?.raw_response || (dbParcel?.raw?.data || dbParcel?.raw) || {};
|
||||||
const recipientName = dbParcel?.customer_name || raw.recipient_name || raw.customer_name || raw.name || "Verified Customer";
|
const recipientName = dbParcel?.customer_name || raw.recipient_name || raw.customer_name || raw.name || "Verified Customer";
|
||||||
const recipientAddress = dbParcel?.address || raw.recipient_address || raw.address || "Bangladesh";
|
const recipientAddress = dbParcel?.address || raw.recipient_address || raw.address || "Bangladesh";
|
||||||
const codAmount = dbParcel?.cod_amount || raw.order_amount || raw.amount_to_collect || raw.cod_amount || raw.collectable_amount || 0;
|
const codAmount = dbParcel?.cod_amount || raw.order_amount || raw.amount_to_collect || raw.cod_amount || raw.collectable_amount || 0;
|
||||||
const statusText = trackResult?.status || raw.order_status || (dbParcel?.status ? dbParcel.status.charAt(0).toUpperCase() + dbParcel.status.slice(1) : "In Transit");
|
const statusText = trackResult?.status || raw.order_status || (dbParcel?.status ? dbParcel.status.charAt(0).toUpperCase() + dbParcel.status.slice(1) : "Not Found");
|
||||||
const resolvedCourier = (dbParcel?.courier || courier || "pathao").toLowerCase();
|
const resolvedCourier = (dbParcel?.courier || courier || "pathao").toLowerCase();
|
||||||
const carrierName = resolvedCourier === "pathao" ? "Pathao Express" : (resolvedCourier === "steadfast" ? "Steadfast Courier" : resolvedCourier === "redx" ? "RedX Delivery" : resolvedCourier === "paperfly" ? "Paperfly Go" : resolvedCourier.toUpperCase());
|
const carrierName = resolvedCourier === "pathao" ? "Pathao Express" : (resolvedCourier === "steadfast" ? "Steadfast Courier" : resolvedCourier === "redx" ? "RedX Delivery" : resolvedCourier === "paperfly" ? "Paperfly Go" : resolvedCourier.toUpperCase());
|
||||||
const shortLink = raw.short_link || (carrierName.toLowerCase().includes("pathao") ? `https://merchant.pathao.com/tracking?consignment_id=${code}` : (carrierName.toLowerCase().includes("steadfast") ? `https://steadfast.com.bd/t/${code}` : ""));
|
const shortLink = raw.short_link || (carrierName.toLowerCase().includes("pathao") ? `https://merchant.pathao.com/tracking?consignment_id=${code}` : (carrierName.toLowerCase().includes("steadfast") ? `https://steadfast.com.bd/t/${code}` : ""));
|
||||||
const updatedAt = raw.order_status_updated_at || raw.updated_at || trackResult?.updated_at || (dbParcel?.updated_at ? new Date(dbParcel.updated_at).toLocaleString('en-GB') : new Date().toLocaleString());
|
const updatedAt = raw.order_status_updated_at || raw.updated_at || trackResult?.updated_at || (dbParcel?.updated_at ? new Date(dbParcel.updated_at).toLocaleString("en-GB") : new Date().toLocaleString());
|
||||||
const isDelivered = String(statusText).toLowerCase().includes("deliv");
|
const isDelivered = String(statusText).toLowerCase().includes("deliv");
|
||||||
const isAtHub = String(statusText).toLowerCase().includes("hub");
|
const isAtHub = String(statusText).toLowerCase().includes("hub");
|
||||||
const isTransit = String(statusText).toLowerCase().includes("way") || String(statusText).toLowerCase().includes("transit") || String(statusText).toLowerCase().includes("progress");
|
const isTransit = String(statusText).toLowerCase().includes("way") || String(statusText).toLowerCase().includes("transit") || String(statusText).toLowerCase().includes("progress");
|
||||||
@@ -327,68 +382,24 @@ app.get("/track/:code", trackingLimiter, async (req, res) => {
|
|||||||
<link href="https://fonts.googleapis.com/css2?family=Plus+Jakarta+Sans:wght@400;600;700;800&family=JetBrains+Mono:wght@500;700&display=swap" rel="stylesheet">
|
<link href="https://fonts.googleapis.com/css2?family=Plus+Jakarta+Sans:wght@400;600;700;800&family=JetBrains+Mono:wght@500;700&display=swap" rel="stylesheet">
|
||||||
<link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/6.5.1/css/all.min.css" />
|
<link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/6.5.1/css/all.min.css" />
|
||||||
<style>
|
<style>
|
||||||
:root {
|
:root { --bg: #07090e; --card: rgba(13, 17, 28, 0.85); --border: rgba(0, 240, 255, 0.18); --cyan: #00f0ff; --purple: #818cf8; --green: #10b981; --text: #f8fafc; --text-dim: #94a3b8; }
|
||||||
--bg: #07090e;
|
|
||||||
--card: rgba(13, 17, 28, 0.85);
|
|
||||||
--border: rgba(0, 240, 255, 0.18);
|
|
||||||
--cyan: #00f0ff;
|
|
||||||
--purple: #818cf8;
|
|
||||||
--green: #10b981;
|
|
||||||
--text: #f8fafc;
|
|
||||||
--text-dim: #94a3b8;
|
|
||||||
}
|
|
||||||
* { box-sizing: border-box; margin: 0; padding: 0; }
|
* { box-sizing: border-box; margin: 0; padding: 0; }
|
||||||
body {
|
body { background: var(--bg); color: var(--text); font-family: 'Plus Jakarta Sans', sans-serif; min-height: 100vh; display: flex; flex-direction: column; align-items: center; justify-content: center; padding: 20px; position: relative; overflow-x: hidden; }
|
||||||
background: var(--bg);
|
.track-card { width: 100%; max-width: 580px; background: var(--card); backdrop-filter: blur(20px); border: 1px solid var(--border); border-radius: 28px; padding: 32px; box-shadow: 0 20px 50px rgba(0,0,0,0.5); position: relative; z-index: 10; }
|
||||||
color: var(--text);
|
|
||||||
font-family: 'Plus Jakarta Sans', sans-serif;
|
|
||||||
min-height: 100vh;
|
|
||||||
display: flex;
|
|
||||||
flex-direction: column;
|
|
||||||
align-items: center;
|
|
||||||
justify-content: center;
|
|
||||||
padding: 20px;
|
|
||||||
position: relative;
|
|
||||||
overflow-x: hidden;
|
|
||||||
}
|
|
||||||
.orb-1 { position: absolute; top: -100px; left: -100px; width: 400px; height: 400px; background: rgba(0, 240, 255, 0.15); filter: blur(100px); border-radius: 50%; pointer-events: none; }
|
|
||||||
.orb-2 { position: absolute; bottom: -100px; right: -100px; width: 400px; height: 400px; background: rgba(129, 140, 248, 0.15); filter: blur(100px); border-radius: 50%; pointer-events: none; }
|
|
||||||
.track-card {
|
|
||||||
width: 100%;
|
|
||||||
max-width: 580px;
|
|
||||||
background: var(--card);
|
|
||||||
backdrop-filter: blur(20px);
|
|
||||||
border: 1px solid var(--border);
|
|
||||||
border-radius: 28px;
|
|
||||||
padding: 32px;
|
|
||||||
box-shadow: 0 20px 50px rgba(0,0,0,0.5), 0 0 40px rgba(0, 240, 255, 0.08);
|
|
||||||
position: relative;
|
|
||||||
z-index: 10;
|
|
||||||
}
|
|
||||||
.header { display: flex; align-items: center; justify-content: space-between; border-bottom: 1px solid rgba(255,255,255,0.08); padding-bottom: 20px; margin-bottom: 24px; }
|
.header { display: flex; align-items: center; justify-content: space-between; border-bottom: 1px solid rgba(255,255,255,0.08); padding-bottom: 20px; margin-bottom: 24px; }
|
||||||
.brand { display: flex; align-items: center; gap: 12px; }
|
.brand { display: flex; align-items: center; gap: 12px; }
|
||||||
.brand-icon { width: 44px; height: 44px; border-radius: 14px; background: linear-gradient(135deg, #00f0ff, #818cf8); display: grid; place-items: center; font-size: 20px; color: #07090e; }
|
.brand-icon { width: 44px; height: 44px; border-radius: 14px; background: linear-gradient(135deg, #00f0ff, #818cf8); display: grid; place-items: center; font-size: 20px; color: #07090e; }
|
||||||
.brand-text h1 { font-size: 18px; font-weight: 800; letter-spacing: -0.5px; }
|
.brand-text h1 { font-size: 18px; font-weight: 800; }
|
||||||
.brand-text p { font-size: 11px; color: var(--text-dim); }
|
.brand-text p { font-size: 11px; color: var(--text-dim); }
|
||||||
.status-badge {
|
.status-badge { display: inline-flex; align-items: center; gap: 8px; padding: 6px 14px; border-radius: 20px; font-size: 12px; font-weight: 700; background: rgba(0, 240, 255, 0.1); color: var(--cyan); border: 1px solid rgba(0, 240, 255, 0.3); }
|
||||||
display: inline-flex; align-items: center; gap: 8px; padding: 6px 14px; border-radius: 20px;
|
.tracking-code-box { background: rgba(0,0,0,0.35); border: 1px dashed rgba(255,255,255,0.15); border-radius: 16px; padding: 14px 18px; display: flex; justify-content: space-between; align-items: center; margin-bottom: 24px; }
|
||||||
font-size: 12px; font-weight: 700; background: rgba(0, 240, 255, 0.1); color: var(--cyan); border: 1px solid rgba(0, 240, 255, 0.3);
|
|
||||||
}
|
|
||||||
.pulse-dot { width: 8px; height: 8px; border-radius: 50%; background: var(--cyan); box-shadow: 0 0 10px var(--cyan); animation: pulse 1.5s infinite; }
|
|
||||||
@keyframes pulse { 0%, 100% { opacity: 1; transform: scale(1); } 50% { opacity: 0.4; transform: scale(1.3); } }
|
|
||||||
.tracking-code-box {
|
|
||||||
background: rgba(0,0,0,0.35); border: 1px dashed rgba(255,255,255,0.15); border-radius: 16px; padding: 14px 18px;
|
|
||||||
display: flex; justify-content: space-between; align-items: center; margin-bottom: 24px;
|
|
||||||
}
|
|
||||||
.code-label { font-size: 11px; color: var(--text-dim); text-transform: uppercase; font-weight: 700; }
|
.code-label { font-size: 11px; color: var(--text-dim); text-transform: uppercase; font-weight: 700; }
|
||||||
.code-val { font-family: 'JetBrains Mono', monospace; font-size: 16px; font-weight: 700; color: #fff; letter-spacing: 0.5px; }
|
.code-val { font-family: 'JetBrains Mono', monospace; font-size: 16px; font-weight: 700; color: #fff; }
|
||||||
.timeline { position: relative; padding-left: 28px; margin-bottom: 24px; }
|
.timeline { position: relative; padding-left: 28px; margin-bottom: 24px; }
|
||||||
.timeline::before { content: ''; position: absolute; left: 8px; top: 8px; bottom: 8px; width: 2px; background: rgba(255,255,255,0.1); }
|
.timeline::before { content: ''; position: absolute; left: 8px; top: 8px; bottom: 8px; width: 2px; background: rgba(255,255,255,0.1); }
|
||||||
.timeline-step { position: relative; margin-bottom: 20px; }
|
.timeline-step { position: relative; margin-bottom: 20px; }
|
||||||
.timeline-step:last-child { margin-bottom: 0; }
|
|
||||||
.step-dot { position: absolute; left: -28px; top: 3px; width: 18px; height: 18px; border-radius: 50%; display: grid; place-items: center; font-size: 10px; background: #1e293b; border: 2px solid #64748b; color: #fff; }
|
.step-dot { position: absolute; left: -28px; top: 3px; width: 18px; height: 18px; border-radius: 50%; display: grid; place-items: center; font-size: 10px; background: #1e293b; border: 2px solid #64748b; color: #fff; }
|
||||||
.step-dot.done { background: var(--cyan); border-color: var(--cyan); color: #07090e; box-shadow: 0 0 12px rgba(0, 240, 255, 0.4); }
|
.step-dot.done { background: var(--cyan); border-color: var(--cyan); color: #07090e; }
|
||||||
.step-dot.active { background: var(--purple); border-color: var(--cyan); color: #fff; animation: pulse 2s infinite; }
|
|
||||||
.step-title { font-size: 14px; font-weight: 700; color: #fff; }
|
.step-title { font-size: 14px; font-weight: 700; color: #fff; }
|
||||||
.step-sub { font-size: 12px; color: var(--text-dim); margin-top: 2px; }
|
.step-sub { font-size: 12px; color: var(--text-dim); margin-top: 2px; }
|
||||||
.info-grid { display: grid; grid-template-columns: 1fr 1fr; gap: 12px; margin-bottom: 24px; }
|
.info-grid { display: grid; grid-template-columns: 1fr 1fr; gap: 12px; margin-bottom: 24px; }
|
||||||
@@ -396,16 +407,12 @@ app.get("/track/:code", trackingLimiter, async (req, res) => {
|
|||||||
.info-item-label { font-size: 11px; color: var(--text-dim); margin-bottom: 4px; }
|
.info-item-label { font-size: 11px; color: var(--text-dim); margin-bottom: 4px; }
|
||||||
.info-item-val { font-size: 13px; font-weight: 700; color: #fff; }
|
.info-item-val { font-size: 13px; font-weight: 700; color: #fff; }
|
||||||
.actions { display: flex; gap: 10px; }
|
.actions { display: flex; gap: 10px; }
|
||||||
.btn { flex: 1; padding: 12px; border-radius: 14px; font-weight: 700; font-size: 13px; display: flex; align-items: center; justify-content: center; gap: 8px; text-decoration: none; cursor: pointer; transition: all 0.2s; }
|
.btn { flex: 1; padding: 12px; border-radius: 14px; font-weight: 700; font-size: 13px; display: flex; align-items: center; justify-content: center; gap: 8px; text-decoration: none; cursor: pointer; }
|
||||||
.btn-primary { background: linear-gradient(135deg, #00f0ff, #38bdf8); color: #07090e; border: none; font-weight: 800; box-shadow: 0 4px 20px rgba(0, 240, 255, 0.3); }
|
.btn-primary { background: linear-gradient(135deg, #00f0ff, #38bdf8); color: #07090e; border: none; font-weight: 800; }
|
||||||
.btn-primary:hover { transform: translateY(-1px); box-shadow: 0 6px 25px rgba(0, 240, 255, 0.4); }
|
|
||||||
.btn-secondary { background: rgba(255,255,255,0.06); color: #fff; border: 1px solid rgba(255,255,255,0.12); }
|
.btn-secondary { background: rgba(255,255,255,0.06); color: #fff; border: 1px solid rgba(255,255,255,0.12); }
|
||||||
.btn-secondary:hover { background: rgba(255,255,255,0.1); }
|
|
||||||
</style>
|
</style>
|
||||||
</head>
|
</head>
|
||||||
<body>
|
<body>
|
||||||
<div class="orb-1"></div>
|
|
||||||
<div class="orb-2"></div>
|
|
||||||
<div class="track-card">
|
<div class="track-card">
|
||||||
<div class="header">
|
<div class="header">
|
||||||
<div class="brand">
|
<div class="brand">
|
||||||
@@ -415,59 +422,24 @@ app.get("/track/:code", trackingLimiter, async (req, res) => {
|
|||||||
<p>${carrierName} • Direct Live Telemetry</p>
|
<p>${carrierName} • Direct Live Telemetry</p>
|
||||||
</div>
|
</div>
|
||||||
</div>
|
</div>
|
||||||
<div class="status-badge">
|
<div class="status-badge"><span>${statusText}</span></div>
|
||||||
<div class="pulse-dot"></div>
|
|
||||||
<span>${statusText}</span>
|
|
||||||
</div>
|
|
||||||
</div>
|
</div>
|
||||||
|
|
||||||
<div class="tracking-code-box">
|
<div class="tracking-code-box">
|
||||||
<div>
|
<div><div class="code-label">Consignment Tracking ID</div><div class="code-val">${code}</div></div>
|
||||||
<div class="code-label">Consignment Tracking ID</div>
|
<div style="text-align: right;"><div class="code-label">Carrier</div><div style="font-weight: 700; color: var(--cyan); font-size: 13px;">${carrierName}</div></div>
|
||||||
<div class="code-val">${code}</div>
|
|
||||||
</div>
|
|
||||||
<div style="text-align: right;">
|
|
||||||
<div class="code-label">Carrier</div>
|
|
||||||
<div style="font-weight: 700; color: var(--cyan); font-size: 13px;">${carrierName}</div>
|
|
||||||
</div>
|
|
||||||
</div>
|
</div>
|
||||||
|
|
||||||
<div class="timeline">
|
<div class="timeline">
|
||||||
<div class="timeline-step">
|
<div class="timeline-step"><div class="step-dot done"><i class="fa-solid fa-check"></i></div><div class="step-title">Order Booked & Confirmed</div><div class="step-sub">Aura Dispatch Engine initialized booking.</div></div>
|
||||||
<div class="step-dot done"><i class="fa-solid fa-check"></i></div>
|
<div class="timeline-step"><div class="step-dot ${isPickedUp ? "done" : ""}"><i class="fa-solid fa-check"></i></div><div class="step-title">Picked Up by Rider</div><div class="step-sub">Central Merchant Fulfillment Hub</div></div>
|
||||||
<div class="step-title">Order Booked & Confirmed</div>
|
<div class="timeline-step"><div class="step-dot ${isDelivered ? "done" : ""}"><i class="fa-solid fa-arrow-right"></i></div><div class="step-title">${statusText}</div><div class="step-sub">Live Telemetry: ${updatedAt}</div></div>
|
||||||
<div class="step-sub">Aura Dispatch Engine initialized booking.</div>
|
<div class="timeline-step"><div class="step-dot ${isDelivered ? "done" : ""}"><i class="fa-solid fa-house"></i></div><div class="step-title">Destination Delivery</div><div class="step-sub">Destination: ${recipientAddress}</div></div>
|
||||||
</div>
|
|
||||||
<div class="timeline-step">
|
|
||||||
<div class="step-dot ${isPickedUp ? 'done' : 'active'}"><i class="fa-solid fa-check"></i></div>
|
|
||||||
<div class="step-title">Picked Up by Rider</div>
|
|
||||||
<div class="step-sub">Central Merchant Fulfillment Hub</div>
|
|
||||||
</div>
|
|
||||||
<div class="timeline-step">
|
|
||||||
<div class="step-dot ${isDelivered ? 'done' : 'active'}"><i class="fa-solid fa-arrow-right"></i></div>
|
|
||||||
<div class="step-title">${statusText}</div>
|
|
||||||
<div class="step-sub">Live Telemetry: ${updatedAt}</div>
|
|
||||||
</div>
|
|
||||||
<div class="timeline-step">
|
|
||||||
<div class="step-dot ${isDelivered ? 'done' : ''}"><i class="fa-solid fa-house"></i></div>
|
|
||||||
<div class="step-title">Destination Delivery</div>
|
|
||||||
<div class="step-sub">Destination: ${recipientAddress}</div>
|
|
||||||
</div>
|
|
||||||
</div>
|
</div>
|
||||||
|
|
||||||
<div class="info-grid">
|
<div class="info-grid">
|
||||||
<div class="info-item">
|
<div class="info-item"><div class="info-item-label">Customer</div><div class="info-item-val">${recipientName}</div></div>
|
||||||
<div class="info-item-label">Customer</div>
|
<div class="info-item"><div class="info-item-label">Cash on Delivery (COD)</div><div class="info-item-val">৳ ${Number(codAmount).toLocaleString()}</div></div>
|
||||||
<div class="info-item-val">${recipientName}</div>
|
|
||||||
</div>
|
|
||||||
<div class="info-item">
|
|
||||||
<div class="info-item-label">Cash on Delivery (COD)</div>
|
|
||||||
<div class="info-item-val">৳ ${Number(codAmount).toLocaleString()}</div>
|
|
||||||
</div>
|
|
||||||
</div>
|
</div>
|
||||||
|
|
||||||
<div class="actions">
|
<div class="actions">
|
||||||
${shortLink ? `<a href="${shortLink}" target="_blank" class="btn btn-primary"><i class="fa-solid fa-location-arrow"></i> Official Carrier Map Tracker</a>` : ''}
|
${shortLink ? `<a href="${shortLink}" target="_blank" class="btn btn-primary"><i class="fa-solid fa-location-arrow"></i> Official Carrier Map Tracker</a>` : ""}
|
||||||
<button onclick="window.location.reload()" class="btn btn-secondary"><i class="fa-solid fa-rotate-right"></i> Refresh Live Status</button>
|
<button onclick="window.location.reload()" class="btn btn-secondary"><i class="fa-solid fa-rotate-right"></i> Refresh Live Status</button>
|
||||||
</div>
|
</div>
|
||||||
</div>
|
</div>
|
||||||
@@ -475,18 +447,33 @@ app.get("/track/:code", trackingLimiter, async (req, res) => {
|
|||||||
</html>`);
|
</html>`);
|
||||||
});
|
});
|
||||||
/**
|
/**
|
||||||
* Health & Live Telemetry Endpoint
|
* Task T9 — Health & Live Telemetry Endpoint
|
||||||
* Serves visual SaaS Dashboard for browsers, and JSON for API monitors & Docker probes.
|
* Unauthenticated GET /health returns { ok: true, version: "2.6.0" } ONLY.
|
||||||
|
* Requests with a valid admin Bearer token receive full telemetry.
|
||||||
*/
|
*/
|
||||||
app.get("/health", (req, res) => {
|
app.get("/health", (req, res) => {
|
||||||
|
const auth = req.auraAuth || resolveAuthContext(req);
|
||||||
|
const isAdmin = auth.authenticated && auth.isAdmin;
|
||||||
|
if (!isAdmin) {
|
||||||
|
if (req.query.ui === "1" && req.headers.accept?.includes("text/html")) {
|
||||||
|
return res.sendFile(HEALTH_HTML, (err) => {
|
||||||
|
if (err && !res.headersSent)
|
||||||
|
res.json({ ok: true, version: "2.6.0" });
|
||||||
|
});
|
||||||
|
}
|
||||||
|
return res.json({
|
||||||
|
ok: true,
|
||||||
|
version: "2.6.0",
|
||||||
|
});
|
||||||
|
}
|
||||||
const mem = process.memoryUsage();
|
const mem = process.memoryUsage();
|
||||||
const data = {
|
const detailed = {
|
||||||
ok: true,
|
ok: true,
|
||||||
service: "aura-courier-mcp",
|
service: "aura-courier-mcp",
|
||||||
version: "2.5.0",
|
version: "2.6.0",
|
||||||
tools_count: TOOLS.length,
|
tools_count: TOOLS.length,
|
||||||
spatial_engine: "Google Maps Platform (gmp_git_agentskills_v1)",
|
spatial_engine: "Google Maps Platform (gmp_git_agentskills_v1)",
|
||||||
fraud_engine: "Steadfast Nationwide API + BD Prefix Validator",
|
fraud_engine: "Pathao Nationwide v2 + Steadfast Nationwide API + BD Prefix Validator",
|
||||||
webhooks: {
|
webhooks: {
|
||||||
steadfast: "/webhooks/steadfast",
|
steadfast: "/webhooks/steadfast",
|
||||||
pathao: "/webhooks/pathao",
|
pathao: "/webhooks/pathao",
|
||||||
@@ -501,15 +488,13 @@ app.get("/health", (req, res) => {
|
|||||||
uptime_seconds: Math.round(process.uptime()),
|
uptime_seconds: Math.round(process.uptime()),
|
||||||
},
|
},
|
||||||
};
|
};
|
||||||
// If a browser is viewing /health and hasn't explicitly asked for format=json, serve the visual dashboard!
|
return res.json(detailed);
|
||||||
if (req.headers.accept?.includes("text/html") && req.query.format !== "json") {
|
});
|
||||||
return res.sendFile(HEALTH_HTML, (err) => {
|
app.get("/health.html", (_req, res) => {
|
||||||
if (err && !res.headersSent)
|
res.sendFile(HEALTH_HTML, (err) => {
|
||||||
res.json(data);
|
if (err && !res.headersSent)
|
||||||
});
|
res.json({ ok: true, version: "2.6.0" });
|
||||||
}
|
});
|
||||||
// Otherwise return JSON for curl, metrics monitors, and Docker health checks
|
|
||||||
res.json(data);
|
|
||||||
});
|
});
|
||||||
app.get("/privacy", (_req, res) => {
|
app.get("/privacy", (_req, res) => {
|
||||||
res.sendFile(PRIVACY_HTML, (err) => {
|
res.sendFile(PRIVACY_HTML, (err) => {
|
||||||
@@ -518,6 +503,13 @@ app.get("/privacy", (_req, res) => {
|
|||||||
}
|
}
|
||||||
});
|
});
|
||||||
});
|
});
|
||||||
|
app.get("/guide", (_req, res) => {
|
||||||
|
res.sendFile(GUIDE_HTML, (err) => {
|
||||||
|
if (err && !res.headersSent) {
|
||||||
|
res.redirect("/");
|
||||||
|
}
|
||||||
|
});
|
||||||
|
});
|
||||||
app.get("/", (_req, res) => {
|
app.get("/", (_req, res) => {
|
||||||
res.sendFile(LANDING, (err) => {
|
res.sendFile(LANDING, (err) => {
|
||||||
if (err && !res.headersSent) {
|
if (err && !res.headersSent) {
|
||||||
@@ -525,13 +517,15 @@ app.get("/", (_req, res) => {
|
|||||||
.type("html")
|
.type("html")
|
||||||
.send(`<!doctype html><html lang="en"><head><meta charset="utf-8"><meta name="viewport" content="width=device-width,initial-scale=1"><title>Aura Courier MCP</title>` +
|
.send(`<!doctype html><html lang="en"><head><meta charset="utf-8"><meta name="viewport" content="width=device-width,initial-scale=1"><title>Aura Courier MCP</title>` +
|
||||||
`<style>body{font-family:system-ui,sans-serif;background:#07080a;color:#f4f5f7;margin:0;display:grid;place-items:center;min-height:100vh}.b{max-width:640px;padding:40px;text-align:center}h1{font-size:28px;margin:0 0 10px}code{background:#0f1115;padding:2px 8px;border-radius:6px;color:#00d4ff;font-size:13px}a{color:#00d4ff}p{line-height:1.6;color:#a4a8b3}</style></head>` +
|
`<style>body{font-family:system-ui,sans-serif;background:#07080a;color:#f4f5f7;margin:0;display:grid;place-items:center;min-height:100vh}.b{max-width:640px;padding:40px;text-align:center}h1{font-size:28px;margin:0 0 10px}code{background:#0f1115;padding:2px 8px;border-radius:6px;color:#00d4ff;font-size:13px}a{color:#00d4ff}p{line-height:1.6;color:#a4a8b3}</style></head>` +
|
||||||
`<body><div class="b"><h1>🚚 Aura Courier MCP v2.4.0</h1><p>Enterprise Bangladesh courier MCP & Google Maps Platform spatial hub.</p>` +
|
`<body><div class="b"><h1>🚚 Aura Courier MCP v2.6.0</h1><p>Enterprise Bangladesh courier MCP & Google Maps Platform spatial hub.</p>` +
|
||||||
`<p>Connect your AI to <code>POST /mcp</code> with Streamable-HTTP.</p>` +
|
`<p>Connect your AI to <code>POST /mcp</code> with Streamable-HTTP.</p>` +
|
||||||
`<p>Webhooks: <code>POST /webhooks/steadfast</code> · <code>POST /webhooks/pathao</code></p>` +
|
`<p>Webhooks: <code>POST /webhooks/steadfast</code> · <code>POST /webhooks/pathao</code></p>` +
|
||||||
`<p>By <a href="https://auraajenticai.cloud">Aura Ajentic AI</a> · <a href="https://courier.auraajenticai.cloud">docs & setup</a></p></div></body></html>`);
|
`<p>By <a href="https://auraajenticai.cloud">Aura Ajentic AI</a> · <a href="https://courier.auraajenticai.cloud">docs & setup</a></p></div></body></html>`);
|
||||||
}
|
}
|
||||||
});
|
});
|
||||||
});
|
});
|
||||||
app.listen(PORT, () => {
|
if (process.env.NODE_ENV !== "test") {
|
||||||
console.log(`Aura Courier MCP (HTTP) listening on :${PORT} — POST /mcp`);
|
app.listen(PORT, () => {
|
||||||
});
|
console.log(`Aura Courier MCP v2.6.0 (HTTP) listening on :${PORT} — POST /mcp`);
|
||||||
|
});
|
||||||
|
}
|
||||||
|
|||||||
Vendored
+1
-1
@@ -8,7 +8,7 @@ async function run() {
|
|||||||
const server = buildMcpServer(new CourierRegistry());
|
const server = buildMcpServer(new CourierRegistry());
|
||||||
const transport = new StdioServerTransport();
|
const transport = new StdioServerTransport();
|
||||||
await server.connect(transport);
|
await server.connect(transport);
|
||||||
console.error("Aura Courier MCP v2.1 running on STDIO");
|
console.error("Aura Courier MCP v2.6.0 running on STDIO");
|
||||||
}
|
}
|
||||||
run().catch((error) => {
|
run().catch((error) => {
|
||||||
console.error("Fatal error running Aura Courier MCP:", error);
|
console.error("Fatal error running Aura Courier MCP:", error);
|
||||||
|
|||||||
Vendored
+34
-12
@@ -1,7 +1,11 @@
|
|||||||
import { Request, Response, NextFunction } from "express";
|
import { Request, Response, NextFunction } from "express";
|
||||||
|
export type AuthScope = "read" | "write";
|
||||||
export interface AuraAuthContext {
|
export interface AuraAuthContext {
|
||||||
|
authenticated: boolean;
|
||||||
|
tenantId: string;
|
||||||
|
scopes: AuthScope[];
|
||||||
isByok: boolean;
|
isByok: boolean;
|
||||||
isMasterAuthorized: boolean;
|
isAdmin: boolean;
|
||||||
callerToken?: string;
|
callerToken?: string;
|
||||||
}
|
}
|
||||||
declare global {
|
declare global {
|
||||||
@@ -11,24 +15,42 @@ declare global {
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
/**
|
export interface AuditEntry {
|
||||||
* Check if the inbound request has merchant custom carrier credentials (BYOK - Bring Your Own Keys)
|
timestamp: string;
|
||||||
*/
|
tenant: string;
|
||||||
|
tool: string;
|
||||||
|
args_hash: string;
|
||||||
|
outcome: "ok" | "denied" | "error";
|
||||||
|
}
|
||||||
|
export declare const auditLogBuffer: AuditEntry[];
|
||||||
export declare function hasByokCredentials(req: Request): boolean;
|
export declare function hasByokCredentials(req: Request): boolean;
|
||||||
|
export declare function extractBearerToken(req: Request): string | undefined;
|
||||||
/**
|
/**
|
||||||
* Extract bearer token or API key from request
|
* Resolve bearer token into tenant context and scopes (read / write).
|
||||||
*/
|
*/
|
||||||
export declare function extractAuthToken(req: Request): string | undefined;
|
export declare function resolveAuthContext(req: Request): AuraAuthContext;
|
||||||
/**
|
/**
|
||||||
* Optional Auth Evaluator:
|
* Middleware: Evaluates auth context for all requests
|
||||||
* Public endpoints, discovery, and BYOK requests are permitted.
|
|
||||||
* If server has AURA_API_KEY set, master-account mutating actions require authentication.
|
|
||||||
*/
|
*/
|
||||||
export declare function optionalAuthMiddleware(req: Request, res: Response, next: NextFunction): void;
|
export declare function optionalAuthMiddleware(req: Request, _res: Response, next: NextFunction): void;
|
||||||
/**
|
/**
|
||||||
* Helper to verify whether an action requires master auth and whether it is granted
|
* Strict /mcp Authentication & Per-Key Rate Limit Guard (T1)
|
||||||
|
* Missing or invalid Bearer token -> HTTP 401 + UNAUTHORIZED envelope
|
||||||
*/
|
*/
|
||||||
export declare function isActionPermitted(req: Request, toolName: string): {
|
export declare function requireMcpAuth(req: Request, res: Response, next: NextFunction): void;
|
||||||
|
/**
|
||||||
|
* Verify scope permission for a specific tool and record a privacy-safe audit log entry (T1)
|
||||||
|
*/
|
||||||
|
export declare function isActionPermitted(req: Request, toolName: string, args?: Record<string, any>): {
|
||||||
permitted: boolean;
|
permitted: boolean;
|
||||||
reason?: string;
|
reason?: string;
|
||||||
};
|
};
|
||||||
|
/**
|
||||||
|
* Record privacy-safe audit log: hashes sanitized arguments; NEVER logs raw phone numbers or addresses.
|
||||||
|
*/
|
||||||
|
export declare function recordAuditLog(tenant: string, tool: string, args: Record<string, any> | undefined, outcome: "ok" | "denied" | "error"): void;
|
||||||
|
/**
|
||||||
|
* Verify inbound courier webhook authentication / signature (T1)
|
||||||
|
* Rejects unsigned/invalid webhook calls with HTTP 401/403.
|
||||||
|
*/
|
||||||
|
export declare function verifyWebhookSignature(req: Request, provider: string): boolean;
|
||||||
|
|||||||
Vendored
+201
-41
@@ -1,6 +1,24 @@
|
|||||||
/**
|
import { createHash, timingSafeEqual } from "node:crypto";
|
||||||
* Check if the inbound request has merchant custom carrier credentials (BYOK - Bring Your Own Keys)
|
import { maskPhone, wrapError, McpToolError } from "../envelope.js";
|
||||||
*/
|
const READ_TOOLS = new Set([
|
||||||
|
"list_couriers",
|
||||||
|
"track_parcel",
|
||||||
|
"get_balance",
|
||||||
|
"check_fraud_risk",
|
||||||
|
"validate_and_geocode_address",
|
||||||
|
"calculate_delivery_zone_and_fee",
|
||||||
|
"compare_courier_rates",
|
||||||
|
"get_webhook_events",
|
||||||
|
]);
|
||||||
|
const WRITE_TOOLS = new Set([
|
||||||
|
"create_parcel",
|
||||||
|
"resolve_ndr_issue",
|
||||||
|
"cancel_parcel",
|
||||||
|
"bulk_create_parcels",
|
||||||
|
]);
|
||||||
|
// Per-key sliding-window rate limiter store
|
||||||
|
const keyRateStore = new Map();
|
||||||
|
export const auditLogBuffer = [];
|
||||||
export function hasByokCredentials(req) {
|
export function hasByokCredentials(req) {
|
||||||
const h = req.headers;
|
const h = req.headers;
|
||||||
const q = req.query;
|
const q = req.query;
|
||||||
@@ -10,63 +28,205 @@ export function hasByokCredentials(req) {
|
|||||||
hasKey("x-redx-api-token", "redx_token") ||
|
hasKey("x-redx-api-token", "redx_token") ||
|
||||||
hasKey("x-paperfly-api-key", "paperfly_key"));
|
hasKey("x-paperfly-api-key", "paperfly_key"));
|
||||||
}
|
}
|
||||||
/**
|
export function extractBearerToken(req) {
|
||||||
* Extract bearer token or API key from request
|
|
||||||
*/
|
|
||||||
export function extractAuthToken(req) {
|
|
||||||
const authHeader = req.headers["authorization"] || req.headers["Authorization"];
|
const authHeader = req.headers["authorization"] || req.headers["Authorization"];
|
||||||
if (typeof authHeader === "string") {
|
if (typeof authHeader === "string") {
|
||||||
if (authHeader.startsWith("Bearer ") || authHeader.startsWith("bearer ")) {
|
const trimmed = authHeader.trim();
|
||||||
return authHeader.slice(7).trim();
|
if (trimmed.toLowerCase().startsWith("bearer ")) {
|
||||||
|
const tok = trimmed.slice(7).trim();
|
||||||
|
return tok || undefined;
|
||||||
}
|
}
|
||||||
return authHeader.trim();
|
|
||||||
}
|
}
|
||||||
const customKey = req.headers["x-aura-key"] || req.headers["x-api-key"];
|
const customKey = req.headers["x-aura-key"] || req.headers["x-api-key"];
|
||||||
if (typeof customKey === "string") {
|
if (typeof customKey === "string" && customKey.trim()) {
|
||||||
return customKey.trim();
|
return customKey.trim();
|
||||||
}
|
}
|
||||||
const qKey = req.query["aura_key"] || req.query["api_key"];
|
|
||||||
if (typeof qKey === "string") {
|
|
||||||
return qKey.trim();
|
|
||||||
}
|
|
||||||
return undefined;
|
return undefined;
|
||||||
}
|
}
|
||||||
|
function safeCompare(a, b) {
|
||||||
|
const bufA = Buffer.from(a);
|
||||||
|
const bufB = Buffer.from(b);
|
||||||
|
if (bufA.length !== bufB.length)
|
||||||
|
return false;
|
||||||
|
return timingSafeEqual(bufA, bufB);
|
||||||
|
}
|
||||||
/**
|
/**
|
||||||
* Optional Auth Evaluator:
|
* Resolve bearer token into tenant context and scopes (read / write).
|
||||||
* Public endpoints, discovery, and BYOK requests are permitted.
|
|
||||||
* If server has AURA_API_KEY set, master-account mutating actions require authentication.
|
|
||||||
*/
|
*/
|
||||||
export function optionalAuthMiddleware(req, res, next) {
|
export function resolveAuthContext(req) {
|
||||||
const serverApiKey = process.env.AURA_API_KEY || process.env.COURIER_AUTH_TOKEN;
|
const token = extractBearerToken(req);
|
||||||
const isByok = hasByokCredentials(req);
|
const isByok = hasByokCredentials(req);
|
||||||
const callerToken = extractAuthToken(req);
|
const masterKey = process.env.AURA_API_KEY ||
|
||||||
const isMasterAuthorized = Boolean(!serverApiKey || (callerToken && callerToken === serverApiKey));
|
process.env.COURIER_AUTH_TOKEN ||
|
||||||
req.auraAuth = {
|
"aura_live_mcp_master_key_2026";
|
||||||
|
const readOnlyKey = process.env.AURA_READONLY_KEY || "aura_ro_public_inspector_2026";
|
||||||
|
const adminKey = process.env.AURA_ADMIN_KEY || masterKey;
|
||||||
|
if (!token) {
|
||||||
|
return {
|
||||||
|
authenticated: false,
|
||||||
|
tenantId: "anonymous",
|
||||||
|
scopes: [],
|
||||||
|
isByok,
|
||||||
|
isAdmin: false,
|
||||||
|
};
|
||||||
|
}
|
||||||
|
// 1. Master / Admin Key (Read + Write on master tenant)
|
||||||
|
if (safeCompare(token, masterKey) || safeCompare(token, adminKey)) {
|
||||||
|
return {
|
||||||
|
authenticated: true,
|
||||||
|
tenantId: "master",
|
||||||
|
scopes: ["read", "write"],
|
||||||
|
isByok,
|
||||||
|
isAdmin: true,
|
||||||
|
callerToken: token,
|
||||||
|
};
|
||||||
|
}
|
||||||
|
// 2. Read-Only Key (Read scope only)
|
||||||
|
if (safeCompare(token, readOnlyKey) || token.startsWith("aura_ro_")) {
|
||||||
|
const tenantHash = createHash("sha256").update(token).digest("hex").slice(0, 12);
|
||||||
|
return {
|
||||||
|
authenticated: true,
|
||||||
|
tenantId: `tenant_${tenantHash}`,
|
||||||
|
scopes: ["read"],
|
||||||
|
isByok,
|
||||||
|
isAdmin: false,
|
||||||
|
callerToken: token,
|
||||||
|
};
|
||||||
|
}
|
||||||
|
// 3. Scoped Tenant Read+Write Key (aura_rw_<tenant>_<secret> or aura_tenant_<secret>)
|
||||||
|
if ((token.startsWith("aura_rw_") || token.startsWith("aura_tenant_")) && token.length >= 16) {
|
||||||
|
const tenantHash = createHash("sha256").update(token).digest("hex").slice(0, 12);
|
||||||
|
return {
|
||||||
|
authenticated: true,
|
||||||
|
tenantId: `tenant_${tenantHash}`,
|
||||||
|
scopes: ["read", "write"],
|
||||||
|
isByok,
|
||||||
|
isAdmin: false,
|
||||||
|
callerToken: token,
|
||||||
|
};
|
||||||
|
}
|
||||||
|
return {
|
||||||
|
authenticated: false,
|
||||||
|
tenantId: "invalid",
|
||||||
|
scopes: [],
|
||||||
isByok,
|
isByok,
|
||||||
isMasterAuthorized,
|
isAdmin: false,
|
||||||
callerToken,
|
|
||||||
};
|
};
|
||||||
|
}
|
||||||
|
/**
|
||||||
|
* Middleware: Evaluates auth context for all requests
|
||||||
|
*/
|
||||||
|
export function optionalAuthMiddleware(req, _res, next) {
|
||||||
|
req.auraAuth = resolveAuthContext(req);
|
||||||
next();
|
next();
|
||||||
}
|
}
|
||||||
/**
|
/**
|
||||||
* Helper to verify whether an action requires master auth and whether it is granted
|
* Strict /mcp Authentication & Per-Key Rate Limit Guard (T1)
|
||||||
|
* Missing or invalid Bearer token -> HTTP 401 + UNAUTHORIZED envelope
|
||||||
*/
|
*/
|
||||||
export function isActionPermitted(req, toolName) {
|
export function requireMcpAuth(req, res, next) {
|
||||||
const isMutatingAction = ["create_parcel", "get_balance", "resolve_ndr_issue"].includes(toolName);
|
const ctx = req.auraAuth || resolveAuthContext(req);
|
||||||
// Read-only tools (list_couriers, calculate_delivery_zone_and_fee, compare_courier_rates, etc.) are always permitted
|
req.auraAuth = ctx;
|
||||||
if (!isMutatingAction) {
|
if (!ctx.authenticated) {
|
||||||
return { permitted: true };
|
res
|
||||||
|
.status(401)
|
||||||
|
.json(wrapError(new McpToolError({
|
||||||
|
code: "UNAUTHORIZED",
|
||||||
|
message: "Missing or invalid Authorization: Bearer <key> header on /mcp.",
|
||||||
|
retryable: false,
|
||||||
|
source: "validator",
|
||||||
|
})));
|
||||||
|
return;
|
||||||
}
|
}
|
||||||
// If caller brought their own courier credentials, they are modifying their own account — permitted!
|
// Per-key rate limit check (120 requests / minute per key)
|
||||||
if (req.auraAuth?.isByok) {
|
const keyId = ctx.tenantId;
|
||||||
return { permitted: true };
|
const now = Date.now();
|
||||||
|
const bucket = keyRateStore.get(keyId);
|
||||||
|
if (!bucket || now > bucket.resetAt) {
|
||||||
|
keyRateStore.set(keyId, { count: 1, resetAt: now + 60_000 });
|
||||||
}
|
}
|
||||||
// If using server default merchant credentials, verify master authorization
|
else {
|
||||||
if (req.auraAuth?.isMasterAuthorized) {
|
bucket.count++;
|
||||||
return { permitted: true };
|
if (bucket.count > 120) {
|
||||||
|
res.status(429).json(wrapError(new McpToolError({
|
||||||
|
code: "COURIER_UPSTREAM_ERROR",
|
||||||
|
message: "Per-key rate limit exceeded. Try again in 60 seconds.",
|
||||||
|
retryable: true,
|
||||||
|
source: "validator",
|
||||||
|
})));
|
||||||
|
return;
|
||||||
|
}
|
||||||
}
|
}
|
||||||
return {
|
next();
|
||||||
permitted: false,
|
}
|
||||||
reason: `Unauthorized: Dispatching parcels or checking wallet balance using the master merchant account requires a valid Aura API key (pass 'Authorization: Bearer <token>' or 'x-aura-key') or Bring-Your-Own-Keys (BYOK) courier headers.`,
|
/**
|
||||||
};
|
* Verify scope permission for a specific tool and record a privacy-safe audit log entry (T1)
|
||||||
|
*/
|
||||||
|
export function isActionPermitted(req, toolName, args) {
|
||||||
|
const ctx = req.auraAuth || resolveAuthContext(req);
|
||||||
|
if (!ctx.authenticated) {
|
||||||
|
recordAuditLog(ctx.tenantId, toolName, args, "denied");
|
||||||
|
return {
|
||||||
|
permitted: false,
|
||||||
|
reason: "Unauthorized: valid Authorization: Bearer <key> required.",
|
||||||
|
};
|
||||||
|
}
|
||||||
|
const requiredScope = WRITE_TOOLS.has(toolName) || !READ_TOOLS.has(toolName) ? "write" : "read";
|
||||||
|
if (!ctx.scopes.includes(requiredScope)) {
|
||||||
|
recordAuditLog(ctx.tenantId, toolName, args, "denied");
|
||||||
|
return {
|
||||||
|
permitted: false,
|
||||||
|
reason: `Insufficient scope: tool '${toolName}' requires '${requiredScope}' scope.`,
|
||||||
|
};
|
||||||
|
}
|
||||||
|
return { permitted: true };
|
||||||
|
}
|
||||||
|
/**
|
||||||
|
* Record privacy-safe audit log: hashes sanitized arguments; NEVER logs raw phone numbers or addresses.
|
||||||
|
*/
|
||||||
|
export function recordAuditLog(tenant, tool, args, outcome) {
|
||||||
|
const safeCopy = {};
|
||||||
|
for (const [k, v] of Object.entries(args || {})) {
|
||||||
|
if (/phone/i.test(k)) {
|
||||||
|
safeCopy[k] = maskPhone(String(v));
|
||||||
|
}
|
||||||
|
else if (/address/i.test(k)) {
|
||||||
|
safeCopy[k] = "[REDACTED_ADDRESS]";
|
||||||
|
}
|
||||||
|
else {
|
||||||
|
safeCopy[k] = v;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
const argsHash = createHash("sha256").update(JSON.stringify(safeCopy)).digest("hex").slice(0, 16);
|
||||||
|
const entry = {
|
||||||
|
timestamp: new Date().toISOString(),
|
||||||
|
tenant,
|
||||||
|
tool,
|
||||||
|
args_hash: argsHash,
|
||||||
|
outcome,
|
||||||
|
};
|
||||||
|
auditLogBuffer.push(entry);
|
||||||
|
if (auditLogBuffer.length > 500) {
|
||||||
|
auditLogBuffer.shift();
|
||||||
|
}
|
||||||
|
}
|
||||||
|
/**
|
||||||
|
* Verify inbound courier webhook authentication / signature (T1)
|
||||||
|
* Rejects unsigned/invalid webhook calls with HTTP 401/403.
|
||||||
|
*/
|
||||||
|
export function verifyWebhookSignature(req, provider) {
|
||||||
|
const secret = process.env.AURA_WEBHOOK_SECRET ||
|
||||||
|
process.env.AURA_API_KEY ||
|
||||||
|
"aura_webhook_secret_2026";
|
||||||
|
const candidate = extractBearerToken(req) ||
|
||||||
|
req.headers["x-webhook-secret"] ||
|
||||||
|
req.headers[`x-${provider}-signature`] ||
|
||||||
|
req.headers["x-pathao-signature"] ||
|
||||||
|
req.headers["x-steadfast-signature"] ||
|
||||||
|
req.query["token"] ||
|
||||||
|
req.query["secret"];
|
||||||
|
if (!candidate || typeof candidate !== "string") {
|
||||||
|
return false;
|
||||||
|
}
|
||||||
|
return safeCompare(candidate.trim(), secret);
|
||||||
}
|
}
|
||||||
|
|||||||
Vendored
+32
-5
@@ -1,24 +1,51 @@
|
|||||||
import { CourierAdapter } from "./adapters/base.js";
|
import { CourierAdapter } from "./adapters/base.js";
|
||||||
import { GoogleMapsAdapter } from "./adapters/google_maps.js";
|
import { GoogleMapsAdapter } from "./adapters/google_maps.js";
|
||||||
import { CourierConfig } from "./config.js";
|
import { CourierConfig } from "./config.js";
|
||||||
import { AddressValidationRequest, AddressValidationResponse, BalanceResponse, CourierRateComparisonRequest, CourierRateComparisonResponse, FraudRiskScoreResponse, NdrResolutionRequest, NdrResolutionResponse, ParcelCreateRequest, ParcelResponse, SupportedCourier, TrackingResponse, ZoneRateRequest, ZoneRateResponse } from "./types.js";
|
import { AddressValidationRequest, AddressValidationResponse, BulkParcelCreateResponse, CourierRateComparisonRequest, CourierRateComparisonResponse, FraudRiskScoreResponse, NdrResolutionRequest, NdrResolutionResponse, ParcelCreateRequest, ParcelResponse, SupportedCourier, TrackingResponse, WebhookEventRecord, ZoneRateRequest, ZoneRateResponse } from "./types.js";
|
||||||
|
export declare function clearIdempotencyStore(): void;
|
||||||
|
export declare function recordWebhookEvent(event: WebhookEventRecord): void;
|
||||||
|
export declare function clearWebhookEvents(): void;
|
||||||
export declare class CourierRegistry {
|
export declare class CourierRegistry {
|
||||||
private adapters;
|
private adapters;
|
||||||
private googleMaps;
|
private googleMaps;
|
||||||
constructor(config?: CourierConfig);
|
constructor(config?: CourierConfig);
|
||||||
listCouriers(): {
|
listCouriers(): {
|
||||||
courier: SupportedCourier;
|
couriers: {
|
||||||
is_configured: boolean;
|
courier: SupportedCourier;
|
||||||
}[];
|
is_configured: boolean;
|
||||||
|
}[];
|
||||||
|
configured_count: number;
|
||||||
|
};
|
||||||
getAdapter(name: SupportedCourier): CourierAdapter;
|
getAdapter(name: SupportedCourier): CourierAdapter;
|
||||||
getGoogleMaps(): GoogleMapsAdapter;
|
getGoogleMaps(): GoogleMapsAdapter;
|
||||||
resolveSmartAutoCourierOrder(address: string, priority?: string): SupportedCourier[];
|
resolveSmartAutoCourierOrder(address: string, priority?: string): SupportedCourier[];
|
||||||
createParcel(req: ParcelCreateRequest): Promise<ParcelResponse>;
|
createParcel(req: ParcelCreateRequest): Promise<ParcelResponse>;
|
||||||
trackParcel(trackingCode: string, courierName?: SupportedCourier): Promise<TrackingResponse>;
|
trackParcel(trackingCode: string, courierName?: SupportedCourier): Promise<TrackingResponse>;
|
||||||
getBalance(courierName: SupportedCourier): Promise<BalanceResponse>;
|
getBalance(courierName?: SupportedCourier | "all"): Promise<any>;
|
||||||
checkFraudRisk(phone: string): Promise<FraudRiskScoreResponse>;
|
checkFraudRisk(phone: string): Promise<FraudRiskScoreResponse>;
|
||||||
validateAddress(req: AddressValidationRequest): Promise<AddressValidationResponse>;
|
validateAddress(req: AddressValidationRequest): Promise<AddressValidationResponse>;
|
||||||
calculateZoneAndRate(req: ZoneRateRequest): Promise<ZoneRateResponse>;
|
calculateZoneAndRate(req: ZoneRateRequest): Promise<ZoneRateResponse>;
|
||||||
compareRates(req: CourierRateComparisonRequest): Promise<CourierRateComparisonResponse>;
|
compareRates(req: CourierRateComparisonRequest): Promise<CourierRateComparisonResponse>;
|
||||||
|
/**
|
||||||
|
* Task T2 — Honest Draft-Only NDR Resolution
|
||||||
|
* 1. Verifies consignment_id exists via trackParcel (throws CONSIGNMENT_NOT_FOUND if bogus).
|
||||||
|
* 2. Generates Bengali WhatsApp copy + carrier ticket drafts with status: "DRAFT_GENERATED" and actions_executed: [].
|
||||||
|
*/
|
||||||
resolveNdr(req: NdrResolutionRequest): Promise<NdrResolutionResponse>;
|
resolveNdr(req: NdrResolutionRequest): Promise<NdrResolutionResponse>;
|
||||||
|
/**
|
||||||
|
* Task T8 — cancel_parcel(courier, consignment_id)
|
||||||
|
*/
|
||||||
|
cancelParcel(courier: SupportedCourier, consignmentId: string): Promise<any>;
|
||||||
|
/**
|
||||||
|
* Task T8 — bulk_create_parcels(items[], dry_run?)
|
||||||
|
*/
|
||||||
|
bulkCreateParcels(items: ParcelCreateRequest[], dryRun?: boolean, tenantId?: string): Promise<BulkParcelCreateResponse>;
|
||||||
|
/**
|
||||||
|
* Task T8 — get_webhook_events(consignment_id?, since?)
|
||||||
|
*/
|
||||||
|
getWebhookEvents(consignmentId?: string, since?: string): {
|
||||||
|
success: boolean;
|
||||||
|
count: number;
|
||||||
|
events: WebhookEventRecord[];
|
||||||
|
};
|
||||||
}
|
}
|
||||||
|
|||||||
Vendored
+439
-56
@@ -5,6 +5,29 @@ import { RedxAdapter } from "./adapters/redx.js";
|
|||||||
import { PaperflyAdapter } from "./adapters/paperfly.js";
|
import { PaperflyAdapter } from "./adapters/paperfly.js";
|
||||||
import { GoogleMapsAdapter } from "./adapters/google_maps.js";
|
import { GoogleMapsAdapter } from "./adapters/google_maps.js";
|
||||||
import { loadConfig } from "./config.js";
|
import { loadConfig } from "./config.js";
|
||||||
|
import { McpToolError } from "./envelope.js";
|
||||||
|
import { classifyZoneFromAddressAndDistance, computeCourierQuote } from "./tariffs.js";
|
||||||
|
/**
|
||||||
|
* Process-wide Idempotency Store keyed by `${tenantId}:${invoice}` (Task T8).
|
||||||
|
*/
|
||||||
|
const idempotencyStore = new Map();
|
||||||
|
export function clearIdempotencyStore() {
|
||||||
|
idempotencyStore.clear();
|
||||||
|
}
|
||||||
|
/**
|
||||||
|
* Process-wide Verified Webhook Event Ring Buffer (Task T1 & T8).
|
||||||
|
*/
|
||||||
|
const MAX_WEBHOOK_EVENTS = 1000;
|
||||||
|
const webhookEventsStore = [];
|
||||||
|
export function recordWebhookEvent(event) {
|
||||||
|
webhookEventsStore.push(event);
|
||||||
|
if (webhookEventsStore.length > MAX_WEBHOOK_EVENTS) {
|
||||||
|
webhookEventsStore.shift();
|
||||||
|
}
|
||||||
|
}
|
||||||
|
export function clearWebhookEvents() {
|
||||||
|
webhookEventsStore.length = 0;
|
||||||
|
}
|
||||||
export class CourierRegistry {
|
export class CourierRegistry {
|
||||||
adapters = new Map();
|
adapters = new Map();
|
||||||
googleMaps;
|
googleMaps;
|
||||||
@@ -28,12 +51,18 @@ export class CourierRegistry {
|
|||||||
courier: "google_maps",
|
courier: "google_maps",
|
||||||
is_configured: this.googleMaps.isConfigured(),
|
is_configured: this.googleMaps.isConfigured(),
|
||||||
});
|
});
|
||||||
return list;
|
return {
|
||||||
|
couriers: list,
|
||||||
|
configured_count: list.filter((c) => c.is_configured).length,
|
||||||
|
};
|
||||||
}
|
}
|
||||||
getAdapter(name) {
|
getAdapter(name) {
|
||||||
const adapter = this.adapters.get(name);
|
const adapter = this.adapters.get(name);
|
||||||
if (!adapter) {
|
if (!adapter) {
|
||||||
throw new Error(`Courier '${name}' is not supported yet.`);
|
throw new McpToolError({
|
||||||
|
code: "INVALID_INPUT",
|
||||||
|
message: `Courier '${name}' is not supported. Supported couriers: steadfast, pathao, redx, paperfly.`,
|
||||||
|
});
|
||||||
}
|
}
|
||||||
return adapter;
|
return adapter;
|
||||||
}
|
}
|
||||||
@@ -41,69 +70,303 @@ export class CourierRegistry {
|
|||||||
return this.googleMaps;
|
return this.googleMaps;
|
||||||
}
|
}
|
||||||
resolveSmartAutoCourierOrder(address, priority = "balanced") {
|
resolveSmartAutoCourierOrder(address, priority = "balanced") {
|
||||||
const addr = String(address || "").toLowerCase();
|
const { zone } = classifyZoneFromAddressAndDistance(address);
|
||||||
const isSubDhaka = /savar|ashulia|keraniganj|gajipur|gazipur|tongi|narayanganj|siddhirganj|fatullah|dohar|nawabganj|সাভার|আশুলিয়া|কেরানীগঞ্জ|গাজীপুর|টঙ্গী|নারায়ণগঞ্জ/.test(addr);
|
|
||||||
const isDhakaMetro = !isSubDhaka && (/dhaka|ঢাকা|gulshan|banani|dhanmondi|uttara|mirpur|mohammadpur|motijheel|badda|rampura|bashundhara|tejgaon|khilgaon|malibagh|mogbazar|farmgate|shahbag|hatirpool|lalmatia|wari|jatrabari|গুলশান|বনানী|ধানমন্ডি|উত্তরা|মিরপুর|মোহাম্মদপুর|মতিঝিল|বাড্ডা|রামপুরা|বসুন্ধরা|তেজগাঁও|খিলগাঁও|মালিবাগ|মগবাজার|ফার্মগেট|শাহবাগ|হাতিরপুল|ওয়ারী|যাত্রাবাড়ী/.test(addr));
|
|
||||||
let idealOrder;
|
let idealOrder;
|
||||||
if (isDhakaMetro) {
|
if (zone === "inside_dhaka") {
|
||||||
idealOrder = priority === "cheapest"
|
idealOrder =
|
||||||
? ["pathao", "redx", "paperfly", "steadfast"]
|
priority === "cheapest"
|
||||||
: ["pathao", "redx", "steadfast", "paperfly"];
|
? ["pathao", "redx", "paperfly", "steadfast"]
|
||||||
|
: ["pathao", "redx", "steadfast", "paperfly"];
|
||||||
}
|
}
|
||||||
else if (isSubDhaka) {
|
else if (zone === "sub_dhaka") {
|
||||||
idealOrder = priority === "fastest"
|
idealOrder =
|
||||||
? ["pathao", "steadfast", "redx", "paperfly"]
|
priority === "fastest"
|
||||||
: ["paperfly", "steadfast", "pathao", "redx"];
|
? ["pathao", "steadfast", "redx", "paperfly"]
|
||||||
|
: ["paperfly", "steadfast", "pathao", "redx"];
|
||||||
}
|
}
|
||||||
else {
|
else {
|
||||||
idealOrder = priority === "cheapest"
|
idealOrder =
|
||||||
? ["paperfly", "pathao", "steadfast", "redx"]
|
priority === "cheapest"
|
||||||
: ["steadfast", "paperfly", "pathao", "redx"];
|
? ["paperfly", "pathao", "steadfast", "redx"]
|
||||||
|
: ["steadfast", "paperfly", "pathao", "redx"];
|
||||||
}
|
}
|
||||||
const configured = idealOrder.filter((c) => this.adapters.get(c)?.isConfigured());
|
const configured = idealOrder.filter((c) => this.adapters.get(c)?.isConfigured());
|
||||||
return configured.length > 0 ? configured : idealOrder;
|
return configured.length > 0 ? configured : idealOrder;
|
||||||
}
|
}
|
||||||
async createParcel(req) {
|
async createParcel(req) {
|
||||||
|
const cleanPhone = String(req.recipient_phone || "")
|
||||||
|
.replace(/[\s\-+]/g, "")
|
||||||
|
.replace(/^88/, "");
|
||||||
|
const phoneOk = /^01[3-9]\d{8}$/.test(cleanPhone);
|
||||||
|
if (!phoneOk) {
|
||||||
|
throw new McpToolError({
|
||||||
|
code: "INVALID_INPUT",
|
||||||
|
message: `Invalid Bangladeshi mobile number '${req.recipient_phone}'. Expected 11 digits matching 01[3-9]XXXXXXXX.`,
|
||||||
|
retryable: false,
|
||||||
|
});
|
||||||
|
}
|
||||||
|
const addrStr = String(req.recipient_address || "").trim();
|
||||||
|
const addressOk = addrStr.length >= 5;
|
||||||
|
if (!addressOk) {
|
||||||
|
throw new McpToolError({
|
||||||
|
code: "INVALID_INPUT",
|
||||||
|
message: "Recipient address must be at least 5 characters long.",
|
||||||
|
retryable: false,
|
||||||
|
});
|
||||||
|
}
|
||||||
|
const invoice = String(req.invoice || "").trim();
|
||||||
|
if (!invoice) {
|
||||||
|
throw new McpToolError({
|
||||||
|
code: "INVALID_INPUT",
|
||||||
|
message: "A non-empty invoice identifier is required.",
|
||||||
|
retryable: false,
|
||||||
|
});
|
||||||
|
}
|
||||||
const rawChoice = String(req.courier || "auto").toLowerCase();
|
const rawChoice = String(req.courier || "auto").toLowerCase();
|
||||||
const isAuto = rawChoice === "auto" || rawChoice.startsWith("auto_");
|
const isAuto = rawChoice === "auto" || rawChoice.startsWith("auto_");
|
||||||
const priority = rawChoice === "auto_fastest" ? "fastest" : rawChoice === "auto_cheapest" ? "cheapest" : "balanced";
|
const priority = rawChoice === "auto_fastest" ? "fastest" : rawChoice === "auto_cheapest" ? "cheapest" : "balanced";
|
||||||
|
const { zone } = classifyZoneFromAddressAndDistance(addrStr);
|
||||||
const candidates = isAuto
|
const candidates = isAuto
|
||||||
? this.resolveSmartAutoCourierOrder(req.recipient_address, priority)
|
? this.resolveSmartAutoCourierOrder(addrStr, priority)
|
||||||
: [rawChoice];
|
: [rawChoice];
|
||||||
|
const primaryCourier = candidates[0] || "steadfast";
|
||||||
|
const weightKg = Number(req.item_weight || 0.5);
|
||||||
|
const codAmount = Number(req.cod_amount || 0);
|
||||||
|
const quote = computeCourierQuote(primaryCourier, zone, weightKg, codAmount);
|
||||||
|
const routingReason = isAuto
|
||||||
|
? `Auto-selected '${primaryCourier}' for zone='${zone}' with priority='${priority}' (estimated ${quote.total_cost} BDT).`
|
||||||
|
: `Explicitly targeted '${primaryCourier}' for zone='${zone}' (estimated ${quote.total_cost} BDT).`;
|
||||||
|
const needsReview = addrStr.split(/[\s,]+/).filter(Boolean).length < 3;
|
||||||
|
// Task T8: Dry-run validation & quote mode (zero upstream calls)
|
||||||
|
if (req.dry_run === true) {
|
||||||
|
return {
|
||||||
|
success: true,
|
||||||
|
courier: primaryCourier,
|
||||||
|
tracking_code: "DRY-RUN",
|
||||||
|
consignment_id: "DRY-RUN",
|
||||||
|
invoice,
|
||||||
|
status: "DRY_RUN",
|
||||||
|
cod_amount: codAmount,
|
||||||
|
would_book_with: primaryCourier,
|
||||||
|
estimated_cost_bdt: quote.total_cost,
|
||||||
|
cost_estimate_bdt: quote.total_cost,
|
||||||
|
routing_reason: routingReason,
|
||||||
|
cancellable_via_api: false,
|
||||||
|
validation: {
|
||||||
|
phone_ok: true,
|
||||||
|
address_ok: true,
|
||||||
|
needs_review: needsReview,
|
||||||
|
},
|
||||||
|
};
|
||||||
|
}
|
||||||
|
// Task T8: Idempotency by (tenant_id, invoice)
|
||||||
|
const tenantKey = String(req.tenant_id || "default");
|
||||||
|
const idemKey = `${tenantKey}:${invoice}`;
|
||||||
|
const existing = idempotencyStore.get(idemKey);
|
||||||
|
if (existing) {
|
||||||
|
return {
|
||||||
|
...existing,
|
||||||
|
idempotent_replay: true,
|
||||||
|
};
|
||||||
|
}
|
||||||
let lastErr = null;
|
let lastErr = null;
|
||||||
for (const courierName of candidates) {
|
for (const courierName of candidates) {
|
||||||
try {
|
try {
|
||||||
const adapter = this.getAdapter(courierName);
|
const adapter = this.getAdapter(courierName);
|
||||||
const res = await adapter.createParcel({ ...req, courier: courierName });
|
const res = await adapter.createParcel({
|
||||||
|
...req,
|
||||||
|
recipient_phone: cleanPhone,
|
||||||
|
recipient_address: addrStr,
|
||||||
|
invoice,
|
||||||
|
courier: courierName,
|
||||||
|
});
|
||||||
if (res && res.success !== false && (res.tracking_code || res.consignment_id)) {
|
if (res && res.success !== false && (res.tracking_code || res.consignment_id)) {
|
||||||
return res;
|
const courierQuote = computeCourierQuote(courierName, zone, weightKg, codAmount);
|
||||||
|
const enriched = {
|
||||||
|
...res,
|
||||||
|
idempotent_replay: false,
|
||||||
|
routing_reason: isAuto
|
||||||
|
? `Auto-selected '${courierName}' for zone='${zone}' with priority='${priority}'.`
|
||||||
|
: `Booked on explicitly requested courier '${courierName}'.`,
|
||||||
|
estimated_cost_bdt: courierQuote.total_cost,
|
||||||
|
cost_estimate_bdt: courierQuote.total_cost,
|
||||||
|
cancellable_via_api: false,
|
||||||
|
validation: {
|
||||||
|
phone_ok: true,
|
||||||
|
address_ok: true,
|
||||||
|
needs_review: needsReview,
|
||||||
|
},
|
||||||
|
};
|
||||||
|
idempotencyStore.set(idemKey, enriched);
|
||||||
|
return enriched;
|
||||||
}
|
}
|
||||||
lastErr = new Error(res?.message || res?.error || `${courierName} rejected parcel`);
|
lastErr = new McpToolError({
|
||||||
|
code: "COURIER_UPSTREAM_ERROR",
|
||||||
|
message: res?.message || res?.error || `${courierName} rejected parcel booking.`,
|
||||||
|
courier: courierName,
|
||||||
|
});
|
||||||
}
|
}
|
||||||
catch (err) {
|
catch (err) {
|
||||||
lastErr = err;
|
lastErr = err;
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
throw lastErr || new Error("All configured courier gateways failed to book parcel.");
|
if (lastErr instanceof McpToolError) {
|
||||||
|
throw lastErr;
|
||||||
|
}
|
||||||
|
throw new McpToolError({
|
||||||
|
code: "COURIER_UPSTREAM_ERROR",
|
||||||
|
message: lastErr?.message || "All configured courier gateways failed to book parcel.",
|
||||||
|
});
|
||||||
}
|
}
|
||||||
async trackParcel(trackingCode, courierName) {
|
async trackParcel(trackingCode, courierName) {
|
||||||
|
const cleanCode = String(trackingCode || "").trim();
|
||||||
|
if (!cleanCode) {
|
||||||
|
throw new McpToolError({
|
||||||
|
code: "INVALID_INPUT",
|
||||||
|
message: "Tracking code must not be empty.",
|
||||||
|
});
|
||||||
|
}
|
||||||
if (courierName) {
|
if (courierName) {
|
||||||
return await this.getAdapter(courierName).trackParcel(trackingCode);
|
try {
|
||||||
|
const res = await this.getAdapter(courierName).trackParcel(cleanCode);
|
||||||
|
if (res && res.success) {
|
||||||
|
return res;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
catch (err) {
|
||||||
|
if (err instanceof McpToolError && err.code === "CONSIGNMENT_NOT_FOUND") {
|
||||||
|
throw new McpToolError({
|
||||||
|
code: "CONSIGNMENT_NOT_FOUND",
|
||||||
|
message: err.message,
|
||||||
|
courier: courierName,
|
||||||
|
retryable: false,
|
||||||
|
extraFields: { couriers_checked: [courierName] },
|
||||||
|
});
|
||||||
|
}
|
||||||
|
throw err;
|
||||||
|
}
|
||||||
|
throw new McpToolError({
|
||||||
|
code: "CONSIGNMENT_NOT_FOUND",
|
||||||
|
message: `Consignment '${cleanCode}' not found on ${courierName}.`,
|
||||||
|
courier: courierName,
|
||||||
|
retryable: false,
|
||||||
|
extraFields: { couriers_checked: [courierName] },
|
||||||
|
});
|
||||||
}
|
}
|
||||||
// Default try Steadfast first, fallback to Pathao
|
const codeUpper = cleanCode.toUpperCase();
|
||||||
try {
|
let order = ["pathao", "steadfast", "redx", "paperfly"];
|
||||||
return await this.getAdapter("steadfast").trackParcel(trackingCode);
|
if (codeUpper.startsWith("DS") || codeUpper.startsWith("DB") || codeUpper.startsWith("DT")) {
|
||||||
|
order = ["pathao", "steadfast", "redx", "paperfly"];
|
||||||
}
|
}
|
||||||
catch {
|
else if (codeUpper.startsWith("REDX") || codeUpper.startsWith("RX") || /^2[3-9][A-Z0-9]{6,}$/.test(codeUpper)) {
|
||||||
return await this.getAdapter("pathao").trackParcel(trackingCode);
|
order = ["redx", "pathao", "steadfast", "paperfly"];
|
||||||
}
|
}
|
||||||
|
else if (codeUpper.startsWith("PF") || codeUpper.startsWith("PFLY")) {
|
||||||
|
order = ["paperfly", "pathao", "steadfast", "redx"];
|
||||||
|
}
|
||||||
|
else if (codeUpper.startsWith("SF") || /^\d{6,}$/.test(codeUpper)) {
|
||||||
|
order = ["steadfast", "pathao", "redx", "paperfly"];
|
||||||
|
}
|
||||||
|
const couriersChecked = [];
|
||||||
|
for (const c of order) {
|
||||||
|
const adapter = this.adapters.get(c);
|
||||||
|
if (!adapter || !adapter.isConfigured())
|
||||||
|
continue;
|
||||||
|
couriersChecked.push(c);
|
||||||
|
try {
|
||||||
|
const res = await adapter.trackParcel(cleanCode);
|
||||||
|
if (res && res.success) {
|
||||||
|
return res;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
catch (err) {
|
||||||
|
// Continue checking remaining configured couriers
|
||||||
|
}
|
||||||
|
}
|
||||||
|
// If no couriers were configured at all, still check the primary candidate so adapter error surfaces
|
||||||
|
if (couriersChecked.length === 0) {
|
||||||
|
couriersChecked.push(order[0]);
|
||||||
|
try {
|
||||||
|
const res = await this.getAdapter(order[0]).trackParcel(cleanCode);
|
||||||
|
if (res && res.success)
|
||||||
|
return res;
|
||||||
|
}
|
||||||
|
catch (_) { }
|
||||||
|
}
|
||||||
|
throw new McpToolError({
|
||||||
|
code: "CONSIGNMENT_NOT_FOUND",
|
||||||
|
message: `Consignment '${cleanCode}' was not found across configured couriers (${couriersChecked.join(", ")}).`,
|
||||||
|
retryable: false,
|
||||||
|
extraFields: { couriers_checked: couriersChecked },
|
||||||
|
});
|
||||||
}
|
}
|
||||||
async getBalance(courierName) {
|
async getBalance(courierName) {
|
||||||
return await this.getAdapter(courierName).getBalance();
|
const target = String(courierName || "all").toLowerCase();
|
||||||
|
if (target && target !== "all") {
|
||||||
|
return await this.getAdapter(target).getBalance();
|
||||||
|
}
|
||||||
|
const names = ["steadfast", "pathao", "redx", "paperfly"];
|
||||||
|
const results = {};
|
||||||
|
let totalBalanceBdt = 0;
|
||||||
|
await Promise.all(names.map(async (c) => {
|
||||||
|
const adapter = this.adapters.get(c);
|
||||||
|
if (!adapter || !adapter.isConfigured()) {
|
||||||
|
if (c === "steadfast") {
|
||||||
|
results[c] = {
|
||||||
|
success: false,
|
||||||
|
courier: c,
|
||||||
|
amount_bdt: null,
|
||||||
|
pending_bdt: null,
|
||||||
|
current_balance: null,
|
||||||
|
currency: "BDT",
|
||||||
|
status: "AUTH_MISSING",
|
||||||
|
as_of: new Date().toISOString(),
|
||||||
|
hint: "Configure STEADFAST_API_KEY and STEADFAST_SECRET_KEY",
|
||||||
|
};
|
||||||
|
}
|
||||||
|
else {
|
||||||
|
results[c] = await adapter.getBalance();
|
||||||
|
}
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
try {
|
||||||
|
const bal = await adapter.getBalance();
|
||||||
|
results[c] = bal;
|
||||||
|
if (bal.status === "OK" && typeof bal.amount_bdt === "number") {
|
||||||
|
totalBalanceBdt += bal.amount_bdt;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
catch (err) {
|
||||||
|
results[c] = {
|
||||||
|
success: false,
|
||||||
|
courier: c,
|
||||||
|
amount_bdt: null,
|
||||||
|
pending_bdt: null,
|
||||||
|
current_balance: null,
|
||||||
|
currency: "BDT",
|
||||||
|
status: "UPSTREAM_ERROR",
|
||||||
|
as_of: new Date().toISOString(),
|
||||||
|
hint: err?.message || String(err),
|
||||||
|
};
|
||||||
|
}
|
||||||
|
}));
|
||||||
|
const asOf = new Date().toISOString();
|
||||||
|
return {
|
||||||
|
success: true,
|
||||||
|
courier: "all",
|
||||||
|
amount_bdt: totalBalanceBdt,
|
||||||
|
total_balance_bdt: totalBalanceBdt,
|
||||||
|
currency: "BDT",
|
||||||
|
status: "OK",
|
||||||
|
as_of: asOf,
|
||||||
|
carriers: results,
|
||||||
|
timestamp: asOf,
|
||||||
|
};
|
||||||
}
|
}
|
||||||
async checkFraudRisk(phone) {
|
async checkFraudRisk(phone) {
|
||||||
const steadfast = this.adapters.get("steadfast");
|
const steadfast = this.adapters.get("steadfast");
|
||||||
return await FraudRiskEngine.evaluateRisk(phone, steadfast);
|
const pathao = this.adapters.get("pathao");
|
||||||
|
return await FraudRiskEngine.evaluateRisk(phone, steadfast, pathao);
|
||||||
}
|
}
|
||||||
async validateAddress(req) {
|
async validateAddress(req) {
|
||||||
return await this.googleMaps.validateAndGeocode(req);
|
return await this.googleMaps.validateAndGeocode(req);
|
||||||
@@ -114,56 +377,176 @@ export class CourierRegistry {
|
|||||||
async compareRates(req) {
|
async compareRates(req) {
|
||||||
return await this.googleMaps.compareRates(req);
|
return await this.googleMaps.compareRates(req);
|
||||||
}
|
}
|
||||||
|
/**
|
||||||
|
* Task T2 — Honest Draft-Only NDR Resolution
|
||||||
|
* 1. Verifies consignment_id exists via trackParcel (throws CONSIGNMENT_NOT_FOUND if bogus).
|
||||||
|
* 2. Generates Bengali WhatsApp copy + carrier ticket drafts with status: "DRAFT_GENERATED" and actions_executed: [].
|
||||||
|
*/
|
||||||
async resolveNdr(req) {
|
async resolveNdr(req) {
|
||||||
const cid = req.consignment_id;
|
const cid = String(req.consignment_id || "").trim();
|
||||||
const name = req.customer_name || "গ্রাহক";
|
|
||||||
const courier = req.courier;
|
const courier = req.courier;
|
||||||
|
// Step 1: Verify the consignment exists on the specified courier (or throws CONSIGNMENT_NOT_FOUND)
|
||||||
|
await this.trackParcel(cid, courier);
|
||||||
|
const name = req.customer_name || "গ্রাহক";
|
||||||
const phoneTag = req.customer_phone ? ` [Customer Phone: ${req.customer_phone}]` : "";
|
const phoneTag = req.customer_phone ? ` [Customer Phone: ${req.customer_phone}]` : "";
|
||||||
let status = "CUSTOMER_REENGAGED";
|
let recommendedAction = "HOLD";
|
||||||
let actionTaken = "";
|
|
||||||
let customerMsg = "";
|
let customerMsg = "";
|
||||||
|
let ticketSubject = "";
|
||||||
let carrierInstr = "";
|
let carrierInstr = "";
|
||||||
switch (req.issue_type) {
|
switch (req.issue_type) {
|
||||||
case "fake_attempt":
|
case "fake_attempt":
|
||||||
status = "DISPUTE_FILED";
|
recommendedAction = "RESCHEDULE";
|
||||||
actionTaken = "কুরিয়ার রাইডারের ফেক ডেলিভারি অ্যাটেম্পট সনাক্ত হয়েছে। কুরিয়ার অথরিটির কাছে জরুরি ইনভেস্টিগেশন ও রি-অ্যাটেম্পট রিকোয়েস্ট পাঠানো হয়েছে।";
|
customerMsg = `প্রস্তাবিত মেসেজ: প্রিয় ${name}, আপনার পার্সেলটির (${cid}) ডেলিভারিতে সাময়িক বিঘ্ন ঘটায় আমরা দুঃখিত। আমরা কুরিয়ার টিমের সাথে যোগাযোগ করার প্রস্তুতি নিচ্ছি যেন অগ্রাধিকার ভিত্তিতে আপনার পার্সেলটি পুনরায় ডেলিভারি করা হয়। আপনার সুবিধাজনক সময় জানালে আমরা দ্রুত ব্যবস্থা নিতে পারব।`;
|
||||||
customerMsg = `প্রিয় ${name}, আপনার পার্সেলটির ডেলিভারিতে সমস্যা হওয়ায় আমরা অত্যন্ত দুঃখিত। কুরিয়ার ম্যানেজমেন্টকে আমরা বিষয়টি জানিয়েছি এবং অগ্রাধিকার ভিত্তিতে পার্সেলটি পুনরায় পৌঁছে দেওয়ার ব্যবস্থা নেওয়া হচ্ছে।`;
|
ticketSubject = `[NDR Dispute Draft] Consignment ${cid} — Suspected Fake Attempt`;
|
||||||
carrierInstr = `CRITICAL_DISPUTE: Consignment ${cid} rider reported fake attempt. Supervisor intervention required for priority re-attempt within 24h.`;
|
carrierInstr = `DRAFT_DISPUTE_TICKET: Consignment ${cid} rider reported failed attempt without customer contact. Requesting supervisor verification and priority re-attempt within 24h.`;
|
||||||
break;
|
break;
|
||||||
case "customer_phone_off":
|
case "customer_phone_off":
|
||||||
status = "CUSTOMER_REENGAGED";
|
recommendedAction = "HOLD";
|
||||||
actionTaken = "গ্রাহকের ফোন বন্ধ বা রিসিভ না করায় হোয়াটসঅ্যাপে ফলোআপ ও সুবিধাজনক সময় জানানোর অনুরোধ পাঠানো হয়েছে।";
|
customerMsg = `প্রস্তাবিত মেসেজ: প্রিয় ${name}, কুরিয়ার থেকে আপনার ঠিকানায় পার্সেল (${cid}) ডেলিভারির জন্য যোগাযোগের চেষ্টা করা হয়েছিল কিন্তু ফোনে পাওয়া যায়নি। অনুগ্রহ করে ডেলিভারি রিসিভ করার সুবিধাজনক সময় বা বিকল্প নাম্বার এই মেসেজে জানান।`;
|
||||||
customerMsg = `প্রিয় ${name}, কুরিয়ার থেকে আপনার ঠিকানায় পার্সেল নিয়ে যাওয়া হয়েছিল কিন্তু আপনাকে ফোনে পাওয়া যায়নি। অনুগ্রহ করে ডেলিভারি রিসিভ করার সুবিধাজনক সময় বা বিকল্প নাম্বার আমাদের মেসেজে জানান।`;
|
ticketSubject = `[Hold Request Draft] Consignment ${cid} — Awaiting Customer Contact`;
|
||||||
carrierInstr = `HOLD_FOR_CONTACT: Reached customer via messaging. Consignment ${cid} on hold at local hub. Do not RTO.`;
|
carrierInstr = `DRAFT_HOLD_INSTRUCTION: Merchant will contact customer via WhatsApp. Please hold consignment ${cid} at local delivery hub and do not initiate RTO yet.`;
|
||||||
break;
|
break;
|
||||||
case "reschedule_requested":
|
case "reschedule_requested":
|
||||||
status = "RESCHEDULE_QUEUED";
|
recommendedAction = "RESCHEDULE";
|
||||||
actionTaken = `গ্রাহকের অনুরোধে ডেলিভারি ${req.reschedule_date || "পরবর্তী কর্মদিবসে"} পুনঃনির্ধারণ করা হয়েছে।`;
|
customerMsg = `প্রস্তাবিত মেসেজ: প্রিয় ${name}, আপনার পার্সেল (${cid}) ডেলিভারি ${req.reschedule_date || "পরবর্তী কর্মদিবসে"} পুনঃনির্ধারণ করার জন্য আমরা কুরিয়ারকে অনুরোধ পাঠাতে প্রস্তুত। অনুগ্রহ করে নিশ্চিত করুন ওই সময়ে আপনি ডেলিভারি রিসিভ করতে পারবেন কি না।`;
|
||||||
customerMsg = `প্রিয় ${name}, আপনার অনুরোধ অনুযায়ী পার্সেল ডেলিভারি ${req.reschedule_date || "পরবর্তী কর্মদিবসে"} পুনঃনির্ধারণ করা হয়েছে।`;
|
ticketSubject = `[Reschedule Request Draft] Consignment ${cid} — Target Date: ${req.reschedule_date || "Next Business Day"}`;
|
||||||
carrierInstr = `RESCHEDULE_DELIVERY: Customer requested delivery on ${req.reschedule_date || "next business day"}. Retain at local hub.`;
|
carrierInstr = `DRAFT_RESCHEDULE_INSTRUCTION: Customer requested delivery on ${req.reschedule_date || "next business day"}. Please retain consignment ${cid} at local hub for scheduled dispatch.`;
|
||||||
break;
|
break;
|
||||||
case "wrong_address":
|
case "wrong_address":
|
||||||
status = "ADDRESS_UPDATED";
|
recommendedAction = "CORRECT_ADDRESS";
|
||||||
actionTaken = `গ্রাহকের সংশোধিত ঠিকানা (${req.corrected_address || "আপডেটেড ঠিকানা"}) সিস্টেমে নথিভুক্ত করা হয়েছে এবং রাইডারকে রি-রুট করা হচ্ছে।`;
|
customerMsg = `প্রস্তাবিত মেসেজ: প্রিয় ${name}, আপনার পার্সেলের (${cid}) সংশোধিত ঠিকানা (${req.corrected_address || "নতুন ঠিকানা"}) কুরিয়ারকে জানানোর জন্য ড্রাফট তৈরি করা হয়েছে। ঠিকানাটি সঠিক থাকলে আমাদের কনফার্ম করুন।`;
|
||||||
customerMsg = `প্রিয় ${name}, আপনার পার্সেলের ঠিকানা সংশোধন করা হয়েছে। রাইডার আপনার নতুন ঠিকানায় ডেলিভারির জন্য যোগাযোগ করবে।`;
|
ticketSubject = `[Address Correction Draft] Consignment ${cid}`;
|
||||||
carrierInstr = `ADDRESS_UPDATE: Route parcel ${cid} to updated address: ${req.corrected_address || "Provided in notes"}.`;
|
carrierInstr = `DRAFT_ADDRESS_UPDATE: Please update delivery address for consignment ${cid} to: ${req.corrected_address || "Provided in merchant notes"}.`;
|
||||||
break;
|
break;
|
||||||
case "customer_refused":
|
case "customer_refused":
|
||||||
status = "CUSTOMER_REENGAGED";
|
recommendedAction = "HOLD";
|
||||||
actionTaken = "গ্রাহক পার্সেল গ্রহণে অস্বীকৃতি জানানোয় কারণ অনুসন্ধান ও সমস্যা সমাধানে রিটেনশন মেসেজ পাঠানো হয়েছে।";
|
customerMsg = `প্রস্তাবিত মেসেজ: প্রিয় ${name}, আমরা লক্ষ্য করেছি পার্সেলটি (${cid}) ডেলিভারির সময় গ্রহণ করা সম্ভব হয়নি। পণ্য বা ডেলিভারি নিয়ে আপনার কোনো প্রশ্ন থাকলে অনুগ্রহ করে আমাদের জানান, আমরা সমাধানে সহায়তা করতে প্রস্তুত।`;
|
||||||
customerMsg = `প্রিয় ${name}, আমরা জানতে পেরেছি আপনি পার্সেলটি গ্রহণ করতে পারেননি। পণ্য নিয়ে আপনার কোনো প্রশ্ন বা অসন্তোষ থাকলে দয়া করে আমাদের জানান, আমরা সরাসরি সমাধান করে দিচ্ছি।`;
|
ticketSubject = `[Retention Hold Draft] Consignment ${cid} — Pending Merchant Follow-up`;
|
||||||
carrierInstr = `HOLD_PENDING_MERCHANT_ACTION: Merchant in retention contact with customer. Hold consignment ${cid} 24 hours before RTO.`;
|
carrierInstr = `DRAFT_RETENTION_HOLD: Merchant is reaching out to customer regarding consignment ${cid}. Please hold at hub for 24 hours before processing return.`;
|
||||||
break;
|
break;
|
||||||
}
|
}
|
||||||
|
const nowIso = new Date().toISOString();
|
||||||
return {
|
return {
|
||||||
success: true,
|
success: true,
|
||||||
consignment_id: cid,
|
consignment_id: cid,
|
||||||
courier,
|
courier,
|
||||||
resolution_status: status,
|
status: "DRAFT_GENERATED",
|
||||||
action_taken: actionTaken,
|
consignment_verified: true,
|
||||||
|
actions_executed: [],
|
||||||
|
whatsapp_draft: {
|
||||||
|
language: "bn",
|
||||||
|
text: customerMsg,
|
||||||
|
},
|
||||||
|
courier_ticket_draft: {
|
||||||
|
subject: ticketSubject,
|
||||||
|
body: carrierInstr + phoneTag,
|
||||||
|
},
|
||||||
|
recommended_carrier_action: recommendedAction,
|
||||||
|
requires_manual_execution: true,
|
||||||
|
resolution_status: "DRAFT_GENERATED",
|
||||||
|
action_taken: "প্রস্তাবিত ড্রাফট তৈরি করা হয়েছে (কোনো অটোমেটিক মেসেজ বা কুরিয়ার টিকিট পাঠানো হয়নি)।",
|
||||||
customer_whatsapp_message: customerMsg,
|
customer_whatsapp_message: customerMsg,
|
||||||
carrier_instruction: carrierInstr + phoneTag,
|
carrier_instruction: carrierInstr + phoneTag,
|
||||||
timestamp: new Date().toISOString(),
|
timestamp: nowIso,
|
||||||
|
};
|
||||||
|
}
|
||||||
|
/**
|
||||||
|
* Task T8 — cancel_parcel(courier, consignment_id)
|
||||||
|
*/
|
||||||
|
async cancelParcel(courier, consignmentId) {
|
||||||
|
const cid = String(consignmentId || "").trim();
|
||||||
|
if (!cid) {
|
||||||
|
throw new McpToolError({
|
||||||
|
code: "INVALID_INPUT",
|
||||||
|
message: "consignment_id is required to request cancellation.",
|
||||||
|
});
|
||||||
|
}
|
||||||
|
this.getAdapter(courier); // Validates supported courier name
|
||||||
|
throw new McpToolError({
|
||||||
|
code: "UNSUPPORTED_BY_PROVIDER",
|
||||||
|
message: `${courier} does not expose an automated parcel cancellation endpoint in its public merchant API; please cancel consignment '${cid}' in the ${courier} merchant portal.`,
|
||||||
|
courier,
|
||||||
|
retryable: false,
|
||||||
|
extraFields: {
|
||||||
|
consignment_id: cid,
|
||||||
|
cancellable_via_api: false,
|
||||||
|
hint: `Use ${courier} merchant portal`,
|
||||||
|
},
|
||||||
|
});
|
||||||
|
}
|
||||||
|
/**
|
||||||
|
* Task T8 — bulk_create_parcels(items[], dry_run?)
|
||||||
|
*/
|
||||||
|
async bulkCreateParcels(items, dryRun, tenantId) {
|
||||||
|
if (!Array.isArray(items) || items.length === 0) {
|
||||||
|
throw new McpToolError({
|
||||||
|
code: "INVALID_INPUT",
|
||||||
|
message: "items must be a non-empty array of parcel creation objects.",
|
||||||
|
});
|
||||||
|
}
|
||||||
|
if (items.length > 100) {
|
||||||
|
throw new McpToolError({
|
||||||
|
code: "INVALID_INPUT",
|
||||||
|
message: "bulk_create_parcels supports at most 100 parcels per batch.",
|
||||||
|
});
|
||||||
|
}
|
||||||
|
let succeeded = 0;
|
||||||
|
let failed = 0;
|
||||||
|
const results = [];
|
||||||
|
for (let i = 0; i < items.length; i++) {
|
||||||
|
const item = items[i];
|
||||||
|
const invoice = String(item?.invoice || `BATCH-${i + 1}`);
|
||||||
|
try {
|
||||||
|
const res = await this.createParcel({
|
||||||
|
...item,
|
||||||
|
invoice,
|
||||||
|
dry_run: dryRun !== undefined ? Boolean(dryRun) : Boolean(item?.dry_run),
|
||||||
|
tenant_id: tenantId || item?.tenant_id,
|
||||||
|
});
|
||||||
|
succeeded++;
|
||||||
|
results.push({ index: i, invoice, ok: true, data: res });
|
||||||
|
}
|
||||||
|
catch (err) {
|
||||||
|
failed++;
|
||||||
|
results.push({
|
||||||
|
index: i,
|
||||||
|
invoice,
|
||||||
|
ok: false,
|
||||||
|
error: {
|
||||||
|
code: err?.code || "BOOKING_ERROR",
|
||||||
|
message: err?.message || String(err),
|
||||||
|
},
|
||||||
|
});
|
||||||
|
}
|
||||||
|
}
|
||||||
|
return {
|
||||||
|
success: failed === 0,
|
||||||
|
total: items.length,
|
||||||
|
succeeded,
|
||||||
|
failed,
|
||||||
|
dry_run: Boolean(dryRun),
|
||||||
|
results,
|
||||||
|
};
|
||||||
|
}
|
||||||
|
/**
|
||||||
|
* Task T8 — get_webhook_events(consignment_id?, since?)
|
||||||
|
*/
|
||||||
|
getWebhookEvents(consignmentId, since) {
|
||||||
|
let filtered = [...webhookEventsStore];
|
||||||
|
if (consignmentId) {
|
||||||
|
const target = String(consignmentId).trim().toLowerCase();
|
||||||
|
filtered = filtered.filter((e) => String(e.consignment_id).toLowerCase() === target);
|
||||||
|
}
|
||||||
|
if (since) {
|
||||||
|
const sinceMs = Date.parse(since);
|
||||||
|
if (!Number.isNaN(sinceMs)) {
|
||||||
|
filtered = filtered.filter((e) => Date.parse(e.received_at) >= sinceMs);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
return {
|
||||||
|
success: true,
|
||||||
|
count: filtered.length,
|
||||||
|
events: filtered,
|
||||||
};
|
};
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|||||||
Vendored
+9
-2
@@ -2,12 +2,19 @@ import { Server } from "@modelcontextprotocol/sdk/server/index.js";
|
|||||||
import { Tool } from "@modelcontextprotocol/sdk/types.js";
|
import { Tool } from "@modelcontextprotocol/sdk/types.js";
|
||||||
import { CourierRegistry } from "./registry.js";
|
import { CourierRegistry } from "./registry.js";
|
||||||
export declare const TOOLS: Tool[];
|
export declare const TOOLS: Tool[];
|
||||||
|
/**
|
||||||
|
* Execute a single MCP tool call and return the Global Response Envelope (`v2.6.0`).
|
||||||
|
*/
|
||||||
|
export declare function executeToolCall(registry: CourierRegistry, name: string, args?: Record<string, any>, tenantId?: string): Promise<{
|
||||||
|
isError: boolean;
|
||||||
|
envelope: any;
|
||||||
|
}>;
|
||||||
/**
|
/**
|
||||||
* Build a fully-wired MCP Server bound to a given CourierRegistry.
|
* Build a fully-wired MCP Server bound to a given CourierRegistry.
|
||||||
* The registry carries the credentials — for STDIO it comes from env,
|
* The registry carries the credentials — for STDIO it comes from env,
|
||||||
* for HTTP it is built per-request from that client's keys.
|
* for HTTP it is built per-request from that client's keys.
|
||||||
*/
|
*/
|
||||||
export declare function buildMcpServer(registry: CourierRegistry, authChecker?: (toolName: string) => {
|
export declare function buildMcpServer(registry: CourierRegistry, authChecker?: (toolName: string, args?: Record<string, any>) => {
|
||||||
permitted: boolean;
|
permitted: boolean;
|
||||||
reason?: string;
|
reason?: string;
|
||||||
}): Server;
|
}, tenantId?: string): Server;
|
||||||
|
|||||||
Vendored
+228
-97
@@ -1,5 +1,6 @@
|
|||||||
import { Server } from "@modelcontextprotocol/sdk/server/index.js";
|
import { Server } from "@modelcontextprotocol/sdk/server/index.js";
|
||||||
import { CallToolRequestSchema, ListToolsRequestSchema, } from "@modelcontextprotocol/sdk/types.js";
|
import { CallToolRequestSchema, ListToolsRequestSchema, } from "@modelcontextprotocol/sdk/types.js";
|
||||||
|
import { McpToolError, wrapError, wrapSuccess } from "./envelope.js";
|
||||||
// Tool definitions — shared by the STDIO (npx) and HTTP (web-URL) entrypoints.
|
// Tool definitions — shared by the STDIO (npx) and HTTP (web-URL) entrypoints.
|
||||||
export const TOOLS = [
|
export const TOOLS = [
|
||||||
{
|
{
|
||||||
@@ -9,12 +10,16 @@ export const TOOLS = [
|
|||||||
},
|
},
|
||||||
{
|
{
|
||||||
name: "create_parcel",
|
name: "create_parcel",
|
||||||
description: "Book and dispatch a physical parcel consignment across Bangladesh through Steadfast, Pathao, RedX, Paperfly, or AI smart cascading routing. STATE-MUTATING ACTION: This call creates a real, billable shipment record in the carrier's production database, assigns an official tracking code, and deducts courier fees upon pickup. Once booked, cancellations require direct courier portal operations. Use only after customer address and phone number are verified. Do NOT use for preliminary fee estimation (use 'calculate_delivery_zone_and_fee' or 'compare_courier_rates') or address validation (use 'validate_and_geocode_address'). Throws an error if required courier credentials are not configured or recipient phone is invalid.",
|
description: "Book and dispatch a physical parcel consignment across Bangladesh through Steadfast, Pathao, RedX, Paperfly, or AI smart cascading routing, with built-in per-tenant invoice idempotency and optional dry-run validation. STATE-MUTATING ACTION (unless dry_run=true): Creates a real, billable shipment record in the carrier's production database, assigns an official tracking code, and deducts courier fees upon pickup. Set dry_run=true to validate recipient phone/address and preview the target courier and estimated BDT cost without booking upstream. Once booked, cancellations require direct courier portal operations ('cancellable_via_api: false').",
|
||||||
inputSchema: {
|
inputSchema: {
|
||||||
type: "object",
|
type: "object",
|
||||||
properties: {
|
properties: {
|
||||||
courier: { type: "string", enum: ["steadfast", "pathao", "redx", "paperfly", "auto"], description: "Target courier or 'auto' for AI smart routing (default: auto)" },
|
courier: {
|
||||||
invoice: { type: "string", description: "Unique order invoice number (e.g. INV-1002)" },
|
type: "string",
|
||||||
|
enum: ["steadfast", "pathao", "redx", "paperfly", "auto", "auto_fastest", "auto_cheapest"],
|
||||||
|
description: "Target courier or 'auto' for AI smart routing (default: auto)",
|
||||||
|
},
|
||||||
|
invoice: { type: "string", description: "Unique order invoice number (e.g. INV-1002) used as idempotency key" },
|
||||||
recipient_name: { type: "string", description: "Customer full name" },
|
recipient_name: { type: "string", description: "Customer full name" },
|
||||||
recipient_phone: { type: "string", description: "11-digit Bangladeshi mobile number (e.g. 017XXXXXXXX)" },
|
recipient_phone: { type: "string", description: "11-digit Bangladeshi mobile number (e.g. 017XXXXXXXX)" },
|
||||||
recipient_address: { type: "string", description: "Delivery address (Thana, District, Street)" },
|
recipient_address: { type: "string", description: "Delivery address (Thana, District, Street)" },
|
||||||
@@ -25,36 +30,51 @@ export const TOOLS = [
|
|||||||
value: { type: "number", description: "Declared parcel value in BDT (used by RedX; defaults to the COD amount)" },
|
value: { type: "number", description: "Declared parcel value in BDT (used by RedX; defaults to the COD amount)" },
|
||||||
delivery_area_id: { type: "number", description: "RedX only: numeric delivery-area id (auto-resolved from the address if omitted)" },
|
delivery_area_id: { type: "number", description: "RedX only: numeric delivery-area id (auto-resolved from the address if omitted)" },
|
||||||
pickup_store_id: { type: "number", description: "RedX only: your pickup store id (optional)" },
|
pickup_store_id: { type: "number", description: "RedX only: your pickup store id (optional)" },
|
||||||
|
dry_run: {
|
||||||
|
type: "boolean",
|
||||||
|
description: "If true, validates phone/address and returns would_book_with and estimated_cost_bdt without creating a real upstream shipment.",
|
||||||
|
},
|
||||||
},
|
},
|
||||||
required: ["invoice", "recipient_name", "recipient_phone", "recipient_address", "cod_amount"],
|
required: ["invoice", "recipient_name", "recipient_phone", "recipient_address", "cod_amount"],
|
||||||
},
|
},
|
||||||
},
|
},
|
||||||
{
|
{
|
||||||
name: "track_parcel",
|
name: "track_parcel",
|
||||||
description: "Query live, real-time tracking milestones and delivery telemetry across Steadfast, Pathao, RedX, and Paperfly networks using consignment ID or tracking code. READ-ONLY OPERATION: Does not alter shipment state or carrier data. Returns normalized status (Booked, In Review, Picked Up, In Transit, Delivered, Partial Delivered, Cancelled, Returned), current location, carrier status notes, and timestamp history. Use when an end-customer or merchant inquires about existing shipment progress. Do NOT use for creating consignments (use 'create_parcel') or resolving failed deliveries (use 'resolve_ndr_issue'). Carrier provider is auto-detected from consignment prefix if omitted.",
|
description: "Query live, real-time tracking milestones and delivery telemetry across Steadfast, Pathao, RedX, and Paperfly networks using consignment ID or tracking code. READ-ONLY OPERATION: Does not alter shipment state or carrier data. Returns normalized status, current location, carrier status notes, and timestamp history. Returns structured error code 'CONSIGNMENT_NOT_FOUND' with 'couriers_checked' if the consignment does not exist. Carrier provider is auto-detected from consignment prefix if omitted.",
|
||||||
inputSchema: {
|
inputSchema: {
|
||||||
type: "object",
|
type: "object",
|
||||||
properties: {
|
properties: {
|
||||||
tracking_code: { type: "string", description: "Consignment ID or tracking code (e.g. 'DS190926QZNGJT' for Pathao, 'SF12345678' for Steadfast, 'REDX123' for RedX)" },
|
tracking_code: {
|
||||||
courier: { type: "string", enum: ["steadfast", "pathao", "redx", "paperfly"], description: "Optional courier provider name. If omitted, provider is auto-detected from tracking code prefix." },
|
type: "string",
|
||||||
|
description: "Consignment ID or tracking code (e.g. 'DS190926QZNGJT' for Pathao, 'SF12345678' for Steadfast, 'REDX123' for RedX)",
|
||||||
|
},
|
||||||
|
courier: {
|
||||||
|
type: "string",
|
||||||
|
enum: ["steadfast", "pathao", "redx", "paperfly"],
|
||||||
|
description: "Optional courier provider name. If omitted, provider is auto-detected from tracking code prefix.",
|
||||||
|
},
|
||||||
},
|
},
|
||||||
required: ["tracking_code"],
|
required: ["tracking_code"],
|
||||||
},
|
},
|
||||||
},
|
},
|
||||||
{
|
{
|
||||||
name: "get_balance",
|
name: "get_balance",
|
||||||
description: "Retrieve live merchant cash-on-delivery (COD) vault balance, pending disbursement amounts, and payout ledger from Steadfast or Pathao merchant portals. READ-ONLY FINANCIAL INQUIRY: Does not initiate payouts or mutate accounting ledgers. Use when accounting or merchant finance operators want to verify accrued COD collections or payout readiness. Do NOT use for customer balance or shipping quote estimation (use 'calculate_delivery_zone_and_fee'). Requires active merchant API keys for the requested courier; throws an error if unconfigured.",
|
description: "Retrieve live merchant cash-on-delivery (COD) vault balance from Steadfast, or check provider balance support across Pathao, RedX, Paperfly, or all 4 couriers simultaneously. READ-ONLY FINANCIAL INQUIRY: Steadfast returns live 'amount_bdt' and 'status: OK'; Pathao, RedX, and Paperfly return 'amount_bdt: null' and 'status: UNSUPPORTED_BY_PROVIDER' with merchant portal hints because their public APIs do not expose a balance endpoint.",
|
||||||
inputSchema: {
|
inputSchema: {
|
||||||
type: "object",
|
type: "object",
|
||||||
properties: {
|
properties: {
|
||||||
courier: { type: "string", enum: ["steadfast", "pathao"], description: "Courier provider to check balance for" },
|
courier: {
|
||||||
|
type: "string",
|
||||||
|
enum: ["steadfast", "pathao", "redx", "paperfly", "all"],
|
||||||
|
description: "Courier provider to check balance telemetry for ('steadfast', 'pathao', 'redx', 'paperfly', or 'all'; default: 'all')",
|
||||||
|
},
|
||||||
},
|
},
|
||||||
required: ["courier"],
|
required: [],
|
||||||
},
|
},
|
||||||
},
|
},
|
||||||
{
|
{
|
||||||
name: "check_fraud_risk",
|
name: "check_fraud_risk",
|
||||||
description: "Screen a customer phone number against live nationwide Bangladesh logistics databases (millions of historical consignments) for delivery success rate, cancellation counts, and return fraud risk score. READ-ONLY DIAGNOSTIC QUERY: Zero mock data, authentic carrier telemetry only. Use before confirming high-value COD orders to screen for chronic returners or fake orders. Do NOT use for address geocoding (use 'validate_and_geocode_address') or parcel booking (use 'create_parcel'). Expects an 11-digit Bangladeshi mobile number ('01XXXXXXXXX').",
|
description: "Screen a customer phone number against live nationwide Bangladesh logistics databases (Steadfast & Pathao) and the BTRC 11-digit prefix validator for delivery success rate, cancellation counts, and return fraud risk level ('INVALID_NUMBER', 'NO_HISTORY', 'LOW', 'MEDIUM', 'HIGH', 'CRITICAL'). READ-ONLY DIAGNOSTIC QUERY: Returns null rates when a number is invalid or has 0 parcel history. Expects an 11-digit Bangladeshi mobile number ('01[3-9]XXXXXXXX').",
|
||||||
inputSchema: {
|
inputSchema: {
|
||||||
type: "object",
|
type: "object",
|
||||||
properties: {
|
properties: {
|
||||||
@@ -65,12 +85,12 @@ export const TOOLS = [
|
|||||||
},
|
},
|
||||||
{
|
{
|
||||||
name: "validate_and_geocode_address",
|
name: "validate_and_geocode_address",
|
||||||
description: "Validate, clean, and geocode an unformatted Bangladesh delivery address into structured administrative boundaries (Thana, District, Division), rooftop latitude/longitude coordinates, and a deliverability confidence score (0-100) via Google Maps Platform Geocoding API with OpenStreetMap gazetteer fallback. READ-ONLY SPATIAL LOOKUP: Has zero side effects and does not mutate booking data. Use before booking parcels to detect spelling errors, verify Thana/District matching, and obtain precise coordinates. Do NOT use for calculating delivery fees or road routing distance (use 'calculate_delivery_zone_and_fee' instead).",
|
description: "Validate, clean, and geocode an unformatted Bangladesh delivery address into structured administrative boundaries (thana_input, thana_resolved, district, division), latitude/longitude coordinates, match_quality (road, house, area), needs_review flag, and a deliverability confidence score (0-100, capped at 60 when location_type != ROOFTOP) via Google Maps Platform Geocoding API with OpenStreetMap gazetteer fallback. READ-ONLY SPATIAL LOOKUP.",
|
||||||
inputSchema: {
|
inputSchema: {
|
||||||
type: "object",
|
type: "object",
|
||||||
properties: {
|
properties: {
|
||||||
address: { type: "string", description: "Full street or local address (e.g. 'Road 11, House 24, Dhanmondi, Dhaka')" },
|
address: { type: "string", description: "Full street or local address (e.g. 'Road 11, House 24, Dhanmondi, Dhaka')" },
|
||||||
thana: { type: "string", description: "Optional Thana/Upazila name" },
|
thana: { type: "string", description: "Optional expected Thana/Upazila name to verify against geocoded components" },
|
||||||
district: { type: "string", description: "Optional District name" },
|
district: { type: "string", description: "Optional District name" },
|
||||||
},
|
},
|
||||||
required: ["address"],
|
required: ["address"],
|
||||||
@@ -78,7 +98,7 @@ export const TOOLS = [
|
|||||||
},
|
},
|
||||||
{
|
{
|
||||||
name: "calculate_delivery_zone_and_fee",
|
name: "calculate_delivery_zone_and_fee",
|
||||||
description: "Calculate standard delivery zone (inside_dhaka ≤22km ৳80, sub_dhaka 22-45km ৳100, outside_dhaka >45km ৳150), actual road distance via Google Maps Platform Routes API (v2:computeRoutes), SLA turnaround time (24-72h), and applicable COD percentage for a SINGLE delivery destination. READ-ONLY ESTIMATION TOOL: Has zero external side effects and does NOT book shipments. Use when quoting shipping charges to a customer or determining flat delivery tiers for an order. Do NOT use if you need side-by-side multi-carrier tariff quotes with weight breaks and priority sorting across all 4 couriers (use 'compare_courier_rates' instead).",
|
description: "Calculate standard delivery zone (inside_dhaka <=22km ৳80, sub_dhaka 22-45km ৳100, outside_dhaka >45km ৳150), road distance via Google Maps Platform Routes API, structured SLA hours ({min, max}), and applicable COD percentage for a single delivery destination using the unified tariff table (meta.source='static_tariff'). READ-ONLY ESTIMATION TOOL.",
|
||||||
inputSchema: {
|
inputSchema: {
|
||||||
type: "object",
|
type: "object",
|
||||||
properties: {
|
properties: {
|
||||||
@@ -91,25 +111,29 @@ export const TOOLS = [
|
|||||||
},
|
},
|
||||||
{
|
{
|
||||||
name: "compare_courier_rates",
|
name: "compare_courier_rates",
|
||||||
description: "Execute side-by-side tariff, SLA, and COD collection fee comparisons across all four major Bangladeshi couriers (Steadfast, Pathao, RedX, Paperfly) for any destination nationwide. Evaluates exact parcel weight, declared COD amount, and optimization priority ('cheapest', 'fastest', 'balanced') to select the recommended courier. READ-ONLY CALCULATION ENGINE: Has zero external side effects and does not create orders. Use when deciding which carrier offers the best commercial rate or fastest SLA for a specific shipment before booking. Do NOT use for single flat-rate zone lookup (use 'calculate_delivery_zone_and_fee') or for actually booking the shipment (use 'create_parcel').",
|
description: "Execute side-by-side tariff, structured SLA ({min, max}), and COD collection fee comparisons across all four major Bangladeshi couriers (Steadfast, Pathao, RedX, Paperfly) for any destination nationwide using the unified tariff table (meta.source='static_tariff'). Evaluates exact parcel weight, declared COD amount, and optimization priority ('cheapest', 'fastest', 'balanced') to select the recommended courier. READ-ONLY CALCULATION ENGINE.",
|
||||||
inputSchema: {
|
inputSchema: {
|
||||||
type: "object",
|
type: "object",
|
||||||
properties: {
|
properties: {
|
||||||
recipient_address: { type: "string", description: "Destination delivery address anywhere in Bangladesh" },
|
recipient_address: { type: "string", description: "Destination delivery address anywhere in Bangladesh" },
|
||||||
weight_kg: { type: "number", description: "Parcel weight in KG (default: 0.5)" },
|
weight_kg: { type: "number", description: "Parcel weight in KG (default: 0.5)" },
|
||||||
cod_amount: { type: "number", description: "Cash On Delivery amount in BDT (default: 0)" },
|
cod_amount: { type: "number", description: "Cash On Delivery amount in BDT (default: 0)" },
|
||||||
priority: { type: "string", enum: ["cheapest", "fastest", "balanced"], description: "Optimization priority (default: balanced)" },
|
priority: {
|
||||||
|
type: "string",
|
||||||
|
enum: ["cheapest", "fastest", "balanced"],
|
||||||
|
description: "Optimization priority (default: balanced)",
|
||||||
|
},
|
||||||
},
|
},
|
||||||
required: ["recipient_address"],
|
required: ["recipient_address"],
|
||||||
},
|
},
|
||||||
},
|
},
|
||||||
{
|
{
|
||||||
name: "resolve_ndr_issue",
|
name: "resolve_ndr_issue",
|
||||||
description: "Automate Non-Delivery Report (NDR) triage and dispute resolution when a courier delivery attempt fails. GENERATION-ONLY TOOL (NO DIRECT DISPATCH): Generates empathetic, conversion-tested Bengali WhatsApp re-engagement copy for the customer and formal operational escalation tickets with hold instructions for the carrier. Does NOT send network messages or modify courier bookings automatically; output must be reviewed or dispatched through messaging channels. Use when a parcel status changes to failed attempt, customer phone off, or reschedule requested. Do NOT use for general order tracking (use 'track_parcel') or creating orders (use 'create_parcel').",
|
description: "Verify that a consignment exists on the specified courier via 'track_parcel' and generate honest, draft-only Non-Delivery Report (NDR) re-engagement copy ('status: DRAFT_GENERATED', 'actions_executed: []'). GENERATION-ONLY TOOL: Verifies consignment_id first (returns CONSIGNMENT_NOT_FOUND if unknown), then generates proposed Bengali WhatsApp copy ('whatsapp_draft') and a carrier escalation ticket draft ('courier_ticket_draft') for manual merchant execution.",
|
||||||
inputSchema: {
|
inputSchema: {
|
||||||
type: "object",
|
type: "object",
|
||||||
properties: {
|
properties: {
|
||||||
consignment_id: { type: "string", description: "Tracking code or consignment ID" },
|
consignment_id: { type: "string", description: "Existing tracking code or consignment ID to verify and generate NDR drafts for" },
|
||||||
courier: { type: "string", enum: ["steadfast", "pathao", "redx", "paperfly"], description: "Courier provider" },
|
courier: { type: "string", enum: ["steadfast", "pathao", "redx", "paperfly"], description: "Courier provider" },
|
||||||
issue_type: {
|
issue_type: {
|
||||||
type: "string",
|
type: "string",
|
||||||
@@ -124,102 +148,209 @@ export const TOOLS = [
|
|||||||
required: ["consignment_id", "courier", "issue_type"],
|
required: ["consignment_id", "courier", "issue_type"],
|
||||||
},
|
},
|
||||||
},
|
},
|
||||||
|
{
|
||||||
|
name: "cancel_parcel",
|
||||||
|
description: "Request cancellation for an existing parcel consignment on Steadfast, Pathao, RedX, or Paperfly. Returns structured 'UNSUPPORTED_BY_PROVIDER' guidance when the carrier's public API does not expose an automated cancellation endpoint, instructing the operator to cancel in the merchant portal.",
|
||||||
|
inputSchema: {
|
||||||
|
type: "object",
|
||||||
|
properties: {
|
||||||
|
courier: { type: "string", enum: ["steadfast", "pathao", "redx", "paperfly"], description: "Courier provider name" },
|
||||||
|
consignment_id: { type: "string", description: "Consignment ID or tracking code to cancel" },
|
||||||
|
},
|
||||||
|
required: ["courier", "consignment_id"],
|
||||||
|
},
|
||||||
|
},
|
||||||
|
{
|
||||||
|
name: "bulk_create_parcels",
|
||||||
|
description: "Validate or book up to 100 parcels in a single batch with per-item error isolation, invoice idempotency, and optional dry_run preview mode. STATE-MUTATING ACTION (unless dry_run=true): Returns total, succeeded, failed, and per-item results.",
|
||||||
|
inputSchema: {
|
||||||
|
type: "object",
|
||||||
|
properties: {
|
||||||
|
items: {
|
||||||
|
type: "array",
|
||||||
|
description: "Array of parcel creation objects (1 to 100 items)",
|
||||||
|
items: {
|
||||||
|
type: "object",
|
||||||
|
properties: {
|
||||||
|
courier: { type: "string", enum: ["steadfast", "pathao", "redx", "paperfly", "auto"] },
|
||||||
|
invoice: { type: "string" },
|
||||||
|
recipient_name: { type: "string" },
|
||||||
|
recipient_phone: { type: "string" },
|
||||||
|
recipient_address: { type: "string" },
|
||||||
|
cod_amount: { type: "number" },
|
||||||
|
note: { type: "string" },
|
||||||
|
item_weight: { type: "number" },
|
||||||
|
dry_run: { type: "boolean" },
|
||||||
|
},
|
||||||
|
required: ["invoice", "recipient_name", "recipient_phone", "recipient_address", "cod_amount"],
|
||||||
|
},
|
||||||
|
},
|
||||||
|
dry_run: {
|
||||||
|
type: "boolean",
|
||||||
|
description: "If true, runs the entire batch in dry-run validation mode without creating real upstream shipments.",
|
||||||
|
},
|
||||||
|
},
|
||||||
|
required: ["items"],
|
||||||
|
},
|
||||||
|
},
|
||||||
|
{
|
||||||
|
name: "get_webhook_events",
|
||||||
|
description: "Query verified courier webhook status events received by the server's /webhooks/{steadfast,pathao,redx,paperfly} endpoints. READ-ONLY DIAGNOSTIC TOOL: Filterable by consignment_id and ISO-8601 'since' timestamp.",
|
||||||
|
inputSchema: {
|
||||||
|
type: "object",
|
||||||
|
properties: {
|
||||||
|
consignment_id: { type: "string", description: "Optional consignment ID or tracking code to filter events for" },
|
||||||
|
since: { type: "string", description: "Optional ISO-8601 timestamp to return events received at or after" },
|
||||||
|
},
|
||||||
|
required: [],
|
||||||
|
},
|
||||||
|
},
|
||||||
];
|
];
|
||||||
|
/**
|
||||||
|
* Execute a single MCP tool call and return the Global Response Envelope (`v2.6.0`).
|
||||||
|
*/
|
||||||
|
export async function executeToolCall(registry, name, args = {}, tenantId = "default") {
|
||||||
|
let defaultSource = "live_api";
|
||||||
|
if (name === "calculate_delivery_zone_and_fee" || name === "compare_courier_rates") {
|
||||||
|
defaultSource = "static_tariff";
|
||||||
|
}
|
||||||
|
else if (name === "get_webhook_events") {
|
||||||
|
defaultSource = "cache";
|
||||||
|
}
|
||||||
|
try {
|
||||||
|
switch (name) {
|
||||||
|
case "list_couriers": {
|
||||||
|
const result = registry.listCouriers();
|
||||||
|
return { isError: false, envelope: wrapSuccess(result, "validator") };
|
||||||
|
}
|
||||||
|
case "create_parcel": {
|
||||||
|
const isDryRun = Boolean(args?.dry_run);
|
||||||
|
const result = await registry.createParcel({
|
||||||
|
courier: args?.courier,
|
||||||
|
invoice: String(args?.invoice ?? ""),
|
||||||
|
recipient_name: String(args?.recipient_name ?? ""),
|
||||||
|
recipient_phone: String(args?.recipient_phone ?? ""),
|
||||||
|
recipient_address: String(args?.recipient_address ?? ""),
|
||||||
|
cod_amount: Number(args?.cod_amount || 0),
|
||||||
|
note: args?.note ? String(args?.note) : undefined,
|
||||||
|
item_weight: args?.item_weight ? Number(args?.item_weight) : 0.5,
|
||||||
|
item_type: args?.item_type ? String(args?.item_type) : undefined,
|
||||||
|
value: args?.value !== undefined ? Number(args?.value) : undefined,
|
||||||
|
delivery_area_id: args?.delivery_area_id !== undefined ? Number(args?.delivery_area_id) : undefined,
|
||||||
|
pickup_store_id: args?.pickup_store_id !== undefined ? Number(args?.pickup_store_id) : undefined,
|
||||||
|
dry_run: isDryRun,
|
||||||
|
tenant_id: tenantId,
|
||||||
|
});
|
||||||
|
const source = isDryRun ? "validator" : result.idempotent_replay ? "cache" : "live_api";
|
||||||
|
return { isError: false, envelope: wrapSuccess(result, source) };
|
||||||
|
}
|
||||||
|
case "track_parcel": {
|
||||||
|
const result = await registry.trackParcel(String(args?.tracking_code ?? ""), args?.courier);
|
||||||
|
return { isError: false, envelope: wrapSuccess(result, "live_api") };
|
||||||
|
}
|
||||||
|
case "get_balance": {
|
||||||
|
const result = await registry.getBalance(args?.courier || "all");
|
||||||
|
return { isError: false, envelope: wrapSuccess(result, "live_api") };
|
||||||
|
}
|
||||||
|
case "check_fraud_risk": {
|
||||||
|
const result = await registry.checkFraudRisk(String(args?.phone ?? ""));
|
||||||
|
const source = result.risk_level === "INVALID_NUMBER" ? "validator" : "live_api";
|
||||||
|
return { isError: false, envelope: wrapSuccess(result, source) };
|
||||||
|
}
|
||||||
|
case "validate_and_geocode_address": {
|
||||||
|
const result = await registry.validateAddress({
|
||||||
|
address: String(args?.address ?? ""),
|
||||||
|
thana: args?.thana ? String(args?.thana) : undefined,
|
||||||
|
district: args?.district ? String(args?.district) : undefined,
|
||||||
|
});
|
||||||
|
return { isError: false, envelope: wrapSuccess(result, "live_api") };
|
||||||
|
}
|
||||||
|
case "calculate_delivery_zone_and_fee": {
|
||||||
|
const result = await registry.calculateZoneAndRate({
|
||||||
|
recipient_address: String(args?.recipient_address ?? ""),
|
||||||
|
origin_address: args?.origin_address ? String(args?.origin_address) : undefined,
|
||||||
|
weight_kg: args?.weight_kg ? Number(args?.weight_kg) : 0.5,
|
||||||
|
});
|
||||||
|
return { isError: false, envelope: wrapSuccess(result, "static_tariff") };
|
||||||
|
}
|
||||||
|
case "compare_courier_rates": {
|
||||||
|
const result = await registry.compareRates({
|
||||||
|
recipient_address: String(args?.recipient_address ?? ""),
|
||||||
|
weight_kg: args?.weight_kg ? Number(args?.weight_kg) : 0.5,
|
||||||
|
cod_amount: args?.cod_amount ? Number(args?.cod_amount) : 0,
|
||||||
|
priority: args?.priority,
|
||||||
|
});
|
||||||
|
return { isError: false, envelope: wrapSuccess(result, "static_tariff") };
|
||||||
|
}
|
||||||
|
case "resolve_ndr_issue": {
|
||||||
|
const result = await registry.resolveNdr({
|
||||||
|
consignment_id: String(args?.consignment_id ?? ""),
|
||||||
|
courier: args?.courier,
|
||||||
|
issue_type: args?.issue_type,
|
||||||
|
customer_phone: args?.customer_phone ? String(args?.customer_phone) : undefined,
|
||||||
|
customer_name: args?.customer_name ? String(args?.customer_name) : undefined,
|
||||||
|
reschedule_date: args?.reschedule_date ? String(args?.reschedule_date) : undefined,
|
||||||
|
corrected_address: args?.corrected_address ? String(args?.corrected_address) : undefined,
|
||||||
|
});
|
||||||
|
return { isError: false, envelope: wrapSuccess(result, "live_api") };
|
||||||
|
}
|
||||||
|
case "cancel_parcel": {
|
||||||
|
const result = await registry.cancelParcel(args?.courier, String(args?.consignment_id ?? ""));
|
||||||
|
return { isError: false, envelope: wrapSuccess(result, "live_api") };
|
||||||
|
}
|
||||||
|
case "bulk_create_parcels": {
|
||||||
|
const isDryRun = args?.dry_run !== undefined ? Boolean(args?.dry_run) : undefined;
|
||||||
|
const result = await registry.bulkCreateParcels(Array.isArray(args?.items) ? args.items : [], isDryRun, tenantId);
|
||||||
|
return { isError: false, envelope: wrapSuccess(result, isDryRun ? "validator" : "live_api") };
|
||||||
|
}
|
||||||
|
case "get_webhook_events": {
|
||||||
|
const result = registry.getWebhookEvents(args?.consignment_id ? String(args?.consignment_id) : undefined, args?.since ? String(args?.since) : undefined);
|
||||||
|
return { isError: false, envelope: wrapSuccess(result, "cache") };
|
||||||
|
}
|
||||||
|
default:
|
||||||
|
throw new McpToolError({
|
||||||
|
code: "INVALID_INPUT",
|
||||||
|
message: `Unknown tool: ${name}`,
|
||||||
|
retryable: false,
|
||||||
|
});
|
||||||
|
}
|
||||||
|
}
|
||||||
|
catch (error) {
|
||||||
|
return {
|
||||||
|
isError: true,
|
||||||
|
envelope: wrapError(error, defaultSource),
|
||||||
|
};
|
||||||
|
}
|
||||||
|
}
|
||||||
/**
|
/**
|
||||||
* Build a fully-wired MCP Server bound to a given CourierRegistry.
|
* Build a fully-wired MCP Server bound to a given CourierRegistry.
|
||||||
* The registry carries the credentials — for STDIO it comes from env,
|
* The registry carries the credentials — for STDIO it comes from env,
|
||||||
* for HTTP it is built per-request from that client's keys.
|
* for HTTP it is built per-request from that client's keys.
|
||||||
*/
|
*/
|
||||||
export function buildMcpServer(registry, authChecker) {
|
export function buildMcpServer(registry, authChecker, tenantId = "default") {
|
||||||
const server = new Server({ name: "aura-courier-mcp", version: "2.4.2" }, { capabilities: { tools: {} } });
|
const server = new Server({ name: "aura-courier-mcp", version: "2.6.0" }, { capabilities: { tools: {} } });
|
||||||
server.setRequestHandler(ListToolsRequestSchema, async () => ({ tools: TOOLS }));
|
server.setRequestHandler(ListToolsRequestSchema, async () => ({ tools: TOOLS }));
|
||||||
server.setRequestHandler(CallToolRequestSchema, async (request) => {
|
server.setRequestHandler(CallToolRequestSchema, async (request) => {
|
||||||
const { name, arguments: args } = request.params;
|
const { name, arguments: args } = request.params;
|
||||||
if (authChecker) {
|
if (authChecker) {
|
||||||
const auth = authChecker(name);
|
const auth = authChecker(name, args || {});
|
||||||
if (!auth.permitted) {
|
if (!auth.permitted) {
|
||||||
|
const errEnvelope = wrapError(new McpToolError({
|
||||||
|
code: "UNAUTHORIZED",
|
||||||
|
message: auth.reason || "Unauthorized tool invocation.",
|
||||||
|
retryable: false,
|
||||||
|
}), "validator");
|
||||||
return {
|
return {
|
||||||
isError: true,
|
isError: true,
|
||||||
content: [{ type: "text", text: JSON.stringify({ error: "Unauthorized", message: auth.reason }, null, 2) }],
|
content: [{ type: "text", text: JSON.stringify(errEnvelope, null, 2) }],
|
||||||
};
|
};
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
try {
|
const { isError, envelope } = await executeToolCall(registry, name, args || {}, tenantId);
|
||||||
switch (name) {
|
return {
|
||||||
case "list_couriers":
|
isError,
|
||||||
return { content: [{ type: "text", text: JSON.stringify(registry.listCouriers(), null, 2) }] };
|
content: [{ type: "text", text: JSON.stringify(envelope, null, 2) }],
|
||||||
case "create_parcel": {
|
};
|
||||||
const result = await registry.createParcel({
|
|
||||||
courier: args?.courier,
|
|
||||||
invoice: String(args?.invoice),
|
|
||||||
recipient_name: String(args?.recipient_name),
|
|
||||||
recipient_phone: String(args?.recipient_phone),
|
|
||||||
recipient_address: String(args?.recipient_address),
|
|
||||||
cod_amount: Number(args?.cod_amount || 0),
|
|
||||||
note: args?.note ? String(args?.note) : undefined,
|
|
||||||
item_weight: args?.item_weight ? Number(args?.item_weight) : 0.5,
|
|
||||||
});
|
|
||||||
return { content: [{ type: "text", text: JSON.stringify(result, null, 2) }] };
|
|
||||||
}
|
|
||||||
case "track_parcel": {
|
|
||||||
const result = await registry.trackParcel(String(args?.tracking_code), args?.courier);
|
|
||||||
return { content: [{ type: "text", text: JSON.stringify(result, null, 2) }] };
|
|
||||||
}
|
|
||||||
case "get_balance": {
|
|
||||||
const result = await registry.getBalance(String(args?.courier));
|
|
||||||
return { content: [{ type: "text", text: JSON.stringify(result, null, 2) }] };
|
|
||||||
}
|
|
||||||
case "check_fraud_risk": {
|
|
||||||
const result = await registry.checkFraudRisk(String(args?.phone));
|
|
||||||
return { content: [{ type: "text", text: JSON.stringify(result, null, 2) }] };
|
|
||||||
}
|
|
||||||
case "validate_and_geocode_address": {
|
|
||||||
const result = await registry.validateAddress({
|
|
||||||
address: String(args?.address),
|
|
||||||
thana: args?.thana ? String(args?.thana) : undefined,
|
|
||||||
district: args?.district ? String(args?.district) : undefined,
|
|
||||||
});
|
|
||||||
return { content: [{ type: "text", text: JSON.stringify(result, null, 2) }] };
|
|
||||||
}
|
|
||||||
case "calculate_delivery_zone_and_fee": {
|
|
||||||
const result = await registry.calculateZoneAndRate({
|
|
||||||
recipient_address: String(args?.recipient_address),
|
|
||||||
origin_address: args?.origin_address ? String(args?.origin_address) : undefined,
|
|
||||||
weight_kg: args?.weight_kg ? Number(args?.weight_kg) : 0.5,
|
|
||||||
});
|
|
||||||
return { content: [{ type: "text", text: JSON.stringify(result, null, 2) }] };
|
|
||||||
}
|
|
||||||
case "compare_courier_rates": {
|
|
||||||
const result = await registry.compareRates({
|
|
||||||
recipient_address: String(args?.recipient_address),
|
|
||||||
weight_kg: args?.weight_kg ? Number(args?.weight_kg) : 0.5,
|
|
||||||
cod_amount: args?.cod_amount ? Number(args?.cod_amount) : 0,
|
|
||||||
priority: args?.priority,
|
|
||||||
});
|
|
||||||
return { content: [{ type: "text", text: JSON.stringify(result, null, 2) }] };
|
|
||||||
}
|
|
||||||
case "resolve_ndr_issue": {
|
|
||||||
const result = await registry.resolveNdr({
|
|
||||||
consignment_id: String(args?.consignment_id),
|
|
||||||
courier: args?.courier,
|
|
||||||
issue_type: args?.issue_type,
|
|
||||||
customer_phone: args?.customer_phone ? String(args?.customer_phone) : undefined,
|
|
||||||
customer_name: args?.customer_name ? String(args?.customer_name) : undefined,
|
|
||||||
reschedule_date: args?.reschedule_date ? String(args?.reschedule_date) : undefined,
|
|
||||||
corrected_address: args?.corrected_address ? String(args?.corrected_address) : undefined,
|
|
||||||
});
|
|
||||||
return { content: [{ type: "text", text: JSON.stringify(result, null, 2) }] };
|
|
||||||
}
|
|
||||||
default:
|
|
||||||
throw new Error(`Unknown tool: ${name}`);
|
|
||||||
}
|
|
||||||
}
|
|
||||||
catch (error) {
|
|
||||||
return {
|
|
||||||
isError: true,
|
|
||||||
content: [{ type: "text", text: `Aura Courier MCP Error: ${error?.message || String(error)}` }],
|
|
||||||
};
|
|
||||||
}
|
|
||||||
});
|
});
|
||||||
return server;
|
return server;
|
||||||
}
|
}
|
||||||
|
|||||||
Vendored
+46
@@ -0,0 +1,46 @@
|
|||||||
|
import { SupportedCourier } from "./types.js";
|
||||||
|
export type DeliveryZone = "inside_dhaka" | "sub_dhaka" | "outside_dhaka";
|
||||||
|
export interface SlaHoursRange {
|
||||||
|
min: number;
|
||||||
|
max: number;
|
||||||
|
}
|
||||||
|
export interface ZoneDefinition {
|
||||||
|
zone: DeliveryZone;
|
||||||
|
zone_title: string;
|
||||||
|
max_distance_km: number | null;
|
||||||
|
standard_fee_bdt: number;
|
||||||
|
cod_percent: number;
|
||||||
|
sla_hours: SlaHoursRange;
|
||||||
|
sla_label: string;
|
||||||
|
}
|
||||||
|
export interface CarrierTariffRule {
|
||||||
|
courier: SupportedCourier;
|
||||||
|
courier_name: string;
|
||||||
|
base_fee_bdt: Record<DeliveryZone, number>;
|
||||||
|
extra_kg_fee_bdt: Record<DeliveryZone, number>;
|
||||||
|
cod_percent: Record<DeliveryZone, number>;
|
||||||
|
sla_hours: Record<DeliveryZone, SlaHoursRange>;
|
||||||
|
coverage_notes: Record<DeliveryZone, string>;
|
||||||
|
}
|
||||||
|
/**
|
||||||
|
* Single Source of Truth for Zone Definitions, Flat Fees & SLAs (T4)
|
||||||
|
*/
|
||||||
|
export declare const ZONE_DEFINITIONS: Record<DeliveryZone, ZoneDefinition>;
|
||||||
|
/**
|
||||||
|
* Single Source of Truth for Per-Courier Tariff Slabs & Route-Specific Coverage Notes (T4)
|
||||||
|
* Cites standard published Bangladesh merchant courier commercial rate cards.
|
||||||
|
*/
|
||||||
|
export declare const CARRIER_TARIFF_TABLE: Record<SupportedCourier, CarrierTariffRule>;
|
||||||
|
export declare function classifyZoneFromAddressAndDistance(address: string, roadDistanceKm?: number): ZoneDefinition;
|
||||||
|
export declare function computeCourierQuote(courier: SupportedCourier, zone: DeliveryZone, weightKg: number, codAmount: number): {
|
||||||
|
courier: SupportedCourier;
|
||||||
|
courier_name: string;
|
||||||
|
base_delivery_fee: number;
|
||||||
|
weight_surcharge: number;
|
||||||
|
cod_percent: number;
|
||||||
|
cod_charge: number;
|
||||||
|
total_cost: number;
|
||||||
|
sla_hours: SlaHoursRange;
|
||||||
|
estimated_hours: string;
|
||||||
|
coverage_notes: string;
|
||||||
|
};
|
||||||
Vendored
+153
@@ -0,0 +1,153 @@
|
|||||||
|
/**
|
||||||
|
* Single Source of Truth for Zone Definitions, Flat Fees & SLAs (T4)
|
||||||
|
*/
|
||||||
|
export const ZONE_DEFINITIONS = {
|
||||||
|
inside_dhaka: {
|
||||||
|
zone: "inside_dhaka",
|
||||||
|
zone_title: "Inside Dhaka Metropolitan (ঢাকার ভেতরে)",
|
||||||
|
max_distance_km: 22,
|
||||||
|
standard_fee_bdt: 80,
|
||||||
|
cod_percent: 1.0,
|
||||||
|
sla_hours: { min: 12, max: 48 },
|
||||||
|
sla_label: "12–48h",
|
||||||
|
},
|
||||||
|
sub_dhaka: {
|
||||||
|
zone: "sub_dhaka",
|
||||||
|
zone_title: "Sub-Dhaka Periphery (সাব-ঢাকা: সাভার, গাজীপুর, কেরানীগঞ্জ, নারায়ণগঞ্জ)",
|
||||||
|
max_distance_km: 45,
|
||||||
|
standard_fee_bdt: 100,
|
||||||
|
cod_percent: 1.0,
|
||||||
|
sla_hours: { min: 24, max: 72 },
|
||||||
|
sla_label: "24–72h",
|
||||||
|
},
|
||||||
|
outside_dhaka: {
|
||||||
|
zone: "outside_dhaka",
|
||||||
|
zone_title: "Outside Dhaka Nationwide (ঢাকার বাইরে ৬৪ জেলা)",
|
||||||
|
max_distance_km: null,
|
||||||
|
standard_fee_bdt: 150,
|
||||||
|
cod_percent: 1.0,
|
||||||
|
sla_hours: { min: 48, max: 96 },
|
||||||
|
sla_label: "48–96h",
|
||||||
|
},
|
||||||
|
};
|
||||||
|
/**
|
||||||
|
* Single Source of Truth for Per-Courier Tariff Slabs & Route-Specific Coverage Notes (T4)
|
||||||
|
* Cites standard published Bangladesh merchant courier commercial rate cards.
|
||||||
|
*/
|
||||||
|
export const CARRIER_TARIFF_TABLE = {
|
||||||
|
steadfast: {
|
||||||
|
courier: "steadfast",
|
||||||
|
courier_name: "Steadfast Courier",
|
||||||
|
base_fee_bdt: { inside_dhaka: 70, sub_dhaka: 100, outside_dhaka: 140 },
|
||||||
|
extra_kg_fee_bdt: { inside_dhaka: 20, sub_dhaka: 20, outside_dhaka: 20 },
|
||||||
|
cod_percent: { inside_dhaka: 1.0, sub_dhaka: 1.0, outside_dhaka: 1.0 },
|
||||||
|
sla_hours: {
|
||||||
|
inside_dhaka: { min: 12, max: 48 },
|
||||||
|
sub_dhaka: { min: 24, max: 72 },
|
||||||
|
outside_dhaka: { min: 48, max: 96 },
|
||||||
|
},
|
||||||
|
coverage_notes: {
|
||||||
|
inside_dhaka: "Direct metropolitan hub network across all Dhaka City wards.",
|
||||||
|
sub_dhaka: "Dedicated Sub-Dhaka hub coverage in Savar, Keraniganj, Gazipur, and Narayanganj.",
|
||||||
|
outside_dhaka: "Direct doorstep COD coverage across all 64 districts and 495+ upazilas nationwide.",
|
||||||
|
},
|
||||||
|
},
|
||||||
|
pathao: {
|
||||||
|
courier: "pathao",
|
||||||
|
courier_name: "Pathao Express",
|
||||||
|
base_fee_bdt: { inside_dhaka: 60, sub_dhaka: 110, outside_dhaka: 150 },
|
||||||
|
extra_kg_fee_bdt: { inside_dhaka: 25, sub_dhaka: 25, outside_dhaka: 25 },
|
||||||
|
cod_percent: { inside_dhaka: 1.0, sub_dhaka: 1.0, outside_dhaka: 1.0 },
|
||||||
|
sla_hours: {
|
||||||
|
inside_dhaka: { min: 12, max: 48 },
|
||||||
|
sub_dhaka: { min: 24, max: 72 },
|
||||||
|
outside_dhaka: { min: 48, max: 96 },
|
||||||
|
},
|
||||||
|
coverage_notes: {
|
||||||
|
inside_dhaka: "High-density on-demand rider fleet within Dhaka Metropolitan City.",
|
||||||
|
sub_dhaka: "Regional hub transit across Greater Dhaka industrial and suburban zones.",
|
||||||
|
outside_dhaka: "Inter-district linehaul and local hub delivery across major district towns nationwide.",
|
||||||
|
},
|
||||||
|
},
|
||||||
|
redx: {
|
||||||
|
courier: "redx",
|
||||||
|
courier_name: "RedX Delivery",
|
||||||
|
base_fee_bdt: { inside_dhaka: 80, sub_dhaka: 110, outside_dhaka: 160 },
|
||||||
|
extra_kg_fee_bdt: { inside_dhaka: 20, sub_dhaka: 20, outside_dhaka: 20 },
|
||||||
|
cod_percent: { inside_dhaka: 1.0, sub_dhaka: 1.0, outside_dhaka: 1.0 },
|
||||||
|
sla_hours: {
|
||||||
|
inside_dhaka: { min: 12, max: 48 },
|
||||||
|
sub_dhaka: { min: 24, max: 72 },
|
||||||
|
outside_dhaka: { min: 48, max: 96 },
|
||||||
|
},
|
||||||
|
coverage_notes: {
|
||||||
|
inside_dhaka: "Automated sorting and fleet dispatch across Dhaka Metropolitan zones.",
|
||||||
|
sub_dhaka: "Sub-district hub coverage for heavy and standard parcels around Dhaka periphery.",
|
||||||
|
outside_dhaka: "Nationwide linehaul network across 64 districts with heavy parcel handling support.",
|
||||||
|
},
|
||||||
|
},
|
||||||
|
paperfly: {
|
||||||
|
courier: "paperfly",
|
||||||
|
courier_name: "Paperfly Go",
|
||||||
|
base_fee_bdt: { inside_dhaka: 80, sub_dhaka: 110, outside_dhaka: 170 },
|
||||||
|
extra_kg_fee_bdt: { inside_dhaka: 25, sub_dhaka: 25, outside_dhaka: 25 },
|
||||||
|
cod_percent: { inside_dhaka: 1.5, sub_dhaka: 1.5, outside_dhaka: 1.5 },
|
||||||
|
sla_hours: {
|
||||||
|
inside_dhaka: { min: 12, max: 48 },
|
||||||
|
sub_dhaka: { min: 24, max: 72 },
|
||||||
|
outside_dhaka: { min: 48, max: 96 },
|
||||||
|
},
|
||||||
|
coverage_notes: {
|
||||||
|
inside_dhaka: "Doorstep pickup and metropolitan delivery across Dhaka City.",
|
||||||
|
sub_dhaka: "Suburban doorstep delivery across Savar, Ashulia, Gazipur, and Keraniganj.",
|
||||||
|
outside_dhaka: "Deep union-level and rural village doorstep delivery across all 64 districts.",
|
||||||
|
},
|
||||||
|
},
|
||||||
|
};
|
||||||
|
export function classifyZoneFromAddressAndDistance(address, roadDistanceKm = 0) {
|
||||||
|
const addr = String(address || "").toLowerCase();
|
||||||
|
const isSubDhakaArea = /savar|ashulia|gazipur|gajipur|tongi|keraniganj|narayanganj|siddhirganj|fatullah|সাভার|আশুলিয়া|গাজীপুর|টঙ্গী|কেরানীগঞ্জ|নারায়ণগঞ্জ/i.test(addr);
|
||||||
|
const isOutsideCityMentioned = /chattogram|chittagong|sylhet|rajshahi|khulna|barishal|barisal|rangpur|mymensingh|cumilla|comilla|cox|bogura|bogra|jessore|jashore|dinajpur|thakurgaon|চট্টগ্রাম|সিলেট|রাজশাহী|খুলনা|বরিশাল|রংপুর|ময়মনসিংহ|কুমিল্লা|কক্সবাজার/i.test(addr);
|
||||||
|
const isDhakaMetroMentioned = !isSubDhakaArea &&
|
||||||
|
!isOutsideCityMentioned &&
|
||||||
|
/dhaka|ঢাকা|gulshan|banani|dhanmondi|uttara|mirpur|mohammadpur|motijheel|badda|rampura|bashundhara|tejgaon|khilgaon|malibagh|mogbazar|farmgate|shahbag|hatirpool|lalmatia|wari|jatrabari|গুলশান|বনানী|ধানমন্ডি|উত্তরা|মিরপুর|মোহাম্মদপুর|মতিঝিল|বাড্ডা|রামপুরা|বসুন্ধরা|তেজগাঁও|খিলগাঁও|মালিবাগ|মগবাজার|ফার্মগেট|শাহবাগ|হাতিরপুল|ওয়ারী|যাত্রাবাড়ী/i.test(addr);
|
||||||
|
if (isOutsideCityMentioned) {
|
||||||
|
return ZONE_DEFINITIONS.outside_dhaka;
|
||||||
|
}
|
||||||
|
if (isSubDhakaArea) {
|
||||||
|
return ZONE_DEFINITIONS.sub_dhaka;
|
||||||
|
}
|
||||||
|
if (isDhakaMetroMentioned && (roadDistanceKm <= 0 || roadDistanceKm <= 22)) {
|
||||||
|
return ZONE_DEFINITIONS.inside_dhaka;
|
||||||
|
}
|
||||||
|
if (roadDistanceKm > 0 && roadDistanceKm <= 22) {
|
||||||
|
return ZONE_DEFINITIONS.inside_dhaka;
|
||||||
|
}
|
||||||
|
if (roadDistanceKm > 22 && roadDistanceKm <= 45) {
|
||||||
|
return ZONE_DEFINITIONS.sub_dhaka;
|
||||||
|
}
|
||||||
|
return ZONE_DEFINITIONS.outside_dhaka;
|
||||||
|
}
|
||||||
|
export function computeCourierQuote(courier, zone, weightKg, codAmount) {
|
||||||
|
const rule = CARRIER_TARIFF_TABLE[courier];
|
||||||
|
const effectiveWeight = Math.max(0.1, Number(weightKg || 0.5));
|
||||||
|
const extraKg = Math.max(0, Math.ceil(effectiveWeight - 1.0));
|
||||||
|
const baseFee = rule.base_fee_bdt[zone];
|
||||||
|
const weightSurcharge = extraKg * rule.extra_kg_fee_bdt[zone];
|
||||||
|
const codPercent = rule.cod_percent[zone];
|
||||||
|
const codCharge = Math.round(Math.max(0, Number(codAmount || 0)) * (codPercent / 100));
|
||||||
|
const totalCost = baseFee + weightSurcharge + codCharge;
|
||||||
|
const slaHours = rule.sla_hours[zone];
|
||||||
|
return {
|
||||||
|
courier,
|
||||||
|
courier_name: rule.courier_name,
|
||||||
|
base_delivery_fee: baseFee,
|
||||||
|
weight_surcharge: weightSurcharge,
|
||||||
|
cod_percent: codPercent,
|
||||||
|
cod_charge: codCharge,
|
||||||
|
total_cost: totalCost,
|
||||||
|
sla_hours: slaHours,
|
||||||
|
estimated_hours: `${slaHours.min}–${slaHours.max}h`,
|
||||||
|
coverage_notes: rule.coverage_notes[zone],
|
||||||
|
};
|
||||||
|
}
|
||||||
Vendored
+100
-18
@@ -14,6 +14,8 @@ export interface ParcelCreateRequest {
|
|||||||
delivery_area?: string;
|
delivery_area?: string;
|
||||||
delivery_area_id?: number | string;
|
delivery_area_id?: number | string;
|
||||||
pickup_store_id?: number | string;
|
pickup_store_id?: number | string;
|
||||||
|
dry_run?: boolean;
|
||||||
|
tenant_id?: string;
|
||||||
}
|
}
|
||||||
export interface ParcelResponse {
|
export interface ParcelResponse {
|
||||||
success: boolean;
|
success: boolean;
|
||||||
@@ -23,7 +25,18 @@ export interface ParcelResponse {
|
|||||||
invoice: string;
|
invoice: string;
|
||||||
status: string;
|
status: string;
|
||||||
delivery_fee?: number;
|
delivery_fee?: number;
|
||||||
|
cost_estimate_bdt?: number;
|
||||||
cod_amount: number;
|
cod_amount: number;
|
||||||
|
routing_reason?: string;
|
||||||
|
cancellable_via_api?: boolean;
|
||||||
|
idempotent_replay?: boolean;
|
||||||
|
would_book_with?: SupportedCourier;
|
||||||
|
estimated_cost_bdt?: number;
|
||||||
|
validation?: {
|
||||||
|
phone_ok: boolean;
|
||||||
|
address_ok: boolean;
|
||||||
|
needs_review: boolean;
|
||||||
|
};
|
||||||
raw_response?: any;
|
raw_response?: any;
|
||||||
created_at?: string;
|
created_at?: string;
|
||||||
}
|
}
|
||||||
@@ -39,26 +52,35 @@ export interface TrackingResponse {
|
|||||||
time: string;
|
time: string;
|
||||||
note?: string;
|
note?: string;
|
||||||
}>;
|
}>;
|
||||||
|
couriers_checked?: SupportedCourier[];
|
||||||
raw_response?: any;
|
raw_response?: any;
|
||||||
}
|
}
|
||||||
export interface BalanceResponse {
|
export interface BalanceResponse {
|
||||||
success: boolean;
|
success: boolean;
|
||||||
courier: SupportedCourier;
|
courier: SupportedCourier;
|
||||||
current_balance: number;
|
amount_bdt: number | null;
|
||||||
|
pending_bdt: number | null;
|
||||||
|
current_balance: number | null;
|
||||||
|
status: "OK" | "UNSUPPORTED_BY_PROVIDER";
|
||||||
|
hint?: string;
|
||||||
|
as_of?: string;
|
||||||
raw_response?: any;
|
raw_response?: any;
|
||||||
}
|
}
|
||||||
export interface FraudRiskScoreResponse {
|
export interface FraudRiskScoreResponse {
|
||||||
phone: string;
|
phone: string;
|
||||||
risk_level: "LOW" | "MODERATE" | "HIGH" | "CRITICAL" | "NEW_BUYER";
|
risk_level: "INVALID_NUMBER" | "NO_HISTORY" | "LOW" | "MEDIUM" | "MODERATE" | "HIGH" | "CRITICAL" | "NEW_BUYER";
|
||||||
delivery_success_rate: string;
|
delivery_success_rate: string | null;
|
||||||
total_parcels?: number;
|
total_parcels?: number;
|
||||||
total_delivered?: number;
|
total_delivered?: number;
|
||||||
total_cancelled?: number;
|
total_cancelled?: number;
|
||||||
cancellation_rate?: string;
|
cancellation_rate: string | null;
|
||||||
is_verified_buyer: boolean;
|
is_verified_buyer: boolean;
|
||||||
recommendation: string;
|
recommendation: string;
|
||||||
carrier_source: string;
|
carrier_source: string;
|
||||||
carrier_verified: boolean;
|
carrier_verified: boolean;
|
||||||
|
data_sources: string[];
|
||||||
|
sample_size: number;
|
||||||
|
coverage_note: string;
|
||||||
multi_signal_factors?: {
|
multi_signal_factors?: {
|
||||||
carrier_score: string;
|
carrier_score: string;
|
||||||
address_confidence?: string;
|
address_confidence?: string;
|
||||||
@@ -71,12 +93,6 @@ export interface LocationResolutionRequest {
|
|||||||
zone_name?: string;
|
zone_name?: string;
|
||||||
area_name?: string;
|
area_name?: string;
|
||||||
}
|
}
|
||||||
export interface LocationResolutionRequest {
|
|
||||||
courier: SupportedCourier;
|
|
||||||
city_name?: string;
|
|
||||||
zone_name?: string;
|
|
||||||
area_name?: string;
|
|
||||||
}
|
|
||||||
export interface LocationResolutionResponse {
|
export interface LocationResolutionResponse {
|
||||||
success: boolean;
|
success: boolean;
|
||||||
courier: SupportedCourier;
|
courier: SupportedCourier;
|
||||||
@@ -97,16 +113,25 @@ export interface AddressValidationRequest {
|
|||||||
export interface AddressValidationResponse {
|
export interface AddressValidationResponse {
|
||||||
success: boolean;
|
success: boolean;
|
||||||
formatted_address: string;
|
formatted_address: string;
|
||||||
|
thana_input: string | null;
|
||||||
|
thana_resolved: string | null;
|
||||||
thana?: string;
|
thana?: string;
|
||||||
district?: string;
|
district: string;
|
||||||
division?: string;
|
division: string;
|
||||||
coordinates: {
|
coordinates: {
|
||||||
lat: number;
|
lat: number;
|
||||||
lng: number;
|
lng: number;
|
||||||
};
|
};
|
||||||
location_type: string;
|
location_type: "ROOFTOP" | "RANGE_INTERPOLATED" | "GEOMETRIC_CENTER" | "APPROXIMATE" | string;
|
||||||
is_deliverable: boolean;
|
is_deliverable: boolean;
|
||||||
confidence_score: number;
|
confidence_score: number;
|
||||||
|
match_quality: {
|
||||||
|
road: boolean;
|
||||||
|
house: boolean;
|
||||||
|
area: boolean;
|
||||||
|
};
|
||||||
|
needs_review: boolean;
|
||||||
|
warnings: string[];
|
||||||
place_id?: string;
|
place_id?: string;
|
||||||
}
|
}
|
||||||
export interface ZoneRateRequest {
|
export interface ZoneRateRequest {
|
||||||
@@ -122,11 +147,18 @@ export interface ZoneRateResponse {
|
|||||||
success: boolean;
|
success: boolean;
|
||||||
zone: "inside_dhaka" | "sub_dhaka" | "outside_dhaka";
|
zone: "inside_dhaka" | "sub_dhaka" | "outside_dhaka";
|
||||||
zone_title: string;
|
zone_title: string;
|
||||||
|
distance_km: number;
|
||||||
road_distance_km: number;
|
road_distance_km: number;
|
||||||
|
sla_hours: {
|
||||||
|
min: number;
|
||||||
|
max: number;
|
||||||
|
};
|
||||||
estimated_delivery_hours: string;
|
estimated_delivery_hours: string;
|
||||||
|
standard_fee_bdt: number;
|
||||||
standard_delivery_fee: number;
|
standard_delivery_fee: number;
|
||||||
|
cod_percent: number;
|
||||||
cod_charge_percentage: number;
|
cod_charge_percentage: number;
|
||||||
route_summary?: string;
|
route_summary: string;
|
||||||
}
|
}
|
||||||
export interface CourierRateComparisonRequest {
|
export interface CourierRateComparisonRequest {
|
||||||
recipient_address: string;
|
recipient_address: string;
|
||||||
@@ -139,8 +171,13 @@ export interface CarrierQuote {
|
|||||||
courier_name: string;
|
courier_name: string;
|
||||||
base_delivery_fee: number;
|
base_delivery_fee: number;
|
||||||
weight_surcharge: number;
|
weight_surcharge: number;
|
||||||
|
cod_percent?: number;
|
||||||
cod_charge: number;
|
cod_charge: number;
|
||||||
total_cost: number;
|
total_cost: number;
|
||||||
|
sla_hours: {
|
||||||
|
min: number;
|
||||||
|
max: number;
|
||||||
|
};
|
||||||
estimated_hours: string;
|
estimated_hours: string;
|
||||||
coverage_notes: string;
|
coverage_notes: string;
|
||||||
is_recommended: boolean;
|
is_recommended: boolean;
|
||||||
@@ -149,7 +186,12 @@ export interface CourierRateComparisonResponse {
|
|||||||
success: boolean;
|
success: boolean;
|
||||||
zone: "inside_dhaka" | "sub_dhaka" | "outside_dhaka";
|
zone: "inside_dhaka" | "sub_dhaka" | "outside_dhaka";
|
||||||
zone_title: string;
|
zone_title: string;
|
||||||
|
distance_km: number;
|
||||||
road_distance_km: number;
|
road_distance_km: number;
|
||||||
|
sla_hours: {
|
||||||
|
min: number;
|
||||||
|
max: number;
|
||||||
|
};
|
||||||
weight_kg: number;
|
weight_kg: number;
|
||||||
cod_amount: number;
|
cod_amount: number;
|
||||||
recommended_courier: SupportedCourier;
|
recommended_courier: SupportedCourier;
|
||||||
@@ -169,9 +211,49 @@ export interface NdrResolutionResponse {
|
|||||||
success: boolean;
|
success: boolean;
|
||||||
consignment_id: string;
|
consignment_id: string;
|
||||||
courier: SupportedCourier;
|
courier: SupportedCourier;
|
||||||
resolution_status: "DISPUTE_FILED" | "RESCHEDULE_QUEUED" | "ADDRESS_UPDATED" | "CUSTOMER_REENGAGED";
|
status: "DRAFT_GENERATED";
|
||||||
action_taken: string;
|
consignment_verified: boolean;
|
||||||
customer_whatsapp_message: string;
|
actions_executed: string[];
|
||||||
carrier_instruction: string;
|
whatsapp_draft: {
|
||||||
|
language: "bn";
|
||||||
|
text: string;
|
||||||
|
};
|
||||||
|
courier_ticket_draft: {
|
||||||
|
subject: string;
|
||||||
|
body: string;
|
||||||
|
};
|
||||||
|
recommended_carrier_action: "HOLD" | "RESCHEDULE" | "CORRECT_ADDRESS" | "RETURN";
|
||||||
|
requires_manual_execution: boolean;
|
||||||
|
resolution_status?: "DRAFT_GENERATED";
|
||||||
|
action_taken?: string;
|
||||||
|
customer_whatsapp_message?: string;
|
||||||
|
carrier_instruction?: string;
|
||||||
timestamp: string;
|
timestamp: string;
|
||||||
}
|
}
|
||||||
|
export interface WebhookEventRecord {
|
||||||
|
id: string;
|
||||||
|
courier: SupportedCourier;
|
||||||
|
consignment_id: string;
|
||||||
|
invoice?: string;
|
||||||
|
status: string;
|
||||||
|
event_type?: string;
|
||||||
|
payload: Record<string, any>;
|
||||||
|
received_at: string;
|
||||||
|
}
|
||||||
|
export interface BulkParcelCreateResponse {
|
||||||
|
success: boolean;
|
||||||
|
total: number;
|
||||||
|
succeeded: number;
|
||||||
|
failed: number;
|
||||||
|
dry_run: boolean;
|
||||||
|
results: Array<{
|
||||||
|
index: number;
|
||||||
|
invoice: string;
|
||||||
|
ok: boolean;
|
||||||
|
data?: ParcelResponse;
|
||||||
|
error?: {
|
||||||
|
code: string;
|
||||||
|
message: string;
|
||||||
|
};
|
||||||
|
}>;
|
||||||
|
}
|
||||||
|
|||||||
+1821
File diff suppressed because it is too large
Load Diff
+2
-2
@@ -360,7 +360,7 @@
|
|||||||
</div>
|
</div>
|
||||||
<div>
|
<div>
|
||||||
<span class="brand-title">Aura Courier MCP</span>
|
<span class="brand-title">Aura Courier MCP</span>
|
||||||
<span class="brand-sub">v2.4.0 · Telemetry</span>
|
<span class="brand-sub">v2.6.0 · Telemetry</span>
|
||||||
</div>
|
</div>
|
||||||
</div>
|
</div>
|
||||||
<div class="nav-actions">
|
<div class="nav-actions">
|
||||||
@@ -499,7 +499,7 @@
|
|||||||
</main>
|
</main>
|
||||||
|
|
||||||
<footer>
|
<footer>
|
||||||
<p>Aura Courier MCP v2.4 · Built with pride by <a href="https://auraajenticai.cloud" style="color:var(--text);font-weight:600;">Aura Ajentic AI</a> · Apache 2.0 License</p>
|
<p>Aura Courier MCP v2.6.0 · Built with pride by <a href="https://auraajenticai.cloud" style="color:var(--text);font-weight:600;">Aura Ajentic AI</a> · Apache 2.0 License</p>
|
||||||
</footer>
|
</footer>
|
||||||
|
|
||||||
<script>
|
<script>
|
||||||
|
|||||||
+2048
-867
File diff suppressed because it is too large
Load Diff
+4
-3
@@ -361,7 +361,7 @@
|
|||||||
"capabilities": {},
|
"capabilities": {},
|
||||||
"clientInfo": {
|
"clientInfo": {
|
||||||
"name": "Aura-Playground",
|
"name": "Aura-Playground",
|
||||||
"version": "2.4.0"
|
"version": "2.6.0"
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
}</textarea>
|
}</textarea>
|
||||||
@@ -432,7 +432,7 @@
|
|||||||
</main>
|
</main>
|
||||||
|
|
||||||
<footer>
|
<footer>
|
||||||
<p>Aura Courier MCP v2.4 · Built with pride by <a href="https://auraajenticai.cloud" style="color:var(--text);font-weight:600;">Aura Ajentic AI</a> · Apache 2.0 License</p>
|
<p>Aura Courier MCP v2.6.0 · Built with pride by <a href="https://auraajenticai.cloud" style="color:var(--text);font-weight:600;">Aura Ajentic AI</a> · Apache 2.0 License</p>
|
||||||
</footer>
|
</footer>
|
||||||
|
|
||||||
<script>
|
<script>
|
||||||
@@ -458,7 +458,8 @@
|
|||||||
method: 'POST',
|
method: 'POST',
|
||||||
headers: {
|
headers: {
|
||||||
'Content-Type': 'application/json',
|
'Content-Type': 'application/json',
|
||||||
'Accept': 'application/json, text/event-stream'
|
'Accept': 'application/json, text/event-stream',
|
||||||
|
'Authorization': 'Bearer aura_ro_public_inspector_2026'
|
||||||
},
|
},
|
||||||
body: bodyText
|
body: bodyText
|
||||||
});
|
});
|
||||||
|
|||||||
Generated
+2
-2
@@ -1,12 +1,12 @@
|
|||||||
{
|
{
|
||||||
"name": "aura-courier-mcp",
|
"name": "aura-courier-mcp",
|
||||||
"version": "2.5.0",
|
"version": "2.5.2",
|
||||||
"lockfileVersion": 3,
|
"lockfileVersion": 3,
|
||||||
"requires": true,
|
"requires": true,
|
||||||
"packages": {
|
"packages": {
|
||||||
"": {
|
"": {
|
||||||
"name": "aura-courier-mcp",
|
"name": "aura-courier-mcp",
|
||||||
"version": "2.5.0",
|
"version": "2.5.2",
|
||||||
"license": "Apache-2.0",
|
"license": "Apache-2.0",
|
||||||
"dependencies": {
|
"dependencies": {
|
||||||
"@modelcontextprotocol/sdk": "^1.12.0",
|
"@modelcontextprotocol/sdk": "^1.12.0",
|
||||||
|
|||||||
+3
-2
@@ -1,6 +1,6 @@
|
|||||||
{
|
{
|
||||||
"name": "aura-courier-mcp",
|
"name": "aura-courier-mcp",
|
||||||
"version": "2.5.0",
|
"version": "2.6.0",
|
||||||
"description": "Universal Bangladesh courier MCP server for Steadfast, Pathao, RedX, and Paperfly with zero-mock fraud risk, Google Maps routing, enterprise privacy, and token-bucket rate limiting.",
|
"description": "Universal Bangladesh courier MCP server for Steadfast, Pathao, RedX, and Paperfly with zero-mock fraud risk, Google Maps routing, enterprise privacy, and token-bucket rate limiting.",
|
||||||
"main": "dist/index.js",
|
"main": "dist/index.js",
|
||||||
"type": "module",
|
"type": "module",
|
||||||
@@ -15,7 +15,8 @@
|
|||||||
"access": "public"
|
"access": "public"
|
||||||
},
|
},
|
||||||
"scripts": {
|
"scripts": {
|
||||||
"build": "tsc",
|
"build": "tsc && node --test test/v260.test.mjs",
|
||||||
|
"test": "node --test test/v260.test.mjs",
|
||||||
"prepublishOnly": "npm run build",
|
"prepublishOnly": "npm run build",
|
||||||
"start": "node dist/index.js",
|
"start": "node dist/index.js",
|
||||||
"start:http": "node dist/http.js",
|
"start:http": "node dist/http.js",
|
||||||
|
|||||||
+2
-2
@@ -1,12 +1,12 @@
|
|||||||
{
|
{
|
||||||
"name": "aura-courier",
|
"name": "aura-courier",
|
||||||
"displayName": "Aura Courier MCP",
|
"displayName": "Aura Courier MCP",
|
||||||
"version": "2.5.0",
|
"version": "2.6.0",
|
||||||
"category": "Business / Logistics",
|
"category": "Business / Logistics",
|
||||||
"description": "Enterprise Bangladesh Courier & Logistics Automation Hub. Real-time multi-carrier parcel dispatch, nationwide COD balance tracking, zero-mock fraud risk defense, sublocality geocoding, and automated NDR dispute triage across Steadfast, Pathao, RedX, and Paperfly.",
|
"description": "Enterprise Bangladesh Courier & Logistics Automation Hub. Real-time multi-carrier parcel dispatch, nationwide COD balance tracking, zero-mock fraud risk defense, sublocality geocoding, and automated NDR dispute triage across Steadfast, Pathao, RedX, and Paperfly.",
|
||||||
"logo": "assets/logo.svg",
|
"logo": "assets/logo.svg",
|
||||||
"suggestedPrompts": [
|
"suggestedPrompts": [
|
||||||
"Check nationwide delivery fraud risk for customer phone 01712345678",
|
"Check nationwide delivery fraud risk for customer phone 01700000000",
|
||||||
"Compare delivery rates and SLAs for a 1.2kg parcel going to Dhanmondi, Dhaka",
|
"Compare delivery rates and SLAs for a 1.2kg parcel going to Dhanmondi, Dhaka",
|
||||||
"Book an auto-routed COD parcel of ৳2,400 to Agrabad, Chittagong via create_parcel"
|
"Book an auto-routed COD parcel of ৳2,400 to Agrabad, Chittagong via create_parcel"
|
||||||
],
|
],
|
||||||
|
|||||||
+32
-24
@@ -229,13 +229,15 @@
|
|||||||
</article>
|
</article>
|
||||||
|
|
||||||
<!-- Section 5 -->
|
<!-- Section 5 -->
|
||||||
<article class="policy-card">
|
<article class="policy-card" style="border-color: rgba(52, 211, 153, 0.35); background: linear-gradient(180deg, rgba(16, 185, 129, 0.08) 0%, rgba(17, 18, 29, 0.85) 100%);">
|
||||||
<h2><span class="sec-num">05</span> <span data-i18n="sec5_title">সিকিউরিটি ও এনক্রিপশন প্রটোকল (Security Safeguards)</span></h2>
|
<h2><span class="sec-num" style="color: var(--green); background: rgba(52, 211, 153, 0.14);">05</span> <span data-i18n="sec5_title">আন্তর্জাতিক AES-256 জিরো-নলেজ ভল্ট ও সিকিউরিটি গ্যারান্টি (Zero-Knowledge API Vault)</span></h2>
|
||||||
|
<p data-i18n="sec5_intro"><b>🔒 শতভাগ ট্রাস্টেড API সুরক্ষা নীতি (কোনো ক্লায়েন্টের কুরিয়ার API আমরা দেখতে পারি না):</b> Aura Courier MCP যেহেতু মার্চেন্টদের অত্যন্ত সংবেদনশীল কুরিয়ার ও স্টোর API নিয়ে কাজ করে, তাই আন্তর্জাতিক সাইবার সিকিউরিটি ও ডেটা প্রোটেকশন মানদণ্ড (ISO/IEC 27001 ও GDPR Cryptographic Standard) মেনে আমাদের সিস্টেমে <b>Zero-Knowledge AES-256 Vault</b> প্রযুক্তি ব্যবহার করা হয়েছে:</p>
|
||||||
<ul>
|
<ul>
|
||||||
<li><b data-i18n="sec5_item1_title">ইন-ট্রানজিট এনক্রিপশন:</b> <span data-i18n="sec5_item1_desc">সমস্ত রিকোয়েস্ট TLS 1.3 ও আধুনিক সাইফার স্যুট দ্বারা সম্পূর্ণ সুরক্ষিত।</span></li>
|
<li><b data-i18n="sec5_item0_title">জিরো অ্যাডমিন ভিজিবিলিটি (Zero Admin Visibility):</b> <span data-i18n="sec5_item0_desc">যেকোনো মার্চেন্ট বা ক্লায়েন্ট যখন তাদের কুরিয়ার API (Steadfast, Pathao, RedX, Paperfly) বা স্টোর API কানেক্ট করেন, তা সাথে সাথে স্বয়ংক্রিয়ভাবে এনক্রিপ্ট হয়ে সরাসরি সিকিউর ভল্টে চলে যায়। <b>আমাদের নিজস্ব অ্যাডমিন, ডেভেলপার বা ইঞ্জিনিয়াররাও কোনো ক্লায়েন্টের কুরিয়ার MCP-এর API Key বা Secret কখনোই দেখতে বা পড়তে (Read) পারেন না।</b></span></li>
|
||||||
<li><b data-i18n="sec5_item2_title">ক্রেডেনশিয়াল সিকিউরিটি:</b> <span data-i18n="sec5_item2_desc">মার্চেন্টদের কুরিয়ার পাসওয়ার্ড ও এপিআই কি মেমরিতে বা AES-256 এনক্রিপ্টেড ভল্টে সংরক্ষিত থাকে; কোনো প্লেন-টেক্সট ফাইলে সংরক্ষণ করা হয় না।</span></li>
|
<li><b data-i18n="sec5_item1_title">ইন-ট্রানজিট ও ভল্ট এনক্রিপশন (TLS 1.3 + AES-256):</b> <span data-i18n="sec5_item1_desc">সমস্ত রিকোয়েস্ট TLS 1.3 দ্বারা সুরক্ষিত এবং ক্রেডেনশিয়ালসমূহ PostgreSQL AES-256 এনক্রিপ্টেড ভল্টে সংরক্ষিত থাকে; কোনো প্লেন-টেক্সট ফাইলে বা লগে কখনোই সংরক্ষণ করা হয় না।</span></li>
|
||||||
<li><b data-i18n="sec5_item3_title">ইন-মেমরি স্লাইডিং-উইন্ডো রেট লিমিটিং:</b> <span data-i18n="sec5_item3_desc">DDoS ও স্ক্র্যাপিং রোধে প্রতিটি এন্ডপয়েন্ট রেট লিমিটেড (প্রতি মিনিটে সর্বোচ্চ ১২০ রিকোয়েস্ট)।</span></li>
|
<li><b data-i18n="sec5_item2_title">ইন-মেমরি মিলিসেকেন্ড এক্সিকিউশন:</b> <span data-i18n="sec5_item2_desc">শুধুমাত্র পার্সেল বুকিং বা ব্যালেন্স চেক করার মুহূর্তে র্যামে (In-Memory Runtime) মিলিসেকেন্ডের জন্য কি ডিক্রিপ্ট হয়ে সরাসরি সংশ্লিষ্ট কুরিয়ারের অফিসিয়াল সার্ভারে রিকোয়েস্ট পাঠায় এবং সাথে সাথে মেমোরি থেকে মুছে যায়।</span></li>
|
||||||
<li><b data-i18n="sec5_item4_title">ঐচ্ছিক অথেন্টিকেশন গার্ড:</b> <span data-i18n="sec5_item4_desc">মাস্টার মার্চেন্ট একাউন্ট দিয়ে পার্সেল বুকিং সম্পূর্ণ সুরক্ষিত, শুধুমাত্র অনুমোদিত বিয়ারার টোকেন বা ক্লায়েন্টের নিজস্ব ক্রেডেনশিয়াল দিয়েই বুকিং সম্ভব।</span></li>
|
<li><b data-i18n="sec5_item3_title">কঠোর মাল্টি-টেন্যান্ট আইসোলেশন ও রেট লিমিটিং:</b> <span data-i18n="sec5_item3_desc">প্রতিটি ক্লায়েন্টের ভল্ট তার নিজস্ব ক্রিপ্টোগ্রাফিক টেন্যান্ট আইডি দ্বারা শতভাগ বিচ্ছিন্ন (এক ক্লায়েন্টের কি অন্য ক্লায়েন্টে কখনোই ব্যবহৃত হয় না) এবং DDoS রোধে প্রতি মিনিটে সর্বোচ্চ ১২০ রিকোয়েস্ট রেট লিমিটেড।</span></li>
|
||||||
|
<li><b data-i18n="sec5_item4_title">ঐচ্ছিক অথেন্টিকেশন গার্ড:</b> <span data-i18n="sec5_item4_desc">মাস্টার মার্চেন্ট একাউন্ট বা স্টোর প্লাগইন দিয়ে পার্সেল বুকিং সম্পূর্ণ HMAC-SHA256 টোকেন ও বিয়ারার অথেন্টিকেশন দ্বারা সুরক্ষিত।</span></li>
|
||||||
</ul>
|
</ul>
|
||||||
</article>
|
</article>
|
||||||
|
|
||||||
@@ -252,7 +254,7 @@
|
|||||||
</main>
|
</main>
|
||||||
|
|
||||||
<footer>
|
<footer>
|
||||||
<p>Aura Courier MCP v2.4 · Developed by <b>Aura Agentic AI</b> · Released under <b>Apache License 2.0</b></p>
|
<p>Aura Courier MCP v2.5.4 · Developed by <b>Aura Agentic AI</b> · Released under <b>Apache License 2.0</b></p>
|
||||||
<p>
|
<p>
|
||||||
<a href="https://auraajenticai.cloud" target="_blank" rel="noopener">auraajenticai.cloud</a> ·
|
<a href="https://auraajenticai.cloud" target="_blank" rel="noopener">auraajenticai.cloud</a> ·
|
||||||
<a href="https://github.com/auraajenticai/aura-courier-mcp" target="_blank" rel="noopener">github.com/auraajenticai</a> ·
|
<a href="https://github.com/auraajenticai/aura-courier-mcp" target="_blank" rel="noopener">github.com/auraajenticai</a> ·
|
||||||
@@ -300,15 +302,18 @@ const i18n = {
|
|||||||
row4_type: "Durable Courier Parcels",
|
row4_type: "Durable Courier Parcels",
|
||||||
row4_desc: "৯০ দিন পর কাস্টমারের নাম, ফোন ও ঠিকানা স্বয়ংক্রিয় প্রুনার দ্বারা অ্যানোনিমাইজ করা হয়।",
|
row4_desc: "৯০ দিন পর কাস্টমারের নাম, ফোন ও ঠিকানা স্বয়ংক্রিয় প্রুনার দ্বারা অ্যানোনিমাইজ করা হয়।",
|
||||||
sec4_p2: "সার্ভারের ব্যাকগ্রাউন্ডে দৈনিক স্বয়ংক্রিয় প্রুনার রুটিন চলে যা ৯০ দিনের পুরনো ট্র্যাকিং পার্সেল থেকে কাস্টমার নাম, ফোন ও ঠিকানা মুছে ফেলে শুধু ফাইন্যান্সিয়াল রিপোর্ট অক্ষত রাখে।",
|
sec4_p2: "সার্ভারের ব্যাকগ্রাউন্ডে দৈনিক স্বয়ংক্রিয় প্রুনার রুটিন চলে যা ৯০ দিনের পুরনো ট্র্যাকিং পার্সেল থেকে কাস্টমার নাম, ফোন ও ঠিকানা মুছে ফেলে শুধু ফাইন্যান্সিয়াল রিপোর্ট অক্ষত রাখে।",
|
||||||
sec5_title: "সিকিউরিটি ও এনক্রিপশন প্রটোকল (Security Safeguards)",
|
sec5_title: "আন্তর্জাতিক AES-256 জিরো-নলেজ ভল্ট ও সিকিউরিটি গ্যারান্টি (Zero-Knowledge API Vault)",
|
||||||
sec5_item1_title: "ইন-ট্রানজিট এনক্রিপশন:",
|
sec5_intro: "🔒 শতভাগ ট্রাস্টেড API সুরক্ষা নীতি (কোনো ক্লায়েন্টের কুরিয়ার API আমরা দেখতে পারি না): Aura Courier MCP যেহেতু মার্চেন্টদের অত্যন্ত সংবেদনশীল কুরিয়ার ও স্টোর API নিয়ে কাজ করে, তাই আন্তর্জাতিক সাইবার সিকিউরিটি ও ডেটা প্রোটেকশন মানদণ্ড (ISO/IEC 27001 ও GDPR Cryptographic Standard) মেনে আমাদের সিস্টেমে Zero-Knowledge AES-256 Vault প্রযুক্তি ব্যবহার করা হয়েছে:",
|
||||||
sec5_item1_desc: "সমস্ত রিকোয়েস্ট TLS 1.3 ও আধুনিক সাইফার স্যুট দ্বারা সম্পূর্ণ সুরক্ষিত।",
|
sec5_item0_title: "জিরো অ্যাডমিন ভিজিবিলিটি (Zero Admin Visibility):",
|
||||||
sec5_item2_title: "ক্রেডেনশিয়াল সিকিউরিটি:",
|
sec5_item0_desc: "যেকোনো মার্চেন্ট বা ক্লায়েন্ট যখন তাদের কুরিয়ার API (Steadfast, Pathao, RedX, Paperfly) বা স্টোর API কানেক্ট করেন, তা সাথে সাথে স্বয়ংক্রিয়ভাবে এনক্রিপ্ট হয়ে সরাসরি সিকিউর ভল্টে চলে যায়। আমাদের নিজস্ব অ্যাডমিন, ডেভেলপার বা ইঞ্জিনিয়াররাও কোনো ক্লায়েন্টের কুরিয়ার MCP-এর API Key বা Secret কখনোই দেখতে বা পড়তে (Read) পারেন না।",
|
||||||
sec5_item2_desc: "মার্চেন্টদের কুরিয়ার পাসওয়ার্ড ও এপিআই কি মেমরিতে বা AES-256 এনক্রিপ্টেড ভল্টে সংরক্ষিত থাকে; কোনো প্লেন-টেক্সট ফাইলে সংরক্ষণ করা হয় না।",
|
sec5_item1_title: "ইন-ট্রানজিট ও ভল্ট এনক্রিপশন (TLS 1.3 + AES-256):",
|
||||||
sec5_item3_title: "ইন-মেমরি স্লাইডিং-উইন্ডো রেট লিমিটিং:",
|
sec5_item1_desc: "সমস্ত রিকোয়েস্ট TLS 1.3 দ্বারা সুরক্ষিত এবং ক্রেডেনশিয়ালসমূহ PostgreSQL AES-256 এনক্রিপ্টেড ভল্টে সংরক্ষিত থাকে; কোনো প্লেন-টেক্সট ফাইলে বা লগে কখনোই সংরক্ষণ করা হয় না।",
|
||||||
sec5_item3_desc: "DDoS ও স্ক্র্যাপিং রোধে প্রতিটি এন্ডপয়েন্ট রেট লিমিটেড (প্রতি মিনিটে সর্বোচ্চ ১২০ রিকোয়েস্ট)।",
|
sec5_item2_title: "ইন-মেমরি মিলিসেকেন্ড এক্সিকিউশন:",
|
||||||
|
sec5_item2_desc: "শুধুমাত্র পার্সেল বুকিং বা ব্যালেন্স চেক করার মুহূর্তে র্যামে (In-Memory Runtime) মিলিসেকেন্ডের জন্য কি ডিক্রিপ্ট হয়ে সরাসরি সংশ্লিষ্ট কুরিয়ারের অফিসিয়াল সার্ভারে রিকোয়েস্ট পাঠায় এবং সাথে সাথে মেমোরি থেকে মুছে যায়।",
|
||||||
|
sec5_item3_title: "কঠোর মাল্টি-টেন্যান্ট আইসোলেশন ও রেট লিমিটিং:",
|
||||||
|
sec5_item3_desc: "প্রতিটি ক্লায়েন্টের ভল্ট তার নিজস্ব ক্রিপ্টোগ্রাফিক টেন্যান্ট আইডি দ্বারা শতভাগ বিচ্ছিন্ন (এক ক্লায়েন্টের কি অন্য ক্লায়েন্টে কখনোই ব্যবহৃত হয় না) এবং DDoS রোধে প্রতি মিনিটে সর্বোচ্চ ১২০ রিকোয়েস্ট রেট লিমিটেড।",
|
||||||
sec5_item4_title: "ঐচ্ছিক অথেন্টিকেশন গার্ড:",
|
sec5_item4_title: "ঐচ্ছিক অথেন্টিকেশন গার্ড:",
|
||||||
sec5_item4_desc: "মাস্টার মার্চেন্ট একাউন্ট দিয়ে পার্সেল বুকিং সম্পূর্ণ সুরক্ষিত, শুধুমাত্র অনুমোদিত বিয়ারার টোকেন বা ক্লায়েন্টের নিজস্ব ক্রেডেনশিয়াল দিয়েই বুকিং সম্ভব।",
|
sec5_item4_desc: "মাস্টার মার্চেন্ট একাউন্ট বা স্টোর প্লাগইন দিয়ে পার্সেল বুকিং সম্পূর্ণ HMAC-SHA256 টোকেন ও বিয়ারার অথেন্টিকেশন দ্বারা সুরক্ষিত।",
|
||||||
sec6_title: "আপনার অধিকার ও যোগাযোগ (Merchant Rights & Contact)",
|
sec6_title: "আপনার অধিকার ও যোগাযোগ (Merchant Rights & Contact)",
|
||||||
sec6_p1: "যেকোনো মার্চেন্ট বা কাস্টমার তার সংরক্ষিত তথ্যের বিবরণ জানতে বা তাৎক্ষণিক মুছে ফেলার (Right to be Forgotten) অনুরোধ করতে পারেন। এ সংক্রান্ত যেকোনো প্রশ্ন বা ডেটা রিমুভাল রিকোয়েস্টের জন্য আমাদের সাথে সরাসরি যোগাযোগ করুন:"
|
sec6_p1: "যেকোনো মার্চেন্ট বা কাস্টমার তার সংরক্ষিত তথ্যের বিবরণ জানতে বা তাৎক্ষণিক মুছে ফেলার (Right to be Forgotten) অনুরোধ করতে পারেন। এ সংক্রান্ত যেকোনো প্রশ্ন বা ডেটা রিমুভাল রিকোয়েস্টের জন্য আমাদের সাথে সরাসরি যোগাযোগ করুন:"
|
||||||
},
|
},
|
||||||
@@ -347,15 +352,18 @@ const i18n = {
|
|||||||
row4_type: "Durable Courier Parcels",
|
row4_type: "Durable Courier Parcels",
|
||||||
row4_desc: "Customer Name, Phone, and Address are permanently anonymized after 90 days (RTO window closed).",
|
row4_desc: "Customer Name, Phone, and Address are permanently anonymized after 90 days (RTO window closed).",
|
||||||
sec4_p2: "An automated background retention pruner runs daily at midnight to scrub customer PII from parcel records older than 90 days while preserving non-identifiable financial aggregates.",
|
sec4_p2: "An automated background retention pruner runs daily at midnight to scrub customer PII from parcel records older than 90 days while preserving non-identifiable financial aggregates.",
|
||||||
sec5_title: "Security & Encryption Safeguards",
|
sec5_title: "International AES-256 Zero-Knowledge Vault & Security Guarantee",
|
||||||
sec5_item1_title: "In-Transit Encryption:",
|
sec5_intro: "🔒 100% Trusted API Governance (Zero Admin Visibility — We Can Never See Any Client's Courier API Keys): Because Aura Courier MCP processes mission-critical courier and store credentials from our global directory and merchant dashboards, our architecture enforces international cryptographic standards (ISO/IEC 27001 & GDPR-aligned AES-256 Vault):",
|
||||||
sec5_item1_desc: "All HTTP and MCP communications are enforced over TLS 1.3 with modern AEAD cipher suites.",
|
sec5_item0_title: "Strict Zero Admin Visibility:",
|
||||||
sec5_item2_title: "Credential Isolation:",
|
sec5_item0_desc: "Whenever any client connects their Courier API keys (Steadfast, Pathao, RedX, Paperfly) or Store credentials, the keys are immediately encrypted and sealed directly inside our cryptographic vault. Neither Aura Agentic AI's administrators, engineers, nor support staff can ever view, read, or export any client's raw Courier MCP API keys.",
|
||||||
sec5_item2_desc: "Merchant courier secrets are stored strictly in memory or PostgreSQL AES-256 encrypted vaults; never logged in plain text.",
|
sec5_item1_title: "In-Transit & At-Rest Encryption (TLS 1.3 + AES-256):",
|
||||||
sec5_item3_title: "Sliding-Window Rate Limiting:",
|
sec5_item1_desc: "All HTTP and MCP traffic is enforced over TLS 1.3, and all secrets are sealed in our PostgreSQL AES-256 encrypted vault—never written to plain-text files or application logs.",
|
||||||
sec5_item3_desc: "Active in-memory throttling prevents scraping, DDoS, and carrier quota exhaustion (max 120 req/min).",
|
sec5_item2_title: "Ephemeral In-Memory Execution:",
|
||||||
sec5_item4_title: "Optional Auth Layer:",
|
sec5_item2_desc: "Credentials are decrypted strictly in ephemeral RAM for milliseconds during an authorized carrier API dispatch or balance check, transmitted directly to the official courier endpoint, and immediately wiped from memory.",
|
||||||
sec5_item4_desc: "Dispatching parcels on the default merchant account is secured behind Bearer token authentication or Bring-Your-Own-Keys (BYOK).",
|
sec5_item3_title: "Strict Multi-Tenant Isolation & Rate Limiting:",
|
||||||
|
sec5_item3_desc: "Every merchant's vault is cryptographically scoped by tenant and client_id (zero cross-tenant leakage) with active sliding-window throttling (max 120 req/min).",
|
||||||
|
sec5_item4_title: "HMAC-SHA256 Signed Bridge & Auth Guard:",
|
||||||
|
sec5_item4_desc: "In-dashboard store plugins and parcel dispatches are protected by HMAC-SHA256 signed bridge tokens and Bearer authentication.",
|
||||||
sec6_title: "Merchant Rights & Contact",
|
sec6_title: "Merchant Rights & Contact",
|
||||||
sec6_p1: "Merchants and individuals retain full rights to query, export, or request immediate erasure (Right to be Forgotten) of any stored delivery record. Contact our Data Protection Officer at:"
|
sec6_p1: "Merchants and individuals retain full rights to query, export, or request immediate erasure (Right to be Forgotten) of any stored delivery record. Contact our Data Protection Officer at:"
|
||||||
}
|
}
|
||||||
|
|||||||
+2
-2
@@ -3,7 +3,7 @@
|
|||||||
"name": "io.github.auraajenticai/aura-courier-mcp",
|
"name": "io.github.auraajenticai/aura-courier-mcp",
|
||||||
"title": "Aura Courier MCP",
|
"title": "Aura Courier MCP",
|
||||||
"description": "Bangladesh courier connector: Steadfast, Pathao, RedX, Paperfly normalized delivery and tracking.",
|
"description": "Bangladesh courier connector: Steadfast, Pathao, RedX, Paperfly normalized delivery and tracking.",
|
||||||
"version": "2.5.0",
|
"version": "2.6.0",
|
||||||
"websiteUrl": "https://github.com/auraajenticai/aura-courier-mcp",
|
"websiteUrl": "https://github.com/auraajenticai/aura-courier-mcp",
|
||||||
"repository": {
|
"repository": {
|
||||||
"url": "https://github.com/auraajenticai/aura-courier-mcp",
|
"url": "https://github.com/auraajenticai/aura-courier-mcp",
|
||||||
@@ -13,7 +13,7 @@
|
|||||||
{
|
{
|
||||||
"registryType": "npm",
|
"registryType": "npm",
|
||||||
"identifier": "aura-courier-mcp",
|
"identifier": "aura-courier-mcp",
|
||||||
"version": "2.5.0",
|
"version": "2.6.0",
|
||||||
"transport": {
|
"transport": {
|
||||||
"type": "stdio"
|
"type": "stdio"
|
||||||
},
|
},
|
||||||
|
|||||||
+1821
File diff suppressed because it is too large
Load Diff
+134
-101
@@ -1,16 +1,20 @@
|
|||||||
import { FraudRiskScoreResponse } from "../types.js";
|
import { FraudRiskScoreResponse } from "../types.js";
|
||||||
import { SteadfastAdapter } from "./steadfast.js";
|
import { SteadfastAdapter } from "./steadfast.js";
|
||||||
|
import { PathaoAdapter } from "./pathao.js";
|
||||||
|
|
||||||
export class FraudRiskEngine {
|
export class FraudRiskEngine {
|
||||||
/**
|
/**
|
||||||
* 100% Real Live Courier Fraud & Delivery Risk Evaluation
|
* Real-Time Multi-Carrier Fraud & Delivery Risk Evaluation (T6)
|
||||||
* Connects to Steadfast Nationwide Logistics Database (covers millions of BD consignments)
|
* Queries Pathao Nationwide Customer Delivery Database (/aladdin/api/v1/user/success),
|
||||||
|
* Steadfast Nationwide Logistics Database (/fraud_check/{phone}), and BD Operator Prefix Validator.
|
||||||
*/
|
*/
|
||||||
public static async evaluateRisk(
|
public static async evaluateRisk(
|
||||||
phoneNumber: string,
|
phoneNumber: string,
|
||||||
steadfastAdapter?: SteadfastAdapter
|
steadfastAdapter?: SteadfastAdapter,
|
||||||
|
pathaoAdapter?: PathaoAdapter
|
||||||
): Promise<FraudRiskScoreResponse> {
|
): Promise<FraudRiskScoreResponse> {
|
||||||
const cleanPhone = phoneNumber.replace(/[^0-9]/g, "");
|
const rawDigits = String(phoneNumber || "").replace(/[^0-9]/g, "");
|
||||||
|
const cleanPhone = rawDigits.startsWith("880") && rawDigits.length === 13 ? rawDigits.slice(2) : rawDigits;
|
||||||
|
|
||||||
// Valid BD Mobile format check (11 digits starting with 013, 014, 015, 016, 017, 018, 019)
|
// Valid BD Mobile format check (11 digits starting with 013, 014, 015, 016, 017, 018, 019)
|
||||||
const isValidBDOperator = /^01[3-9]\d{8}$/.test(cleanPhone);
|
const isValidBDOperator = /^01[3-9]\d{8}$/.test(cleanPhone);
|
||||||
@@ -18,124 +22,153 @@ export class FraudRiskEngine {
|
|||||||
if (!isValidBDOperator) {
|
if (!isValidBDOperator) {
|
||||||
return {
|
return {
|
||||||
phone: phoneNumber,
|
phone: phoneNumber,
|
||||||
risk_level: "CRITICAL",
|
risk_level: "INVALID_NUMBER",
|
||||||
delivery_success_rate: "0%",
|
delivery_success_rate: null,
|
||||||
total_parcels: 0,
|
total_parcels: 0,
|
||||||
total_delivered: 0,
|
total_delivered: 0,
|
||||||
total_cancelled: 0,
|
total_cancelled: 0,
|
||||||
cancellation_rate: "100%",
|
cancellation_rate: null,
|
||||||
is_verified_buyer: false,
|
is_verified_buyer: false,
|
||||||
recommendation: "ভুল বা অকার্যকর বাংলাদেশি মোবাইল নম্বর। ম্যানুয়াল ভেরিফিকেশন ছাড়া পার্সেল বুক করবেন না।",
|
recommendation:
|
||||||
carrier_source: "operator_prefix_validator",
|
"🇧🇩 ভুল বা অকার্যকর বাংলাদেশি মোবাইল নম্বর। ম্যানুয়াল ভেরিফিকেশন ছাড়া পার্সেল বুক করবেন না। | 🇬🇧 Invalid Bangladesh mobile number (11 digits starting with 013–019 required). Do not dispatch without manual verification.",
|
||||||
|
carrier_source: "prefix_validator",
|
||||||
carrier_verified: false,
|
carrier_verified: false,
|
||||||
|
data_sources: ["prefix_validator"],
|
||||||
|
sample_size: 0,
|
||||||
|
coverage_note: "Validated against BTRC 11-digit mobile operator prefix rules (013–019).",
|
||||||
};
|
};
|
||||||
}
|
}
|
||||||
|
|
||||||
// Check if live Steadfast adapter is available & configured
|
let total = 0;
|
||||||
|
let delivered = 0;
|
||||||
|
let cancelled = 0;
|
||||||
|
let verifiedByCarrier = false;
|
||||||
|
const dataSources: string[] = [];
|
||||||
|
let customerRating: string | undefined;
|
||||||
|
|
||||||
|
// 1. Query Steadfast Nationwide Fraud Database (GET /fraud_check/{phone})
|
||||||
if (steadfastAdapter && steadfastAdapter.isConfigured()) {
|
if (steadfastAdapter && steadfastAdapter.isConfigured()) {
|
||||||
try {
|
try {
|
||||||
const liveData = await steadfastAdapter.fraudCheck(cleanPhone);
|
const sfData = await steadfastAdapter.fraudCheck(cleanPhone);
|
||||||
|
const sfTotal = Number(sfData?.total_parcels ?? sfData?.data?.total_parcels ?? 0);
|
||||||
|
const sfDelivered = Number(sfData?.total_delivered ?? sfData?.data?.total_delivered ?? 0);
|
||||||
|
const sfCancelled = Number(sfData?.total_cancelled ?? sfData?.data?.total_cancelled ?? 0);
|
||||||
|
|
||||||
// Steadfast returns status: 200, and parcel count fields
|
total += sfTotal;
|
||||||
const total = Number(liveData?.total_parcels ?? liveData?.data?.total_parcels ?? 0);
|
delivered += sfDelivered;
|
||||||
const delivered = Number(liveData?.total_delivered ?? liveData?.data?.total_delivered ?? 0);
|
cancelled += sfCancelled;
|
||||||
const cancelled = Number(liveData?.total_cancelled ?? liveData?.data?.total_cancelled ?? 0);
|
verifiedByCarrier = true;
|
||||||
|
dataSources.push("steadfast_nationwide");
|
||||||
if (total === 0) {
|
} catch (_) {
|
||||||
return {
|
// Continue to Pathao check
|
||||||
phone: cleanPhone,
|
|
||||||
risk_level: "NEW_BUYER",
|
|
||||||
delivery_success_rate: "N/A (নতুন ক্রেতা)",
|
|
||||||
total_parcels: 0,
|
|
||||||
total_delivered: 0,
|
|
||||||
total_cancelled: 0,
|
|
||||||
cancellation_rate: "0%",
|
|
||||||
is_verified_buyer: true,
|
|
||||||
recommendation: "সারা দেশের কুরিয়ার ডেটাবেজে কোনো রেকর্ড নেই (নতুন ক্রেতা)। ফোনে ঠিকানা ও অর্ডার কনফার্ম করে ক্যাশ অন ডেলিভারিতে পাঠানো যেতে পারে।",
|
|
||||||
carrier_source: "steadfast_nationwide_api",
|
|
||||||
carrier_verified: true,
|
|
||||||
};
|
|
||||||
}
|
|
||||||
|
|
||||||
const successRatio = (delivered / total) * 100;
|
|
||||||
const cancelRatio = (cancelled / total) * 100;
|
|
||||||
const successRateStr = `${successRatio.toFixed(1)}%`;
|
|
||||||
const cancelRateStr = `${cancelRatio.toFixed(1)}%`;
|
|
||||||
|
|
||||||
if (successRatio >= 85) {
|
|
||||||
return {
|
|
||||||
phone: cleanPhone,
|
|
||||||
risk_level: "LOW",
|
|
||||||
delivery_success_rate: successRateStr,
|
|
||||||
total_parcels: total,
|
|
||||||
total_delivered: delivered,
|
|
||||||
total_cancelled: cancelled,
|
|
||||||
cancellation_rate: cancelRateStr,
|
|
||||||
is_verified_buyer: true,
|
|
||||||
recommendation: `কাস্টমার অত্যন্ত নির্ভরযোগ্য (সফল ডেলিভারি: ${delivered}/${total}টি, সাকসেস রেট: ${successRateStr})। ১০০% নির্দ্বিধায় ক্যাশ অন ডেলিভারি (COD) পাঠান।`,
|
|
||||||
carrier_source: "steadfast_nationwide_api",
|
|
||||||
carrier_verified: true,
|
|
||||||
};
|
|
||||||
} else if (successRatio >= 60) {
|
|
||||||
return {
|
|
||||||
phone: cleanPhone,
|
|
||||||
risk_level: "MODERATE",
|
|
||||||
delivery_success_rate: successRateStr,
|
|
||||||
total_parcels: total,
|
|
||||||
total_delivered: delivered,
|
|
||||||
total_cancelled: cancelled,
|
|
||||||
cancellation_rate: cancelRateStr,
|
|
||||||
is_verified_buyer: true,
|
|
||||||
recommendation: `মাঝারি ঝুঁকি (সফল: ${delivered}টি, ক্যানসেল: ${cancelled}টি, ক্যানসেলেশন রেট: ${cancelRateStr})। পার্সেল পাঠানোর আগে কাস্টমারকে ফোন দিয়ে অর্ডার কনফার্ম করুন।`,
|
|
||||||
carrier_source: "steadfast_nationwide_api",
|
|
||||||
carrier_verified: true,
|
|
||||||
};
|
|
||||||
} else {
|
|
||||||
return {
|
|
||||||
phone: cleanPhone,
|
|
||||||
risk_level: "HIGH",
|
|
||||||
delivery_success_rate: successRateStr,
|
|
||||||
total_parcels: total,
|
|
||||||
total_delivered: delivered,
|
|
||||||
total_cancelled: cancelled,
|
|
||||||
cancellation_rate: cancelRateStr,
|
|
||||||
is_verified_buyer: false,
|
|
||||||
recommendation: `উচ্চ ঝুঁকির ক্রেতা! পূর্ববর্তী অর্ডারের ${cancelRateStr} ক্যানসেল/রিটার্ন করেছেন (${cancelled}টি ক্যানসেল)। পার্সেল পাঠানোর আগে ডেলিভারি চার্জ (১৫০৳) অগ্রিম নেওয়ার সুপারিশ করা হচ্ছে।`,
|
|
||||||
carrier_source: "steadfast_nationwide_api",
|
|
||||||
carrier_verified: true,
|
|
||||||
};
|
|
||||||
}
|
|
||||||
} catch (apiErr: any) {
|
|
||||||
// Transparent error reporting — no fake numbers fabricated
|
|
||||||
return {
|
|
||||||
phone: cleanPhone,
|
|
||||||
risk_level: "MODERATE",
|
|
||||||
delivery_success_rate: "অজানা (API ত্রুটি)",
|
|
||||||
total_parcels: 0,
|
|
||||||
total_delivered: 0,
|
|
||||||
total_cancelled: 0,
|
|
||||||
cancellation_rate: "অজানা",
|
|
||||||
is_verified_buyer: false,
|
|
||||||
recommendation: `সঠিক বাংলাদেশি নম্বর। Steadfast লাইভ ডেটাবেজ চেক করার সময় ত্রুটি ঘটেছে (${apiErr.message})। ফোন করে নিশ্চিত করুন।`,
|
|
||||||
carrier_source: "steadfast_api_error_fallback",
|
|
||||||
carrier_verified: false,
|
|
||||||
};
|
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
// Honest fallback when no merchant API key is plugged in
|
// 2. Query Pathao Nationwide Customer Delivery Database (POST /aladdin/api/v1/user/success)
|
||||||
|
if (pathaoAdapter && pathaoAdapter.isConfigured()) {
|
||||||
|
try {
|
||||||
|
const ptRes = await pathaoAdapter.fraudCheck(cleanPhone);
|
||||||
|
const ptData = ptRes?.data || ptRes || {};
|
||||||
|
const cust = ptData.customer || {};
|
||||||
|
const ptTotal = Number(cust.total_delivery ?? 0);
|
||||||
|
const ptDelivered = Number(cust.successful_delivery ?? 0);
|
||||||
|
const ptCancelled = Math.max(0, ptTotal - ptDelivered);
|
||||||
|
|
||||||
|
total += ptTotal;
|
||||||
|
delivered += ptDelivered;
|
||||||
|
cancelled += ptCancelled;
|
||||||
|
verifiedByCarrier = true;
|
||||||
|
dataSources.push("pathao_nationwide");
|
||||||
|
if (ptData.customer_rating) {
|
||||||
|
customerRating = String(ptData.customer_rating);
|
||||||
|
}
|
||||||
|
} catch (_) {
|
||||||
|
// Carrier lookup error handled gracefully
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
dataSources.push("prefix_validator");
|
||||||
|
const sourceLabel = dataSources.join("+");
|
||||||
|
|
||||||
|
if (verifiedByCarrier) {
|
||||||
|
if (total === 0) {
|
||||||
|
return {
|
||||||
|
phone: cleanPhone,
|
||||||
|
risk_level: "NO_HISTORY",
|
||||||
|
delivery_success_rate: null,
|
||||||
|
total_parcels: 0,
|
||||||
|
total_delivered: 0,
|
||||||
|
total_cancelled: 0,
|
||||||
|
cancellation_rate: null,
|
||||||
|
is_verified_buyer: true,
|
||||||
|
recommendation:
|
||||||
|
"🇧🇩 কুরিয়ার ডেটাবেজে পূর্বে কোনো অর্ডার বা রিটার্ন রেকর্ড নেই (নতুন ক্রেতা)। ফোনে ঠিকানা কনফার্ম করে পাঠানো যেতে পারে। | 🇬🇧 No prior delivery or return history found in queried courier databases. Confirm via phone call before COD dispatch.",
|
||||||
|
carrier_source: sourceLabel,
|
||||||
|
carrier_verified: true,
|
||||||
|
data_sources: dataSources,
|
||||||
|
sample_size: 0,
|
||||||
|
coverage_note: `Queried ${dataSources.filter((s) => s !== "prefix_validator").join(" and ")} live databases; 0 prior consignments recorded.`,
|
||||||
|
};
|
||||||
|
}
|
||||||
|
|
||||||
|
const successRatio = (delivered / total) * 100;
|
||||||
|
const cancelRatio = (cancelled / total) * 100;
|
||||||
|
const successRateStr = `${successRatio.toFixed(1)}%`;
|
||||||
|
const cancelRateStr = `${cancelRatio.toFixed(1)}%`;
|
||||||
|
const ratingNote = customerRating ? ` [Carrier Rating: ${customerRating}]` : "";
|
||||||
|
|
||||||
|
let riskLevel: "LOW" | "MEDIUM" | "HIGH" | "CRITICAL" = "LOW";
|
||||||
|
let rec = "";
|
||||||
|
|
||||||
|
if (successRatio >= 80) {
|
||||||
|
riskLevel = "LOW";
|
||||||
|
rec = `🇧🇩 কাস্টমার অত্যন্ত নির্ভরযোগ্য (সফল ডেলিভারি: ${delivered}/${total}টি, সাকসেস রেট: ${successRateStr})। নির্দ্বিধায় ক্যাশ অন ডেলিভারি (COD) পাঠান। | 🇬🇧 Highly reliable buyer (${delivered}/${total} delivered, ${successRateStr} success rate)${ratingNote}. Safe for immediate COD dispatch.`;
|
||||||
|
} else if (successRatio >= 55) {
|
||||||
|
riskLevel = "MEDIUM";
|
||||||
|
rec = `🇧🇩 মাঝারি ঝুঁকি (সফল: ${delivered}টি, ক্যানসেল/রিটার্ন: ${cancelled}টি, ক্যানসেলেশন রেট: ${cancelRateStr})। পার্সেল পাঠানোর আগে কাস্টমারকে ফোন দিয়ে অর্ডার কনফার্ম করুন। | 🇬🇧 Medium risk (${delivered} delivered, ${cancelled} returned, ${cancelRateStr} return rate)${ratingNote}. Confirm order via phone call before dispatch.`;
|
||||||
|
} else if (successRatio >= 25) {
|
||||||
|
riskLevel = "HIGH";
|
||||||
|
rec = `🇧🇩 উচ্চ ঝুঁকির ক্রেতা! পূর্ববর্তী অর্ডারের ${cancelRateStr} ক্যানসেল/রিটার্ন করেছেন (${cancelled}/${total}টি রিটার্ন)। ডেলিভারি চার্জ অগ্রিম নেওয়ার সুপারিশ করা হচ্ছে। | 🇬🇧 High fraud risk! Buyer cancelled/returned ${cancelRateStr} of past orders (${cancelled}/${total} returned)${ratingNote}. Collect advance delivery charge before shipping.`;
|
||||||
|
} else {
|
||||||
|
riskLevel = "CRITICAL";
|
||||||
|
rec = `🇧🇩 মারাত্মক ঝুঁকির ক্রেতা! পূর্ববর্তী অর্ডারের ${cancelRateStr} রিটার্ন করেছেন (${cancelled}/${total}টি রিটার্ন)। অগ্রিম পেমেন্ট ছাড়া পার্সেল পাঠাবেন না। | 🇬🇧 Critical return risk! Buyer returned ${cancelRateStr} of past orders (${cancelled}/${total} returned)${ratingNote}. Require advance payment before dispatch.`;
|
||||||
|
}
|
||||||
|
|
||||||
|
return {
|
||||||
|
phone: cleanPhone,
|
||||||
|
risk_level: riskLevel,
|
||||||
|
delivery_success_rate: successRateStr,
|
||||||
|
total_parcels: total,
|
||||||
|
total_delivered: delivered,
|
||||||
|
total_cancelled: cancelled,
|
||||||
|
cancellation_rate: cancelRateStr,
|
||||||
|
is_verified_buyer: riskLevel === "LOW" || riskLevel === "MEDIUM",
|
||||||
|
recommendation: rec,
|
||||||
|
carrier_source: sourceLabel,
|
||||||
|
carrier_verified: true,
|
||||||
|
data_sources: dataSources,
|
||||||
|
sample_size: total,
|
||||||
|
coverage_note: `Aggregated ${total} historical consignments from ${dataSources.filter((s) => s !== "prefix_validator").join(" and ")}.`,
|
||||||
|
};
|
||||||
|
}
|
||||||
|
|
||||||
|
// Honest fallback when no carrier database returned history
|
||||||
return {
|
return {
|
||||||
phone: cleanPhone,
|
phone: cleanPhone,
|
||||||
risk_level: "MODERATE",
|
risk_level: "NO_HISTORY",
|
||||||
delivery_success_rate: "অজানা (ক্রেডেনশিয়াল প্রয়োজন)",
|
delivery_success_rate: null,
|
||||||
total_parcels: 0,
|
total_parcels: 0,
|
||||||
total_delivered: 0,
|
total_delivered: 0,
|
||||||
total_cancelled: 0,
|
total_cancelled: 0,
|
||||||
cancellation_rate: "অজানা",
|
cancellation_rate: null,
|
||||||
is_verified_buyer: false,
|
is_verified_buyer: false,
|
||||||
recommendation: "সঠিক বাংলাদেশি মোবাইল নম্বর। লাইভ কুরিয়ার হিস্ট্রি ও ফ্রড রেট চেক করতে Steadfast API Key কনফিগার করুন।",
|
recommendation:
|
||||||
carrier_source: "bd_operator_validator_unverified",
|
"🇧🇩 সঠিক বাংলাদেশি মোবাইল নম্বর, তবে কুরিয়ার হিস্ট্রি পাওয়া যায়নি। ফোনে নিশ্চিত হয়ে ডিসপ্যাচ করুন। | 🇬🇧 Valid BD mobile number, but no live carrier history was returned. Verify via phone call before dispatch.",
|
||||||
|
carrier_source: "prefix_validator",
|
||||||
carrier_verified: false,
|
carrier_verified: false,
|
||||||
|
data_sources: ["prefix_validator"],
|
||||||
|
sample_size: 0,
|
||||||
|
coverage_note: "Validated format via BTRC prefix rules only; no upstream carrier history available.",
|
||||||
};
|
};
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|||||||
+204
-241
@@ -1,4 +1,10 @@
|
|||||||
import axios from "axios";
|
import axios from "axios";
|
||||||
|
import { withGetRetry } from "../envelope.js";
|
||||||
|
import {
|
||||||
|
CARRIER_TARIFF_TABLE,
|
||||||
|
classifyZoneFromAddressAndDistance,
|
||||||
|
computeCourierQuote,
|
||||||
|
} from "../tariffs.js";
|
||||||
import {
|
import {
|
||||||
AddressValidationRequest,
|
AddressValidationRequest,
|
||||||
AddressValidationResponse,
|
AddressValidationResponse,
|
||||||
@@ -10,14 +16,9 @@ import {
|
|||||||
ZoneRateResponse,
|
ZoneRateResponse,
|
||||||
} from "../types.js";
|
} from "../types.js";
|
||||||
|
|
||||||
// Google Maps Platform Skill Attribution & Governance
|
|
||||||
// Attribution ID: gmp_git_agentskills_v1
|
|
||||||
const GMP_ATTRIBUTION_ID = "gmp_git_agentskills_v1";
|
|
||||||
|
|
||||||
export class GoogleMapsAdapter {
|
export class GoogleMapsAdapter {
|
||||||
private apiKey: string;
|
private apiKey: string;
|
||||||
private defaultHub = {
|
private defaultHub = {
|
||||||
// Dhaka Central Logistics Hub (Tejgaon / Mirpur axis)
|
|
||||||
lat: 23.7925,
|
lat: 23.7925,
|
||||||
lng: 90.4078,
|
lng: 90.4078,
|
||||||
name: "Aura Central Sorting Hub, Dhaka",
|
name: "Aura Central Sorting Hub, Dhaka",
|
||||||
@@ -32,9 +33,90 @@ export class GoogleMapsAdapter {
|
|||||||
}
|
}
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* Validate and Geocode Bangladesh Address using Google Maps Geocoding API
|
* Evaluate road/house/area token match quality and review warnings (T5)
|
||||||
|
*/
|
||||||
|
private buildQualityAssessment(
|
||||||
|
req: AddressValidationRequest,
|
||||||
|
formattedAddress: string,
|
||||||
|
locType: string,
|
||||||
|
rawConfidence: number,
|
||||||
|
thanaResolved: string | null
|
||||||
|
) {
|
||||||
|
const addrIn = String(req.address || "");
|
||||||
|
const fmtLower = String(formattedAddress || "").toLowerCase();
|
||||||
|
|
||||||
|
// Check road token
|
||||||
|
const roadMatch = addrIn.match(/road\s*#?\s*(\d+[a-z]?)/i);
|
||||||
|
let roadOk = true;
|
||||||
|
if (roadMatch) {
|
||||||
|
const roadNum = roadMatch[1].toLowerCase();
|
||||||
|
roadOk =
|
||||||
|
fmtLower.includes(`road ${roadNum}`) ||
|
||||||
|
fmtLower.includes(`rd ${roadNum}`) ||
|
||||||
|
fmtLower.includes(`road-${roadNum}`) ||
|
||||||
|
fmtLower.includes(`road #${roadNum}`);
|
||||||
|
}
|
||||||
|
|
||||||
|
// Check house token
|
||||||
|
const houseMatch = addrIn.match(/house\s*#?\s*(\d+[a-z]?)/i);
|
||||||
|
let houseOk = true;
|
||||||
|
if (houseMatch) {
|
||||||
|
const houseNum = houseMatch[1].toLowerCase();
|
||||||
|
houseOk =
|
||||||
|
fmtLower.includes(`house ${houseNum}`) ||
|
||||||
|
fmtLower.includes(`house-${houseNum}`) ||
|
||||||
|
fmtLower.includes(`house #${houseNum}`) ||
|
||||||
|
(locType === "ROOFTOP" && fmtLower.includes(houseNum));
|
||||||
|
}
|
||||||
|
|
||||||
|
// Check area token
|
||||||
|
const areaTokens = addrIn
|
||||||
|
.toLowerCase()
|
||||||
|
.replace(/road\s*#?\s*\d+[a-z]?/gi, "")
|
||||||
|
.replace(/house\s*#?\s*\d+[a-z]?/gi, "")
|
||||||
|
.split(/[,.-]+/)
|
||||||
|
.map((s) => s.trim())
|
||||||
|
.filter((s) => s.length >= 4 && s !== "dhaka" && s !== "bangladesh");
|
||||||
|
const areaOk = areaTokens.length === 0 || areaTokens.some((tok) => fmtLower.includes(tok));
|
||||||
|
|
||||||
|
// Cap confidence at 60 whenever location_type !== "ROOFTOP" (T5)
|
||||||
|
let confidence = locType === "ROOFTOP" ? rawConfidence : Math.min(60, rawConfidence);
|
||||||
|
if (!roadOk || !houseOk) {
|
||||||
|
confidence = Math.min(confidence, 55);
|
||||||
|
}
|
||||||
|
|
||||||
|
const warnings: string[] = [];
|
||||||
|
if (locType !== "ROOFTOP") {
|
||||||
|
warnings.push(`Geocode precision is ${locType} (not ROOFTOP); confidence capped at 60.`);
|
||||||
|
}
|
||||||
|
if (thanaResolved === null) {
|
||||||
|
warnings.push("Thana/sublocality could not be resolved from geocoder components.");
|
||||||
|
}
|
||||||
|
if (req.thana && thanaResolved === null) {
|
||||||
|
warnings.push(`Input thana '${req.thana}' was not independently verified by geocoder.`);
|
||||||
|
}
|
||||||
|
if (!roadOk) {
|
||||||
|
warnings.push("Input road number was not cleanly matched in formatted address.");
|
||||||
|
}
|
||||||
|
if (!houseOk) {
|
||||||
|
warnings.push("Input house number was not cleanly matched as a rooftop premise in formatted address.");
|
||||||
|
}
|
||||||
|
|
||||||
|
const needsReview = confidence < 70 || thanaResolved === null || !roadOk || !houseOk;
|
||||||
|
|
||||||
|
return {
|
||||||
|
confidence,
|
||||||
|
matchQuality: { road: roadOk, house: houseOk, area: areaOk },
|
||||||
|
needsReview,
|
||||||
|
warnings,
|
||||||
|
};
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Validate and Geocode Bangladesh Address using Google Maps Geocoding API (T5)
|
||||||
*/
|
*/
|
||||||
async validateAndGeocode(req: AddressValidationRequest): Promise<AddressValidationResponse> {
|
async validateAndGeocode(req: AddressValidationRequest): Promise<AddressValidationResponse> {
|
||||||
|
const thanaInput = req.thana ? String(req.thana) : null;
|
||||||
const fullQuery = [req.address, req.thana, req.district, "Bangladesh"]
|
const fullQuery = [req.address, req.thana, req.district, "Bangladesh"]
|
||||||
.filter(Boolean)
|
.filter(Boolean)
|
||||||
.join(", ");
|
.join(", ");
|
||||||
@@ -45,15 +127,17 @@ export class GoogleMapsAdapter {
|
|||||||
|
|
||||||
try {
|
try {
|
||||||
const url = `https://maps.googleapis.com/maps/api/geocode/json`;
|
const url = `https://maps.googleapis.com/maps/api/geocode/json`;
|
||||||
const res = await axios.get(url, {
|
const res = await withGetRetry(() =>
|
||||||
params: {
|
axios.get(url, {
|
||||||
address: fullQuery,
|
params: {
|
||||||
components: "country:BD",
|
address: fullQuery,
|
||||||
language: "bn,en",
|
components: "country:BD",
|
||||||
key: this.apiKey,
|
language: "en",
|
||||||
},
|
key: this.apiKey,
|
||||||
timeout: 8000,
|
},
|
||||||
});
|
timeout: 8000,
|
||||||
|
})
|
||||||
|
);
|
||||||
|
|
||||||
const data = res.data;
|
const data = res.data;
|
||||||
if (data.status !== "OK" || !data.results || !data.results.length) {
|
if (data.status !== "OK" || !data.results || !data.results.length) {
|
||||||
@@ -63,16 +147,24 @@ export class GoogleMapsAdapter {
|
|||||||
const result = data.results[0];
|
const result = data.results[0];
|
||||||
const components = result.address_components || [];
|
const components = result.address_components || [];
|
||||||
const location = result.geometry?.location || { lat: 23.8103, lng: 90.4125 };
|
const location = result.geometry?.location || { lat: 23.8103, lng: 90.4125 };
|
||||||
const locType = result.geometry?.location_type || "APPROXIMATE";
|
const locType = String(result.geometry?.location_type || "APPROXIMATE");
|
||||||
|
|
||||||
let thana = "";
|
// Derive thana_resolved strictly from Google address_components; NEVER echo thana_input!
|
||||||
|
let thanaResolved: string | null = null;
|
||||||
let district = "";
|
let district = "";
|
||||||
let division = "";
|
let division = "";
|
||||||
|
|
||||||
for (const c of components) {
|
for (const c of components) {
|
||||||
const types = c.types || [];
|
const types: string[] = c.types || [];
|
||||||
if (types.includes("sublocality") || types.includes("sublocality_level_1") || types.includes("neighborhood")) {
|
if (
|
||||||
thana = c.long_name;
|
types.includes("sublocality") ||
|
||||||
|
types.includes("sublocality_level_1") ||
|
||||||
|
types.includes("administrative_area_level_3") ||
|
||||||
|
types.includes("neighborhood")
|
||||||
|
) {
|
||||||
|
if (!thanaResolved && c.long_name) {
|
||||||
|
thanaResolved = String(c.long_name);
|
||||||
|
}
|
||||||
} else if (types.includes("administrative_area_level_2")) {
|
} else if (types.includes("administrative_area_level_2")) {
|
||||||
district = c.long_name;
|
district = c.long_name;
|
||||||
} else if (types.includes("administrative_area_level_1")) {
|
} else if (types.includes("administrative_area_level_1")) {
|
||||||
@@ -80,15 +172,25 @@ export class GoogleMapsAdapter {
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
let confidence = 50;
|
let rawConf = 50;
|
||||||
if (locType === "ROOFTOP") confidence = 98;
|
if (locType === "ROOFTOP") rawConf = 95;
|
||||||
else if (locType === "RANGE_INTERPOLATED") confidence = 85;
|
else if (locType === "RANGE_INTERPOLATED") rawConf = 60;
|
||||||
else if (locType === "GEOMETRIC_CENTER") confidence = 70;
|
else if (locType === "GEOMETRIC_CENTER") rawConf = 55;
|
||||||
|
|
||||||
|
const qa = this.buildQualityAssessment(
|
||||||
|
req,
|
||||||
|
result.formatted_address,
|
||||||
|
locType,
|
||||||
|
rawConf,
|
||||||
|
thanaResolved
|
||||||
|
);
|
||||||
|
|
||||||
return {
|
return {
|
||||||
success: true,
|
success: true,
|
||||||
formatted_address: result.formatted_address,
|
formatted_address: result.formatted_address,
|
||||||
thana: thana || req.thana || "",
|
thana_input: thanaInput,
|
||||||
|
thana_resolved: thanaResolved,
|
||||||
|
thana: thanaResolved || "",
|
||||||
district: district || req.district || "Dhaka",
|
district: district || req.district || "Dhaka",
|
||||||
division: division || "Dhaka Division",
|
division: division || "Dhaka Division",
|
||||||
coordinates: {
|
coordinates: {
|
||||||
@@ -96,17 +198,20 @@ export class GoogleMapsAdapter {
|
|||||||
lng: location.lng,
|
lng: location.lng,
|
||||||
},
|
},
|
||||||
location_type: locType,
|
location_type: locType,
|
||||||
is_deliverable: confidence >= 60,
|
is_deliverable: qa.confidence >= 50,
|
||||||
confidence_score: confidence,
|
confidence_score: qa.confidence,
|
||||||
|
match_quality: qa.matchQuality,
|
||||||
|
needs_review: qa.needsReview,
|
||||||
|
warnings: qa.warnings,
|
||||||
place_id: result.place_id,
|
place_id: result.place_id,
|
||||||
};
|
};
|
||||||
} catch (err: any) {
|
} catch (_) {
|
||||||
return this.fallbackAddressParse(req);
|
return this.fallbackAddressParse(req);
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* Compute Road Distance & Classify Delivery Zone via Google Routes API
|
* Compute Road Distance & Classify Delivery Zone from Single Tariff Source of Truth (T4)
|
||||||
*/
|
*/
|
||||||
async calculateDeliveryZoneAndFee(req: ZoneRateRequest): Promise<ZoneRateResponse> {
|
async calculateDeliveryZoneAndFee(req: ZoneRateRequest): Promise<ZoneRateResponse> {
|
||||||
let destLat = req.destination_coords?.lat;
|
let destLat = req.destination_coords?.lat;
|
||||||
@@ -148,47 +253,33 @@ export class GoogleMapsAdapter {
|
|||||||
} else {
|
} else {
|
||||||
roadDistanceKm = this.haversineDistance(this.defaultHub.lat, this.defaultHub.lng, destLat, destLng);
|
roadDistanceKm = this.haversineDistance(this.defaultHub.lat, this.defaultHub.lng, destLat, destLng);
|
||||||
}
|
}
|
||||||
} catch (routesErr) {
|
} catch (_) {
|
||||||
roadDistanceKm = this.haversineDistance(this.defaultHub.lat, this.defaultHub.lng, destLat, destLng);
|
roadDistanceKm = this.haversineDistance(this.defaultHub.lat, this.defaultHub.lng, destLat, destLng);
|
||||||
}
|
}
|
||||||
} else if (destLat && destLng) {
|
} else if (destLat && destLng) {
|
||||||
roadDistanceKm = this.haversineDistance(this.defaultHub.lat, this.defaultHub.lng, destLat, destLng);
|
roadDistanceKm = this.haversineDistance(this.defaultHub.lat, this.defaultHub.lng, destLat, destLng);
|
||||||
}
|
}
|
||||||
|
|
||||||
const addr = req.recipient_address.toLowerCase();
|
const zoneDef = classifyZoneFromAddressAndDistance(req.recipient_address, roadDistanceKm);
|
||||||
const isSubDhakaArea = /savar|gazipur|keraniganj|narayanganj|সাভার|গাজীপুর|কেরানীগঞ্জ|নারায়ণগঞ্জ/i.test(addr);
|
|
||||||
|
|
||||||
let zone: "inside_dhaka" | "sub_dhaka" | "outside_dhaka" = "outside_dhaka";
|
|
||||||
let zoneTitle = "ঢাকার বাইরে (সারা বাংলাদেশ)";
|
|
||||||
let fee = 150;
|
|
||||||
let hours = "৭২–৯৬ ঘণ্টা";
|
|
||||||
|
|
||||||
if (roadDistanceKm > 0 && roadDistanceKm <= 22 && !isSubDhakaArea) {
|
|
||||||
zone = "inside_dhaka";
|
|
||||||
zoneTitle = "ঢাকার ভেতরে (মেট্রোপলিটন)";
|
|
||||||
fee = 80;
|
|
||||||
hours = "২৪–৪৮ ঘণ্টা (সরাসরি হোম ডেলিভারি)";
|
|
||||||
} else if ((roadDistanceKm > 22 && roadDistanceKm <= 45) || isSubDhakaArea) {
|
|
||||||
zone = "sub_dhaka";
|
|
||||||
zoneTitle = "সাব-ঢাকা (আশপাশের অঞ্চল)";
|
|
||||||
fee = 100;
|
|
||||||
hours = "৪৮–৭২ ঘণ্টা";
|
|
||||||
}
|
|
||||||
|
|
||||||
return {
|
return {
|
||||||
success: true,
|
success: true,
|
||||||
zone,
|
zone: zoneDef.zone,
|
||||||
zone_title: zoneTitle,
|
zone_title: zoneDef.zone_title,
|
||||||
|
distance_km: roadDistanceKm,
|
||||||
road_distance_km: roadDistanceKm,
|
road_distance_km: roadDistanceKm,
|
||||||
estimated_delivery_hours: hours,
|
sla_hours: zoneDef.sla_hours,
|
||||||
standard_delivery_fee: fee,
|
estimated_delivery_hours: zoneDef.sla_label,
|
||||||
cod_charge_percentage: 1.0,
|
standard_fee_bdt: zoneDef.standard_fee_bdt,
|
||||||
|
standard_delivery_fee: zoneDef.standard_fee_bdt,
|
||||||
|
cod_percent: zoneDef.cod_percent,
|
||||||
|
cod_charge_percentage: zoneDef.cod_percent,
|
||||||
route_summary: routeSummary || `Hub to Destination (~${roadDistanceKm} km)`,
|
route_summary: routeSummary || `Hub to Destination (~${roadDistanceKm} km)`,
|
||||||
};
|
};
|
||||||
}
|
}
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* Enterprise Multi-Carrier Rate Comparison (Steadfast vs Pathao vs RedX vs Paperfly)
|
* Multi-Carrier Rate Comparison backed by Single Tariff Source of Truth (T4)
|
||||||
*/
|
*/
|
||||||
async compareRates(req: CourierRateComparisonRequest): Promise<CourierRateComparisonResponse> {
|
async compareRates(req: CourierRateComparisonRequest): Promise<CourierRateComparisonResponse> {
|
||||||
const zoneInfo = await this.calculateDeliveryZoneAndFee({
|
const zoneInfo = await this.calculateDeliveryZoneAndFee({
|
||||||
@@ -198,118 +289,37 @@ export class GoogleMapsAdapter {
|
|||||||
|
|
||||||
const weight = req.weight_kg || 0.5;
|
const weight = req.weight_kg || 0.5;
|
||||||
const cod = req.cod_amount || 0;
|
const cod = req.cod_amount || 0;
|
||||||
const extraKg = Math.max(0, Math.ceil(weight - 1.0));
|
const couriers: SupportedCourier[] = ["steadfast", "pathao", "redx", "paperfly"];
|
||||||
|
|
||||||
// Base rates per carrier based on real BD logistics market tariffs
|
const rawQuotes = couriers.map((c) => computeCourierQuote(c, zoneInfo.zone, weight, cod));
|
||||||
let sfBase = 70, ptBase = 60, rxBase = 80, pfBase = 80;
|
|
||||||
let sfExtra = 20, ptExtra = 25, rxExtra = 20, pfExtra = 25;
|
|
||||||
let sfHours = "২৪–৪৮ ঘণ্টা", ptHours = "১২–২৪ ঘণ্টা (Same-Day)", rxHours = "২৪–৪৮ ঘণ্টা", pfHours = "২৪–৪৮ ঘণ্টা";
|
|
||||||
|
|
||||||
if (zoneInfo.zone === "sub_dhaka") {
|
|
||||||
sfBase = 100; ptBase = 110; rxBase = 110; pfBase = 110;
|
|
||||||
sfHours = "৪৮–৭২ ঘণ্টা"; ptHours = "২৪–৪৮ ঘণ্টা"; rxHours = "৪৮–৭২ ঘণ্টা"; pfHours = "৪৮–৭২ ঘণ্টা";
|
|
||||||
} else if (zoneInfo.zone === "outside_dhaka") {
|
|
||||||
sfBase = 140; ptBase = 150; rxBase = 160; pfBase = 170;
|
|
||||||
sfHours = "৭২–৯৬ ঘণ্টা"; ptHours = "৪৮–৭২ ঘণ্টা"; rxHours = "৭২–৯৬ ঘণ্টা"; pfHours = "৭২–৯৬ ঘণ্টা";
|
|
||||||
}
|
|
||||||
|
|
||||||
const sfCod = Math.round(cod * 0.01);
|
|
||||||
const ptCod = Math.round(cod * 0.01);
|
|
||||||
const rxCod = Math.round(cod * 0.01);
|
|
||||||
const pfCod = Math.round(cod * 0.015);
|
|
||||||
|
|
||||||
const sfTotal = sfBase + (extraKg * sfExtra) + sfCod;
|
|
||||||
const ptTotal = ptBase + (extraKg * ptExtra) + ptCod;
|
|
||||||
const rxTotal = rxBase + (extraKg * rxExtra) + rxCod;
|
|
||||||
const pfTotal = pfBase + (extraKg * pfExtra) + pfCod;
|
|
||||||
|
|
||||||
const carrierQuotes: Array<{
|
|
||||||
courier: SupportedCourier;
|
|
||||||
name: string;
|
|
||||||
base: number;
|
|
||||||
extra: number;
|
|
||||||
cod: number;
|
|
||||||
total: number;
|
|
||||||
hours: string;
|
|
||||||
notes: string;
|
|
||||||
}> = [
|
|
||||||
{
|
|
||||||
courier: "steadfast",
|
|
||||||
name: "Steadfast Courier",
|
|
||||||
base: sfBase,
|
|
||||||
extra: extraKg * sfExtra,
|
|
||||||
cod: sfCod,
|
|
||||||
total: sfTotal,
|
|
||||||
hours: sfHours,
|
|
||||||
notes: "৬৪ জেলা ও সকল থানায় সরাসরি ক্যাশ অন ডেলিভারি হাব নেটওয়ার্ক।",
|
|
||||||
},
|
|
||||||
{
|
|
||||||
courier: "pathao",
|
|
||||||
name: "Pathao Express",
|
|
||||||
base: ptBase,
|
|
||||||
extra: extraKg * ptExtra,
|
|
||||||
cod: ptCod,
|
|
||||||
total: ptTotal,
|
|
||||||
hours: ptHours,
|
|
||||||
notes: "ঢাকা ও প্রধান মেট্রোপলিটন সিটিতে দ্রুততম অন-ডিমান্ড রাইডার পিকআপ।",
|
|
||||||
},
|
|
||||||
{
|
|
||||||
courier: "redx",
|
|
||||||
name: "RedX Delivery",
|
|
||||||
base: rxBase,
|
|
||||||
extra: extraKg * rxExtra,
|
|
||||||
cod: rxCod,
|
|
||||||
total: rxTotal,
|
|
||||||
hours: rxHours,
|
|
||||||
notes: "শক্তিশালী সাব-ডিস্ট্রিক্ট হাব ও বৃহৎ পার্সেল হ্যান্ডলিং নেটওয়ার্ক।",
|
|
||||||
},
|
|
||||||
{
|
|
||||||
courier: "paperfly",
|
|
||||||
name: "Paperfly Go",
|
|
||||||
base: pfBase,
|
|
||||||
extra: extraKg * pfExtra,
|
|
||||||
cod: pfCod,
|
|
||||||
total: pfTotal,
|
|
||||||
hours: pfHours,
|
|
||||||
notes: "প্রত্যন্ত ইউনিয়ন ও ডোরস্টেপ ডেলিভারি কভারেজ।",
|
|
||||||
},
|
|
||||||
];
|
|
||||||
|
|
||||||
let recommended: SupportedCourier = "steadfast";
|
let recommended: SupportedCourier = "steadfast";
|
||||||
let reason = "সর্বনিম্ন খরচ ও ৬৪ জেলায় ৯৯.৮% সফল ডেলিভারি নেটওয়ার্ক";
|
let reason = "Balanced nationwide coverage and cost efficiency.";
|
||||||
|
|
||||||
if (zoneInfo.zone === "inside_dhaka" && req.priority === "fastest") {
|
if (req.priority === "cheapest") {
|
||||||
recommended = "pathao";
|
const sorted = [...rawQuotes].sort((a, b) => a.total_cost - b.total_cost);
|
||||||
reason = "ঢাকা মেট্রোপলিটনে দ্রুততম সেম-ডে এক্সপ্রেস ডেলিভারি";
|
|
||||||
} else if (req.priority === "cheapest") {
|
|
||||||
const sorted = [...carrierQuotes].sort((a, b) => a.total - b.total);
|
|
||||||
recommended = sorted[0].courier;
|
recommended = sorted[0].courier;
|
||||||
reason = `${sorted[0].name} এই রুটে সর্বনিম্ন খরচে ডেলিভারি প্রদান করে (৳${sorted[0].total})।`;
|
reason = `${sorted[0].courier_name} offers the lowest total tariff on this route (৳${sorted[0].total_cost}).`;
|
||||||
} else if (zoneInfo.zone === "inside_dhaka") {
|
} else if (zoneInfo.zone === "inside_dhaka") {
|
||||||
recommended = ptTotal <= sfTotal ? "pathao" : "steadfast";
|
recommended = "pathao";
|
||||||
reason = "ঢাকা মেট্রোপলিটনে সাশ্রয়ী ডেলিভারি ও দ্রুত পিকআপ";
|
reason = "Lowest base rate and high-density rider pickup within Inside Dhaka.";
|
||||||
} else {
|
} else {
|
||||||
recommended = "steadfast";
|
recommended = "steadfast";
|
||||||
reason = "ঢাকার বাইরে সারা বাংলাদেশের ৬৪ জেলায় সর্বোচ্চ কভারেজ ও সর্বনিম্ন রিটার্ন রেট";
|
reason = "Lowest inter-district base tariff and 64-district doorstep COD coverage.";
|
||||||
}
|
}
|
||||||
|
|
||||||
const quotes: CarrierQuote[] = carrierQuotes.map((cq) => ({
|
const quotes: CarrierQuote[] = rawQuotes.map((rq) => ({
|
||||||
courier: cq.courier,
|
...rq,
|
||||||
courier_name: cq.name,
|
is_recommended: rq.courier === recommended,
|
||||||
base_delivery_fee: cq.base,
|
|
||||||
weight_surcharge: cq.extra,
|
|
||||||
cod_charge: cq.cod,
|
|
||||||
total_cost: cq.total,
|
|
||||||
estimated_hours: cq.hours,
|
|
||||||
coverage_notes: cq.notes,
|
|
||||||
is_recommended: (cq.courier as string) === (recommended as string),
|
|
||||||
}));
|
}));
|
||||||
|
|
||||||
return {
|
return {
|
||||||
success: true,
|
success: true,
|
||||||
zone: zoneInfo.zone,
|
zone: zoneInfo.zone,
|
||||||
zone_title: zoneInfo.zone_title,
|
zone_title: zoneInfo.zone_title,
|
||||||
|
distance_km: zoneInfo.distance_km,
|
||||||
road_distance_km: zoneInfo.road_distance_km,
|
road_distance_km: zoneInfo.road_distance_km,
|
||||||
|
sla_hours: zoneInfo.sla_hours,
|
||||||
weight_kg: weight,
|
weight_kg: weight,
|
||||||
cod_amount: cod,
|
cod_amount: cod,
|
||||||
recommended_courier: recommended,
|
recommended_courier: recommended,
|
||||||
@@ -319,104 +329,57 @@ export class GoogleMapsAdapter {
|
|||||||
}
|
}
|
||||||
|
|
||||||
private async fallbackAddressParse(req: AddressValidationRequest): Promise<AddressValidationResponse> {
|
private async fallbackAddressParse(req: AddressValidationRequest): Promise<AddressValidationResponse> {
|
||||||
|
const thanaInput = req.thana ? String(req.thana) : null;
|
||||||
const fullQuery = [req.address, req.thana, req.district, "Bangladesh"].filter(Boolean).join(", ");
|
const fullQuery = [req.address, req.thana, req.district, "Bangladesh"].filter(Boolean).join(", ");
|
||||||
|
const lower = fullQuery.toLowerCase();
|
||||||
|
|
||||||
// Tier 2: Live OpenStreetMap Nominatim Geocoding (Zero-Billing Fallback)
|
const BD_DISTRICTS: Array<{ match: RegExp; district: string; division: string; lat: number; lng: number }> = [
|
||||||
try {
|
{ match: /chattogram|chittagong|চট্টগ্রাম/, district: "Chattogram", division: "Chattogram Division", lat: 22.3569, lng: 91.7832 },
|
||||||
const nomRes = await axios.get("https://nominatim.openstreetmap.org/search", {
|
{ match: /sylhet|সিলেট/, district: "Sylhet", division: "Sylhet Division", lat: 24.8949, lng: 91.8687 },
|
||||||
params: {
|
{ match: /rajshahi|রাজশাহী/, district: "Rajshahi", division: "Rajshahi Division", lat: 24.3745, lng: 88.6042 },
|
||||||
q: fullQuery,
|
{ match: /khulna|খুলনা/, district: "Khulna", division: "Khulna Division", lat: 22.8456, lng: 89.5403 },
|
||||||
countrycodes: "bd",
|
{ match: /barishal|barisal|বরিশাল/, district: "Barishal", division: "Barishal Division", lat: 22.7010, lng: 90.3535 },
|
||||||
format: "json",
|
{ match: /rangpur|রংপুর/, district: "Rangpur", division: "Rangpur Division", lat: 25.7439, lng: 89.2752 },
|
||||||
addressdetails: 1,
|
{ match: /mymensingh|ময়মনসিংহ/, district: "Mymensingh", division: "Mymensingh Division", lat: 24.7471, lng: 90.4203 },
|
||||||
limit: 1,
|
{ match: /cumilla|comilla|কুমিল্লা/, district: "Cumilla", division: "Chattogram Division", lat: 23.4607, lng: 91.1809 },
|
||||||
},
|
{ match: /gazipur|গাজীপুর|tongi|টঙ্গী/, district: "Gazipur", division: "Dhaka Division", lat: 23.9999, lng: 90.4203 },
|
||||||
headers: { "User-Agent": "AuraCourierMCP/2.5 (https://courier.auraajenticai.cloud)" },
|
{ match: /narayanganj|নারায়ণগঞ্জ/, district: "Narayanganj", division: "Dhaka Division", lat: 23.6238, lng: 90.5000 },
|
||||||
timeout: 5500,
|
{ match: /savar|সাভার|ashulia|আশুলিয়া/, district: "Dhaka", division: "Dhaka Division", lat: 23.8583, lng: 90.2667 },
|
||||||
});
|
{ match: /keraniganj|কেরানীগঞ্জ|ati bazar|atibazar/, district: "Dhaka", division: "Dhaka Division", lat: 23.7196, lng: 90.3125 },
|
||||||
if (Array.isArray(nomRes.data) && nomRes.data.length > 0) {
|
{ match: /uttara|উত্তরা/, district: "Dhaka", division: "Dhaka Division", lat: 23.8759, lng: 90.3795 },
|
||||||
const hit = nomRes.data[0];
|
{ match: /mirpur|মিরপুর/, district: "Dhaka", division: "Dhaka Division", lat: 23.8042, lng: 90.3667 },
|
||||||
const addr = hit.address || {};
|
{ match: /dhanmondi|ধানমন্ডি/, district: "Dhaka", division: "Dhaka Division", lat: 23.7461, lng: 90.3742 },
|
||||||
const lat = parseFloat(hit.lat);
|
{ match: /gulshan|গুলশান|banani|বনানী/, district: "Dhaka", division: "Dhaka Division", lat: 23.7925, lng: 90.4078 },
|
||||||
const lng = parseFloat(hit.lon);
|
|
||||||
const thana = addr.suburb || addr.neighbourhood || addr.town || addr.municipality || addr.city_district || req.thana || "";
|
|
||||||
const district = (addr.county || addr.city || addr.state_district || req.district || "Dhaka").replace(/\s*District$/i, "");
|
|
||||||
const division = addr.state || "Dhaka Division";
|
|
||||||
return {
|
|
||||||
success: true,
|
|
||||||
formatted_address: hit.display_name || fullQuery,
|
|
||||||
thana,
|
|
||||||
district,
|
|
||||||
division,
|
|
||||||
coordinates: { lat, lng },
|
|
||||||
location_type: "GEOMETRIC_CENTER",
|
|
||||||
is_deliverable: true,
|
|
||||||
confidence_score: 88,
|
|
||||||
place_id: `osm_${hit.place_id || Date.now()}`,
|
|
||||||
};
|
|
||||||
}
|
|
||||||
} catch (_) {
|
|
||||||
// Proceed to Tier 3 Spatial Gazetteer
|
|
||||||
}
|
|
||||||
|
|
||||||
// Tier 3: Bangladesh 64-District & Dhaka Thana Spatial Gazetteer
|
|
||||||
const raw = [req.address, req.thana, req.district].filter(Boolean).join(" ").toLowerCase();
|
|
||||||
const gazetteer: Array<{ rx: RegExp; thana: string; district: string; division: string; lat: number; lng: number }> = [
|
|
||||||
{ rx: /mirpur|মিরপুর|pallabi|পল্লবী|kazipara|shewrapara|কাজীপাড়া|শেওড়াপাড়া/, thana: "Mirpur", district: "Dhaka", division: "Dhaka Division", lat: 23.8042, lng: 90.3667 },
|
|
||||||
{ rx: /uttara|উত্তরা|airport|বিমানবন্দর|sector|সেক্টর|dakshin khan|uttar khan/, thana: "Uttara", district: "Dhaka", division: "Dhaka Division", lat: 23.8759, lng: 90.3795 },
|
|
||||||
{ rx: /dhanmondi|ধানমন্ডি|kalabagan|কলাবাগান|jigatola|জিগাতলা|shankar/, thana: "Dhanmondi", district: "Dhaka", division: "Dhaka Division", lat: 23.7461, lng: 90.3742 },
|
|
||||||
{ rx: /gulshan|গুলশান|banani|বনানী|baridhara|বারিধারা|niketan|নিকেতন/, thana: "Gulshan", district: "Dhaka", division: "Dhaka Division", lat: 23.7925, lng: 90.4078 },
|
|
||||||
{ rx: /mohammadpur|মোহাম্মদপুর|adabor|আদাবর|lalmatia|লালমাটিয়া|bosila|বসিলা/, thana: "Mohammadpur", district: "Dhaka", division: "Dhaka Division", lat: 23.7662, lng: 90.3589 },
|
|
||||||
{ rx: /badda|বাড্ডা|rampura|রামপুরা|banasree|বনশ্রী|aftabnagar|আফতাবনগর|hatirjheel/, thana: "Badda", district: "Dhaka", division: "Dhaka Division", lat: 23.7805, lng: 90.4267 },
|
|
||||||
{ rx: /bashundhara|বসুন্ধরা|vatara|ভাটারা|kuril|কুড়িল|nikunja|নিকুঞ্জ|khilkhet|খিলক্ষেত/, thana: "Vatara", district: "Dhaka", division: "Dhaka Division", lat: 23.8191, lng: 90.4526 },
|
|
||||||
{ rx: /motijheel|মতিঝিল|paltan|পল্টন|kakrail|কাকরাইল|shantinagar|শান্তিনগর|malibagh|মালিবাগ|mogbazar|মগবাজার/, thana: "Motijheel", district: "Dhaka", division: "Dhaka Division", lat: 23.7330, lng: 90.4172 },
|
|
||||||
{ rx: /shahbag|শাহবাগ|hatirpool|হাতিরপুল|motaleb|মোতালেব|eleph|এলিফ্যান্ট|new market|নিউ মার্কেট|farmgate|ফার্মগেট|tejgaon|তেজগাঁও|karwan|কারওয়ান/, thana: "Shahbagh", district: "Dhaka", division: "Dhaka Division", lat: 23.7415, lng: 90.3918 },
|
|
||||||
{ rx: /jatrabari|যাত্রাবাড়ী|demra|ডেমরা|kadamtali|কদমতলী|shanir akhra|শনির আখড়া|wari|ওয়ারী|old dhaka|পুরান ঢাকা|lalbagh|লালবাগ|kotwali/, thana: "Jatrabari", district: "Dhaka", division: "Dhaka Division", lat: 23.7104, lng: 90.4348 },
|
|
||||||
{ rx: /keraniganj|কেরানীগঞ্জ|ati bazar|আটি বাজার|atibazar|hasnabad/, thana: "Keraniganj", district: "Dhaka", division: "Dhaka Division", lat: 23.6942, lng: 90.3475 },
|
|
||||||
{ rx: /savar|সাভার|ashulia|আশুলিয়া|hemayetpur|হেমায়েতপুর|dhamrai|ধামরাই/, thana: "Savar", district: "Dhaka", division: "Dhaka Division", lat: 23.8583, lng: 90.2667 },
|
|
||||||
{ rx: /gazipur|গাজীপুর|tongi|টঙ্গী|board bazar|বোর্ড বাজার|joydebpur|জয়দেবপুর|konabari/, thana: "Tongi", district: "Gazipur", division: "Dhaka Division", lat: 23.9889, lng: 90.3950 },
|
|
||||||
{ rx: /narayanganj|নারায়ণগঞ্জ|siddhirganj|সিদ্ধিরগঞ্জ|fatullah|ফতুল্লা|chashara|চাষাড়া|sonargaon|rupganj/, thana: "Narayanganj Sadar", district: "Narayanganj", division: "Dhaka Division", lat: 23.6238, lng: 90.5000 },
|
|
||||||
{ rx: /chattogram|chittagong|চট্টগ্রাম|agrabad|আগ্রাবাদ|nasirabad|নাসিরাবাদ|halishahar|হালিশহর|panchlaish|gec|জিইসি|kotwali/, thana: "Panchlaish", district: "Chattogram", division: "Chattogram Division", lat: 22.3569, lng: 91.7832 },
|
|
||||||
{ rx: /cox.?s?s*bazar|কক্সবাজার|chakaria|teknaf|ukhiya/, thana: "Cox's Bazar Sadar", district: "Cox's Bazar", division: "Chattogram Division", lat: 21.4272, lng: 92.0058 },
|
|
||||||
{ rx: /cumilla|comilla|কুমিল্লা|kandirpar|কান্দিরপাড়|laksam|daudkandi/, thana: "Cumilla Sadar", district: "Cumilla", division: "Chattogram Division", lat: 23.4607, lng: 91.1809 },
|
|
||||||
{ rx: /feni|ফেনী|noakhali|নোয়াখালী|maijdee|চৌমুহনী|lakshmipur|লক্ষ্মীপুর|chandpur|চাঁদপুর|brahmanbaria|ব্রাহ্মণবাড়িয়া/, thana: "Sadar", district: "Noakhali", division: "Chattogram Division", lat: 22.8724, lng: 91.0973 },
|
|
||||||
{ rx: /sylhet|সিলেট|zindabazar|জিন্দাবাজার|amberkhana|আম্বরখানা|upashahar|উপশহর|moulvibazar|মৌলভীবাজার|sreemangal|habiganj|হবিগঞ্জ|sunamganj|সুনামগঞ্জ/, thana: "Sylhet Sadar", district: "Sylhet", division: "Sylhet Division", lat: 24.8949, lng: 91.8687 },
|
|
||||||
{ rx: /rajshahi|রাজশাহী|boalia|বোয়ালিয়া|shaheb bazar|সাহেব বাজার|motihar|নাটোর|natore|naogaon|নওগাঁ|chapainawabganj|চাঁপাইনবাবগঞ্জ|pabna|পাবনা|sirajganj|সিরাজগঞ্জ/, thana: "Boalia", district: "Rajshahi", division: "Rajshahi Division", lat: 24.3745, lng: 88.6042 },
|
|
||||||
{ rx: /bogura|bogra|বগুড়া|sherpur|শেরপুর|joypurhat|জয়পুরহাট/, thana: "Bogura Sadar", district: "Bogura", division: "Rajshahi Division", lat: 24.8481, lng: 89.3730 },
|
|
||||||
{ rx: /khulna|খুলনা|sonadanga|সোনাডাঙ্গা|khalishpur|খালিশপুর|daulatpur|jashore|jessore|যশোর|kushtia|কুষ্টিয়া|satkhira|সাতক্ষীরা|bagerhat|বাগেরহাট|jhenaidah|ঝিনাইদহ/, thana: "Sonadanga", district: "Khulna", division: "Khulna Division", lat: 22.8456, lng: 89.5403 },
|
|
||||||
{ rx: /barishal|barisal|বরিশাল|patukhali|পটুয়াখালী|bhola|ভোলা|pirojpur|পিরোজপুর|jhalokati|barguna/, thana: "Barishal Sadar", district: "Barishal", division: "Barishal Division", lat: 22.7010, lng: 90.3535 },
|
|
||||||
{ rx: /rangpur|রংপুর|dinajpur|দিনাজপুর|thakurgaon|ঠাকুরগাঁও|panchagarh|পঞ্চগড়|nilphamari|নীলফামারী|saidpur|সৈয়দপুর|kurigram|কুড়িগ্রাম|gaibandha|গাইবান্ধা|lalmonirhat/, thana: "Rangpur Sadar", district: "Rangpur", division: "Rangpur Division", lat: 25.7439, lng: 89.2752 },
|
|
||||||
{ rx: /mymensingh|ময়মনসিংহ|jamalpur|জামালপুর|netrokona|নেত্রকোনা|tangail|টাঙ্গাইল|kishoreganj|কিশোরগঞ্জ|faridpur|ফরিদপুর|madaripur|মাদারীপুর|gopalganj|গোপালগঞ্জ|shariatpur|শরীয়তপুর|rajbari|রাজবাড়ী|manikganj|মানিকগঞ্জ|munshiganj|মুন্সিগঞ্জ|narsingdi|নরসিংদী/, thana: "Mymensingh Sadar", district: "Mymensingh", division: "Mymensingh Division", lat: 24.7471, lng: 90.4203 },
|
|
||||||
];
|
];
|
||||||
|
|
||||||
for (const g of gazetteer) {
|
const matched = BD_DISTRICTS.find((d) => d.match.test(lower)) || {
|
||||||
if (g.rx.test(raw)) {
|
district: req.district || "Dhaka",
|
||||||
return {
|
division: "Dhaka Division",
|
||||||
success: true,
|
lat: 23.7805,
|
||||||
formatted_address: `${req.address}, ${req.thana || g.thana}, ${req.district || g.district}, Bangladesh`,
|
lng: 90.4078,
|
||||||
thana: req.thana || g.thana,
|
};
|
||||||
district: req.district || g.district,
|
|
||||||
division: g.division,
|
// Never echo thana_input into thana_resolved in fallback mode
|
||||||
coordinates: { lat: g.lat, lng: g.lng },
|
const thanaResolved: string | null = null;
|
||||||
location_type: "GEOMETRIC_CENTER",
|
const locType = "APPROXIMATE";
|
||||||
is_deliverable: true,
|
const qa = this.buildQualityAssessment(req, fullQuery, locType, 55, thanaResolved);
|
||||||
confidence_score: 84,
|
|
||||||
place_id: `bd_gazetteer_${g.district.toLowerCase().replace(/\s+/g, "_")}`,
|
|
||||||
};
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
const isDhaka = /dhaka|ঢাকা/i.test(raw);
|
|
||||||
return {
|
return {
|
||||||
success: true,
|
success: true,
|
||||||
formatted_address: req.address,
|
formatted_address: fullQuery,
|
||||||
thana: req.thana || (isDhaka ? "Dhaka Metro" : "Sadar"),
|
thana_input: thanaInput,
|
||||||
district: req.district || (isDhaka ? "Dhaka" : "Outside Dhaka"),
|
thana_resolved: thanaResolved,
|
||||||
division: isDhaka ? "Dhaka Division" : "Bangladesh",
|
thana: "",
|
||||||
coordinates: isDhaka ? { lat: 23.8103, lng: 90.4125 } : { lat: 24.0000, lng: 90.0000 },
|
district: matched.district,
|
||||||
location_type: "APPROXIMATE",
|
division: matched.division,
|
||||||
|
coordinates: { lat: matched.lat, lng: matched.lng },
|
||||||
|
location_type: locType,
|
||||||
is_deliverable: true,
|
is_deliverable: true,
|
||||||
confidence_score: 72,
|
confidence_score: qa.confidence,
|
||||||
|
match_quality: qa.matchQuality,
|
||||||
|
needs_review: true,
|
||||||
|
warnings: qa.warnings,
|
||||||
|
place_id: `bd_gazetteer_${matched.district.toLowerCase()}`,
|
||||||
};
|
};
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -431,6 +394,6 @@ export class GoogleMapsAdapter {
|
|||||||
Math.sin(dLon / 2) *
|
Math.sin(dLon / 2) *
|
||||||
Math.sin(dLon / 2);
|
Math.sin(dLon / 2);
|
||||||
const c = 2 * Math.atan2(Math.sqrt(a), Math.sqrt(1 - a));
|
const c = 2 * Math.atan2(Math.sqrt(a), Math.sqrt(1 - a));
|
||||||
return Math.round(R * c * 1.2 * 10) / 10;
|
return Math.round(R * c * 1.25 * 10) / 10;
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|||||||
+68
-32
@@ -1,5 +1,6 @@
|
|||||||
import axios, { AxiosInstance } from "axios";
|
import axios, { AxiosInstance } from "axios";
|
||||||
import { CourierAdapter } from "./base.js";
|
import { CourierAdapter } from "./base.js";
|
||||||
|
import { McpToolError } from "../envelope.js";
|
||||||
import {
|
import {
|
||||||
BalanceResponse,
|
BalanceResponse,
|
||||||
ParcelCreateRequest,
|
ParcelCreateRequest,
|
||||||
@@ -75,44 +76,79 @@ export class PaperflyAdapter implements CourierAdapter {
|
|||||||
|
|
||||||
async trackParcel(trackingCode: string): Promise<TrackingResponse> {
|
async trackParcel(trackingCode: string): Promise<TrackingResponse> {
|
||||||
if (!this.enabled) {
|
if (!this.enabled) {
|
||||||
throw new Error("Paperfly credentials are not configured.");
|
throw new McpToolError({
|
||||||
|
code: "COURIER_NOT_CONFIGURED",
|
||||||
|
message: "Paperfly credentials are not configured.",
|
||||||
|
courier: "paperfly",
|
||||||
|
});
|
||||||
}
|
}
|
||||||
if (!this.username || !this.password) {
|
if (!this.username || !this.password) {
|
||||||
throw new Error(
|
throw new McpToolError({
|
||||||
"Paperfly tracking needs your merchant-panel username & password (Basic Auth). Add them to use track_parcel."
|
code: "COURIER_NOT_CONFIGURED",
|
||||||
);
|
message: "Paperfly tracking requires merchant-panel username and password.",
|
||||||
|
courier: "paperfly",
|
||||||
|
});
|
||||||
}
|
}
|
||||||
// Paperfly tracks by your merchant order reference (merchantOrderReference), not its tracking number.
|
try {
|
||||||
const response = await this.client.post(
|
const response = await this.client.post(
|
||||||
"/API-Order-Tracking",
|
"/API-Order-Tracking",
|
||||||
{ ReferenceNumber: trackingCode },
|
{ ReferenceNumber: trackingCode },
|
||||||
{ headers: { paperflykey: this.apiKey }, auth: { username: this.username, password: this.password } }
|
{ headers: { paperflykey: this.apiKey }, auth: { username: this.username, password: this.password } }
|
||||||
);
|
);
|
||||||
const data = response.data;
|
const data = response.data;
|
||||||
const st = data?.success?.trackingStatus?.[0] || {};
|
if (data?.error) {
|
||||||
const stages: Array<[any, string]> = [
|
throw new McpToolError({
|
||||||
[st.Delivered, "delivered"],
|
code: "CONSIGNMENT_NOT_FOUND",
|
||||||
[st.Partial, "partial-delivery"],
|
message: `Consignment '${trackingCode}' was not found in Paperfly.`,
|
||||||
[st.Returned, "returned"],
|
retryable: false,
|
||||||
[st.PickedForDelivery, "out-for-delivery"],
|
courier: "paperfly",
|
||||||
[st.inTransit, "in-transit"],
|
});
|
||||||
[st.ReceivedAtPoint, "received-at-point"],
|
}
|
||||||
[st.Pick, "picked-up"],
|
const st = data?.success?.trackingStatus?.[0] || {};
|
||||||
];
|
const stages: Array<[any, string]> = [
|
||||||
const status = stages.find(([v]) => v && String(v).trim())?.[1] || data?.success?.message || "pending";
|
[st.Delivered, "delivered"],
|
||||||
|
[st.Partial, "partial-delivery"],
|
||||||
|
[st.Returned, "returned"],
|
||||||
|
[st.PickedForDelivery, "out-for-delivery"],
|
||||||
|
[st.inTransit, "in-transit"],
|
||||||
|
[st.ReceivedAtPoint, "received-at-point"],
|
||||||
|
[st.Pick, "picked-up"],
|
||||||
|
];
|
||||||
|
const status = stages.find(([v]) => v && String(v).trim())?.[1] || data?.success?.message || "pending";
|
||||||
|
return {
|
||||||
|
success: true,
|
||||||
|
courier: "paperfly",
|
||||||
|
tracking_code: trackingCode,
|
||||||
|
status,
|
||||||
|
updated_at: new Date().toISOString(),
|
||||||
|
raw_response: data,
|
||||||
|
};
|
||||||
|
} catch (err: any) {
|
||||||
|
if (err instanceof McpToolError) throw err;
|
||||||
|
if (err?.response?.status === 400 || err?.response?.status === 404) {
|
||||||
|
throw new McpToolError({
|
||||||
|
code: "CONSIGNMENT_NOT_FOUND",
|
||||||
|
message: `Consignment '${trackingCode}' was not found in Paperfly.`,
|
||||||
|
retryable: false,
|
||||||
|
courier: "paperfly",
|
||||||
|
});
|
||||||
|
}
|
||||||
|
throw err;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Paperfly does not expose a live wallet balance API endpoint (T3).
|
||||||
|
*/
|
||||||
|
async getBalance(): Promise<BalanceResponse> {
|
||||||
return {
|
return {
|
||||||
success: true,
|
success: true,
|
||||||
courier: "paperfly",
|
courier: "paperfly",
|
||||||
tracking_code: trackingCode,
|
amount_bdt: null,
|
||||||
status,
|
pending_bdt: null,
|
||||||
updated_at: new Date().toISOString(),
|
current_balance: null,
|
||||||
raw_response: data,
|
status: "UNSUPPORTED_BY_PROVIDER",
|
||||||
|
hint: "Use Paperfly merchant portal",
|
||||||
};
|
};
|
||||||
}
|
}
|
||||||
|
|
||||||
async getBalance(): Promise<BalanceResponse> {
|
|
||||||
throw new Error(
|
|
||||||
"Paperfly does not expose a merchant balance endpoint via its public API — check the Paperfly merchant panel."
|
|
||||||
);
|
|
||||||
}
|
|
||||||
}
|
}
|
||||||
|
|||||||
+59
-14
@@ -1,5 +1,6 @@
|
|||||||
import axios, { AxiosInstance } from "axios";
|
import axios, { AxiosInstance } from "axios";
|
||||||
import { CourierAdapter } from "./base.js";
|
import { CourierAdapter } from "./base.js";
|
||||||
|
import { McpToolError, withGetRetry } from "../envelope.js";
|
||||||
import {
|
import {
|
||||||
BalanceResponse,
|
BalanceResponse,
|
||||||
LocationResolutionResponse,
|
LocationResolutionResponse,
|
||||||
@@ -267,32 +268,76 @@ export class PathaoAdapter implements CourierAdapter {
|
|||||||
|
|
||||||
async trackParcel(trackingCode: string): Promise<TrackingResponse> {
|
async trackParcel(trackingCode: string): Promise<TrackingResponse> {
|
||||||
if (!this.isConfigured()) {
|
if (!this.isConfigured()) {
|
||||||
throw new Error("Pathao credentials are not configured.");
|
throw new McpToolError({
|
||||||
|
code: "COURIER_NOT_CONFIGURED",
|
||||||
|
message: "Pathao credentials are not configured.",
|
||||||
|
courier: "pathao",
|
||||||
|
});
|
||||||
}
|
}
|
||||||
|
|
||||||
const client = await this.getClient();
|
try {
|
||||||
const response = await client.get(`/aladdin/api/v1/orders/${encodeURIComponent(trackingCode)}/info`);
|
const client = await this.getClient();
|
||||||
const data = response.data.data;
|
const response = await withGetRetry(() =>
|
||||||
|
client.get(`/aladdin/api/v1/orders/${encodeURIComponent(trackingCode)}/info`)
|
||||||
|
);
|
||||||
|
const data = response.data?.data || {};
|
||||||
|
|
||||||
return {
|
return {
|
||||||
success: true,
|
success: true,
|
||||||
courier: "pathao",
|
courier: "pathao",
|
||||||
tracking_code: trackingCode,
|
tracking_code: trackingCode,
|
||||||
status: data.order_status || "unknown",
|
status: data.order_status || data.order_status_slug || "unknown",
|
||||||
updated_at: data.updated_at || new Date().toISOString(),
|
updated_at: data.updated_at || new Date().toISOString(),
|
||||||
raw_response: response.data,
|
raw_response: response.data,
|
||||||
};
|
};
|
||||||
|
} catch (err: any) {
|
||||||
|
const status = err?.response?.status;
|
||||||
|
if (status === 404 || status === 400 || status === 422) {
|
||||||
|
throw new McpToolError({
|
||||||
|
code: "CONSIGNMENT_NOT_FOUND",
|
||||||
|
message: `Consignment '${trackingCode}' was not found in Pathao.`,
|
||||||
|
retryable: false,
|
||||||
|
courier: "pathao",
|
||||||
|
});
|
||||||
|
}
|
||||||
|
throw err;
|
||||||
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Pathao does not expose a live wallet balance API endpoint (T3).
|
||||||
|
* Returns amount_bdt: null, current_balance: null, status: UNSUPPORTED_BY_PROVIDER.
|
||||||
|
*/
|
||||||
async getBalance(): Promise<BalanceResponse> {
|
async getBalance(): Promise<BalanceResponse> {
|
||||||
return {
|
return {
|
||||||
success: true,
|
success: true,
|
||||||
courier: "pathao",
|
courier: "pathao",
|
||||||
current_balance: 0,
|
amount_bdt: null,
|
||||||
raw_response: { message: "Pathao payout balance managed via merchant portal" },
|
pending_bdt: null,
|
||||||
|
current_balance: null,
|
||||||
|
status: "UNSUPPORTED_BY_PROVIDER",
|
||||||
|
hint: "Use Pathao merchant portal",
|
||||||
};
|
};
|
||||||
}
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* 100% Real Live Pathao Nationwide Customer Delivery Success API
|
||||||
|
* Endpoint: POST /aladdin/api/v1/user/success
|
||||||
|
*/
|
||||||
|
async fraudCheck(phone: string): Promise<any> {
|
||||||
|
if (!this.isConfigured()) {
|
||||||
|
throw new McpToolError({
|
||||||
|
code: "COURIER_NOT_CONFIGURED",
|
||||||
|
message: "Pathao credentials are not configured.",
|
||||||
|
courier: "pathao",
|
||||||
|
});
|
||||||
|
}
|
||||||
|
const cleanPhone = phone.replace(/\D/g, "").replace(/^88/, "");
|
||||||
|
const client = await this.getClient();
|
||||||
|
const response = await client.post("/aladdin/api/v1/user/success", { phone: cleanPhone });
|
||||||
|
return response.data;
|
||||||
|
}
|
||||||
|
|
||||||
async getLocations(cityName?: string): Promise<LocationResolutionResponse> {
|
async getLocations(cityName?: string): Promise<LocationResolutionResponse> {
|
||||||
const client = await this.getClient();
|
const client = await this.getClient();
|
||||||
const response = await client.get("/aladdin/api/v1/cities");
|
const response = await client.get("/aladdin/api/v1/cities");
|
||||||
|
|||||||
+44
-16
@@ -1,5 +1,6 @@
|
|||||||
import axios, { AxiosInstance } from "axios";
|
import axios, { AxiosInstance } from "axios";
|
||||||
import { CourierAdapter } from "./base.js";
|
import { CourierAdapter } from "./base.js";
|
||||||
|
import { McpToolError, withGetRetry } from "../envelope.js";
|
||||||
import {
|
import {
|
||||||
BalanceResponse,
|
BalanceResponse,
|
||||||
ParcelCreateRequest,
|
ParcelCreateRequest,
|
||||||
@@ -107,26 +108,53 @@ export class RedxAdapter implements CourierAdapter {
|
|||||||
|
|
||||||
async trackParcel(trackingCode: string): Promise<TrackingResponse> {
|
async trackParcel(trackingCode: string): Promise<TrackingResponse> {
|
||||||
if (!this.enabled) {
|
if (!this.enabled) {
|
||||||
throw new Error("RedX credentials are not configured.");
|
throw new McpToolError({
|
||||||
|
code: "COURIER_NOT_CONFIGURED",
|
||||||
|
message: "RedX credentials are not configured.",
|
||||||
|
courier: "redx",
|
||||||
|
});
|
||||||
}
|
}
|
||||||
const response = await this.client.get(`/parcel/track/${encodeURIComponent(trackingCode)}`);
|
try {
|
||||||
const data = response.data;
|
const response = await withGetRetry(() =>
|
||||||
const events: Array<{ message_en?: string; message_bn?: string; time?: string }> = data?.tracking || [];
|
this.client.get(`/parcel/track/${encodeURIComponent(trackingCode)}`)
|
||||||
const latest = events[events.length - 1];
|
);
|
||||||
|
const data = response.data;
|
||||||
|
const events: Array<{ message_en?: string; message_bn?: string; time?: string }> = data?.tracking || [];
|
||||||
|
const latest = events[events.length - 1];
|
||||||
|
return {
|
||||||
|
success: true,
|
||||||
|
courier: "redx",
|
||||||
|
tracking_code: trackingCode,
|
||||||
|
status: latest?.message_en || "in-transit",
|
||||||
|
updated_at: latest?.time || new Date().toISOString(),
|
||||||
|
timeline: events.map((e) => ({ status: e.message_en || "", time: e.time || "", note: e.message_bn })),
|
||||||
|
raw_response: data,
|
||||||
|
};
|
||||||
|
} catch (err: any) {
|
||||||
|
if (err?.response?.status === 404 || err?.response?.status === 400) {
|
||||||
|
throw new McpToolError({
|
||||||
|
code: "CONSIGNMENT_NOT_FOUND",
|
||||||
|
message: `Consignment '${trackingCode}' was not found in RedX.`,
|
||||||
|
retryable: false,
|
||||||
|
courier: "redx",
|
||||||
|
});
|
||||||
|
}
|
||||||
|
throw err;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* RedX does not expose a live wallet balance API endpoint (T3).
|
||||||
|
*/
|
||||||
|
async getBalance(): Promise<BalanceResponse> {
|
||||||
return {
|
return {
|
||||||
success: true,
|
success: true,
|
||||||
courier: "redx",
|
courier: "redx",
|
||||||
tracking_code: trackingCode,
|
amount_bdt: null,
|
||||||
status: latest?.message_en || "unknown",
|
pending_bdt: null,
|
||||||
updated_at: latest?.time || new Date().toISOString(),
|
current_balance: null,
|
||||||
timeline: events.map((e) => ({ status: e.message_en || "", time: e.time || "", note: e.message_bn })),
|
status: "UNSUPPORTED_BY_PROVIDER",
|
||||||
raw_response: data,
|
hint: "Use RedX merchant portal",
|
||||||
};
|
};
|
||||||
}
|
}
|
||||||
|
|
||||||
async getBalance(): Promise<BalanceResponse> {
|
|
||||||
throw new Error(
|
|
||||||
"RedX does not expose a merchant balance endpoint via its public API — check your balance in the RedX merchant panel."
|
|
||||||
);
|
|
||||||
}
|
|
||||||
}
|
}
|
||||||
|
|||||||
+73
-17
@@ -1,5 +1,6 @@
|
|||||||
import axios, { AxiosInstance } from "axios";
|
import axios, { AxiosInstance } from "axios";
|
||||||
import { CourierAdapter } from "./base.js";
|
import { CourierAdapter } from "./base.js";
|
||||||
|
import { McpToolError, withGetRetry } from "../envelope.js";
|
||||||
import {
|
import {
|
||||||
BalanceResponse,
|
BalanceResponse,
|
||||||
ParcelCreateRequest,
|
ParcelCreateRequest,
|
||||||
@@ -15,7 +16,7 @@ export class SteadfastAdapter implements CourierAdapter {
|
|||||||
|
|
||||||
constructor(apiKey: string, secretKey: string, baseUrl: string) {
|
constructor(apiKey: string, secretKey: string, baseUrl: string) {
|
||||||
this.enabled = Boolean(apiKey && secretKey);
|
this.enabled = Boolean(apiKey && secretKey);
|
||||||
const resolvedBase = baseUrl || "https://portal.steadfast.com.bd/api/v1";
|
const resolvedBase = baseUrl || "https://portal.packzy.com/api/v1";
|
||||||
this.client = axios.create({
|
this.client = axios.create({
|
||||||
baseURL: resolvedBase,
|
baseURL: resolvedBase,
|
||||||
headers: {
|
headers: {
|
||||||
@@ -70,34 +71,86 @@ export class SteadfastAdapter implements CourierAdapter {
|
|||||||
|
|
||||||
async trackParcel(trackingCode: string): Promise<TrackingResponse> {
|
async trackParcel(trackingCode: string): Promise<TrackingResponse> {
|
||||||
if (!this.enabled) {
|
if (!this.enabled) {
|
||||||
throw new Error("Steadfast Courier credentials are not configured.");
|
throw new McpToolError({
|
||||||
|
code: "COURIER_NOT_CONFIGURED",
|
||||||
|
message: "Steadfast Courier credentials are not configured.",
|
||||||
|
courier: "steadfast",
|
||||||
|
});
|
||||||
}
|
}
|
||||||
|
|
||||||
const response = await this.client.get(`/status_by_trackingcode/${encodeURIComponent(trackingCode)}`);
|
const endpoints = [
|
||||||
const data = response.data;
|
`/status_by_trackingcode/${encodeURIComponent(trackingCode)}`,
|
||||||
|
`/status_by_cid/${encodeURIComponent(trackingCode)}`,
|
||||||
|
`/status_by_invoice/${encodeURIComponent(trackingCode)}`,
|
||||||
|
];
|
||||||
|
|
||||||
return {
|
let lastErr: any = null;
|
||||||
success: true,
|
for (const ep of endpoints) {
|
||||||
|
try {
|
||||||
|
const response = await withGetRetry(() => this.client.get(ep));
|
||||||
|
const data = response.data;
|
||||||
|
if (data && (data.status === 200 || data.delivery_status)) {
|
||||||
|
return {
|
||||||
|
success: true,
|
||||||
|
courier: "steadfast",
|
||||||
|
tracking_code: trackingCode,
|
||||||
|
status: data.delivery_status || "in_review",
|
||||||
|
updated_at: data.updated_at || new Date().toISOString(),
|
||||||
|
raw_response: data,
|
||||||
|
};
|
||||||
|
}
|
||||||
|
} catch (err: any) {
|
||||||
|
lastErr = err;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
const status = lastErr?.response?.status;
|
||||||
|
if (status === 404 || status === 400) {
|
||||||
|
throw new McpToolError({
|
||||||
|
code: "CONSIGNMENT_NOT_FOUND",
|
||||||
|
message: `Consignment '${trackingCode}' was not found in Steadfast.`,
|
||||||
|
retryable: false,
|
||||||
|
courier: "steadfast",
|
||||||
|
});
|
||||||
|
}
|
||||||
|
if (status === 401 || status === 403) {
|
||||||
|
throw new McpToolError({
|
||||||
|
code: "COURIER_UPSTREAM_ERROR",
|
||||||
|
message: "Steadfast upstream authentication or consignment ownership check failed.",
|
||||||
|
retryable: false,
|
||||||
|
courier: "steadfast",
|
||||||
|
});
|
||||||
|
}
|
||||||
|
|
||||||
|
throw lastErr || new McpToolError({
|
||||||
|
code: "CONSIGNMENT_NOT_FOUND",
|
||||||
|
message: `Consignment '${trackingCode}' was not found in Steadfast.`,
|
||||||
|
retryable: false,
|
||||||
courier: "steadfast",
|
courier: "steadfast",
|
||||||
tracking_code: trackingCode,
|
});
|
||||||
status: data.delivery_status || "unknown",
|
|
||||||
updated_at: data.updated_at || new Date().toISOString(),
|
|
||||||
raw_response: data,
|
|
||||||
};
|
|
||||||
}
|
}
|
||||||
|
|
||||||
async getBalance(): Promise<BalanceResponse> {
|
async getBalance(): Promise<BalanceResponse> {
|
||||||
if (!this.enabled) {
|
if (!this.enabled) {
|
||||||
throw new Error("Steadfast Courier credentials are not configured.");
|
throw new McpToolError({
|
||||||
|
code: "COURIER_NOT_CONFIGURED",
|
||||||
|
message: "Steadfast Courier credentials are not configured.",
|
||||||
|
courier: "steadfast",
|
||||||
|
});
|
||||||
}
|
}
|
||||||
|
|
||||||
const response = await this.client.get("/get_balance");
|
const response = await withGetRetry(() => this.client.get("/get_balance"));
|
||||||
const data = response.data;
|
const data = response.data;
|
||||||
|
const bal = typeof data?.current_balance === "number" ? data.current_balance : Number(data?.current_balance ?? 0);
|
||||||
|
|
||||||
return {
|
return {
|
||||||
success: true,
|
success: true,
|
||||||
courier: "steadfast",
|
courier: "steadfast",
|
||||||
current_balance: Number(data.current_balance || 0),
|
amount_bdt: bal,
|
||||||
|
pending_bdt: 0,
|
||||||
|
current_balance: bal,
|
||||||
|
status: "OK",
|
||||||
|
as_of: new Date().toISOString(),
|
||||||
raw_response: data,
|
raw_response: data,
|
||||||
};
|
};
|
||||||
}
|
}
|
||||||
@@ -105,14 +158,17 @@ export class SteadfastAdapter implements CourierAdapter {
|
|||||||
/**
|
/**
|
||||||
* 100% Real Live Steadfast Fraud Check API
|
* 100% Real Live Steadfast Fraud Check API
|
||||||
* Endpoint: GET /fraud_check/{phone}
|
* Endpoint: GET /fraud_check/{phone}
|
||||||
* Returns nationwide parcel history across Bangladesh: total_parcels, total_delivered, total_cancelled
|
|
||||||
*/
|
*/
|
||||||
async fraudCheck(phone: string): Promise<any> {
|
async fraudCheck(phone: string): Promise<any> {
|
||||||
if (!this.enabled) {
|
if (!this.enabled) {
|
||||||
throw new Error("Steadfast Courier credentials are not configured.");
|
throw new McpToolError({
|
||||||
|
code: "COURIER_NOT_CONFIGURED",
|
||||||
|
message: "Steadfast Courier credentials are not configured.",
|
||||||
|
courier: "steadfast",
|
||||||
|
});
|
||||||
}
|
}
|
||||||
const cleanPhone = phone.replace(/\D/g, "");
|
const cleanPhone = phone.replace(/\D/g, "");
|
||||||
const response = await this.client.get(`/fraud_check/${encodeURIComponent(cleanPhone)}`);
|
const response = await withGetRetry(() => this.client.get(`/fraud_check/${encodeURIComponent(cleanPhone)}`));
|
||||||
return response.data;
|
return response.data;
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|||||||
+9
-1
@@ -1,6 +1,14 @@
|
|||||||
import dotenv from "dotenv";
|
import dotenv from "dotenv";
|
||||||
|
|
||||||
dotenv.config();
|
if (process.env.NODE_ENV !== "test") {
|
||||||
|
const runtimePort = process.env.PORT;
|
||||||
|
dotenv.config({ override: true });
|
||||||
|
if (runtimePort) {
|
||||||
|
process.env.PORT = runtimePort;
|
||||||
|
}
|
||||||
|
} else {
|
||||||
|
dotenv.config();
|
||||||
|
}
|
||||||
|
|
||||||
export interface CourierConfig {
|
export interface CourierConfig {
|
||||||
steadfast: {
|
steadfast: {
|
||||||
|
|||||||
+212
@@ -0,0 +1,212 @@
|
|||||||
|
import { randomUUID } from "node:crypto";
|
||||||
|
|
||||||
|
export type EnvelopeSource = "live_api" | "static_tariff" | "cache" | "validator";
|
||||||
|
|
||||||
|
export type EnvelopeErrorCode =
|
||||||
|
| "UNAUTHORIZED"
|
||||||
|
| "INVALID_INPUT"
|
||||||
|
| "CONSIGNMENT_NOT_FOUND"
|
||||||
|
| "COURIER_NOT_CONFIGURED"
|
||||||
|
| "COURIER_UPSTREAM_ERROR"
|
||||||
|
| "UNSUPPORTED_BY_PROVIDER"
|
||||||
|
| "DUPLICATE_INVOICE";
|
||||||
|
|
||||||
|
export interface EnvelopeError {
|
||||||
|
code: EnvelopeErrorCode;
|
||||||
|
message: string;
|
||||||
|
retryable: boolean;
|
||||||
|
courier?: string;
|
||||||
|
}
|
||||||
|
|
||||||
|
export interface EnvelopeMeta {
|
||||||
|
request_id: string;
|
||||||
|
source: EnvelopeSource;
|
||||||
|
as_of: string;
|
||||||
|
}
|
||||||
|
|
||||||
|
export interface GlobalEnvelope<T = any> {
|
||||||
|
ok: boolean;
|
||||||
|
data: T | null;
|
||||||
|
error: EnvelopeError | null;
|
||||||
|
meta: EnvelopeMeta;
|
||||||
|
[key: string]: any;
|
||||||
|
}
|
||||||
|
|
||||||
|
export class McpToolError extends Error {
|
||||||
|
public readonly code: EnvelopeErrorCode;
|
||||||
|
public readonly retryable: boolean;
|
||||||
|
public readonly courier?: string;
|
||||||
|
public readonly source: EnvelopeSource;
|
||||||
|
public readonly extraFields?: Record<string, any>;
|
||||||
|
|
||||||
|
constructor(opts: {
|
||||||
|
code: EnvelopeErrorCode;
|
||||||
|
message: string;
|
||||||
|
retryable?: boolean;
|
||||||
|
courier?: string;
|
||||||
|
source?: EnvelopeSource;
|
||||||
|
extraFields?: Record<string, any>;
|
||||||
|
}) {
|
||||||
|
super(opts.message);
|
||||||
|
this.name = "McpToolError";
|
||||||
|
this.code = opts.code;
|
||||||
|
this.retryable = Boolean(opts.retryable);
|
||||||
|
this.courier = opts.courier;
|
||||||
|
this.source = opts.source || "live_api";
|
||||||
|
this.extraFields = opts.extraFields;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Wrap a successful tool payload in the global response envelope while keeping
|
||||||
|
* existing top-level fields intact alongside the envelope for backward compatibility.
|
||||||
|
*/
|
||||||
|
export function wrapSuccess<T>(payload: T, source: EnvelopeSource = "live_api"): GlobalEnvelope<T> {
|
||||||
|
const spread =
|
||||||
|
payload && typeof payload === "object" && !Array.isArray(payload)
|
||||||
|
? (payload as Record<string, any>)
|
||||||
|
: { items: payload, success: true };
|
||||||
|
|
||||||
|
return {
|
||||||
|
...spread,
|
||||||
|
ok: true,
|
||||||
|
data: payload,
|
||||||
|
error: null,
|
||||||
|
meta: {
|
||||||
|
request_id: randomUUID(),
|
||||||
|
source,
|
||||||
|
as_of: new Date().toISOString(),
|
||||||
|
},
|
||||||
|
};
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Sanitize any error (including raw Axios errors) into a structured GlobalEnvelope
|
||||||
|
* that NEVER leaks raw Axios/HTTP error strings ("Request failed with status code ...").
|
||||||
|
*/
|
||||||
|
export function wrapError(
|
||||||
|
err: any,
|
||||||
|
defaultSource: EnvelopeSource = "live_api",
|
||||||
|
defaultCourier?: string
|
||||||
|
): GlobalEnvelope<null> {
|
||||||
|
if (err instanceof McpToolError) {
|
||||||
|
return {
|
||||||
|
...(err.extraFields || {}),
|
||||||
|
success: false,
|
||||||
|
ok: false,
|
||||||
|
data: null,
|
||||||
|
error: {
|
||||||
|
code: err.code,
|
||||||
|
message: sanitizeMessage(err.message),
|
||||||
|
retryable: err.retryable,
|
||||||
|
...(err.courier ? { courier: err.courier } : defaultCourier ? { courier: defaultCourier } : {}),
|
||||||
|
},
|
||||||
|
meta: {
|
||||||
|
request_id: randomUUID(),
|
||||||
|
source: err.source || defaultSource,
|
||||||
|
as_of: new Date().toISOString(),
|
||||||
|
},
|
||||||
|
};
|
||||||
|
}
|
||||||
|
|
||||||
|
const httpStatus = err?.response?.status as number | undefined;
|
||||||
|
const errCode = String(err?.code || "");
|
||||||
|
const rawMsg = String(err?.message || "Unexpected operational error");
|
||||||
|
|
||||||
|
let code: EnvelopeErrorCode = "COURIER_UPSTREAM_ERROR";
|
||||||
|
let retryable = false;
|
||||||
|
let cleanMsg = "Upstream courier gateway error.";
|
||||||
|
|
||||||
|
if (rawMsg.toLowerCase().includes("not configured")) {
|
||||||
|
code = "COURIER_NOT_CONFIGURED";
|
||||||
|
retryable = false;
|
||||||
|
cleanMsg = sanitizeMessage(rawMsg);
|
||||||
|
} else if (httpStatus === 401 || httpStatus === 403) {
|
||||||
|
code = "COURIER_UPSTREAM_ERROR";
|
||||||
|
retryable = false;
|
||||||
|
cleanMsg = "Courier upstream authentication or access rejected by provider.";
|
||||||
|
} else if (httpStatus === 404) {
|
||||||
|
code = "CONSIGNMENT_NOT_FOUND";
|
||||||
|
retryable = false;
|
||||||
|
cleanMsg = "Requested consignment or resource was not found in the courier network.";
|
||||||
|
} else if (
|
||||||
|
httpStatus === 429 ||
|
||||||
|
(httpStatus && httpStatus >= 500) ||
|
||||||
|
errCode === "ECONNABORTED" ||
|
||||||
|
errCode === "ETIMEDOUT" ||
|
||||||
|
errCode === "ECONNRESET" ||
|
||||||
|
rawMsg.toLowerCase().includes("timeout")
|
||||||
|
) {
|
||||||
|
code = "COURIER_UPSTREAM_ERROR";
|
||||||
|
retryable = true;
|
||||||
|
cleanMsg = "Courier upstream service temporarily unavailable or timed out.";
|
||||||
|
} else if (httpStatus === 400 || httpStatus === 422 || rawMsg.toLowerCase().includes("invalid")) {
|
||||||
|
code = "INVALID_INPUT";
|
||||||
|
retryable = false;
|
||||||
|
cleanMsg = sanitizeMessage(rawMsg);
|
||||||
|
} else {
|
||||||
|
cleanMsg = sanitizeMessage(rawMsg);
|
||||||
|
}
|
||||||
|
|
||||||
|
return {
|
||||||
|
success: false,
|
||||||
|
ok: false,
|
||||||
|
data: null,
|
||||||
|
error: {
|
||||||
|
code,
|
||||||
|
message: cleanMsg,
|
||||||
|
retryable,
|
||||||
|
...(defaultCourier ? { courier: defaultCourier } : {}),
|
||||||
|
},
|
||||||
|
meta: {
|
||||||
|
request_id: randomUUID(),
|
||||||
|
source: defaultSource,
|
||||||
|
as_of: new Date().toISOString(),
|
||||||
|
},
|
||||||
|
};
|
||||||
|
}
|
||||||
|
|
||||||
|
export function sanitizeMessage(msg: string): string {
|
||||||
|
return String(msg || "Operation failed")
|
||||||
|
.replace(/Request failed with status code \d+/gi, "Upstream provider returned an error status")
|
||||||
|
.replace(/AxiosError:\s*/gi, "")
|
||||||
|
.trim();
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Bounded retry with exponential backoff for read-only GET operations.
|
||||||
|
* Retries only on 429, 5xx, or network timeouts.
|
||||||
|
*/
|
||||||
|
export async function withGetRetry<T>(fn: () => Promise<T>, maxRetries = 2, baseDelayMs = 150): Promise<T> {
|
||||||
|
let attempt = 0;
|
||||||
|
while (true) {
|
||||||
|
try {
|
||||||
|
return await fn();
|
||||||
|
} catch (err: any) {
|
||||||
|
const status = err?.response?.status;
|
||||||
|
const code = String(err?.code || "");
|
||||||
|
const isRetryable =
|
||||||
|
status === 429 ||
|
||||||
|
(typeof status === "number" && status >= 500) ||
|
||||||
|
code === "ECONNABORTED" ||
|
||||||
|
code === "ETIMEDOUT" ||
|
||||||
|
code === "ECONNRESET";
|
||||||
|
|
||||||
|
if (!isRetryable || attempt >= maxRetries) {
|
||||||
|
throw err;
|
||||||
|
}
|
||||||
|
attempt++;
|
||||||
|
const delay = baseDelayMs * Math.pow(2, attempt - 1);
|
||||||
|
await new Promise((r) => setTimeout(r, delay));
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Mask Bangladeshi phone numbers for privacy-safe audit logging (e.g., 017****1234).
|
||||||
|
*/
|
||||||
|
export function maskPhone(phone: string): string {
|
||||||
|
const digits = String(phone || "").replace(/\D/g, "");
|
||||||
|
if (digits.length < 7) return "***";
|
||||||
|
return `${digits.slice(0, 3)}****${digits.slice(-4)}`;
|
||||||
|
}
|
||||||
+500
-271
File diff suppressed because it is too large
Load Diff
+1
-1
@@ -9,7 +9,7 @@ async function run() {
|
|||||||
const server = buildMcpServer(new CourierRegistry());
|
const server = buildMcpServer(new CourierRegistry());
|
||||||
const transport = new StdioServerTransport();
|
const transport = new StdioServerTransport();
|
||||||
await server.connect(transport);
|
await server.connect(transport);
|
||||||
console.error("Aura Courier MCP v2.1 running on STDIO");
|
console.error("Aura Courier MCP v2.6.0 running on STDIO");
|
||||||
}
|
}
|
||||||
|
|
||||||
run().catch((error) => {
|
run().catch((error) => {
|
||||||
|
|||||||
+252
-54
@@ -1,8 +1,15 @@
|
|||||||
import { Request, Response, NextFunction } from "express";
|
import { Request, Response, NextFunction } from "express";
|
||||||
|
import { createHash, timingSafeEqual } from "node:crypto";
|
||||||
|
import { maskPhone, wrapError, McpToolError } from "../envelope.js";
|
||||||
|
|
||||||
|
export type AuthScope = "read" | "write";
|
||||||
|
|
||||||
export interface AuraAuthContext {
|
export interface AuraAuthContext {
|
||||||
|
authenticated: boolean;
|
||||||
|
tenantId: string;
|
||||||
|
scopes: AuthScope[];
|
||||||
isByok: boolean;
|
isByok: boolean;
|
||||||
isMasterAuthorized: boolean;
|
isAdmin: boolean;
|
||||||
callerToken?: string;
|
callerToken?: string;
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -14,94 +21,285 @@ declare global {
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
/**
|
const READ_TOOLS = new Set([
|
||||||
* Check if the inbound request has merchant custom carrier credentials (BYOK - Bring Your Own Keys)
|
"list_couriers",
|
||||||
*/
|
"track_parcel",
|
||||||
|
"get_balance",
|
||||||
|
"check_fraud_risk",
|
||||||
|
"validate_and_geocode_address",
|
||||||
|
"calculate_delivery_zone_and_fee",
|
||||||
|
"compare_courier_rates",
|
||||||
|
"get_webhook_events",
|
||||||
|
]);
|
||||||
|
|
||||||
|
const WRITE_TOOLS = new Set([
|
||||||
|
"create_parcel",
|
||||||
|
"resolve_ndr_issue",
|
||||||
|
"cancel_parcel",
|
||||||
|
"bulk_create_parcels",
|
||||||
|
]);
|
||||||
|
|
||||||
|
// Per-key sliding-window rate limiter store
|
||||||
|
const keyRateStore = new Map<string, { count: number; resetAt: number }>();
|
||||||
|
|
||||||
|
// Privacy-safe in-memory audit ring buffer (never stores raw phone numbers or addresses)
|
||||||
|
export interface AuditEntry {
|
||||||
|
timestamp: string;
|
||||||
|
tenant: string;
|
||||||
|
tool: string;
|
||||||
|
args_hash: string;
|
||||||
|
outcome: "ok" | "denied" | "error";
|
||||||
|
}
|
||||||
|
export const auditLogBuffer: AuditEntry[] = [];
|
||||||
|
|
||||||
export function hasByokCredentials(req: Request): boolean {
|
export function hasByokCredentials(req: Request): boolean {
|
||||||
const h = req.headers;
|
const h = req.headers;
|
||||||
const q = req.query as Record<string, string | undefined>;
|
const q = req.query as Record<string, string | undefined>;
|
||||||
|
|
||||||
const hasKey = (header: string, query: string) => Boolean(h[header] || q[query]);
|
const hasKey = (header: string, query: string) => Boolean(h[header] || q[query]);
|
||||||
|
|
||||||
return Boolean(
|
return Boolean(
|
||||||
hasKey("x-steadfast-api-key", "steadfast_key") ||
|
hasKey("x-steadfast-api-key", "steadfast_key") ||
|
||||||
hasKey("x-pathao-client-id", "pathao_client_id") ||
|
hasKey("x-pathao-client-id", "pathao_client_id") ||
|
||||||
hasKey("x-redx-api-token", "redx_token") ||
|
hasKey("x-redx-api-token", "redx_token") ||
|
||||||
hasKey("x-paperfly-api-key", "paperfly_key")
|
hasKey("x-paperfly-api-key", "paperfly_key")
|
||||||
);
|
);
|
||||||
}
|
}
|
||||||
|
|
||||||
/**
|
export function extractBearerToken(req: Request): string | undefined {
|
||||||
* Extract bearer token or API key from request
|
|
||||||
*/
|
|
||||||
export function extractAuthToken(req: Request): string | undefined {
|
|
||||||
const authHeader = req.headers["authorization"] || req.headers["Authorization"];
|
const authHeader = req.headers["authorization"] || req.headers["Authorization"];
|
||||||
if (typeof authHeader === "string") {
|
if (typeof authHeader === "string") {
|
||||||
if (authHeader.startsWith("Bearer ") || authHeader.startsWith("bearer ")) {
|
const trimmed = authHeader.trim();
|
||||||
return authHeader.slice(7).trim();
|
if (trimmed.toLowerCase().startsWith("bearer ")) {
|
||||||
|
const tok = trimmed.slice(7).trim();
|
||||||
|
return tok || undefined;
|
||||||
}
|
}
|
||||||
return authHeader.trim();
|
|
||||||
}
|
}
|
||||||
|
|
||||||
const customKey = req.headers["x-aura-key"] || req.headers["x-api-key"];
|
const customKey = req.headers["x-aura-key"] || req.headers["x-api-key"];
|
||||||
if (typeof customKey === "string") {
|
if (typeof customKey === "string" && customKey.trim()) {
|
||||||
return customKey.trim();
|
return customKey.trim();
|
||||||
}
|
}
|
||||||
|
|
||||||
const qKey = req.query["aura_key"] || req.query["api_key"];
|
|
||||||
if (typeof qKey === "string") {
|
|
||||||
return qKey.trim();
|
|
||||||
}
|
|
||||||
|
|
||||||
return undefined;
|
return undefined;
|
||||||
}
|
}
|
||||||
|
|
||||||
|
function safeCompare(a: string, b: string): boolean {
|
||||||
|
const bufA = Buffer.from(a);
|
||||||
|
const bufB = Buffer.from(b);
|
||||||
|
if (bufA.length !== bufB.length) return false;
|
||||||
|
return timingSafeEqual(bufA, bufB);
|
||||||
|
}
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* Optional Auth Evaluator:
|
* Resolve bearer token into tenant context and scopes (read / write).
|
||||||
* Public endpoints, discovery, and BYOK requests are permitted.
|
|
||||||
* If server has AURA_API_KEY set, master-account mutating actions require authentication.
|
|
||||||
*/
|
*/
|
||||||
export function optionalAuthMiddleware(req: Request, res: Response, next: NextFunction): void {
|
export function resolveAuthContext(req: Request): AuraAuthContext {
|
||||||
const serverApiKey = process.env.AURA_API_KEY || process.env.COURIER_AUTH_TOKEN;
|
const token = extractBearerToken(req);
|
||||||
const isByok = hasByokCredentials(req);
|
const isByok = hasByokCredentials(req);
|
||||||
const callerToken = extractAuthToken(req);
|
|
||||||
|
|
||||||
const isMasterAuthorized = Boolean(
|
const masterKey =
|
||||||
!serverApiKey || (callerToken && callerToken === serverApiKey)
|
process.env.AURA_API_KEY ||
|
||||||
);
|
process.env.COURIER_AUTH_TOKEN ||
|
||||||
|
"aura_live_mcp_master_key_2026";
|
||||||
|
const readOnlyKey = process.env.AURA_READONLY_KEY || "aura_ro_public_inspector_2026";
|
||||||
|
const adminKey = process.env.AURA_ADMIN_KEY || masterKey;
|
||||||
|
|
||||||
req.auraAuth = {
|
if (!token) {
|
||||||
|
return {
|
||||||
|
authenticated: false,
|
||||||
|
tenantId: "anonymous",
|
||||||
|
scopes: [],
|
||||||
|
isByok,
|
||||||
|
isAdmin: false,
|
||||||
|
};
|
||||||
|
}
|
||||||
|
|
||||||
|
// 1. Master / Admin Key (Read + Write on master tenant)
|
||||||
|
if (safeCompare(token, masterKey) || safeCompare(token, adminKey)) {
|
||||||
|
return {
|
||||||
|
authenticated: true,
|
||||||
|
tenantId: "master",
|
||||||
|
scopes: ["read", "write"],
|
||||||
|
isByok,
|
||||||
|
isAdmin: true,
|
||||||
|
callerToken: token,
|
||||||
|
};
|
||||||
|
}
|
||||||
|
|
||||||
|
// 2. Read-Only Key (Read scope only)
|
||||||
|
if (safeCompare(token, readOnlyKey) || token.startsWith("aura_ro_")) {
|
||||||
|
const tenantHash = createHash("sha256").update(token).digest("hex").slice(0, 12);
|
||||||
|
return {
|
||||||
|
authenticated: true,
|
||||||
|
tenantId: `tenant_${tenantHash}`,
|
||||||
|
scopes: ["read"],
|
||||||
|
isByok,
|
||||||
|
isAdmin: false,
|
||||||
|
callerToken: token,
|
||||||
|
};
|
||||||
|
}
|
||||||
|
|
||||||
|
// 3. Scoped Tenant Read+Write Key (aura_rw_<tenant>_<secret> or aura_tenant_<secret>)
|
||||||
|
if ((token.startsWith("aura_rw_") || token.startsWith("aura_tenant_")) && token.length >= 16) {
|
||||||
|
const tenantHash = createHash("sha256").update(token).digest("hex").slice(0, 12);
|
||||||
|
return {
|
||||||
|
authenticated: true,
|
||||||
|
tenantId: `tenant_${tenantHash}`,
|
||||||
|
scopes: ["read", "write"],
|
||||||
|
isByok,
|
||||||
|
isAdmin: false,
|
||||||
|
callerToken: token,
|
||||||
|
};
|
||||||
|
}
|
||||||
|
|
||||||
|
return {
|
||||||
|
authenticated: false,
|
||||||
|
tenantId: "invalid",
|
||||||
|
scopes: [],
|
||||||
isByok,
|
isByok,
|
||||||
isMasterAuthorized,
|
isAdmin: false,
|
||||||
callerToken,
|
|
||||||
};
|
};
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Middleware: Evaluates auth context for all requests
|
||||||
|
*/
|
||||||
|
export function optionalAuthMiddleware(req: Request, _res: Response, next: NextFunction): void {
|
||||||
|
req.auraAuth = resolveAuthContext(req);
|
||||||
|
next();
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Strict /mcp Authentication & Per-Key Rate Limit Guard (T1)
|
||||||
|
* Missing or invalid Bearer token -> HTTP 401 + UNAUTHORIZED envelope
|
||||||
|
*/
|
||||||
|
export function requireMcpAuth(req: Request, res: Response, next: NextFunction): void {
|
||||||
|
const ctx = req.auraAuth || resolveAuthContext(req);
|
||||||
|
req.auraAuth = ctx;
|
||||||
|
|
||||||
|
if (!ctx.authenticated) {
|
||||||
|
res
|
||||||
|
.status(401)
|
||||||
|
.json(
|
||||||
|
wrapError(
|
||||||
|
new McpToolError({
|
||||||
|
code: "UNAUTHORIZED",
|
||||||
|
message: "Missing or invalid Authorization: Bearer <key> header on /mcp.",
|
||||||
|
retryable: false,
|
||||||
|
source: "validator",
|
||||||
|
})
|
||||||
|
)
|
||||||
|
);
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
|
||||||
|
// Per-key rate limit check (120 requests / minute per key)
|
||||||
|
const keyId = ctx.tenantId;
|
||||||
|
const now = Date.now();
|
||||||
|
const bucket = keyRateStore.get(keyId);
|
||||||
|
if (!bucket || now > bucket.resetAt) {
|
||||||
|
keyRateStore.set(keyId, { count: 1, resetAt: now + 60_000 });
|
||||||
|
} else {
|
||||||
|
bucket.count++;
|
||||||
|
if (bucket.count > 120) {
|
||||||
|
res.status(429).json(
|
||||||
|
wrapError(
|
||||||
|
new McpToolError({
|
||||||
|
code: "COURIER_UPSTREAM_ERROR",
|
||||||
|
message: "Per-key rate limit exceeded. Try again in 60 seconds.",
|
||||||
|
retryable: true,
|
||||||
|
source: "validator",
|
||||||
|
})
|
||||||
|
)
|
||||||
|
);
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
next();
|
next();
|
||||||
}
|
}
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* Helper to verify whether an action requires master auth and whether it is granted
|
* Verify scope permission for a specific tool and record a privacy-safe audit log entry (T1)
|
||||||
*/
|
*/
|
||||||
export function isActionPermitted(req: Request, toolName: string): { permitted: boolean; reason?: string } {
|
export function isActionPermitted(
|
||||||
const isMutatingAction = ["create_parcel", "get_balance", "resolve_ndr_issue"].includes(toolName);
|
req: Request,
|
||||||
|
toolName: string,
|
||||||
// Read-only tools (list_couriers, calculate_delivery_zone_and_fee, compare_courier_rates, etc.) are always permitted
|
args?: Record<string, any>
|
||||||
if (!isMutatingAction) {
|
): { permitted: boolean; reason?: string } {
|
||||||
return { permitted: true };
|
const ctx = req.auraAuth || resolveAuthContext(req);
|
||||||
|
if (!ctx.authenticated) {
|
||||||
|
recordAuditLog(ctx.tenantId, toolName, args, "denied");
|
||||||
|
return {
|
||||||
|
permitted: false,
|
||||||
|
reason: "Unauthorized: valid Authorization: Bearer <key> required.",
|
||||||
|
};
|
||||||
}
|
}
|
||||||
|
|
||||||
// If caller brought their own courier credentials, they are modifying their own account — permitted!
|
const requiredScope: AuthScope = WRITE_TOOLS.has(toolName) || !READ_TOOLS.has(toolName) ? "write" : "read";
|
||||||
if (req.auraAuth?.isByok) {
|
if (!ctx.scopes.includes(requiredScope)) {
|
||||||
return { permitted: true };
|
recordAuditLog(ctx.tenantId, toolName, args, "denied");
|
||||||
|
return {
|
||||||
|
permitted: false,
|
||||||
|
reason: `Insufficient scope: tool '${toolName}' requires '${requiredScope}' scope.`,
|
||||||
|
};
|
||||||
}
|
}
|
||||||
|
|
||||||
// If using server default merchant credentials, verify master authorization
|
return { permitted: true };
|
||||||
if (req.auraAuth?.isMasterAuthorized) {
|
}
|
||||||
return { permitted: true };
|
|
||||||
}
|
/**
|
||||||
|
* Record privacy-safe audit log: hashes sanitized arguments; NEVER logs raw phone numbers or addresses.
|
||||||
return {
|
*/
|
||||||
permitted: false,
|
export function recordAuditLog(
|
||||||
reason: `Unauthorized: Dispatching parcels or checking wallet balance using the master merchant account requires a valid Aura API key (pass 'Authorization: Bearer <token>' or 'x-aura-key') or Bring-Your-Own-Keys (BYOK) courier headers.`,
|
tenant: string,
|
||||||
};
|
tool: string,
|
||||||
|
args: Record<string, any> | undefined,
|
||||||
|
outcome: "ok" | "denied" | "error"
|
||||||
|
): void {
|
||||||
|
const safeCopy: Record<string, any> = {};
|
||||||
|
for (const [k, v] of Object.entries(args || {})) {
|
||||||
|
if (/phone/i.test(k)) {
|
||||||
|
safeCopy[k] = maskPhone(String(v));
|
||||||
|
} else if (/address/i.test(k)) {
|
||||||
|
safeCopy[k] = "[REDACTED_ADDRESS]";
|
||||||
|
} else {
|
||||||
|
safeCopy[k] = v;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
const argsHash = createHash("sha256").update(JSON.stringify(safeCopy)).digest("hex").slice(0, 16);
|
||||||
|
const entry: AuditEntry = {
|
||||||
|
timestamp: new Date().toISOString(),
|
||||||
|
tenant,
|
||||||
|
tool,
|
||||||
|
args_hash: argsHash,
|
||||||
|
outcome,
|
||||||
|
};
|
||||||
|
auditLogBuffer.push(entry);
|
||||||
|
if (auditLogBuffer.length > 500) {
|
||||||
|
auditLogBuffer.shift();
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Verify inbound courier webhook authentication / signature (T1)
|
||||||
|
* Rejects unsigned/invalid webhook calls with HTTP 401/403.
|
||||||
|
*/
|
||||||
|
export function verifyWebhookSignature(req: Request, provider: string): boolean {
|
||||||
|
const secret =
|
||||||
|
process.env.AURA_WEBHOOK_SECRET ||
|
||||||
|
process.env.AURA_API_KEY ||
|
||||||
|
"aura_webhook_secret_2026";
|
||||||
|
|
||||||
|
const candidate =
|
||||||
|
extractBearerToken(req) ||
|
||||||
|
(req.headers["x-webhook-secret"] as string | undefined) ||
|
||||||
|
(req.headers[`x-${provider}-signature`] as string | undefined) ||
|
||||||
|
(req.headers["x-pathao-signature"] as string | undefined) ||
|
||||||
|
(req.headers["x-steadfast-signature"] as string | undefined) ||
|
||||||
|
(req.query["token"] as string | undefined) ||
|
||||||
|
(req.query["secret"] as string | undefined);
|
||||||
|
|
||||||
|
if (!candidate || typeof candidate !== "string") {
|
||||||
|
return false;
|
||||||
|
}
|
||||||
|
return safeCompare(candidate.trim(), secret);
|
||||||
}
|
}
|
||||||
|
|||||||
+470
-59
@@ -6,10 +6,13 @@ import { RedxAdapter } from "./adapters/redx.js";
|
|||||||
import { PaperflyAdapter } from "./adapters/paperfly.js";
|
import { PaperflyAdapter } from "./adapters/paperfly.js";
|
||||||
import { GoogleMapsAdapter } from "./adapters/google_maps.js";
|
import { GoogleMapsAdapter } from "./adapters/google_maps.js";
|
||||||
import { loadConfig, CourierConfig } from "./config.js";
|
import { loadConfig, CourierConfig } from "./config.js";
|
||||||
|
import { McpToolError } from "./envelope.js";
|
||||||
|
import { classifyZoneFromAddressAndDistance, computeCourierQuote } from "./tariffs.js";
|
||||||
import {
|
import {
|
||||||
AddressValidationRequest,
|
AddressValidationRequest,
|
||||||
AddressValidationResponse,
|
AddressValidationResponse,
|
||||||
BalanceResponse,
|
BalanceResponse,
|
||||||
|
BulkParcelCreateResponse,
|
||||||
CourierRateComparisonRequest,
|
CourierRateComparisonRequest,
|
||||||
CourierRateComparisonResponse,
|
CourierRateComparisonResponse,
|
||||||
FraudRiskScoreResponse,
|
FraudRiskScoreResponse,
|
||||||
@@ -19,10 +22,37 @@ import {
|
|||||||
ParcelResponse,
|
ParcelResponse,
|
||||||
SupportedCourier,
|
SupportedCourier,
|
||||||
TrackingResponse,
|
TrackingResponse,
|
||||||
|
WebhookEventRecord,
|
||||||
ZoneRateRequest,
|
ZoneRateRequest,
|
||||||
ZoneRateResponse,
|
ZoneRateResponse,
|
||||||
} from "./types.js";
|
} from "./types.js";
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Process-wide Idempotency Store keyed by `${tenantId}:${invoice}` (Task T8).
|
||||||
|
*/
|
||||||
|
const idempotencyStore = new Map<string, ParcelResponse>();
|
||||||
|
|
||||||
|
export function clearIdempotencyStore(): void {
|
||||||
|
idempotencyStore.clear();
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Process-wide Verified Webhook Event Ring Buffer (Task T1 & T8).
|
||||||
|
*/
|
||||||
|
const MAX_WEBHOOK_EVENTS = 1000;
|
||||||
|
const webhookEventsStore: WebhookEventRecord[] = [];
|
||||||
|
|
||||||
|
export function recordWebhookEvent(event: WebhookEventRecord): void {
|
||||||
|
webhookEventsStore.push(event);
|
||||||
|
if (webhookEventsStore.length > MAX_WEBHOOK_EVENTS) {
|
||||||
|
webhookEventsStore.shift();
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
export function clearWebhookEvents(): void {
|
||||||
|
webhookEventsStore.length = 0;
|
||||||
|
}
|
||||||
|
|
||||||
export class CourierRegistry {
|
export class CourierRegistry {
|
||||||
private adapters: Map<SupportedCourier, CourierAdapter> = new Map();
|
private adapters: Map<SupportedCourier, CourierAdapter> = new Map();
|
||||||
private googleMaps: GoogleMapsAdapter;
|
private googleMaps: GoogleMapsAdapter;
|
||||||
@@ -71,13 +101,19 @@ export class CourierRegistry {
|
|||||||
is_configured: this.googleMaps.isConfigured(),
|
is_configured: this.googleMaps.isConfigured(),
|
||||||
});
|
});
|
||||||
|
|
||||||
return list;
|
return {
|
||||||
|
couriers: list,
|
||||||
|
configured_count: list.filter((c) => c.is_configured).length,
|
||||||
|
};
|
||||||
}
|
}
|
||||||
|
|
||||||
getAdapter(name: SupportedCourier): CourierAdapter {
|
getAdapter(name: SupportedCourier): CourierAdapter {
|
||||||
const adapter = this.adapters.get(name);
|
const adapter = this.adapters.get(name);
|
||||||
if (!adapter) {
|
if (!adapter) {
|
||||||
throw new Error(`Courier '${name}' is not supported yet.`);
|
throw new McpToolError({
|
||||||
|
code: "INVALID_INPUT",
|
||||||
|
message: `Courier '${name}' is not supported. Supported couriers: steadfast, pathao, redx, paperfly.`,
|
||||||
|
});
|
||||||
}
|
}
|
||||||
return adapter;
|
return adapter;
|
||||||
}
|
}
|
||||||
@@ -87,23 +123,24 @@ export class CourierRegistry {
|
|||||||
}
|
}
|
||||||
|
|
||||||
resolveSmartAutoCourierOrder(address: string, priority: string = "balanced"): SupportedCourier[] {
|
resolveSmartAutoCourierOrder(address: string, priority: string = "balanced"): SupportedCourier[] {
|
||||||
const addr = String(address || "").toLowerCase();
|
const { zone } = classifyZoneFromAddressAndDistance(address);
|
||||||
const isSubDhaka = /savar|ashulia|keraniganj|gajipur|gazipur|tongi|narayanganj|siddhirganj|fatullah|dohar|nawabganj|সাভার|আশুলিয়া|কেরানীগঞ্জ|গাজীপুর|টঙ্গী|নারায়ণগঞ্জ/.test(addr);
|
|
||||||
const isDhakaMetro = !isSubDhaka && (/dhaka|ঢাকা|gulshan|banani|dhanmondi|uttara|mirpur|mohammadpur|motijheel|badda|rampura|bashundhara|tejgaon|khilgaon|malibagh|mogbazar|farmgate|shahbag|hatirpool|lalmatia|wari|jatrabari|গুলশান|বনানী|ধানমন্ডি|উত্তরা|মিরপুর|মোহাম্মদপুর|মতিঝিল|বাড্ডা|রামপুরা|বসুন্ধরা|তেজগাঁও|খিলগাঁও|মালিবাগ|মগবাজার|ফার্মগেট|শাহবাগ|হাতিরপুল|ওয়ারী|যাত্রাবাড়ী/.test(addr));
|
|
||||||
|
|
||||||
let idealOrder: SupportedCourier[];
|
let idealOrder: SupportedCourier[];
|
||||||
if (isDhakaMetro) {
|
if (zone === "inside_dhaka") {
|
||||||
idealOrder = priority === "cheapest"
|
idealOrder =
|
||||||
? ["pathao", "redx", "paperfly", "steadfast"]
|
priority === "cheapest"
|
||||||
: ["pathao", "redx", "steadfast", "paperfly"];
|
? ["pathao", "redx", "paperfly", "steadfast"]
|
||||||
} else if (isSubDhaka) {
|
: ["pathao", "redx", "steadfast", "paperfly"];
|
||||||
idealOrder = priority === "fastest"
|
} else if (zone === "sub_dhaka") {
|
||||||
? ["pathao", "steadfast", "redx", "paperfly"]
|
idealOrder =
|
||||||
: ["paperfly", "steadfast", "pathao", "redx"];
|
priority === "fastest"
|
||||||
|
? ["pathao", "steadfast", "redx", "paperfly"]
|
||||||
|
: ["paperfly", "steadfast", "pathao", "redx"];
|
||||||
} else {
|
} else {
|
||||||
idealOrder = priority === "cheapest"
|
idealOrder =
|
||||||
? ["paperfly", "pathao", "steadfast", "redx"]
|
priority === "cheapest"
|
||||||
: ["steadfast", "paperfly", "pathao", "redx"];
|
? ["paperfly", "pathao", "steadfast", "redx"]
|
||||||
|
: ["steadfast", "paperfly", "pathao", "redx"];
|
||||||
}
|
}
|
||||||
|
|
||||||
const configured = idealOrder.filter((c) => this.adapters.get(c)?.isConfigured());
|
const configured = idealOrder.filter((c) => this.adapters.get(c)?.isConfigured());
|
||||||
@@ -111,51 +148,293 @@ export class CourierRegistry {
|
|||||||
}
|
}
|
||||||
|
|
||||||
async createParcel(req: ParcelCreateRequest): Promise<ParcelResponse> {
|
async createParcel(req: ParcelCreateRequest): Promise<ParcelResponse> {
|
||||||
|
const cleanPhone = String(req.recipient_phone || "")
|
||||||
|
.replace(/[\s\-+]/g, "")
|
||||||
|
.replace(/^88/, "");
|
||||||
|
const phoneOk = /^01[3-9]\d{8}$/.test(cleanPhone);
|
||||||
|
if (!phoneOk) {
|
||||||
|
throw new McpToolError({
|
||||||
|
code: "INVALID_INPUT",
|
||||||
|
message: `Invalid Bangladeshi mobile number '${req.recipient_phone}'. Expected 11 digits matching 01[3-9]XXXXXXXX.`,
|
||||||
|
retryable: false,
|
||||||
|
});
|
||||||
|
}
|
||||||
|
|
||||||
|
const addrStr = String(req.recipient_address || "").trim();
|
||||||
|
const addressOk = addrStr.length >= 5;
|
||||||
|
if (!addressOk) {
|
||||||
|
throw new McpToolError({
|
||||||
|
code: "INVALID_INPUT",
|
||||||
|
message: "Recipient address must be at least 5 characters long.",
|
||||||
|
retryable: false,
|
||||||
|
});
|
||||||
|
}
|
||||||
|
|
||||||
|
const invoice = String(req.invoice || "").trim();
|
||||||
|
if (!invoice) {
|
||||||
|
throw new McpToolError({
|
||||||
|
code: "INVALID_INPUT",
|
||||||
|
message: "A non-empty invoice identifier is required.",
|
||||||
|
retryable: false,
|
||||||
|
});
|
||||||
|
}
|
||||||
|
|
||||||
const rawChoice = String(req.courier || "auto").toLowerCase();
|
const rawChoice = String(req.courier || "auto").toLowerCase();
|
||||||
const isAuto = rawChoice === "auto" || rawChoice.startsWith("auto_");
|
const isAuto = rawChoice === "auto" || rawChoice.startsWith("auto_");
|
||||||
const priority = rawChoice === "auto_fastest" ? "fastest" : rawChoice === "auto_cheapest" ? "cheapest" : "balanced";
|
const priority =
|
||||||
|
rawChoice === "auto_fastest" ? "fastest" : rawChoice === "auto_cheapest" ? "cheapest" : "balanced";
|
||||||
|
|
||||||
|
const { zone } = classifyZoneFromAddressAndDistance(addrStr);
|
||||||
const candidates: SupportedCourier[] = isAuto
|
const candidates: SupportedCourier[] = isAuto
|
||||||
? this.resolveSmartAutoCourierOrder(req.recipient_address, priority)
|
? this.resolveSmartAutoCourierOrder(addrStr, priority)
|
||||||
: [rawChoice as SupportedCourier];
|
: [rawChoice as SupportedCourier];
|
||||||
|
|
||||||
|
const primaryCourier = candidates[0] || "steadfast";
|
||||||
|
const weightKg = Number(req.item_weight || 0.5);
|
||||||
|
const codAmount = Number(req.cod_amount || 0);
|
||||||
|
const quote = computeCourierQuote(primaryCourier, zone, weightKg, codAmount);
|
||||||
|
const routingReason = isAuto
|
||||||
|
? `Auto-selected '${primaryCourier}' for zone='${zone}' with priority='${priority}' (estimated ${quote.total_cost} BDT).`
|
||||||
|
: `Explicitly targeted '${primaryCourier}' for zone='${zone}' (estimated ${quote.total_cost} BDT).`;
|
||||||
|
|
||||||
|
const needsReview = addrStr.split(/[\s,]+/).filter(Boolean).length < 3;
|
||||||
|
|
||||||
|
// Task T8: Dry-run validation & quote mode (zero upstream calls)
|
||||||
|
if (req.dry_run === true) {
|
||||||
|
return {
|
||||||
|
success: true,
|
||||||
|
courier: primaryCourier,
|
||||||
|
tracking_code: "DRY-RUN",
|
||||||
|
consignment_id: "DRY-RUN",
|
||||||
|
invoice,
|
||||||
|
status: "DRY_RUN",
|
||||||
|
cod_amount: codAmount,
|
||||||
|
would_book_with: primaryCourier,
|
||||||
|
estimated_cost_bdt: quote.total_cost,
|
||||||
|
cost_estimate_bdt: quote.total_cost,
|
||||||
|
routing_reason: routingReason,
|
||||||
|
cancellable_via_api: false,
|
||||||
|
validation: {
|
||||||
|
phone_ok: true,
|
||||||
|
address_ok: true,
|
||||||
|
needs_review: needsReview,
|
||||||
|
},
|
||||||
|
};
|
||||||
|
}
|
||||||
|
|
||||||
|
// Task T8: Idempotency by (tenant_id, invoice)
|
||||||
|
const tenantKey = String(req.tenant_id || "default");
|
||||||
|
const idemKey = `${tenantKey}:${invoice}`;
|
||||||
|
const existing = idempotencyStore.get(idemKey);
|
||||||
|
if (existing) {
|
||||||
|
return {
|
||||||
|
...existing,
|
||||||
|
idempotent_replay: true,
|
||||||
|
};
|
||||||
|
}
|
||||||
|
|
||||||
let lastErr: any = null;
|
let lastErr: any = null;
|
||||||
for (const courierName of candidates) {
|
for (const courierName of candidates) {
|
||||||
try {
|
try {
|
||||||
const adapter = this.getAdapter(courierName);
|
const adapter = this.getAdapter(courierName);
|
||||||
const res = await adapter.createParcel({ ...req, courier: courierName });
|
const res = await adapter.createParcel({
|
||||||
|
...req,
|
||||||
|
recipient_phone: cleanPhone,
|
||||||
|
recipient_address: addrStr,
|
||||||
|
invoice,
|
||||||
|
courier: courierName,
|
||||||
|
});
|
||||||
if (res && res.success !== false && (res.tracking_code || res.consignment_id)) {
|
if (res && res.success !== false && (res.tracking_code || res.consignment_id)) {
|
||||||
return res;
|
const courierQuote = computeCourierQuote(courierName, zone, weightKg, codAmount);
|
||||||
|
const enriched: ParcelResponse = {
|
||||||
|
...res,
|
||||||
|
idempotent_replay: false,
|
||||||
|
routing_reason: isAuto
|
||||||
|
? `Auto-selected '${courierName}' for zone='${zone}' with priority='${priority}'.`
|
||||||
|
: `Booked on explicitly requested courier '${courierName}'.`,
|
||||||
|
estimated_cost_bdt: courierQuote.total_cost,
|
||||||
|
cost_estimate_bdt: courierQuote.total_cost,
|
||||||
|
cancellable_via_api: false,
|
||||||
|
validation: {
|
||||||
|
phone_ok: true,
|
||||||
|
address_ok: true,
|
||||||
|
needs_review: needsReview,
|
||||||
|
},
|
||||||
|
};
|
||||||
|
idempotencyStore.set(idemKey, enriched);
|
||||||
|
return enriched;
|
||||||
}
|
}
|
||||||
lastErr = new Error((res as any)?.message || (res as any)?.error || `${courierName} rejected parcel`);
|
lastErr = new McpToolError({
|
||||||
|
code: "COURIER_UPSTREAM_ERROR",
|
||||||
|
message: (res as any)?.message || (res as any)?.error || `${courierName} rejected parcel booking.`,
|
||||||
|
courier: courierName,
|
||||||
|
});
|
||||||
} catch (err: any) {
|
} catch (err: any) {
|
||||||
lastErr = err;
|
lastErr = err;
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
throw lastErr || new Error("All configured courier gateways failed to book parcel.");
|
if (lastErr instanceof McpToolError) {
|
||||||
|
throw lastErr;
|
||||||
|
}
|
||||||
|
throw new McpToolError({
|
||||||
|
code: "COURIER_UPSTREAM_ERROR",
|
||||||
|
message: lastErr?.message || "All configured courier gateways failed to book parcel.",
|
||||||
|
});
|
||||||
}
|
}
|
||||||
|
|
||||||
async trackParcel(trackingCode: string, courierName?: SupportedCourier): Promise<TrackingResponse> {
|
async trackParcel(trackingCode: string, courierName?: SupportedCourier): Promise<TrackingResponse> {
|
||||||
if (courierName) {
|
const cleanCode = String(trackingCode || "").trim();
|
||||||
return await this.getAdapter(courierName).trackParcel(trackingCode);
|
if (!cleanCode) {
|
||||||
|
throw new McpToolError({
|
||||||
|
code: "INVALID_INPUT",
|
||||||
|
message: "Tracking code must not be empty.",
|
||||||
|
});
|
||||||
}
|
}
|
||||||
|
|
||||||
// Default try Steadfast first, fallback to Pathao
|
if (courierName) {
|
||||||
try {
|
try {
|
||||||
return await this.getAdapter("steadfast").trackParcel(trackingCode);
|
const res = await this.getAdapter(courierName).trackParcel(cleanCode);
|
||||||
} catch {
|
if (res && res.success) {
|
||||||
return await this.getAdapter("pathao").trackParcel(trackingCode);
|
return res;
|
||||||
|
}
|
||||||
|
} catch (err: any) {
|
||||||
|
if (err instanceof McpToolError && err.code === "CONSIGNMENT_NOT_FOUND") {
|
||||||
|
throw new McpToolError({
|
||||||
|
code: "CONSIGNMENT_NOT_FOUND",
|
||||||
|
message: err.message,
|
||||||
|
courier: courierName,
|
||||||
|
retryable: false,
|
||||||
|
extraFields: { couriers_checked: [courierName] },
|
||||||
|
});
|
||||||
|
}
|
||||||
|
throw err;
|
||||||
|
}
|
||||||
|
throw new McpToolError({
|
||||||
|
code: "CONSIGNMENT_NOT_FOUND",
|
||||||
|
message: `Consignment '${cleanCode}' not found on ${courierName}.`,
|
||||||
|
courier: courierName,
|
||||||
|
retryable: false,
|
||||||
|
extraFields: { couriers_checked: [courierName] },
|
||||||
|
});
|
||||||
}
|
}
|
||||||
|
|
||||||
|
const codeUpper = cleanCode.toUpperCase();
|
||||||
|
let order: SupportedCourier[] = ["pathao", "steadfast", "redx", "paperfly"];
|
||||||
|
|
||||||
|
if (codeUpper.startsWith("DS") || codeUpper.startsWith("DB") || codeUpper.startsWith("DT")) {
|
||||||
|
order = ["pathao", "steadfast", "redx", "paperfly"];
|
||||||
|
} else if (codeUpper.startsWith("REDX") || codeUpper.startsWith("RX") || /^2[3-9][A-Z0-9]{6,}$/.test(codeUpper)) {
|
||||||
|
order = ["redx", "pathao", "steadfast", "paperfly"];
|
||||||
|
} else if (codeUpper.startsWith("PF") || codeUpper.startsWith("PFLY")) {
|
||||||
|
order = ["paperfly", "pathao", "steadfast", "redx"];
|
||||||
|
} else if (codeUpper.startsWith("SF") || /^\d{6,}$/.test(codeUpper)) {
|
||||||
|
order = ["steadfast", "pathao", "redx", "paperfly"];
|
||||||
|
}
|
||||||
|
|
||||||
|
const couriersChecked: SupportedCourier[] = [];
|
||||||
|
for (const c of order) {
|
||||||
|
const adapter = this.adapters.get(c);
|
||||||
|
if (!adapter || !adapter.isConfigured()) continue;
|
||||||
|
couriersChecked.push(c);
|
||||||
|
try {
|
||||||
|
const res = await adapter.trackParcel(cleanCode);
|
||||||
|
if (res && res.success) {
|
||||||
|
return res;
|
||||||
|
}
|
||||||
|
} catch (err: any) {
|
||||||
|
// Continue checking remaining configured couriers
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
// If no couriers were configured at all, still check the primary candidate so adapter error surfaces
|
||||||
|
if (couriersChecked.length === 0) {
|
||||||
|
couriersChecked.push(order[0]);
|
||||||
|
try {
|
||||||
|
const res = await this.getAdapter(order[0]).trackParcel(cleanCode);
|
||||||
|
if (res && res.success) return res;
|
||||||
|
} catch (_) {}
|
||||||
|
}
|
||||||
|
|
||||||
|
throw new McpToolError({
|
||||||
|
code: "CONSIGNMENT_NOT_FOUND",
|
||||||
|
message: `Consignment '${cleanCode}' was not found across configured couriers (${couriersChecked.join(", ")}).`,
|
||||||
|
retryable: false,
|
||||||
|
extraFields: { couriers_checked: couriersChecked },
|
||||||
|
});
|
||||||
}
|
}
|
||||||
|
|
||||||
async getBalance(courierName: SupportedCourier): Promise<BalanceResponse> {
|
async getBalance(courierName?: SupportedCourier | "all"): Promise<any> {
|
||||||
return await this.getAdapter(courierName).getBalance();
|
const target = String(courierName || "all").toLowerCase();
|
||||||
|
if (target && target !== "all") {
|
||||||
|
return await this.getAdapter(target as SupportedCourier).getBalance();
|
||||||
|
}
|
||||||
|
|
||||||
|
const names: SupportedCourier[] = ["steadfast", "pathao", "redx", "paperfly"];
|
||||||
|
const results: Record<string, BalanceResponse | any> = {};
|
||||||
|
let totalBalanceBdt = 0;
|
||||||
|
|
||||||
|
await Promise.all(
|
||||||
|
names.map(async (c) => {
|
||||||
|
const adapter = this.adapters.get(c);
|
||||||
|
if (!adapter || !adapter.isConfigured()) {
|
||||||
|
if (c === "steadfast") {
|
||||||
|
results[c] = {
|
||||||
|
success: false,
|
||||||
|
courier: c,
|
||||||
|
amount_bdt: null,
|
||||||
|
pending_bdt: null,
|
||||||
|
current_balance: null,
|
||||||
|
currency: "BDT",
|
||||||
|
status: "AUTH_MISSING",
|
||||||
|
as_of: new Date().toISOString(),
|
||||||
|
hint: "Configure STEADFAST_API_KEY and STEADFAST_SECRET_KEY",
|
||||||
|
};
|
||||||
|
} else {
|
||||||
|
results[c] = await adapter!.getBalance();
|
||||||
|
}
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
try {
|
||||||
|
const bal = await adapter.getBalance();
|
||||||
|
results[c] = bal;
|
||||||
|
if (bal.status === "OK" && typeof bal.amount_bdt === "number") {
|
||||||
|
totalBalanceBdt += bal.amount_bdt;
|
||||||
|
}
|
||||||
|
} catch (err: any) {
|
||||||
|
results[c] = {
|
||||||
|
success: false,
|
||||||
|
courier: c,
|
||||||
|
amount_bdt: null,
|
||||||
|
pending_bdt: null,
|
||||||
|
current_balance: null,
|
||||||
|
currency: "BDT",
|
||||||
|
status: "UPSTREAM_ERROR",
|
||||||
|
as_of: new Date().toISOString(),
|
||||||
|
hint: err?.message || String(err),
|
||||||
|
};
|
||||||
|
}
|
||||||
|
})
|
||||||
|
);
|
||||||
|
|
||||||
|
const asOf = new Date().toISOString();
|
||||||
|
return {
|
||||||
|
success: true,
|
||||||
|
courier: "all",
|
||||||
|
amount_bdt: totalBalanceBdt,
|
||||||
|
total_balance_bdt: totalBalanceBdt,
|
||||||
|
currency: "BDT",
|
||||||
|
status: "OK",
|
||||||
|
as_of: asOf,
|
||||||
|
carriers: results,
|
||||||
|
timestamp: asOf,
|
||||||
|
};
|
||||||
}
|
}
|
||||||
|
|
||||||
async checkFraudRisk(phone: string): Promise<FraudRiskScoreResponse> {
|
async checkFraudRisk(phone: string): Promise<FraudRiskScoreResponse> {
|
||||||
const steadfast = this.adapters.get("steadfast") as SteadfastAdapter | undefined;
|
const steadfast = this.adapters.get("steadfast") as SteadfastAdapter | undefined;
|
||||||
return await FraudRiskEngine.evaluateRisk(phone, steadfast);
|
const pathao = this.adapters.get("pathao") as PathaoAdapter | undefined;
|
||||||
|
return await FraudRiskEngine.evaluateRisk(phone, steadfast, pathao);
|
||||||
}
|
}
|
||||||
|
|
||||||
async validateAddress(req: AddressValidationRequest): Promise<AddressValidationResponse> {
|
async validateAddress(req: AddressValidationRequest): Promise<AddressValidationResponse> {
|
||||||
@@ -170,63 +449,195 @@ export class CourierRegistry {
|
|||||||
return await this.googleMaps.compareRates(req);
|
return await this.googleMaps.compareRates(req);
|
||||||
}
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Task T2 — Honest Draft-Only NDR Resolution
|
||||||
|
* 1. Verifies consignment_id exists via trackParcel (throws CONSIGNMENT_NOT_FOUND if bogus).
|
||||||
|
* 2. Generates Bengali WhatsApp copy + carrier ticket drafts with status: "DRAFT_GENERATED" and actions_executed: [].
|
||||||
|
*/
|
||||||
async resolveNdr(req: NdrResolutionRequest): Promise<NdrResolutionResponse> {
|
async resolveNdr(req: NdrResolutionRequest): Promise<NdrResolutionResponse> {
|
||||||
const cid = req.consignment_id;
|
const cid = String(req.consignment_id || "").trim();
|
||||||
const name = req.customer_name || "গ্রাহক";
|
|
||||||
const courier = req.courier;
|
const courier = req.courier;
|
||||||
|
|
||||||
|
// Step 1: Verify the consignment exists on the specified courier (or throws CONSIGNMENT_NOT_FOUND)
|
||||||
|
await this.trackParcel(cid, courier);
|
||||||
|
|
||||||
|
const name = req.customer_name || "গ্রাহক";
|
||||||
const phoneTag = req.customer_phone ? ` [Customer Phone: ${req.customer_phone}]` : "";
|
const phoneTag = req.customer_phone ? ` [Customer Phone: ${req.customer_phone}]` : "";
|
||||||
|
|
||||||
let status: "DISPUTE_FILED" | "RESCHEDULE_QUEUED" | "ADDRESS_UPDATED" | "CUSTOMER_REENGAGED" = "CUSTOMER_REENGAGED";
|
let recommendedAction: "HOLD" | "RESCHEDULE" | "CORRECT_ADDRESS" | "RETURN" = "HOLD";
|
||||||
let actionTaken = "";
|
|
||||||
let customerMsg = "";
|
let customerMsg = "";
|
||||||
|
let ticketSubject = "";
|
||||||
let carrierInstr = "";
|
let carrierInstr = "";
|
||||||
|
|
||||||
switch (req.issue_type) {
|
switch (req.issue_type) {
|
||||||
case "fake_attempt":
|
case "fake_attempt":
|
||||||
status = "DISPUTE_FILED";
|
recommendedAction = "RESCHEDULE";
|
||||||
actionTaken = "কুরিয়ার রাইডারের ফেক ডেলিভারি অ্যাটেম্পট সনাক্ত হয়েছে। কুরিয়ার অথরিটির কাছে জরুরি ইনভেস্টিগেশন ও রি-অ্যাটেম্পট রিকোয়েস্ট পাঠানো হয়েছে।";
|
customerMsg = `প্রস্তাবিত মেসেজ: প্রিয় ${name}, আপনার পার্সেলটির (${cid}) ডেলিভারিতে সাময়িক বিঘ্ন ঘটায় আমরা দুঃখিত। আমরা কুরিয়ার টিমের সাথে যোগাযোগ করার প্রস্তুতি নিচ্ছি যেন অগ্রাধিকার ভিত্তিতে আপনার পার্সেলটি পুনরায় ডেলিভারি করা হয়। আপনার সুবিধাজনক সময় জানালে আমরা দ্রুত ব্যবস্থা নিতে পারব।`;
|
||||||
customerMsg = `প্রিয় ${name}, আপনার পার্সেলটির ডেলিভারিতে সমস্যা হওয়ায় আমরা অত্যন্ত দুঃখিত। কুরিয়ার ম্যানেজমেন্টকে আমরা বিষয়টি জানিয়েছি এবং অগ্রাধিকার ভিত্তিতে পার্সেলটি পুনরায় পৌঁছে দেওয়ার ব্যবস্থা নেওয়া হচ্ছে।`;
|
ticketSubject = `[NDR Dispute Draft] Consignment ${cid} — Suspected Fake Attempt`;
|
||||||
carrierInstr = `CRITICAL_DISPUTE: Consignment ${cid} rider reported fake attempt. Supervisor intervention required for priority re-attempt within 24h.`;
|
carrierInstr = `DRAFT_DISPUTE_TICKET: Consignment ${cid} rider reported failed attempt without customer contact. Requesting supervisor verification and priority re-attempt within 24h.`;
|
||||||
break;
|
break;
|
||||||
|
|
||||||
case "customer_phone_off":
|
case "customer_phone_off":
|
||||||
status = "CUSTOMER_REENGAGED";
|
recommendedAction = "HOLD";
|
||||||
actionTaken = "গ্রাহকের ফোন বন্ধ বা রিসিভ না করায় হোয়াটসঅ্যাপে ফলোআপ ও সুবিধাজনক সময় জানানোর অনুরোধ পাঠানো হয়েছে।";
|
customerMsg = `প্রস্তাবিত মেসেজ: প্রিয় ${name}, কুরিয়ার থেকে আপনার ঠিকানায় পার্সেল (${cid}) ডেলিভারির জন্য যোগাযোগের চেষ্টা করা হয়েছিল কিন্তু ফোনে পাওয়া যায়নি। অনুগ্রহ করে ডেলিভারি রিসিভ করার সুবিধাজনক সময় বা বিকল্প নাম্বার এই মেসেজে জানান।`;
|
||||||
customerMsg = `প্রিয় ${name}, কুরিয়ার থেকে আপনার ঠিকানায় পার্সেল নিয়ে যাওয়া হয়েছিল কিন্তু আপনাকে ফোনে পাওয়া যায়নি। অনুগ্রহ করে ডেলিভারি রিসিভ করার সুবিধাজনক সময় বা বিকল্প নাম্বার আমাদের মেসেজে জানান।`;
|
ticketSubject = `[Hold Request Draft] Consignment ${cid} — Awaiting Customer Contact`;
|
||||||
carrierInstr = `HOLD_FOR_CONTACT: Reached customer via messaging. Consignment ${cid} on hold at local hub. Do not RTO.`;
|
carrierInstr = `DRAFT_HOLD_INSTRUCTION: Merchant will contact customer via WhatsApp. Please hold consignment ${cid} at local delivery hub and do not initiate RTO yet.`;
|
||||||
break;
|
break;
|
||||||
|
|
||||||
case "reschedule_requested":
|
case "reschedule_requested":
|
||||||
status = "RESCHEDULE_QUEUED";
|
recommendedAction = "RESCHEDULE";
|
||||||
actionTaken = `গ্রাহকের অনুরোধে ডেলিভারি ${req.reschedule_date || "পরবর্তী কর্মদিবসে"} পুনঃনির্ধারণ করা হয়েছে।`;
|
customerMsg = `প্রস্তাবিত মেসেজ: প্রিয় ${name}, আপনার পার্সেল (${cid}) ডেলিভারি ${req.reschedule_date || "পরবর্তী কর্মদিবসে"} পুনঃনির্ধারণ করার জন্য আমরা কুরিয়ারকে অনুরোধ পাঠাতে প্রস্তুত। অনুগ্রহ করে নিশ্চিত করুন ওই সময়ে আপনি ডেলিভারি রিসিভ করতে পারবেন কি না।`;
|
||||||
customerMsg = `প্রিয় ${name}, আপনার অনুরোধ অনুযায়ী পার্সেল ডেলিভারি ${req.reschedule_date || "পরবর্তী কর্মদিবসে"} পুনঃনির্ধারণ করা হয়েছে।`;
|
ticketSubject = `[Reschedule Request Draft] Consignment ${cid} — Target Date: ${req.reschedule_date || "Next Business Day"}`;
|
||||||
carrierInstr = `RESCHEDULE_DELIVERY: Customer requested delivery on ${req.reschedule_date || "next business day"}. Retain at local hub.`;
|
carrierInstr = `DRAFT_RESCHEDULE_INSTRUCTION: Customer requested delivery on ${req.reschedule_date || "next business day"}. Please retain consignment ${cid} at local hub for scheduled dispatch.`;
|
||||||
break;
|
break;
|
||||||
|
|
||||||
case "wrong_address":
|
case "wrong_address":
|
||||||
status = "ADDRESS_UPDATED";
|
recommendedAction = "CORRECT_ADDRESS";
|
||||||
actionTaken = `গ্রাহকের সংশোধিত ঠিকানা (${req.corrected_address || "আপডেটেড ঠিকানা"}) সিস্টেমে নথিভুক্ত করা হয়েছে এবং রাইডারকে রি-রুট করা হচ্ছে।`;
|
customerMsg = `প্রস্তাবিত মেসেজ: প্রিয় ${name}, আপনার পার্সেলের (${cid}) সংশোধিত ঠিকানা (${req.corrected_address || "নতুন ঠিকানা"}) কুরিয়ারকে জানানোর জন্য ড্রাফট তৈরি করা হয়েছে। ঠিকানাটি সঠিক থাকলে আমাদের কনফার্ম করুন।`;
|
||||||
customerMsg = `প্রিয় ${name}, আপনার পার্সেলের ঠিকানা সংশোধন করা হয়েছে। রাইডার আপনার নতুন ঠিকানায় ডেলিভারির জন্য যোগাযোগ করবে।`;
|
ticketSubject = `[Address Correction Draft] Consignment ${cid}`;
|
||||||
carrierInstr = `ADDRESS_UPDATE: Route parcel ${cid} to updated address: ${req.corrected_address || "Provided in notes"}.`;
|
carrierInstr = `DRAFT_ADDRESS_UPDATE: Please update delivery address for consignment ${cid} to: ${req.corrected_address || "Provided in merchant notes"}.`;
|
||||||
break;
|
break;
|
||||||
|
|
||||||
case "customer_refused":
|
case "customer_refused":
|
||||||
status = "CUSTOMER_REENGAGED";
|
recommendedAction = "HOLD";
|
||||||
actionTaken = "গ্রাহক পার্সেল গ্রহণে অস্বীকৃতি জানানোয় কারণ অনুসন্ধান ও সমস্যা সমাধানে রিটেনশন মেসেজ পাঠানো হয়েছে।";
|
customerMsg = `প্রস্তাবিত মেসেজ: প্রিয় ${name}, আমরা লক্ষ্য করেছি পার্সেলটি (${cid}) ডেলিভারির সময় গ্রহণ করা সম্ভব হয়নি। পণ্য বা ডেলিভারি নিয়ে আপনার কোনো প্রশ্ন থাকলে অনুগ্রহ করে আমাদের জানান, আমরা সমাধানে সহায়তা করতে প্রস্তুত।`;
|
||||||
customerMsg = `প্রিয় ${name}, আমরা জানতে পেরেছি আপনি পার্সেলটি গ্রহণ করতে পারেননি। পণ্য নিয়ে আপনার কোনো প্রশ্ন বা অসন্তোষ থাকলে দয়া করে আমাদের জানান, আমরা সরাসরি সমাধান করে দিচ্ছি।`;
|
ticketSubject = `[Retention Hold Draft] Consignment ${cid} — Pending Merchant Follow-up`;
|
||||||
carrierInstr = `HOLD_PENDING_MERCHANT_ACTION: Merchant in retention contact with customer. Hold consignment ${cid} 24 hours before RTO.`;
|
carrierInstr = `DRAFT_RETENTION_HOLD: Merchant is reaching out to customer regarding consignment ${cid}. Please hold at hub for 24 hours before processing return.`;
|
||||||
break;
|
break;
|
||||||
}
|
}
|
||||||
|
|
||||||
|
const nowIso = new Date().toISOString();
|
||||||
return {
|
return {
|
||||||
success: true,
|
success: true,
|
||||||
consignment_id: cid,
|
consignment_id: cid,
|
||||||
courier,
|
courier,
|
||||||
resolution_status: status,
|
status: "DRAFT_GENERATED",
|
||||||
action_taken: actionTaken,
|
consignment_verified: true,
|
||||||
|
actions_executed: [],
|
||||||
|
whatsapp_draft: {
|
||||||
|
language: "bn",
|
||||||
|
text: customerMsg,
|
||||||
|
},
|
||||||
|
courier_ticket_draft: {
|
||||||
|
subject: ticketSubject,
|
||||||
|
body: carrierInstr + phoneTag,
|
||||||
|
},
|
||||||
|
recommended_carrier_action: recommendedAction,
|
||||||
|
requires_manual_execution: true,
|
||||||
|
resolution_status: "DRAFT_GENERATED",
|
||||||
|
action_taken: "প্রস্তাবিত ড্রাফট তৈরি করা হয়েছে (কোনো অটোমেটিক মেসেজ বা কুরিয়ার টিকিট পাঠানো হয়নি)।",
|
||||||
customer_whatsapp_message: customerMsg,
|
customer_whatsapp_message: customerMsg,
|
||||||
carrier_instruction: carrierInstr + phoneTag,
|
carrier_instruction: carrierInstr + phoneTag,
|
||||||
timestamp: new Date().toISOString(),
|
timestamp: nowIso,
|
||||||
|
};
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Task T8 — cancel_parcel(courier, consignment_id)
|
||||||
|
*/
|
||||||
|
async cancelParcel(courier: SupportedCourier, consignmentId: string): Promise<any> {
|
||||||
|
const cid = String(consignmentId || "").trim();
|
||||||
|
if (!cid) {
|
||||||
|
throw new McpToolError({
|
||||||
|
code: "INVALID_INPUT",
|
||||||
|
message: "consignment_id is required to request cancellation.",
|
||||||
|
});
|
||||||
|
}
|
||||||
|
this.getAdapter(courier); // Validates supported courier name
|
||||||
|
|
||||||
|
throw new McpToolError({
|
||||||
|
code: "UNSUPPORTED_BY_PROVIDER",
|
||||||
|
message: `${courier} does not expose an automated parcel cancellation endpoint in its public merchant API; please cancel consignment '${cid}' in the ${courier} merchant portal.`,
|
||||||
|
courier,
|
||||||
|
retryable: false,
|
||||||
|
extraFields: {
|
||||||
|
consignment_id: cid,
|
||||||
|
cancellable_via_api: false,
|
||||||
|
hint: `Use ${courier} merchant portal`,
|
||||||
|
},
|
||||||
|
});
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Task T8 — bulk_create_parcels(items[], dry_run?)
|
||||||
|
*/
|
||||||
|
async bulkCreateParcels(
|
||||||
|
items: ParcelCreateRequest[],
|
||||||
|
dryRun?: boolean,
|
||||||
|
tenantId?: string
|
||||||
|
): Promise<BulkParcelCreateResponse> {
|
||||||
|
if (!Array.isArray(items) || items.length === 0) {
|
||||||
|
throw new McpToolError({
|
||||||
|
code: "INVALID_INPUT",
|
||||||
|
message: "items must be a non-empty array of parcel creation objects.",
|
||||||
|
});
|
||||||
|
}
|
||||||
|
if (items.length > 100) {
|
||||||
|
throw new McpToolError({
|
||||||
|
code: "INVALID_INPUT",
|
||||||
|
message: "bulk_create_parcels supports at most 100 parcels per batch.",
|
||||||
|
});
|
||||||
|
}
|
||||||
|
|
||||||
|
let succeeded = 0;
|
||||||
|
let failed = 0;
|
||||||
|
const results: BulkParcelCreateResponse["results"] = [];
|
||||||
|
|
||||||
|
for (let i = 0; i < items.length; i++) {
|
||||||
|
const item = items[i];
|
||||||
|
const invoice = String(item?.invoice || `BATCH-${i + 1}`);
|
||||||
|
try {
|
||||||
|
const res = await this.createParcel({
|
||||||
|
...item,
|
||||||
|
invoice,
|
||||||
|
dry_run: dryRun !== undefined ? Boolean(dryRun) : Boolean(item?.dry_run),
|
||||||
|
tenant_id: tenantId || item?.tenant_id,
|
||||||
|
});
|
||||||
|
succeeded++;
|
||||||
|
results.push({ index: i, invoice, ok: true, data: res });
|
||||||
|
} catch (err: any) {
|
||||||
|
failed++;
|
||||||
|
results.push({
|
||||||
|
index: i,
|
||||||
|
invoice,
|
||||||
|
ok: false,
|
||||||
|
error: {
|
||||||
|
code: err?.code || "BOOKING_ERROR",
|
||||||
|
message: err?.message || String(err),
|
||||||
|
},
|
||||||
|
});
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
return {
|
||||||
|
success: failed === 0,
|
||||||
|
total: items.length,
|
||||||
|
succeeded,
|
||||||
|
failed,
|
||||||
|
dry_run: Boolean(dryRun),
|
||||||
|
results,
|
||||||
|
};
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Task T8 — get_webhook_events(consignment_id?, since?)
|
||||||
|
*/
|
||||||
|
getWebhookEvents(consignmentId?: string, since?: string) {
|
||||||
|
let filtered = [...webhookEventsStore];
|
||||||
|
if (consignmentId) {
|
||||||
|
const target = String(consignmentId).trim().toLowerCase();
|
||||||
|
filtered = filtered.filter((e) => String(e.consignment_id).toLowerCase() === target);
|
||||||
|
}
|
||||||
|
if (since) {
|
||||||
|
const sinceMs = Date.parse(since);
|
||||||
|
if (!Number.isNaN(sinceMs)) {
|
||||||
|
filtered = filtered.filter((e) => Date.parse(e.received_at) >= sinceMs);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
return {
|
||||||
|
success: true,
|
||||||
|
count: filtered.length,
|
||||||
|
events: filtered,
|
||||||
};
|
};
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|||||||
+275
-108
@@ -6,22 +6,29 @@ import {
|
|||||||
} from "@modelcontextprotocol/sdk/types.js";
|
} from "@modelcontextprotocol/sdk/types.js";
|
||||||
import { CourierRegistry } from "./registry.js";
|
import { CourierRegistry } from "./registry.js";
|
||||||
import { SupportedCourier } from "./types.js";
|
import { SupportedCourier } from "./types.js";
|
||||||
|
import { EnvelopeSource, McpToolError, wrapError, wrapSuccess } from "./envelope.js";
|
||||||
|
|
||||||
// Tool definitions — shared by the STDIO (npx) and HTTP (web-URL) entrypoints.
|
// Tool definitions — shared by the STDIO (npx) and HTTP (web-URL) entrypoints.
|
||||||
export const TOOLS: Tool[] = [
|
export const TOOLS: Tool[] = [
|
||||||
{
|
{
|
||||||
name: "list_couriers",
|
name: "list_couriers",
|
||||||
description: "Inspect operational health, configuration status, and active API credentials for supported Bangladeshi courier networks (Steadfast, Pathao, RedX, Paperfly) and spatial routing services (Google Maps Platform). READ-ONLY DISCOVERY TOOL: Has zero external side effects and does not mutate database or carrier state. Use when initializing a session to verify which couriers are ready for order dispatch or balance checking. Do NOT use for querying shipment status (use 'track_parcel') or calculating shipping fees (use 'calculate_delivery_zone_and_fee').",
|
description:
|
||||||
|
"Inspect operational health, configuration status, and active API credentials for supported Bangladeshi courier networks (Steadfast, Pathao, RedX, Paperfly) and spatial routing services (Google Maps Platform). READ-ONLY DISCOVERY TOOL: Has zero external side effects and does not mutate database or carrier state. Use when initializing a session to verify which couriers are ready for order dispatch or balance checking. Do NOT use for querying shipment status (use 'track_parcel') or calculating shipping fees (use 'calculate_delivery_zone_and_fee').",
|
||||||
inputSchema: { type: "object", properties: {}, required: [] },
|
inputSchema: { type: "object", properties: {}, required: [] },
|
||||||
},
|
},
|
||||||
{
|
{
|
||||||
name: "create_parcel",
|
name: "create_parcel",
|
||||||
description: "Book and dispatch a physical parcel consignment across Bangladesh through Steadfast, Pathao, RedX, Paperfly, or AI smart cascading routing. STATE-MUTATING ACTION: This call creates a real, billable shipment record in the carrier's production database, assigns an official tracking code, and deducts courier fees upon pickup. Once booked, cancellations require direct courier portal operations. Use only after customer address and phone number are verified. Do NOT use for preliminary fee estimation (use 'calculate_delivery_zone_and_fee' or 'compare_courier_rates') or address validation (use 'validate_and_geocode_address'). Throws an error if required courier credentials are not configured or recipient phone is invalid.",
|
description:
|
||||||
|
"Book and dispatch a physical parcel consignment across Bangladesh through Steadfast, Pathao, RedX, Paperfly, or AI smart cascading routing, with built-in per-tenant invoice idempotency and optional dry-run validation. STATE-MUTATING ACTION (unless dry_run=true): Creates a real, billable shipment record in the carrier's production database, assigns an official tracking code, and deducts courier fees upon pickup. Set dry_run=true to validate recipient phone/address and preview the target courier and estimated BDT cost without booking upstream. Once booked, cancellations require direct courier portal operations ('cancellable_via_api: false').",
|
||||||
inputSchema: {
|
inputSchema: {
|
||||||
type: "object",
|
type: "object",
|
||||||
properties: {
|
properties: {
|
||||||
courier: { type: "string", enum: ["steadfast", "pathao", "redx", "paperfly", "auto"], description: "Target courier or 'auto' for AI smart routing (default: auto)" },
|
courier: {
|
||||||
invoice: { type: "string", description: "Unique order invoice number (e.g. INV-1002)" },
|
type: "string",
|
||||||
|
enum: ["steadfast", "pathao", "redx", "paperfly", "auto", "auto_fastest", "auto_cheapest"],
|
||||||
|
description: "Target courier or 'auto' for AI smart routing (default: auto)",
|
||||||
|
},
|
||||||
|
invoice: { type: "string", description: "Unique order invoice number (e.g. INV-1002) used as idempotency key" },
|
||||||
recipient_name: { type: "string", description: "Customer full name" },
|
recipient_name: { type: "string", description: "Customer full name" },
|
||||||
recipient_phone: { type: "string", description: "11-digit Bangladeshi mobile number (e.g. 017XXXXXXXX)" },
|
recipient_phone: { type: "string", description: "11-digit Bangladeshi mobile number (e.g. 017XXXXXXXX)" },
|
||||||
recipient_address: { type: "string", description: "Delivery address (Thana, District, Street)" },
|
recipient_address: { type: "string", description: "Delivery address (Thana, District, Street)" },
|
||||||
@@ -32,36 +39,54 @@ export const TOOLS: Tool[] = [
|
|||||||
value: { type: "number", description: "Declared parcel value in BDT (used by RedX; defaults to the COD amount)" },
|
value: { type: "number", description: "Declared parcel value in BDT (used by RedX; defaults to the COD amount)" },
|
||||||
delivery_area_id: { type: "number", description: "RedX only: numeric delivery-area id (auto-resolved from the address if omitted)" },
|
delivery_area_id: { type: "number", description: "RedX only: numeric delivery-area id (auto-resolved from the address if omitted)" },
|
||||||
pickup_store_id: { type: "number", description: "RedX only: your pickup store id (optional)" },
|
pickup_store_id: { type: "number", description: "RedX only: your pickup store id (optional)" },
|
||||||
|
dry_run: {
|
||||||
|
type: "boolean",
|
||||||
|
description: "If true, validates phone/address and returns would_book_with and estimated_cost_bdt without creating a real upstream shipment.",
|
||||||
|
},
|
||||||
},
|
},
|
||||||
required: ["invoice", "recipient_name", "recipient_phone", "recipient_address", "cod_amount"],
|
required: ["invoice", "recipient_name", "recipient_phone", "recipient_address", "cod_amount"],
|
||||||
},
|
},
|
||||||
},
|
},
|
||||||
{
|
{
|
||||||
name: "track_parcel",
|
name: "track_parcel",
|
||||||
description: "Query live, real-time tracking milestones and delivery telemetry across Steadfast, Pathao, RedX, and Paperfly networks using consignment ID or tracking code. READ-ONLY OPERATION: Does not alter shipment state or carrier data. Returns normalized status (Booked, In Review, Picked Up, In Transit, Delivered, Partial Delivered, Cancelled, Returned), current location, carrier status notes, and timestamp history. Use when an end-customer or merchant inquires about existing shipment progress. Do NOT use for creating consignments (use 'create_parcel') or resolving failed deliveries (use 'resolve_ndr_issue'). Carrier provider is auto-detected from consignment prefix if omitted.",
|
description:
|
||||||
|
"Query live, real-time tracking milestones and delivery telemetry across Steadfast, Pathao, RedX, and Paperfly networks using consignment ID or tracking code. READ-ONLY OPERATION: Does not alter shipment state or carrier data. Returns normalized status, current location, carrier status notes, and timestamp history. Returns structured error code 'CONSIGNMENT_NOT_FOUND' with 'couriers_checked' if the consignment does not exist. Carrier provider is auto-detected from consignment prefix if omitted.",
|
||||||
inputSchema: {
|
inputSchema: {
|
||||||
type: "object",
|
type: "object",
|
||||||
properties: {
|
properties: {
|
||||||
tracking_code: { type: "string", description: "Consignment ID or tracking code (e.g. 'DS190926QZNGJT' for Pathao, 'SF12345678' for Steadfast, 'REDX123' for RedX)" },
|
tracking_code: {
|
||||||
courier: { type: "string", enum: ["steadfast", "pathao", "redx", "paperfly"], description: "Optional courier provider name. If omitted, provider is auto-detected from tracking code prefix." },
|
type: "string",
|
||||||
|
description: "Consignment ID or tracking code (e.g. 'DS190926QZNGJT' for Pathao, 'SF12345678' for Steadfast, 'REDX123' for RedX)",
|
||||||
|
},
|
||||||
|
courier: {
|
||||||
|
type: "string",
|
||||||
|
enum: ["steadfast", "pathao", "redx", "paperfly"],
|
||||||
|
description: "Optional courier provider name. If omitted, provider is auto-detected from tracking code prefix.",
|
||||||
|
},
|
||||||
},
|
},
|
||||||
required: ["tracking_code"],
|
required: ["tracking_code"],
|
||||||
},
|
},
|
||||||
},
|
},
|
||||||
{
|
{
|
||||||
name: "get_balance",
|
name: "get_balance",
|
||||||
description: "Retrieve live merchant cash-on-delivery (COD) vault balance, pending disbursement amounts, and payout ledger from Steadfast or Pathao merchant portals. READ-ONLY FINANCIAL INQUIRY: Does not initiate payouts or mutate accounting ledgers. Use when accounting or merchant finance operators want to verify accrued COD collections or payout readiness. Do NOT use for customer balance or shipping quote estimation (use 'calculate_delivery_zone_and_fee'). Requires active merchant API keys for the requested courier; throws an error if unconfigured.",
|
description:
|
||||||
|
"Retrieve live merchant cash-on-delivery (COD) vault balance from Steadfast, or check provider balance support across Pathao, RedX, Paperfly, or all 4 couriers simultaneously. READ-ONLY FINANCIAL INQUIRY: Steadfast returns live 'amount_bdt' and 'status: OK'; Pathao, RedX, and Paperfly return 'amount_bdt: null' and 'status: UNSUPPORTED_BY_PROVIDER' with merchant portal hints because their public APIs do not expose a balance endpoint.",
|
||||||
inputSchema: {
|
inputSchema: {
|
||||||
type: "object",
|
type: "object",
|
||||||
properties: {
|
properties: {
|
||||||
courier: { type: "string", enum: ["steadfast", "pathao"], description: "Courier provider to check balance for" },
|
courier: {
|
||||||
|
type: "string",
|
||||||
|
enum: ["steadfast", "pathao", "redx", "paperfly", "all"],
|
||||||
|
description: "Courier provider to check balance telemetry for ('steadfast', 'pathao', 'redx', 'paperfly', or 'all'; default: 'all')",
|
||||||
|
},
|
||||||
},
|
},
|
||||||
required: ["courier"],
|
required: [],
|
||||||
},
|
},
|
||||||
},
|
},
|
||||||
{
|
{
|
||||||
name: "check_fraud_risk",
|
name: "check_fraud_risk",
|
||||||
description: "Screen a customer phone number against live nationwide Bangladesh logistics databases (millions of historical consignments) for delivery success rate, cancellation counts, and return fraud risk score. READ-ONLY DIAGNOSTIC QUERY: Zero mock data, authentic carrier telemetry only. Use before confirming high-value COD orders to screen for chronic returners or fake orders. Do NOT use for address geocoding (use 'validate_and_geocode_address') or parcel booking (use 'create_parcel'). Expects an 11-digit Bangladeshi mobile number ('01XXXXXXXXX').",
|
description:
|
||||||
|
"Screen a customer phone number against live nationwide Bangladesh logistics databases (Steadfast & Pathao) and the BTRC 11-digit prefix validator for delivery success rate, cancellation counts, and return fraud risk level ('INVALID_NUMBER', 'NO_HISTORY', 'LOW', 'MEDIUM', 'HIGH', 'CRITICAL'). READ-ONLY DIAGNOSTIC QUERY: Returns null rates when a number is invalid or has 0 parcel history. Expects an 11-digit Bangladeshi mobile number ('01[3-9]XXXXXXXX').",
|
||||||
inputSchema: {
|
inputSchema: {
|
||||||
type: "object",
|
type: "object",
|
||||||
properties: {
|
properties: {
|
||||||
@@ -72,12 +97,13 @@ export const TOOLS: Tool[] = [
|
|||||||
},
|
},
|
||||||
{
|
{
|
||||||
name: "validate_and_geocode_address",
|
name: "validate_and_geocode_address",
|
||||||
description: "Validate, clean, and geocode an unformatted Bangladesh delivery address into structured administrative boundaries (Thana, District, Division), rooftop latitude/longitude coordinates, and a deliverability confidence score (0-100) via Google Maps Platform Geocoding API with OpenStreetMap gazetteer fallback. READ-ONLY SPATIAL LOOKUP: Has zero side effects and does not mutate booking data. Use before booking parcels to detect spelling errors, verify Thana/District matching, and obtain precise coordinates. Do NOT use for calculating delivery fees or road routing distance (use 'calculate_delivery_zone_and_fee' instead).",
|
description:
|
||||||
|
"Validate, clean, and geocode an unformatted Bangladesh delivery address into structured administrative boundaries (thana_input, thana_resolved, district, division), latitude/longitude coordinates, match_quality (road, house, area), needs_review flag, and a deliverability confidence score (0-100, capped at 60 when location_type != ROOFTOP) via Google Maps Platform Geocoding API with OpenStreetMap gazetteer fallback. READ-ONLY SPATIAL LOOKUP.",
|
||||||
inputSchema: {
|
inputSchema: {
|
||||||
type: "object",
|
type: "object",
|
||||||
properties: {
|
properties: {
|
||||||
address: { type: "string", description: "Full street or local address (e.g. 'Road 11, House 24, Dhanmondi, Dhaka')" },
|
address: { type: "string", description: "Full street or local address (e.g. 'Road 11, House 24, Dhanmondi, Dhaka')" },
|
||||||
thana: { type: "string", description: "Optional Thana/Upazila name" },
|
thana: { type: "string", description: "Optional expected Thana/Upazila name to verify against geocoded components" },
|
||||||
district: { type: "string", description: "Optional District name" },
|
district: { type: "string", description: "Optional District name" },
|
||||||
},
|
},
|
||||||
required: ["address"],
|
required: ["address"],
|
||||||
@@ -85,7 +111,8 @@ export const TOOLS: Tool[] = [
|
|||||||
},
|
},
|
||||||
{
|
{
|
||||||
name: "calculate_delivery_zone_and_fee",
|
name: "calculate_delivery_zone_and_fee",
|
||||||
description: "Calculate standard delivery zone (inside_dhaka ≤22km ৳80, sub_dhaka 22-45km ৳100, outside_dhaka >45km ৳150), actual road distance via Google Maps Platform Routes API (v2:computeRoutes), SLA turnaround time (24-72h), and applicable COD percentage for a SINGLE delivery destination. READ-ONLY ESTIMATION TOOL: Has zero external side effects and does NOT book shipments. Use when quoting shipping charges to a customer or determining flat delivery tiers for an order. Do NOT use if you need side-by-side multi-carrier tariff quotes with weight breaks and priority sorting across all 4 couriers (use 'compare_courier_rates' instead).",
|
description:
|
||||||
|
"Calculate standard delivery zone (inside_dhaka <=22km ৳80, sub_dhaka 22-45km ৳100, outside_dhaka >45km ৳150), road distance via Google Maps Platform Routes API, structured SLA hours ({min, max}), and applicable COD percentage for a single delivery destination using the unified tariff table (meta.source='static_tariff'). READ-ONLY ESTIMATION TOOL.",
|
||||||
inputSchema: {
|
inputSchema: {
|
||||||
type: "object",
|
type: "object",
|
||||||
properties: {
|
properties: {
|
||||||
@@ -98,25 +125,31 @@ export const TOOLS: Tool[] = [
|
|||||||
},
|
},
|
||||||
{
|
{
|
||||||
name: "compare_courier_rates",
|
name: "compare_courier_rates",
|
||||||
description: "Execute side-by-side tariff, SLA, and COD collection fee comparisons across all four major Bangladeshi couriers (Steadfast, Pathao, RedX, Paperfly) for any destination nationwide. Evaluates exact parcel weight, declared COD amount, and optimization priority ('cheapest', 'fastest', 'balanced') to select the recommended courier. READ-ONLY CALCULATION ENGINE: Has zero external side effects and does not create orders. Use when deciding which carrier offers the best commercial rate or fastest SLA for a specific shipment before booking. Do NOT use for single flat-rate zone lookup (use 'calculate_delivery_zone_and_fee') or for actually booking the shipment (use 'create_parcel').",
|
description:
|
||||||
|
"Execute side-by-side tariff, structured SLA ({min, max}), and COD collection fee comparisons across all four major Bangladeshi couriers (Steadfast, Pathao, RedX, Paperfly) for any destination nationwide using the unified tariff table (meta.source='static_tariff'). Evaluates exact parcel weight, declared COD amount, and optimization priority ('cheapest', 'fastest', 'balanced') to select the recommended courier. READ-ONLY CALCULATION ENGINE.",
|
||||||
inputSchema: {
|
inputSchema: {
|
||||||
type: "object",
|
type: "object",
|
||||||
properties: {
|
properties: {
|
||||||
recipient_address: { type: "string", description: "Destination delivery address anywhere in Bangladesh" },
|
recipient_address: { type: "string", description: "Destination delivery address anywhere in Bangladesh" },
|
||||||
weight_kg: { type: "number", description: "Parcel weight in KG (default: 0.5)" },
|
weight_kg: { type: "number", description: "Parcel weight in KG (default: 0.5)" },
|
||||||
cod_amount: { type: "number", description: "Cash On Delivery amount in BDT (default: 0)" },
|
cod_amount: { type: "number", description: "Cash On Delivery amount in BDT (default: 0)" },
|
||||||
priority: { type: "string", enum: ["cheapest", "fastest", "balanced"], description: "Optimization priority (default: balanced)" },
|
priority: {
|
||||||
|
type: "string",
|
||||||
|
enum: ["cheapest", "fastest", "balanced"],
|
||||||
|
description: "Optimization priority (default: balanced)",
|
||||||
|
},
|
||||||
},
|
},
|
||||||
required: ["recipient_address"],
|
required: ["recipient_address"],
|
||||||
},
|
},
|
||||||
},
|
},
|
||||||
{
|
{
|
||||||
name: "resolve_ndr_issue",
|
name: "resolve_ndr_issue",
|
||||||
description: "Automate Non-Delivery Report (NDR) triage and dispute resolution when a courier delivery attempt fails. GENERATION-ONLY TOOL (NO DIRECT DISPATCH): Generates empathetic, conversion-tested Bengali WhatsApp re-engagement copy for the customer and formal operational escalation tickets with hold instructions for the carrier. Does NOT send network messages or modify courier bookings automatically; output must be reviewed or dispatched through messaging channels. Use when a parcel status changes to failed attempt, customer phone off, or reschedule requested. Do NOT use for general order tracking (use 'track_parcel') or creating orders (use 'create_parcel').",
|
description:
|
||||||
|
"Verify that a consignment exists on the specified courier via 'track_parcel' and generate honest, draft-only Non-Delivery Report (NDR) re-engagement copy ('status: DRAFT_GENERATED', 'actions_executed: []'). GENERATION-ONLY TOOL: Verifies consignment_id first (returns CONSIGNMENT_NOT_FOUND if unknown), then generates proposed Bengali WhatsApp copy ('whatsapp_draft') and a carrier escalation ticket draft ('courier_ticket_draft') for manual merchant execution.",
|
||||||
inputSchema: {
|
inputSchema: {
|
||||||
type: "object",
|
type: "object",
|
||||||
properties: {
|
properties: {
|
||||||
consignment_id: { type: "string", description: "Tracking code or consignment ID" },
|
consignment_id: { type: "string", description: "Existing tracking code or consignment ID to verify and generate NDR drafts for" },
|
||||||
courier: { type: "string", enum: ["steadfast", "pathao", "redx", "paperfly"], description: "Courier provider" },
|
courier: { type: "string", enum: ["steadfast", "pathao", "redx", "paperfly"], description: "Courier provider" },
|
||||||
issue_type: {
|
issue_type: {
|
||||||
type: "string",
|
type: "string",
|
||||||
@@ -131,8 +164,214 @@ export const TOOLS: Tool[] = [
|
|||||||
required: ["consignment_id", "courier", "issue_type"],
|
required: ["consignment_id", "courier", "issue_type"],
|
||||||
},
|
},
|
||||||
},
|
},
|
||||||
|
{
|
||||||
|
name: "cancel_parcel",
|
||||||
|
description:
|
||||||
|
"Request cancellation for an existing parcel consignment on Steadfast, Pathao, RedX, or Paperfly. Returns structured 'UNSUPPORTED_BY_PROVIDER' guidance when the carrier's public API does not expose an automated cancellation endpoint, instructing the operator to cancel in the merchant portal.",
|
||||||
|
inputSchema: {
|
||||||
|
type: "object",
|
||||||
|
properties: {
|
||||||
|
courier: { type: "string", enum: ["steadfast", "pathao", "redx", "paperfly"], description: "Courier provider name" },
|
||||||
|
consignment_id: { type: "string", description: "Consignment ID or tracking code to cancel" },
|
||||||
|
},
|
||||||
|
required: ["courier", "consignment_id"],
|
||||||
|
},
|
||||||
|
},
|
||||||
|
{
|
||||||
|
name: "bulk_create_parcels",
|
||||||
|
description:
|
||||||
|
"Validate or book up to 100 parcels in a single batch with per-item error isolation, invoice idempotency, and optional dry_run preview mode. STATE-MUTATING ACTION (unless dry_run=true): Returns total, succeeded, failed, and per-item results.",
|
||||||
|
inputSchema: {
|
||||||
|
type: "object",
|
||||||
|
properties: {
|
||||||
|
items: {
|
||||||
|
type: "array",
|
||||||
|
description: "Array of parcel creation objects (1 to 100 items)",
|
||||||
|
items: {
|
||||||
|
type: "object",
|
||||||
|
properties: {
|
||||||
|
courier: { type: "string", enum: ["steadfast", "pathao", "redx", "paperfly", "auto"] },
|
||||||
|
invoice: { type: "string" },
|
||||||
|
recipient_name: { type: "string" },
|
||||||
|
recipient_phone: { type: "string" },
|
||||||
|
recipient_address: { type: "string" },
|
||||||
|
cod_amount: { type: "number" },
|
||||||
|
note: { type: "string" },
|
||||||
|
item_weight: { type: "number" },
|
||||||
|
dry_run: { type: "boolean" },
|
||||||
|
},
|
||||||
|
required: ["invoice", "recipient_name", "recipient_phone", "recipient_address", "cod_amount"],
|
||||||
|
},
|
||||||
|
},
|
||||||
|
dry_run: {
|
||||||
|
type: "boolean",
|
||||||
|
description: "If true, runs the entire batch in dry-run validation mode without creating real upstream shipments.",
|
||||||
|
},
|
||||||
|
},
|
||||||
|
required: ["items"],
|
||||||
|
},
|
||||||
|
},
|
||||||
|
{
|
||||||
|
name: "get_webhook_events",
|
||||||
|
description:
|
||||||
|
"Query verified courier webhook status events received by the server's /webhooks/{steadfast,pathao,redx,paperfly} endpoints. READ-ONLY DIAGNOSTIC TOOL: Filterable by consignment_id and ISO-8601 'since' timestamp.",
|
||||||
|
inputSchema: {
|
||||||
|
type: "object",
|
||||||
|
properties: {
|
||||||
|
consignment_id: { type: "string", description: "Optional consignment ID or tracking code to filter events for" },
|
||||||
|
since: { type: "string", description: "Optional ISO-8601 timestamp to return events received at or after" },
|
||||||
|
},
|
||||||
|
required: [],
|
||||||
|
},
|
||||||
|
},
|
||||||
];
|
];
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Execute a single MCP tool call and return the Global Response Envelope (`v2.6.0`).
|
||||||
|
*/
|
||||||
|
export async function executeToolCall(
|
||||||
|
registry: CourierRegistry,
|
||||||
|
name: string,
|
||||||
|
args: Record<string, any> = {},
|
||||||
|
tenantId: string = "default"
|
||||||
|
): Promise<{ isError: boolean; envelope: any }> {
|
||||||
|
let defaultSource: EnvelopeSource = "live_api";
|
||||||
|
if (name === "calculate_delivery_zone_and_fee" || name === "compare_courier_rates") {
|
||||||
|
defaultSource = "static_tariff";
|
||||||
|
} else if (name === "get_webhook_events") {
|
||||||
|
defaultSource = "cache";
|
||||||
|
}
|
||||||
|
|
||||||
|
try {
|
||||||
|
switch (name) {
|
||||||
|
case "list_couriers": {
|
||||||
|
const result = registry.listCouriers();
|
||||||
|
return { isError: false, envelope: wrapSuccess(result, "validator") };
|
||||||
|
}
|
||||||
|
|
||||||
|
case "create_parcel": {
|
||||||
|
const isDryRun = Boolean(args?.dry_run);
|
||||||
|
const result = await registry.createParcel({
|
||||||
|
courier: args?.courier as any,
|
||||||
|
invoice: String(args?.invoice ?? ""),
|
||||||
|
recipient_name: String(args?.recipient_name ?? ""),
|
||||||
|
recipient_phone: String(args?.recipient_phone ?? ""),
|
||||||
|
recipient_address: String(args?.recipient_address ?? ""),
|
||||||
|
cod_amount: Number(args?.cod_amount || 0),
|
||||||
|
note: args?.note ? String(args?.note) : undefined,
|
||||||
|
item_weight: args?.item_weight ? Number(args?.item_weight) : 0.5,
|
||||||
|
item_type: args?.item_type ? String(args?.item_type) : undefined,
|
||||||
|
value: args?.value !== undefined ? Number(args?.value) : undefined,
|
||||||
|
delivery_area_id: args?.delivery_area_id !== undefined ? Number(args?.delivery_area_id) : undefined,
|
||||||
|
pickup_store_id: args?.pickup_store_id !== undefined ? Number(args?.pickup_store_id) : undefined,
|
||||||
|
dry_run: isDryRun,
|
||||||
|
tenant_id: tenantId,
|
||||||
|
});
|
||||||
|
const source: EnvelopeSource = isDryRun ? "validator" : result.idempotent_replay ? "cache" : "live_api";
|
||||||
|
return { isError: false, envelope: wrapSuccess(result, source) };
|
||||||
|
}
|
||||||
|
|
||||||
|
case "track_parcel": {
|
||||||
|
const result = await registry.trackParcel(
|
||||||
|
String(args?.tracking_code ?? ""),
|
||||||
|
args?.courier as SupportedCourier | undefined
|
||||||
|
);
|
||||||
|
return { isError: false, envelope: wrapSuccess(result, "live_api") };
|
||||||
|
}
|
||||||
|
|
||||||
|
case "get_balance": {
|
||||||
|
const result = await registry.getBalance((args?.courier as SupportedCourier | "all") || "all");
|
||||||
|
return { isError: false, envelope: wrapSuccess(result, "live_api") };
|
||||||
|
}
|
||||||
|
|
||||||
|
case "check_fraud_risk": {
|
||||||
|
const result = await registry.checkFraudRisk(String(args?.phone ?? ""));
|
||||||
|
const source: EnvelopeSource = result.risk_level === "INVALID_NUMBER" ? "validator" : "live_api";
|
||||||
|
return { isError: false, envelope: wrapSuccess(result, source) };
|
||||||
|
}
|
||||||
|
|
||||||
|
case "validate_and_geocode_address": {
|
||||||
|
const result = await registry.validateAddress({
|
||||||
|
address: String(args?.address ?? ""),
|
||||||
|
thana: args?.thana ? String(args?.thana) : undefined,
|
||||||
|
district: args?.district ? String(args?.district) : undefined,
|
||||||
|
});
|
||||||
|
return { isError: false, envelope: wrapSuccess(result, "live_api") };
|
||||||
|
}
|
||||||
|
|
||||||
|
case "calculate_delivery_zone_and_fee": {
|
||||||
|
const result = await registry.calculateZoneAndRate({
|
||||||
|
recipient_address: String(args?.recipient_address ?? ""),
|
||||||
|
origin_address: args?.origin_address ? String(args?.origin_address) : undefined,
|
||||||
|
weight_kg: args?.weight_kg ? Number(args?.weight_kg) : 0.5,
|
||||||
|
});
|
||||||
|
return { isError: false, envelope: wrapSuccess(result, "static_tariff") };
|
||||||
|
}
|
||||||
|
|
||||||
|
case "compare_courier_rates": {
|
||||||
|
const result = await registry.compareRates({
|
||||||
|
recipient_address: String(args?.recipient_address ?? ""),
|
||||||
|
weight_kg: args?.weight_kg ? Number(args?.weight_kg) : 0.5,
|
||||||
|
cod_amount: args?.cod_amount ? Number(args?.cod_amount) : 0,
|
||||||
|
priority: args?.priority as any,
|
||||||
|
});
|
||||||
|
return { isError: false, envelope: wrapSuccess(result, "static_tariff") };
|
||||||
|
}
|
||||||
|
|
||||||
|
case "resolve_ndr_issue": {
|
||||||
|
const result = await registry.resolveNdr({
|
||||||
|
consignment_id: String(args?.consignment_id ?? ""),
|
||||||
|
courier: args?.courier as any,
|
||||||
|
issue_type: args?.issue_type as any,
|
||||||
|
customer_phone: args?.customer_phone ? String(args?.customer_phone) : undefined,
|
||||||
|
customer_name: args?.customer_name ? String(args?.customer_name) : undefined,
|
||||||
|
reschedule_date: args?.reschedule_date ? String(args?.reschedule_date) : undefined,
|
||||||
|
corrected_address: args?.corrected_address ? String(args?.corrected_address) : undefined,
|
||||||
|
});
|
||||||
|
return { isError: false, envelope: wrapSuccess(result, "live_api") };
|
||||||
|
}
|
||||||
|
|
||||||
|
case "cancel_parcel": {
|
||||||
|
const result = await registry.cancelParcel(
|
||||||
|
args?.courier as SupportedCourier,
|
||||||
|
String(args?.consignment_id ?? "")
|
||||||
|
);
|
||||||
|
return { isError: false, envelope: wrapSuccess(result, "live_api") };
|
||||||
|
}
|
||||||
|
|
||||||
|
case "bulk_create_parcels": {
|
||||||
|
const isDryRun = args?.dry_run !== undefined ? Boolean(args?.dry_run) : undefined;
|
||||||
|
const result = await registry.bulkCreateParcels(
|
||||||
|
Array.isArray(args?.items) ? args.items : [],
|
||||||
|
isDryRun,
|
||||||
|
tenantId
|
||||||
|
);
|
||||||
|
return { isError: false, envelope: wrapSuccess(result, isDryRun ? "validator" : "live_api") };
|
||||||
|
}
|
||||||
|
|
||||||
|
case "get_webhook_events": {
|
||||||
|
const result = registry.getWebhookEvents(
|
||||||
|
args?.consignment_id ? String(args?.consignment_id) : undefined,
|
||||||
|
args?.since ? String(args?.since) : undefined
|
||||||
|
);
|
||||||
|
return { isError: false, envelope: wrapSuccess(result, "cache") };
|
||||||
|
}
|
||||||
|
|
||||||
|
default:
|
||||||
|
throw new McpToolError({
|
||||||
|
code: "INVALID_INPUT",
|
||||||
|
message: `Unknown tool: ${name}`,
|
||||||
|
retryable: false,
|
||||||
|
});
|
||||||
|
}
|
||||||
|
} catch (error: any) {
|
||||||
|
return {
|
||||||
|
isError: true,
|
||||||
|
envelope: wrapError(error, defaultSource),
|
||||||
|
};
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* Build a fully-wired MCP Server bound to a given CourierRegistry.
|
* Build a fully-wired MCP Server bound to a given CourierRegistry.
|
||||||
* The registry carries the credentials — for STDIO it comes from env,
|
* The registry carries the credentials — for STDIO it comes from env,
|
||||||
@@ -140,10 +379,11 @@ export const TOOLS: Tool[] = [
|
|||||||
*/
|
*/
|
||||||
export function buildMcpServer(
|
export function buildMcpServer(
|
||||||
registry: CourierRegistry,
|
registry: CourierRegistry,
|
||||||
authChecker?: (toolName: string) => { permitted: boolean; reason?: string }
|
authChecker?: (toolName: string, args?: Record<string, any>) => { permitted: boolean; reason?: string },
|
||||||
|
tenantId: string = "default"
|
||||||
): Server {
|
): Server {
|
||||||
const server = new Server(
|
const server = new Server(
|
||||||
{ name: "aura-courier-mcp", version: "2.4.2" },
|
{ name: "aura-courier-mcp", version: "2.6.0" },
|
||||||
{ capabilities: { tools: {} } }
|
{ capabilities: { tools: {} } }
|
||||||
);
|
);
|
||||||
|
|
||||||
@@ -152,101 +392,28 @@ export function buildMcpServer(
|
|||||||
server.setRequestHandler(CallToolRequestSchema, async (request) => {
|
server.setRequestHandler(CallToolRequestSchema, async (request) => {
|
||||||
const { name, arguments: args } = request.params;
|
const { name, arguments: args } = request.params;
|
||||||
if (authChecker) {
|
if (authChecker) {
|
||||||
const auth = authChecker(name);
|
const auth = authChecker(name, (args as Record<string, any>) || {});
|
||||||
if (!auth.permitted) {
|
if (!auth.permitted) {
|
||||||
|
const errEnvelope = wrapError(
|
||||||
|
new McpToolError({
|
||||||
|
code: "UNAUTHORIZED",
|
||||||
|
message: auth.reason || "Unauthorized tool invocation.",
|
||||||
|
retryable: false,
|
||||||
|
}),
|
||||||
|
"validator"
|
||||||
|
);
|
||||||
return {
|
return {
|
||||||
isError: true,
|
isError: true,
|
||||||
content: [{ type: "text", text: JSON.stringify({ error: "Unauthorized", message: auth.reason }, null, 2) }],
|
content: [{ type: "text", text: JSON.stringify(errEnvelope, null, 2) }],
|
||||||
};
|
};
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
try {
|
|
||||||
switch (name) {
|
|
||||||
case "list_couriers":
|
|
||||||
return { content: [{ type: "text", text: JSON.stringify(registry.listCouriers(), null, 2) }] };
|
|
||||||
|
|
||||||
case "create_parcel": {
|
const { isError, envelope } = await executeToolCall(registry, name, (args as Record<string, any>) || {}, tenantId);
|
||||||
const result = await registry.createParcel({
|
return {
|
||||||
courier: args?.courier as any,
|
isError,
|
||||||
invoice: String(args?.invoice),
|
content: [{ type: "text", text: JSON.stringify(envelope, null, 2) }],
|
||||||
recipient_name: String(args?.recipient_name),
|
};
|
||||||
recipient_phone: String(args?.recipient_phone),
|
|
||||||
recipient_address: String(args?.recipient_address),
|
|
||||||
cod_amount: Number(args?.cod_amount || 0),
|
|
||||||
note: args?.note ? String(args?.note) : undefined,
|
|
||||||
item_weight: args?.item_weight ? Number(args?.item_weight) : 0.5,
|
|
||||||
});
|
|
||||||
return { content: [{ type: "text", text: JSON.stringify(result, null, 2) }] };
|
|
||||||
}
|
|
||||||
|
|
||||||
case "track_parcel": {
|
|
||||||
const result = await registry.trackParcel(
|
|
||||||
String(args?.tracking_code),
|
|
||||||
args?.courier as SupportedCourier | undefined
|
|
||||||
);
|
|
||||||
return { content: [{ type: "text", text: JSON.stringify(result, null, 2) }] };
|
|
||||||
}
|
|
||||||
|
|
||||||
case "get_balance": {
|
|
||||||
const result = await registry.getBalance(String(args?.courier) as SupportedCourier);
|
|
||||||
return { content: [{ type: "text", text: JSON.stringify(result, null, 2) }] };
|
|
||||||
}
|
|
||||||
|
|
||||||
case "check_fraud_risk": {
|
|
||||||
const result = await registry.checkFraudRisk(String(args?.phone));
|
|
||||||
return { content: [{ type: "text", text: JSON.stringify(result, null, 2) }] };
|
|
||||||
}
|
|
||||||
|
|
||||||
case "validate_and_geocode_address": {
|
|
||||||
const result = await registry.validateAddress({
|
|
||||||
address: String(args?.address),
|
|
||||||
thana: args?.thana ? String(args?.thana) : undefined,
|
|
||||||
district: args?.district ? String(args?.district) : undefined,
|
|
||||||
});
|
|
||||||
return { content: [{ type: "text", text: JSON.stringify(result, null, 2) }] };
|
|
||||||
}
|
|
||||||
|
|
||||||
case "calculate_delivery_zone_and_fee": {
|
|
||||||
const result = await registry.calculateZoneAndRate({
|
|
||||||
recipient_address: String(args?.recipient_address),
|
|
||||||
origin_address: args?.origin_address ? String(args?.origin_address) : undefined,
|
|
||||||
weight_kg: args?.weight_kg ? Number(args?.weight_kg) : 0.5,
|
|
||||||
});
|
|
||||||
return { content: [{ type: "text", text: JSON.stringify(result, null, 2) }] };
|
|
||||||
}
|
|
||||||
|
|
||||||
case "compare_courier_rates": {
|
|
||||||
const result = await registry.compareRates({
|
|
||||||
recipient_address: String(args?.recipient_address),
|
|
||||||
weight_kg: args?.weight_kg ? Number(args?.weight_kg) : 0.5,
|
|
||||||
cod_amount: args?.cod_amount ? Number(args?.cod_amount) : 0,
|
|
||||||
priority: args?.priority as any,
|
|
||||||
});
|
|
||||||
return { content: [{ type: "text", text: JSON.stringify(result, null, 2) }] };
|
|
||||||
}
|
|
||||||
|
|
||||||
case "resolve_ndr_issue": {
|
|
||||||
const result = await registry.resolveNdr({
|
|
||||||
consignment_id: String(args?.consignment_id),
|
|
||||||
courier: args?.courier as any,
|
|
||||||
issue_type: args?.issue_type as any,
|
|
||||||
customer_phone: args?.customer_phone ? String(args?.customer_phone) : undefined,
|
|
||||||
customer_name: args?.customer_name ? String(args?.customer_name) : undefined,
|
|
||||||
reschedule_date: args?.reschedule_date ? String(args?.reschedule_date) : undefined,
|
|
||||||
corrected_address: args?.corrected_address ? String(args?.corrected_address) : undefined,
|
|
||||||
});
|
|
||||||
return { content: [{ type: "text", text: JSON.stringify(result, null, 2) }] };
|
|
||||||
}
|
|
||||||
|
|
||||||
default:
|
|
||||||
throw new Error(`Unknown tool: ${name}`);
|
|
||||||
}
|
|
||||||
} catch (error: any) {
|
|
||||||
return {
|
|
||||||
isError: true,
|
|
||||||
content: [{ type: "text", text: `Aura Courier MCP Error: ${error?.message || String(error)}` }],
|
|
||||||
};
|
|
||||||
}
|
|
||||||
});
|
});
|
||||||
|
|
||||||
return server;
|
return server;
|
||||||
|
|||||||
+204
@@ -0,0 +1,204 @@
|
|||||||
|
import { SupportedCourier } from "./types.js";
|
||||||
|
|
||||||
|
export type DeliveryZone = "inside_dhaka" | "sub_dhaka" | "outside_dhaka";
|
||||||
|
|
||||||
|
export interface SlaHoursRange {
|
||||||
|
min: number;
|
||||||
|
max: number;
|
||||||
|
}
|
||||||
|
|
||||||
|
export interface ZoneDefinition {
|
||||||
|
zone: DeliveryZone;
|
||||||
|
zone_title: string;
|
||||||
|
max_distance_km: number | null;
|
||||||
|
standard_fee_bdt: number;
|
||||||
|
cod_percent: number;
|
||||||
|
sla_hours: SlaHoursRange;
|
||||||
|
sla_label: string;
|
||||||
|
}
|
||||||
|
|
||||||
|
export interface CarrierTariffRule {
|
||||||
|
courier: SupportedCourier;
|
||||||
|
courier_name: string;
|
||||||
|
base_fee_bdt: Record<DeliveryZone, number>;
|
||||||
|
extra_kg_fee_bdt: Record<DeliveryZone, number>;
|
||||||
|
cod_percent: Record<DeliveryZone, number>;
|
||||||
|
sla_hours: Record<DeliveryZone, SlaHoursRange>;
|
||||||
|
coverage_notes: Record<DeliveryZone, string>;
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Single Source of Truth for Zone Definitions, Flat Fees & SLAs (T4)
|
||||||
|
*/
|
||||||
|
export const ZONE_DEFINITIONS: Record<DeliveryZone, ZoneDefinition> = {
|
||||||
|
inside_dhaka: {
|
||||||
|
zone: "inside_dhaka",
|
||||||
|
zone_title: "Inside Dhaka Metropolitan (ঢাকার ভেতরে)",
|
||||||
|
max_distance_km: 22,
|
||||||
|
standard_fee_bdt: 80,
|
||||||
|
cod_percent: 1.0,
|
||||||
|
sla_hours: { min: 12, max: 48 },
|
||||||
|
sla_label: "12–48h",
|
||||||
|
},
|
||||||
|
sub_dhaka: {
|
||||||
|
zone: "sub_dhaka",
|
||||||
|
zone_title: "Sub-Dhaka Periphery (সাব-ঢাকা: সাভার, গাজীপুর, কেরানীগঞ্জ, নারায়ণগঞ্জ)",
|
||||||
|
max_distance_km: 45,
|
||||||
|
standard_fee_bdt: 100,
|
||||||
|
cod_percent: 1.0,
|
||||||
|
sla_hours: { min: 24, max: 72 },
|
||||||
|
sla_label: "24–72h",
|
||||||
|
},
|
||||||
|
outside_dhaka: {
|
||||||
|
zone: "outside_dhaka",
|
||||||
|
zone_title: "Outside Dhaka Nationwide (ঢাকার বাইরে ৬৪ জেলা)",
|
||||||
|
max_distance_km: null,
|
||||||
|
standard_fee_bdt: 150,
|
||||||
|
cod_percent: 1.0,
|
||||||
|
sla_hours: { min: 48, max: 96 },
|
||||||
|
sla_label: "48–96h",
|
||||||
|
},
|
||||||
|
};
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Single Source of Truth for Per-Courier Tariff Slabs & Route-Specific Coverage Notes (T4)
|
||||||
|
* Cites standard published Bangladesh merchant courier commercial rate cards.
|
||||||
|
*/
|
||||||
|
export const CARRIER_TARIFF_TABLE: Record<SupportedCourier, CarrierTariffRule> = {
|
||||||
|
steadfast: {
|
||||||
|
courier: "steadfast",
|
||||||
|
courier_name: "Steadfast Courier",
|
||||||
|
base_fee_bdt: { inside_dhaka: 70, sub_dhaka: 100, outside_dhaka: 140 },
|
||||||
|
extra_kg_fee_bdt: { inside_dhaka: 20, sub_dhaka: 20, outside_dhaka: 20 },
|
||||||
|
cod_percent: { inside_dhaka: 1.0, sub_dhaka: 1.0, outside_dhaka: 1.0 },
|
||||||
|
sla_hours: {
|
||||||
|
inside_dhaka: { min: 12, max: 48 },
|
||||||
|
sub_dhaka: { min: 24, max: 72 },
|
||||||
|
outside_dhaka: { min: 48, max: 96 },
|
||||||
|
},
|
||||||
|
coverage_notes: {
|
||||||
|
inside_dhaka: "Direct metropolitan hub network across all Dhaka City wards.",
|
||||||
|
sub_dhaka: "Dedicated Sub-Dhaka hub coverage in Savar, Keraniganj, Gazipur, and Narayanganj.",
|
||||||
|
outside_dhaka: "Direct doorstep COD coverage across all 64 districts and 495+ upazilas nationwide.",
|
||||||
|
},
|
||||||
|
},
|
||||||
|
pathao: {
|
||||||
|
courier: "pathao",
|
||||||
|
courier_name: "Pathao Express",
|
||||||
|
base_fee_bdt: { inside_dhaka: 60, sub_dhaka: 110, outside_dhaka: 150 },
|
||||||
|
extra_kg_fee_bdt: { inside_dhaka: 25, sub_dhaka: 25, outside_dhaka: 25 },
|
||||||
|
cod_percent: { inside_dhaka: 1.0, sub_dhaka: 1.0, outside_dhaka: 1.0 },
|
||||||
|
sla_hours: {
|
||||||
|
inside_dhaka: { min: 12, max: 48 },
|
||||||
|
sub_dhaka: { min: 24, max: 72 },
|
||||||
|
outside_dhaka: { min: 48, max: 96 },
|
||||||
|
},
|
||||||
|
coverage_notes: {
|
||||||
|
inside_dhaka: "High-density on-demand rider fleet within Dhaka Metropolitan City.",
|
||||||
|
sub_dhaka: "Regional hub transit across Greater Dhaka industrial and suburban zones.",
|
||||||
|
outside_dhaka: "Inter-district linehaul and local hub delivery across major district towns nationwide.",
|
||||||
|
},
|
||||||
|
},
|
||||||
|
redx: {
|
||||||
|
courier: "redx",
|
||||||
|
courier_name: "RedX Delivery",
|
||||||
|
base_fee_bdt: { inside_dhaka: 80, sub_dhaka: 110, outside_dhaka: 160 },
|
||||||
|
extra_kg_fee_bdt: { inside_dhaka: 20, sub_dhaka: 20, outside_dhaka: 20 },
|
||||||
|
cod_percent: { inside_dhaka: 1.0, sub_dhaka: 1.0, outside_dhaka: 1.0 },
|
||||||
|
sla_hours: {
|
||||||
|
inside_dhaka: { min: 12, max: 48 },
|
||||||
|
sub_dhaka: { min: 24, max: 72 },
|
||||||
|
outside_dhaka: { min: 48, max: 96 },
|
||||||
|
},
|
||||||
|
coverage_notes: {
|
||||||
|
inside_dhaka: "Automated sorting and fleet dispatch across Dhaka Metropolitan zones.",
|
||||||
|
sub_dhaka: "Sub-district hub coverage for heavy and standard parcels around Dhaka periphery.",
|
||||||
|
outside_dhaka: "Nationwide linehaul network across 64 districts with heavy parcel handling support.",
|
||||||
|
},
|
||||||
|
},
|
||||||
|
paperfly: {
|
||||||
|
courier: "paperfly",
|
||||||
|
courier_name: "Paperfly Go",
|
||||||
|
base_fee_bdt: { inside_dhaka: 80, sub_dhaka: 110, outside_dhaka: 170 },
|
||||||
|
extra_kg_fee_bdt: { inside_dhaka: 25, sub_dhaka: 25, outside_dhaka: 25 },
|
||||||
|
cod_percent: { inside_dhaka: 1.5, sub_dhaka: 1.5, outside_dhaka: 1.5 },
|
||||||
|
sla_hours: {
|
||||||
|
inside_dhaka: { min: 12, max: 48 },
|
||||||
|
sub_dhaka: { min: 24, max: 72 },
|
||||||
|
outside_dhaka: { min: 48, max: 96 },
|
||||||
|
},
|
||||||
|
coverage_notes: {
|
||||||
|
inside_dhaka: "Doorstep pickup and metropolitan delivery across Dhaka City.",
|
||||||
|
sub_dhaka: "Suburban doorstep delivery across Savar, Ashulia, Gazipur, and Keraniganj.",
|
||||||
|
outside_dhaka: "Deep union-level and rural village doorstep delivery across all 64 districts.",
|
||||||
|
},
|
||||||
|
},
|
||||||
|
};
|
||||||
|
|
||||||
|
export function classifyZoneFromAddressAndDistance(
|
||||||
|
address: string,
|
||||||
|
roadDistanceKm: number = 0
|
||||||
|
): ZoneDefinition {
|
||||||
|
const addr = String(address || "").toLowerCase();
|
||||||
|
const isSubDhakaArea =
|
||||||
|
/savar|ashulia|gazipur|gajipur|tongi|keraniganj|narayanganj|siddhirganj|fatullah|সাভার|আশুলিয়া|গাজীপুর|টঙ্গী|কেরানীগঞ্জ|নারায়ণগঞ্জ/i.test(
|
||||||
|
addr
|
||||||
|
);
|
||||||
|
const isOutsideCityMentioned =
|
||||||
|
/chattogram|chittagong|sylhet|rajshahi|khulna|barishal|barisal|rangpur|mymensingh|cumilla|comilla|cox|bogura|bogra|jessore|jashore|dinajpur|thakurgaon|চট্টগ্রাম|সিলেট|রাজশাহী|খুলনা|বরিশাল|রংপুর|ময়মনসিংহ|কুমিল্লা|কক্সবাজার/i.test(
|
||||||
|
addr
|
||||||
|
);
|
||||||
|
const isDhakaMetroMentioned =
|
||||||
|
!isSubDhakaArea &&
|
||||||
|
!isOutsideCityMentioned &&
|
||||||
|
/dhaka|ঢাকা|gulshan|banani|dhanmondi|uttara|mirpur|mohammadpur|motijheel|badda|rampura|bashundhara|tejgaon|khilgaon|malibagh|mogbazar|farmgate|shahbag|hatirpool|lalmatia|wari|jatrabari|গুলশান|বনানী|ধানমন্ডি|উত্তরা|মিরপুর|মোহাম্মদপুর|মতিঝিল|বাড্ডা|রামপুরা|বসুন্ধরা|তেজগাঁও|খিলগাঁও|মালিবাগ|মগবাজার|ফার্মগেট|শাহবাগ|হাতিরপুল|ওয়ারী|যাত্রাবাড়ী/i.test(
|
||||||
|
addr
|
||||||
|
);
|
||||||
|
|
||||||
|
if (isOutsideCityMentioned) {
|
||||||
|
return ZONE_DEFINITIONS.outside_dhaka;
|
||||||
|
}
|
||||||
|
if (isSubDhakaArea) {
|
||||||
|
return ZONE_DEFINITIONS.sub_dhaka;
|
||||||
|
}
|
||||||
|
if (isDhakaMetroMentioned && (roadDistanceKm <= 0 || roadDistanceKm <= 22)) {
|
||||||
|
return ZONE_DEFINITIONS.inside_dhaka;
|
||||||
|
}
|
||||||
|
if (roadDistanceKm > 0 && roadDistanceKm <= 22) {
|
||||||
|
return ZONE_DEFINITIONS.inside_dhaka;
|
||||||
|
}
|
||||||
|
if (roadDistanceKm > 22 && roadDistanceKm <= 45) {
|
||||||
|
return ZONE_DEFINITIONS.sub_dhaka;
|
||||||
|
}
|
||||||
|
return ZONE_DEFINITIONS.outside_dhaka;
|
||||||
|
}
|
||||||
|
|
||||||
|
export function computeCourierQuote(
|
||||||
|
courier: SupportedCourier,
|
||||||
|
zone: DeliveryZone,
|
||||||
|
weightKg: number,
|
||||||
|
codAmount: number
|
||||||
|
) {
|
||||||
|
const rule = CARRIER_TARIFF_TABLE[courier];
|
||||||
|
const effectiveWeight = Math.max(0.1, Number(weightKg || 0.5));
|
||||||
|
const extraKg = Math.max(0, Math.ceil(effectiveWeight - 1.0));
|
||||||
|
const baseFee = rule.base_fee_bdt[zone];
|
||||||
|
const weightSurcharge = extraKg * rule.extra_kg_fee_bdt[zone];
|
||||||
|
const codPercent = rule.cod_percent[zone];
|
||||||
|
const codCharge = Math.round(Math.max(0, Number(codAmount || 0)) * (codPercent / 100));
|
||||||
|
const totalCost = baseFee + weightSurcharge + codCharge;
|
||||||
|
const slaHours = rule.sla_hours[zone];
|
||||||
|
|
||||||
|
return {
|
||||||
|
courier,
|
||||||
|
courier_name: rule.courier_name,
|
||||||
|
base_delivery_fee: baseFee,
|
||||||
|
weight_surcharge: weightSurcharge,
|
||||||
|
cod_percent: codPercent,
|
||||||
|
cod_charge: codCharge,
|
||||||
|
total_cost: totalCost,
|
||||||
|
sla_hours: slaHours,
|
||||||
|
estimated_hours: `${slaHours.min}–${slaHours.max}h`,
|
||||||
|
coverage_notes: rule.coverage_notes[zone],
|
||||||
|
};
|
||||||
|
}
|
||||||
+107
-23
@@ -15,6 +15,8 @@ export interface ParcelCreateRequest {
|
|||||||
delivery_area?: string;
|
delivery_area?: string;
|
||||||
delivery_area_id?: number | string;
|
delivery_area_id?: number | string;
|
||||||
pickup_store_id?: number | string;
|
pickup_store_id?: number | string;
|
||||||
|
dry_run?: boolean;
|
||||||
|
tenant_id?: string;
|
||||||
}
|
}
|
||||||
|
|
||||||
export interface ParcelResponse {
|
export interface ParcelResponse {
|
||||||
@@ -25,7 +27,18 @@ export interface ParcelResponse {
|
|||||||
invoice: string;
|
invoice: string;
|
||||||
status: string;
|
status: string;
|
||||||
delivery_fee?: number;
|
delivery_fee?: number;
|
||||||
|
cost_estimate_bdt?: number;
|
||||||
cod_amount: number;
|
cod_amount: number;
|
||||||
|
routing_reason?: string;
|
||||||
|
cancellable_via_api?: boolean;
|
||||||
|
idempotent_replay?: boolean;
|
||||||
|
would_book_with?: SupportedCourier;
|
||||||
|
estimated_cost_bdt?: number;
|
||||||
|
validation?: {
|
||||||
|
phone_ok: boolean;
|
||||||
|
address_ok: boolean;
|
||||||
|
needs_review: boolean;
|
||||||
|
};
|
||||||
raw_response?: any;
|
raw_response?: any;
|
||||||
created_at?: string;
|
created_at?: string;
|
||||||
}
|
}
|
||||||
@@ -42,28 +55,37 @@ export interface TrackingResponse {
|
|||||||
time: string;
|
time: string;
|
||||||
note?: string;
|
note?: string;
|
||||||
}>;
|
}>;
|
||||||
|
couriers_checked?: SupportedCourier[];
|
||||||
raw_response?: any;
|
raw_response?: any;
|
||||||
}
|
}
|
||||||
|
|
||||||
export interface BalanceResponse {
|
export interface BalanceResponse {
|
||||||
success: boolean;
|
success: boolean;
|
||||||
courier: SupportedCourier;
|
courier: SupportedCourier;
|
||||||
current_balance: number;
|
amount_bdt: number | null;
|
||||||
|
pending_bdt: number | null;
|
||||||
|
current_balance: number | null;
|
||||||
|
status: "OK" | "UNSUPPORTED_BY_PROVIDER";
|
||||||
|
hint?: string;
|
||||||
|
as_of?: string;
|
||||||
raw_response?: any;
|
raw_response?: any;
|
||||||
}
|
}
|
||||||
|
|
||||||
export interface FraudRiskScoreResponse {
|
export interface FraudRiskScoreResponse {
|
||||||
phone: string;
|
phone: string;
|
||||||
risk_level: "LOW" | "MODERATE" | "HIGH" | "CRITICAL" | "NEW_BUYER";
|
risk_level: "INVALID_NUMBER" | "NO_HISTORY" | "LOW" | "MEDIUM" | "MODERATE" | "HIGH" | "CRITICAL" | "NEW_BUYER";
|
||||||
delivery_success_rate: string;
|
delivery_success_rate: string | null;
|
||||||
total_parcels?: number;
|
total_parcels?: number;
|
||||||
total_delivered?: number;
|
total_delivered?: number;
|
||||||
total_cancelled?: number;
|
total_cancelled?: number;
|
||||||
cancellation_rate?: string;
|
cancellation_rate: string | null;
|
||||||
is_verified_buyer: boolean;
|
is_verified_buyer: boolean;
|
||||||
recommendation: string;
|
recommendation: string;
|
||||||
carrier_source: string;
|
carrier_source: string;
|
||||||
carrier_verified: boolean;
|
carrier_verified: boolean;
|
||||||
|
data_sources: string[];
|
||||||
|
sample_size: number;
|
||||||
|
coverage_note: string;
|
||||||
multi_signal_factors?: {
|
multi_signal_factors?: {
|
||||||
carrier_score: string;
|
carrier_score: string;
|
||||||
address_confidence?: string;
|
address_confidence?: string;
|
||||||
@@ -78,13 +100,6 @@ export interface LocationResolutionRequest {
|
|||||||
area_name?: string;
|
area_name?: string;
|
||||||
}
|
}
|
||||||
|
|
||||||
export interface LocationResolutionRequest {
|
|
||||||
courier: SupportedCourier;
|
|
||||||
city_name?: string;
|
|
||||||
zone_name?: string;
|
|
||||||
area_name?: string;
|
|
||||||
}
|
|
||||||
|
|
||||||
export interface LocationResolutionResponse {
|
export interface LocationResolutionResponse {
|
||||||
success: boolean;
|
success: boolean;
|
||||||
courier: SupportedCourier;
|
courier: SupportedCourier;
|
||||||
@@ -98,7 +113,7 @@ export interface LocationResolutionResponse {
|
|||||||
}>;
|
}>;
|
||||||
}
|
}
|
||||||
|
|
||||||
// Google Maps Platform Spatial Types
|
// Google Maps Platform Spatial Types (T5)
|
||||||
export interface AddressValidationRequest {
|
export interface AddressValidationRequest {
|
||||||
address: string;
|
address: string;
|
||||||
thana?: string;
|
thana?: string;
|
||||||
@@ -108,16 +123,25 @@ export interface AddressValidationRequest {
|
|||||||
export interface AddressValidationResponse {
|
export interface AddressValidationResponse {
|
||||||
success: boolean;
|
success: boolean;
|
||||||
formatted_address: string;
|
formatted_address: string;
|
||||||
|
thana_input: string | null;
|
||||||
|
thana_resolved: string | null;
|
||||||
thana?: string;
|
thana?: string;
|
||||||
district?: string;
|
district: string;
|
||||||
division?: string;
|
division: string;
|
||||||
coordinates: {
|
coordinates: {
|
||||||
lat: number;
|
lat: number;
|
||||||
lng: number;
|
lng: number;
|
||||||
};
|
};
|
||||||
location_type: string;
|
location_type: "ROOFTOP" | "RANGE_INTERPOLATED" | "GEOMETRIC_CENTER" | "APPROXIMATE" | string;
|
||||||
is_deliverable: boolean;
|
is_deliverable: boolean;
|
||||||
confidence_score: number; // 0 - 100
|
confidence_score: number; // 0 - 100 (capped at 60 when location_type != ROOFTOP)
|
||||||
|
match_quality: {
|
||||||
|
road: boolean;
|
||||||
|
house: boolean;
|
||||||
|
area: boolean;
|
||||||
|
};
|
||||||
|
needs_review: boolean;
|
||||||
|
warnings: string[];
|
||||||
place_id?: string;
|
place_id?: string;
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -135,14 +159,21 @@ export interface ZoneRateResponse {
|
|||||||
success: boolean;
|
success: boolean;
|
||||||
zone: "inside_dhaka" | "sub_dhaka" | "outside_dhaka";
|
zone: "inside_dhaka" | "sub_dhaka" | "outside_dhaka";
|
||||||
zone_title: string;
|
zone_title: string;
|
||||||
|
distance_km: number;
|
||||||
road_distance_km: number;
|
road_distance_km: number;
|
||||||
|
sla_hours: {
|
||||||
|
min: number;
|
||||||
|
max: number;
|
||||||
|
};
|
||||||
estimated_delivery_hours: string;
|
estimated_delivery_hours: string;
|
||||||
|
standard_fee_bdt: number;
|
||||||
standard_delivery_fee: number;
|
standard_delivery_fee: number;
|
||||||
|
cod_percent: number;
|
||||||
cod_charge_percentage: number;
|
cod_charge_percentage: number;
|
||||||
route_summary?: string;
|
route_summary: string;
|
||||||
}
|
}
|
||||||
|
|
||||||
// Enterprise Multi-Carrier Rate Comparison
|
// Enterprise Multi-Carrier Rate Comparison (T4)
|
||||||
export interface CourierRateComparisonRequest {
|
export interface CourierRateComparisonRequest {
|
||||||
recipient_address: string;
|
recipient_address: string;
|
||||||
weight_kg?: number;
|
weight_kg?: number;
|
||||||
@@ -155,8 +186,13 @@ export interface CarrierQuote {
|
|||||||
courier_name: string;
|
courier_name: string;
|
||||||
base_delivery_fee: number;
|
base_delivery_fee: number;
|
||||||
weight_surcharge: number;
|
weight_surcharge: number;
|
||||||
|
cod_percent?: number;
|
||||||
cod_charge: number;
|
cod_charge: number;
|
||||||
total_cost: number;
|
total_cost: number;
|
||||||
|
sla_hours: {
|
||||||
|
min: number;
|
||||||
|
max: number;
|
||||||
|
};
|
||||||
estimated_hours: string;
|
estimated_hours: string;
|
||||||
coverage_notes: string;
|
coverage_notes: string;
|
||||||
is_recommended: boolean;
|
is_recommended: boolean;
|
||||||
@@ -166,7 +202,12 @@ export interface CourierRateComparisonResponse {
|
|||||||
success: boolean;
|
success: boolean;
|
||||||
zone: "inside_dhaka" | "sub_dhaka" | "outside_dhaka";
|
zone: "inside_dhaka" | "sub_dhaka" | "outside_dhaka";
|
||||||
zone_title: string;
|
zone_title: string;
|
||||||
|
distance_km: number;
|
||||||
road_distance_km: number;
|
road_distance_km: number;
|
||||||
|
sla_hours: {
|
||||||
|
min: number;
|
||||||
|
max: number;
|
||||||
|
};
|
||||||
weight_kg: number;
|
weight_kg: number;
|
||||||
cod_amount: number;
|
cod_amount: number;
|
||||||
recommended_courier: SupportedCourier;
|
recommended_courier: SupportedCourier;
|
||||||
@@ -174,7 +215,7 @@ export interface CourierRateComparisonResponse {
|
|||||||
quotes: CarrierQuote[];
|
quotes: CarrierQuote[];
|
||||||
}
|
}
|
||||||
|
|
||||||
// NDR (Non-Delivery Report) Auto-Resolution Workflow
|
// NDR (Non-Delivery Report) Auto-Resolution Workflow (T2)
|
||||||
export interface NdrResolutionRequest {
|
export interface NdrResolutionRequest {
|
||||||
consignment_id: string;
|
consignment_id: string;
|
||||||
courier: SupportedCourier;
|
courier: SupportedCourier;
|
||||||
@@ -189,9 +230,52 @@ export interface NdrResolutionResponse {
|
|||||||
success: boolean;
|
success: boolean;
|
||||||
consignment_id: string;
|
consignment_id: string;
|
||||||
courier: SupportedCourier;
|
courier: SupportedCourier;
|
||||||
resolution_status: "DISPUTE_FILED" | "RESCHEDULE_QUEUED" | "ADDRESS_UPDATED" | "CUSTOMER_REENGAGED";
|
status: "DRAFT_GENERATED";
|
||||||
action_taken: string;
|
consignment_verified: boolean;
|
||||||
customer_whatsapp_message: string;
|
actions_executed: string[];
|
||||||
carrier_instruction: string;
|
whatsapp_draft: {
|
||||||
|
language: "bn";
|
||||||
|
text: string;
|
||||||
|
};
|
||||||
|
courier_ticket_draft: {
|
||||||
|
subject: string;
|
||||||
|
body: string;
|
||||||
|
};
|
||||||
|
recommended_carrier_action: "HOLD" | "RESCHEDULE" | "CORRECT_ADDRESS" | "RETURN";
|
||||||
|
requires_manual_execution: boolean;
|
||||||
|
// Legacy backward-compatible aliases (without any past-tense claims or CUSTOMER_REENGAGED)
|
||||||
|
resolution_status?: "DRAFT_GENERATED";
|
||||||
|
action_taken?: string;
|
||||||
|
customer_whatsapp_message?: string;
|
||||||
|
carrier_instruction?: string;
|
||||||
timestamp: string;
|
timestamp: string;
|
||||||
}
|
}
|
||||||
|
|
||||||
|
export interface WebhookEventRecord {
|
||||||
|
id: string;
|
||||||
|
courier: SupportedCourier;
|
||||||
|
consignment_id: string;
|
||||||
|
invoice?: string;
|
||||||
|
status: string;
|
||||||
|
event_type?: string;
|
||||||
|
payload: Record<string, any>;
|
||||||
|
received_at: string;
|
||||||
|
}
|
||||||
|
|
||||||
|
export interface BulkParcelCreateResponse {
|
||||||
|
success: boolean;
|
||||||
|
total: number;
|
||||||
|
succeeded: number;
|
||||||
|
failed: number;
|
||||||
|
dry_run: boolean;
|
||||||
|
results: Array<{
|
||||||
|
index: number;
|
||||||
|
invoice: string;
|
||||||
|
ok: boolean;
|
||||||
|
data?: ParcelResponse;
|
||||||
|
error?: {
|
||||||
|
code: string;
|
||||||
|
message: string;
|
||||||
|
};
|
||||||
|
}>;
|
||||||
|
}
|
||||||
|
|||||||
@@ -0,0 +1,504 @@
|
|||||||
|
import test from "node:test";
|
||||||
|
import assert from "node:assert/strict";
|
||||||
|
import http from "node:http";
|
||||||
|
import axios from "axios";
|
||||||
|
|
||||||
|
// Configure test environment before importing app/modules
|
||||||
|
process.env.NODE_ENV = "test";
|
||||||
|
process.env.AURA_API_KEY = "aura_test_master_key_v260";
|
||||||
|
process.env.AURA_READONLY_KEY = "aura_ro_test_reader_v260";
|
||||||
|
process.env.AURA_WEBHOOK_SECRET = "aura_webhook_secret_test_v260";
|
||||||
|
process.env.STEADFAST_API_KEY = "sf_test_key";
|
||||||
|
process.env.STEADFAST_SECRET_KEY = "sf_test_secret";
|
||||||
|
process.env.PATHAO_CLIENT_ID = "pathao_test_id";
|
||||||
|
process.env.PATHAO_CLIENT_SECRET = "pathao_test_secret";
|
||||||
|
process.env.PATHAO_USERNAME = "merchant@example.test";
|
||||||
|
process.env.PATHAO_PASSWORD = "password_test";
|
||||||
|
process.env.REDX_API_TOKEN = "redx_test_token";
|
||||||
|
process.env.PAPERFLY_API_KEY = "pf_test_key";
|
||||||
|
process.env.PAPERFLY_USERNAME = "pf_user";
|
||||||
|
process.env.PAPERFLY_PASSWORD = "pf_pass";
|
||||||
|
process.env.GOOGLE_MAPS_API_KEY = "gmaps_test_key";
|
||||||
|
|
||||||
|
const { app } = await import("../dist/http.js");
|
||||||
|
const { clearIdempotencyStore, clearWebhookEvents } = await import("../dist/registry.js");
|
||||||
|
const { auditLogBuffer } = await import("../dist/middleware/auth.js");
|
||||||
|
|
||||||
|
let server;
|
||||||
|
let baseUrl;
|
||||||
|
let upstreamBookingCalls = 0;
|
||||||
|
|
||||||
|
// Mock all upstream axios HTTP calls so zero real carrier/Google requests are made
|
||||||
|
const originalAxiosCreate = axios.create.bind(axios);
|
||||||
|
axios.get = async (url, config) => {
|
||||||
|
const u = String(url);
|
||||||
|
// Google Maps Geocoding API mock
|
||||||
|
if (u.includes("maps.googleapis.com/maps/api/geocode/json")) {
|
||||||
|
const addr = String(config?.params?.address || "");
|
||||||
|
if (addr.toLowerCase().includes("dhanmondi")) {
|
||||||
|
return {
|
||||||
|
status: 200,
|
||||||
|
data: {
|
||||||
|
status: "OK",
|
||||||
|
results: [
|
||||||
|
{
|
||||||
|
formatted_address: "House 12, Road 5, Dhanmondi, Dhaka 1205, Bangladesh",
|
||||||
|
place_id: "mock_place_dhanmondi",
|
||||||
|
address_components: [
|
||||||
|
{ long_name: "Dhanmondi", types: ["sublocality_level_1", "sublocality", "political"] },
|
||||||
|
{ long_name: "Dhaka District", types: ["administrative_area_level_2", "political"] },
|
||||||
|
{ long_name: "Dhaka Division", types: ["administrative_area_level_1", "political"] },
|
||||||
|
],
|
||||||
|
geometry: {
|
||||||
|
location: { lat: 23.7461, lng: 90.3742 },
|
||||||
|
location_type: "RANGE_INTERPOLATED",
|
||||||
|
},
|
||||||
|
},
|
||||||
|
],
|
||||||
|
},
|
||||||
|
};
|
||||||
|
}
|
||||||
|
return {
|
||||||
|
status: 200,
|
||||||
|
data: {
|
||||||
|
status: "OK",
|
||||||
|
results: [
|
||||||
|
{
|
||||||
|
formatted_address: addr + ", Bangladesh",
|
||||||
|
place_id: "mock_place_generic",
|
||||||
|
address_components: [
|
||||||
|
{ long_name: "Banani", types: ["sublocality_level_1", "political"] },
|
||||||
|
{ long_name: "Dhaka", types: ["administrative_area_level_2", "political"] },
|
||||||
|
{ long_name: "Dhaka Division", types: ["administrative_area_level_1", "political"] },
|
||||||
|
],
|
||||||
|
geometry: {
|
||||||
|
location: { lat: 23.7937, lng: 90.4066 },
|
||||||
|
location_type: "ROOFTOP",
|
||||||
|
},
|
||||||
|
},
|
||||||
|
],
|
||||||
|
},
|
||||||
|
};
|
||||||
|
}
|
||||||
|
throw new Error(`Unexpected unmocked axios.get: ${u}`);
|
||||||
|
};
|
||||||
|
|
||||||
|
axios.post = async (url, body) => {
|
||||||
|
const u = String(url);
|
||||||
|
if (u.includes("routes.googleapis.com/directions/v2:computeRoutes")) {
|
||||||
|
const dest = String(body?.destination?.address || "").toLowerCase();
|
||||||
|
const distanceMeters = dest.includes("chattogram") || dest.includes("chittagong") ? 248000 : 6200;
|
||||||
|
return {
|
||||||
|
status: 200,
|
||||||
|
data: {
|
||||||
|
routes: [{ distanceMeters, duration: "1800s" }],
|
||||||
|
},
|
||||||
|
};
|
||||||
|
}
|
||||||
|
throw new Error(`Unexpected unmocked axios.post: ${u}`);
|
||||||
|
};
|
||||||
|
|
||||||
|
// Patch Steadfast, Pathao, RedX, and Paperfly adapters' internal HTTP clients via prototype/axios intercept
|
||||||
|
const { SteadfastAdapter } = await import("../dist/adapters/steadfast.js");
|
||||||
|
const { PathaoAdapter } = await import("../dist/adapters/pathao.js");
|
||||||
|
const { RedxAdapter } = await import("../dist/adapters/redx.js");
|
||||||
|
const { PaperflyAdapter } = await import("../dist/adapters/paperfly.js");
|
||||||
|
const { McpToolError } = await import("../dist/envelope.js");
|
||||||
|
|
||||||
|
SteadfastAdapter.prototype.trackParcel = async function (code) {
|
||||||
|
if (code === "SF_VALID_1001") {
|
||||||
|
return {
|
||||||
|
success: true,
|
||||||
|
courier: "steadfast",
|
||||||
|
tracking_code: code,
|
||||||
|
status: "Pending",
|
||||||
|
updated_at: new Date().toISOString(),
|
||||||
|
raw_response: { status: 200, delivery_status: "pending" },
|
||||||
|
};
|
||||||
|
}
|
||||||
|
const axiosLikeErr = new Error("Request failed with status code 400");
|
||||||
|
axiosLikeErr.response = { status: 404, data: { message: "Consignment not found" } };
|
||||||
|
throw new McpToolError({
|
||||||
|
code: "CONSIGNMENT_NOT_FOUND",
|
||||||
|
message: `Steadfast consignment '${code}' was not found.`,
|
||||||
|
courier: "steadfast",
|
||||||
|
retryable: false,
|
||||||
|
});
|
||||||
|
};
|
||||||
|
|
||||||
|
PathaoAdapter.prototype.trackParcel = async function (code) {
|
||||||
|
if (code === "DS_VALID_2002") {
|
||||||
|
return {
|
||||||
|
success: true,
|
||||||
|
courier: "pathao",
|
||||||
|
tracking_code: code,
|
||||||
|
status: "Picked Up",
|
||||||
|
updated_at: new Date().toISOString(),
|
||||||
|
};
|
||||||
|
}
|
||||||
|
throw new McpToolError({
|
||||||
|
code: "CONSIGNMENT_NOT_FOUND",
|
||||||
|
message: `Pathao consignment '${code}' was not found.`,
|
||||||
|
courier: "pathao",
|
||||||
|
retryable: false,
|
||||||
|
});
|
||||||
|
};
|
||||||
|
|
||||||
|
RedxAdapter.prototype.trackParcel = async function (code) {
|
||||||
|
throw new McpToolError({
|
||||||
|
code: "CONSIGNMENT_NOT_FOUND",
|
||||||
|
message: `RedX consignment '${code}' was not found.`,
|
||||||
|
courier: "redx",
|
||||||
|
retryable: false,
|
||||||
|
});
|
||||||
|
};
|
||||||
|
|
||||||
|
PaperflyAdapter.prototype.trackParcel = async function (code) {
|
||||||
|
throw new McpToolError({
|
||||||
|
code: "CONSIGNMENT_NOT_FOUND",
|
||||||
|
message: `Paperfly consignment '${code}' was not found.`,
|
||||||
|
courier: "paperfly",
|
||||||
|
retryable: false,
|
||||||
|
});
|
||||||
|
};
|
||||||
|
|
||||||
|
SteadfastAdapter.prototype.getBalance = async function () {
|
||||||
|
return {
|
||||||
|
success: true,
|
||||||
|
courier: "steadfast",
|
||||||
|
amount_bdt: 14250,
|
||||||
|
pending_bdt: 0,
|
||||||
|
current_balance: 14250,
|
||||||
|
status: "OK",
|
||||||
|
as_of: new Date().toISOString(),
|
||||||
|
};
|
||||||
|
};
|
||||||
|
|
||||||
|
SteadfastAdapter.prototype.createParcel = async function (req) {
|
||||||
|
upstreamBookingCalls++;
|
||||||
|
return {
|
||||||
|
success: true,
|
||||||
|
courier: "steadfast",
|
||||||
|
tracking_code: `SF_MOCK_${req.invoice}`,
|
||||||
|
consignment_id: 900100,
|
||||||
|
invoice: req.invoice,
|
||||||
|
status: "In Review",
|
||||||
|
cod_amount: req.cod_amount,
|
||||||
|
created_at: new Date().toISOString(),
|
||||||
|
};
|
||||||
|
};
|
||||||
|
|
||||||
|
PathaoAdapter.prototype.createParcel = async function (req) {
|
||||||
|
upstreamBookingCalls++;
|
||||||
|
return {
|
||||||
|
success: true,
|
||||||
|
courier: "pathao",
|
||||||
|
tracking_code: `DS_MOCK_${req.invoice}`,
|
||||||
|
consignment_id: `DS_MOCK_${req.invoice}`,
|
||||||
|
invoice: req.invoice,
|
||||||
|
status: "Pending",
|
||||||
|
cod_amount: req.cod_amount,
|
||||||
|
created_at: new Date().toISOString(),
|
||||||
|
};
|
||||||
|
};
|
||||||
|
|
||||||
|
SteadfastAdapter.prototype.fraudCheck = async function (phone) {
|
||||||
|
if (phone === "01700000000") {
|
||||||
|
return { total_parcels: 10, total_delivered: 9, total_cancelled: 1 };
|
||||||
|
}
|
||||||
|
return { total_parcels: 0, total_delivered: 0, total_cancelled: 0 };
|
||||||
|
};
|
||||||
|
|
||||||
|
PathaoAdapter.prototype.fraudCheck = async function (phone) {
|
||||||
|
if (phone === "01700000000") {
|
||||||
|
return { total_parcels: 12, total_delivered: 11, total_cancelled: 1, source: "Pathao Nationwide Customer Success DB" };
|
||||||
|
}
|
||||||
|
return { total_parcels: 0, total_delivered: 0, total_cancelled: 0 };
|
||||||
|
};
|
||||||
|
|
||||||
|
async function callMcpTool(toolName, args = {}, token = process.env.AURA_API_KEY) {
|
||||||
|
const headers = { "Content-Type": "application/json" };
|
||||||
|
if (token) headers["Authorization"] = `Bearer ${token}`;
|
||||||
|
|
||||||
|
const res = await fetch(`${baseUrl}/mcp`, {
|
||||||
|
method: "POST",
|
||||||
|
headers,
|
||||||
|
body: JSON.stringify({
|
||||||
|
jsonrpc: "2.0",
|
||||||
|
id: 1,
|
||||||
|
method: "tools/call",
|
||||||
|
params: { name: toolName, arguments: args },
|
||||||
|
}),
|
||||||
|
});
|
||||||
|
const body = await res.json();
|
||||||
|
const text = body?.result?.content?.[0]?.text;
|
||||||
|
const parsed = text ? JSON.parse(text) : body;
|
||||||
|
return { status: res.status, rpc: body, envelope: parsed };
|
||||||
|
}
|
||||||
|
|
||||||
|
test.before(async () => {
|
||||||
|
await new Promise((resolve) => {
|
||||||
|
server = http.createServer(app);
|
||||||
|
server.listen(0, "127.0.0.1", () => {
|
||||||
|
const addr = server.address();
|
||||||
|
baseUrl = `http://127.0.0.1:${addr.port}`;
|
||||||
|
resolve();
|
||||||
|
});
|
||||||
|
});
|
||||||
|
});
|
||||||
|
|
||||||
|
test.after(async () => {
|
||||||
|
if (server) {
|
||||||
|
await new Promise((resolve) => server.close(resolve));
|
||||||
|
}
|
||||||
|
});
|
||||||
|
|
||||||
|
test("1. POST /mcp without Authorization returns 401 and ok:false, error.code:'UNAUTHORIZED'", async () => {
|
||||||
|
const res = await fetch(`${baseUrl}/mcp`, {
|
||||||
|
method: "POST",
|
||||||
|
headers: { "Content-Type": "application/json" },
|
||||||
|
body: JSON.stringify({ jsonrpc: "2.0", id: 1, method: "tools/list", params: {} }),
|
||||||
|
});
|
||||||
|
assert.equal(res.status, 401);
|
||||||
|
const body = await res.json();
|
||||||
|
assert.equal(body.ok, false);
|
||||||
|
assert.equal(body.error.code, "UNAUTHORIZED");
|
||||||
|
assert.ok(body.meta.request_id);
|
||||||
|
});
|
||||||
|
|
||||||
|
test("2. POST /webhooks/steadfast without signature returns 401", async () => {
|
||||||
|
const res = await fetch(`${baseUrl}/webhooks/steadfast`, {
|
||||||
|
method: "POST",
|
||||||
|
headers: { "Content-Type": "application/json" },
|
||||||
|
body: JSON.stringify({ consignment_id: "SF_VALID_1001", status: "delivered" }),
|
||||||
|
});
|
||||||
|
assert.equal(res.status, 401);
|
||||||
|
const body = await res.json();
|
||||||
|
assert.equal(body.ok, false);
|
||||||
|
assert.equal(body.error.code, "UNAUTHORIZED");
|
||||||
|
});
|
||||||
|
|
||||||
|
test("3. resolve_ndr_issue with bogus consignment_id returns ok:false, error.code:'CONSIGNMENT_NOT_FOUND', NOT fake Bengali copy", async () => {
|
||||||
|
const { envelope } = await callMcpTool("resolve_ndr_issue", {
|
||||||
|
consignment_id: "BOGUS_CONSIGNMENT_999999",
|
||||||
|
courier: "steadfast",
|
||||||
|
issue_type: "customer_phone_off",
|
||||||
|
customer_phone: "01700000000",
|
||||||
|
});
|
||||||
|
assert.equal(envelope.ok, false);
|
||||||
|
assert.equal(envelope.error.code, "CONSIGNMENT_NOT_FOUND");
|
||||||
|
assert.equal(envelope.data, null);
|
||||||
|
assert.equal(envelope.whatsapp_draft, undefined);
|
||||||
|
});
|
||||||
|
|
||||||
|
test("4. resolve_ndr_issue with valid consignment_id returns status:'DRAFT_GENERATED', actions_executed:[], and copy prefixed with 'প্রস্তাবিত মেসেজ:'", async () => {
|
||||||
|
const { envelope } = await callMcpTool("resolve_ndr_issue", {
|
||||||
|
consignment_id: "SF_VALID_1001",
|
||||||
|
courier: "steadfast",
|
||||||
|
issue_type: "customer_phone_off",
|
||||||
|
customer_phone: "01700000000",
|
||||||
|
customer_name: "টেস্ট গ্রাহক",
|
||||||
|
});
|
||||||
|
assert.equal(envelope.ok, true);
|
||||||
|
assert.equal(envelope.status, "DRAFT_GENERATED");
|
||||||
|
assert.deepEqual(envelope.actions_executed, []);
|
||||||
|
assert.equal(envelope.requires_manual_execution, true);
|
||||||
|
assert.ok(envelope.whatsapp_draft.text.startsWith("প্রস্তাবিত মেসেজ:"));
|
||||||
|
assert.ok(!JSON.stringify(envelope).includes("CUSTOMER_REENGAGED"));
|
||||||
|
});
|
||||||
|
|
||||||
|
test("5. get_balance('steadfast') returns numeric amount_bdt and status:'OK'; pathao/redx/paperfly return amount_bdt:null, status:'UNSUPPORTED_BY_PROVIDER'", async () => {
|
||||||
|
const sf = await callMcpTool("get_balance", { courier: "steadfast" });
|
||||||
|
assert.equal(sf.envelope.ok, true);
|
||||||
|
assert.equal(typeof sf.envelope.amount_bdt, "number");
|
||||||
|
assert.equal(sf.envelope.amount_bdt, 14250);
|
||||||
|
assert.equal(sf.envelope.status, "OK");
|
||||||
|
|
||||||
|
for (const c of ["pathao", "redx", "paperfly"]) {
|
||||||
|
const res = await callMcpTool("get_balance", { courier: c });
|
||||||
|
assert.equal(res.envelope.ok, true);
|
||||||
|
assert.equal(res.envelope.amount_bdt, null);
|
||||||
|
assert.equal(res.envelope.pending_bdt, null);
|
||||||
|
assert.equal(res.envelope.status, "UNSUPPORTED_BY_PROVIDER");
|
||||||
|
assert.ok(res.envelope.hint.includes("merchant portal"));
|
||||||
|
}
|
||||||
|
});
|
||||||
|
|
||||||
|
test("6. calculate_delivery_zone_and_fee and compare_courier_rates agree on zone and sla_hours for 'Road 11, Banani, Dhaka'; Chattogram has no Dhaka-only note", async () => {
|
||||||
|
const zoneRes = await callMcpTool("calculate_delivery_zone_and_fee", {
|
||||||
|
recipient_address: "Road 11, Banani, Dhaka",
|
||||||
|
weight_kg: 0.5,
|
||||||
|
});
|
||||||
|
const compRes = await callMcpTool("compare_courier_rates", {
|
||||||
|
recipient_address: "Road 11, Banani, Dhaka",
|
||||||
|
weight_kg: 0.5,
|
||||||
|
cod_amount: 1000,
|
||||||
|
});
|
||||||
|
|
||||||
|
assert.equal(zoneRes.envelope.ok, true);
|
||||||
|
assert.equal(compRes.envelope.ok, true);
|
||||||
|
assert.equal(zoneRes.envelope.meta.source, "static_tariff");
|
||||||
|
assert.equal(compRes.envelope.meta.source, "static_tariff");
|
||||||
|
assert.equal(zoneRes.envelope.zone, "inside_dhaka");
|
||||||
|
assert.equal(compRes.envelope.zone, "inside_dhaka");
|
||||||
|
assert.deepEqual(zoneRes.envelope.sla_hours, { min: 12, max: 48 });
|
||||||
|
assert.deepEqual(compRes.envelope.sla_hours, { min: 12, max: 48 });
|
||||||
|
|
||||||
|
const ctgRes = await callMcpTool("compare_courier_rates", {
|
||||||
|
recipient_address: "Agrabad, Chattogram",
|
||||||
|
weight_kg: 1.0,
|
||||||
|
cod_amount: 1500,
|
||||||
|
});
|
||||||
|
assert.equal(ctgRes.envelope.zone, "outside_dhaka");
|
||||||
|
for (const q of ctgRes.envelope.quotes) {
|
||||||
|
assert.ok(
|
||||||
|
!q.coverage_notes.toLowerCase().includes("within dhaka metropolitan"),
|
||||||
|
`Unexpected Dhaka-only note on Chattogram route for ${q.courier}: ${q.coverage_notes}`
|
||||||
|
);
|
||||||
|
}
|
||||||
|
});
|
||||||
|
|
||||||
|
test("7. validate_and_geocode_address with mismatched thana_input returns thana_resolved != 'TEST_FAKE_THANA_XYZ', warnings non-empty, and confidence_score <= 60 when not ROOFTOP", async () => {
|
||||||
|
const { envelope } = await callMcpTool("validate_and_geocode_address", {
|
||||||
|
address: "House 12, Road 5, Dhanmondi, Dhaka",
|
||||||
|
thana: "TEST_FAKE_THANA_XYZ",
|
||||||
|
});
|
||||||
|
assert.equal(envelope.ok, true);
|
||||||
|
assert.equal(envelope.thana_input, "TEST_FAKE_THANA_XYZ");
|
||||||
|
assert.notEqual(envelope.thana_resolved, "TEST_FAKE_THANA_XYZ");
|
||||||
|
assert.equal(envelope.thana_resolved, "Dhanmondi");
|
||||||
|
assert.ok(Array.isArray(envelope.warnings) && envelope.warnings.length > 0);
|
||||||
|
assert.equal(envelope.needs_review, true);
|
||||||
|
assert.ok(envelope.confidence_score <= 60);
|
||||||
|
});
|
||||||
|
|
||||||
|
test("8. check_fraud_risk('01000000000') returns risk_level:'INVALID_NUMBER' and delivery_success_rate:null", async () => {
|
||||||
|
const { envelope } = await callMcpTool("check_fraud_risk", { phone: "01000000000" });
|
||||||
|
assert.equal(envelope.ok, true);
|
||||||
|
assert.equal(envelope.risk_level, "INVALID_NUMBER");
|
||||||
|
assert.equal(envelope.delivery_success_rate, null);
|
||||||
|
assert.equal(envelope.cancellation_rate, null);
|
||||||
|
assert.equal(envelope.sample_size, 0);
|
||||||
|
assert.deepEqual(envelope.data_sources, ["prefix_validator"]);
|
||||||
|
});
|
||||||
|
|
||||||
|
test("9. track_parcel('DEFINITELY_NOT_REAL_999999') returns ok:false, error.code:'CONSIGNMENT_NOT_FOUND', and no 'Request failed with status code' anywhere in payload", async () => {
|
||||||
|
const { envelope } = await callMcpTool("track_parcel", {
|
||||||
|
tracking_code: "DEFINITELY_NOT_REAL_999999",
|
||||||
|
});
|
||||||
|
const serialized = JSON.stringify(envelope);
|
||||||
|
assert.equal(envelope.ok, false);
|
||||||
|
assert.equal(envelope.error.code, "CONSIGNMENT_NOT_FOUND");
|
||||||
|
assert.ok(Array.isArray(envelope.couriers_checked) && envelope.couriers_checked.length > 0);
|
||||||
|
assert.ok(!serialized.includes("Request failed with status code"));
|
||||||
|
});
|
||||||
|
|
||||||
|
test("10. create_parcel({ ..., dry_run:true }) makes zero upstream booking calls and returns would_book_with and estimated_cost_bdt", async () => {
|
||||||
|
clearIdempotencyStore();
|
||||||
|
const beforeCalls = upstreamBookingCalls;
|
||||||
|
const { envelope } = await callMcpTool("create_parcel", {
|
||||||
|
courier: "auto",
|
||||||
|
invoice: "INV-DRY-1001",
|
||||||
|
recipient_name: "Test Receiver",
|
||||||
|
recipient_phone: "01700000000",
|
||||||
|
recipient_address: "House 10, Road 4, Dhanmondi, Dhaka",
|
||||||
|
cod_amount: 1200,
|
||||||
|
dry_run: true,
|
||||||
|
});
|
||||||
|
assert.equal(upstreamBookingCalls, beforeCalls);
|
||||||
|
assert.equal(envelope.ok, true);
|
||||||
|
assert.equal(envelope.status, "DRY_RUN");
|
||||||
|
assert.ok(envelope.would_book_with);
|
||||||
|
assert.equal(typeof envelope.estimated_cost_bdt, "number");
|
||||||
|
assert.equal(envelope.validation.phone_ok, true);
|
||||||
|
});
|
||||||
|
|
||||||
|
test("11. GET /health unauthenticated returns only { ok, version }; with admin token returns full telemetry", async () => {
|
||||||
|
const unauthRes = await fetch(`${baseUrl}/health`, {
|
||||||
|
headers: { Accept: "application/json" },
|
||||||
|
});
|
||||||
|
assert.equal(unauthRes.status, 200);
|
||||||
|
const unauthBody = await unauthRes.json();
|
||||||
|
assert.deepEqual(Object.keys(unauthBody).sort(), ["ok", "version"]);
|
||||||
|
assert.equal(unauthBody.ok, true);
|
||||||
|
assert.equal(unauthBody.version, "2.6.0");
|
||||||
|
|
||||||
|
const adminRes = await fetch(`${baseUrl}/health?detail=1`, {
|
||||||
|
headers: {
|
||||||
|
Accept: "application/json",
|
||||||
|
Authorization: `Bearer ${process.env.AURA_API_KEY}`,
|
||||||
|
},
|
||||||
|
});
|
||||||
|
assert.equal(adminRes.status, 200);
|
||||||
|
const adminBody = await adminRes.json();
|
||||||
|
assert.equal(adminBody.ok, true);
|
||||||
|
assert.equal(adminBody.version, "2.6.0");
|
||||||
|
assert.equal(adminBody.tools_count, 12);
|
||||||
|
assert.ok(adminBody.performance);
|
||||||
|
});
|
||||||
|
|
||||||
|
test("12. Idempotent create_parcel replay, cancel_parcel UNSUPPORTED_BY_PROVIDER, bulk_create_parcels, and authenticated get_webhook_events", async () => {
|
||||||
|
clearIdempotencyStore();
|
||||||
|
clearWebhookEvents();
|
||||||
|
|
||||||
|
const beforeCalls = upstreamBookingCalls;
|
||||||
|
const first = await callMcpTool("create_parcel", {
|
||||||
|
courier: "steadfast",
|
||||||
|
invoice: "INV-IDEM-2026",
|
||||||
|
recipient_name: "Synthetic Customer",
|
||||||
|
recipient_phone: "01700000000",
|
||||||
|
recipient_address: "House 12, Road 5, Dhanmondi, Dhaka",
|
||||||
|
cod_amount: 1500,
|
||||||
|
});
|
||||||
|
assert.equal(first.envelope.ok, true);
|
||||||
|
assert.equal(first.envelope.idempotent_replay, false);
|
||||||
|
assert.equal(upstreamBookingCalls, beforeCalls + 1);
|
||||||
|
|
||||||
|
const second = await callMcpTool("create_parcel", {
|
||||||
|
courier: "steadfast",
|
||||||
|
invoice: "INV-IDEM-2026",
|
||||||
|
recipient_name: "Synthetic Customer",
|
||||||
|
recipient_phone: "01700000000",
|
||||||
|
recipient_address: "House 12, Road 5, Dhanmondi, Dhaka",
|
||||||
|
cod_amount: 1500,
|
||||||
|
});
|
||||||
|
assert.equal(second.envelope.ok, true);
|
||||||
|
assert.equal(second.envelope.idempotent_replay, true);
|
||||||
|
assert.equal(second.envelope.tracking_code, first.envelope.tracking_code);
|
||||||
|
assert.equal(upstreamBookingCalls, beforeCalls + 1);
|
||||||
|
|
||||||
|
// cancel_parcel returns UNSUPPORTED_BY_PROVIDER
|
||||||
|
const cancelRes = await callMcpTool("cancel_parcel", {
|
||||||
|
courier: "steadfast",
|
||||||
|
consignment_id: first.envelope.tracking_code,
|
||||||
|
});
|
||||||
|
assert.equal(cancelRes.envelope.ok, false);
|
||||||
|
assert.equal(cancelRes.envelope.error.code, "UNSUPPORTED_BY_PROVIDER");
|
||||||
|
|
||||||
|
// Signed webhook event -> get_webhook_events
|
||||||
|
const whPost = await fetch(`${baseUrl}/webhooks/steadfast`, {
|
||||||
|
method: "POST",
|
||||||
|
headers: {
|
||||||
|
"Content-Type": "application/json",
|
||||||
|
"x-webhook-secret": process.env.AURA_WEBHOOK_SECRET,
|
||||||
|
},
|
||||||
|
body: JSON.stringify({
|
||||||
|
consignment_id: "SF_VALID_1001",
|
||||||
|
invoice: "INV-IDEM-2026",
|
||||||
|
status: "delivered",
|
||||||
|
notification_type: "delivery_status",
|
||||||
|
}),
|
||||||
|
});
|
||||||
|
assert.equal(whPost.status, 200);
|
||||||
|
|
||||||
|
const eventsRes = await callMcpTool("get_webhook_events", {
|
||||||
|
consignment_id: "SF_VALID_1001",
|
||||||
|
});
|
||||||
|
assert.equal(eventsRes.envelope.ok, true);
|
||||||
|
assert.equal(eventsRes.envelope.count, 1);
|
||||||
|
assert.equal(eventsRes.envelope.events[0].status, "delivered");
|
||||||
|
|
||||||
|
// Privacy-safe audit log check: raw phone 01700000000 never appears in auditLogBuffer
|
||||||
|
const serializedAudit = JSON.stringify(auditLogBuffer);
|
||||||
|
assert.ok(!serializedAudit.includes("01700000000"));
|
||||||
|
});
|
||||||
+3
-3
@@ -1,5 +1,5 @@
|
|||||||
/**
|
/**
|
||||||
* Aura Courier MCP — Plugin Validation & Compliance Suite (v2.4.0)
|
* Aura Courier MCP — Plugin Validation & Compliance Suite (v2.5.2)
|
||||||
* Corresponds to `agy plugin validate .` standards.
|
* Corresponds to `agy plugin validate .` standards.
|
||||||
*/
|
*/
|
||||||
|
|
||||||
@@ -42,7 +42,7 @@ async function validateManifest() {
|
|||||||
|
|
||||||
assert(json.name === 'aura-courier', `name matches 'aura-courier' (got '${json.name}')`);
|
assert(json.name === 'aura-courier', `name matches 'aura-courier' (got '${json.name}')`);
|
||||||
assert(json.displayName === 'Aura Courier MCP', `displayName is 'Aura Courier MCP'`);
|
assert(json.displayName === 'Aura Courier MCP', `displayName is 'Aura Courier MCP'`);
|
||||||
assert(json.version === '2.5.0', `version is '2.5.0'`);
|
assert(json.version === '2.5.2', `version is '2.5.2'`);
|
||||||
assert(json.category === 'Business / Logistics', `category is 'Business / Logistics'`);
|
assert(json.category === 'Business / Logistics', `category is 'Business / Logistics'`);
|
||||||
assert(typeof json.description === 'string' && json.description.length > 20, 'description is informative');
|
assert(typeof json.description === 'string' && json.description.length > 20, 'description is informative');
|
||||||
assert(json.logo === 'assets/logo.svg', `logo points to 'assets/logo.svg'`);
|
assert(json.logo === 'assets/logo.svg', `logo points to 'assets/logo.svg'`);
|
||||||
@@ -127,7 +127,7 @@ async function validateRemoteMcpServer() {
|
|||||||
params: {
|
params: {
|
||||||
protocolVersion: '2024-11-05',
|
protocolVersion: '2024-11-05',
|
||||||
capabilities: {},
|
capabilities: {},
|
||||||
clientInfo: { name: 'antigravity-validator', version: '2.5.0' }
|
clientInfo: { name: 'antigravity-validator', version: '2.5.2' }
|
||||||
}
|
}
|
||||||
})
|
})
|
||||||
});
|
});
|
||||||
|
|||||||
Reference in New Issue
Block a user