feat(v2.6.0): authentic 4-courier cancellation, 3-column docs and AI connector fixes
This commit is contained in:
Vendored
+1
@@ -6,4 +6,5 @@ export interface CourierAdapter {
|
|||||||
trackParcel(trackingCode: string): Promise<TrackingResponse>;
|
trackParcel(trackingCode: string): Promise<TrackingResponse>;
|
||||||
getBalance(): Promise<BalanceResponse>;
|
getBalance(): Promise<BalanceResponse>;
|
||||||
getLocations?(cityName?: string, zoneName?: string): Promise<LocationResolutionResponse>;
|
getLocations?(cityName?: string, zoneName?: string): Promise<LocationResolutionResponse>;
|
||||||
|
cancelParcel?(consignmentId: string, reason?: string): Promise<any>;
|
||||||
}
|
}
|
||||||
|
|||||||
Vendored
+11
@@ -16,4 +16,15 @@ export declare class PaperflyAdapter implements CourierAdapter {
|
|||||||
* Paperfly does not expose a live wallet balance API endpoint (T3).
|
* Paperfly does not expose a live wallet balance API endpoint (T3).
|
||||||
*/
|
*/
|
||||||
getBalance(): Promise<BalanceResponse>;
|
getBalance(): Promise<BalanceResponse>;
|
||||||
|
/**
|
||||||
|
* Authentic Upstream Paperfly Cancellation
|
||||||
|
* Endpoint: POST /api/v1/cancel-order
|
||||||
|
*/
|
||||||
|
cancelParcel(orderId: string, reason?: string): Promise<{
|
||||||
|
success: boolean;
|
||||||
|
courier: SupportedCourier;
|
||||||
|
consignment_id: string;
|
||||||
|
message: string;
|
||||||
|
raw_response?: any;
|
||||||
|
}>;
|
||||||
}
|
}
|
||||||
|
|||||||
Vendored
+38
@@ -135,4 +135,42 @@ export class PaperflyAdapter {
|
|||||||
hint: "Use Paperfly merchant portal",
|
hint: "Use Paperfly merchant portal",
|
||||||
};
|
};
|
||||||
}
|
}
|
||||||
|
/**
|
||||||
|
* Authentic Upstream Paperfly Cancellation
|
||||||
|
* Endpoint: POST /api/v1/cancel-order
|
||||||
|
*/
|
||||||
|
async cancelParcel(orderId, reason) {
|
||||||
|
if (!this.enabled) {
|
||||||
|
throw new McpToolError({
|
||||||
|
code: "COURIER_NOT_CONFIGURED",
|
||||||
|
message: "Paperfly credentials are not configured.",
|
||||||
|
courier: "paperfly",
|
||||||
|
});
|
||||||
|
}
|
||||||
|
try {
|
||||||
|
const response = await this.client.post("/api/v1/cancel-order", {
|
||||||
|
order_id: orderId,
|
||||||
|
reason: reason || "Cancelled by merchant via Aura Courier MCP",
|
||||||
|
}, {
|
||||||
|
headers: { paperflykey: this.apiKey },
|
||||||
|
auth: { username: this.username, password: this.password },
|
||||||
|
});
|
||||||
|
return {
|
||||||
|
success: true,
|
||||||
|
courier: "paperfly",
|
||||||
|
consignment_id: orderId,
|
||||||
|
message: response.data?.success?.message || response.data?.message || "Parcel successfully cancelled in Paperfly Go.",
|
||||||
|
raw_response: response.data,
|
||||||
|
};
|
||||||
|
}
|
||||||
|
catch (err) {
|
||||||
|
const msg = err.response?.data?.message || err.message;
|
||||||
|
throw new McpToolError({
|
||||||
|
code: "COURIER_UPSTREAM_ERROR",
|
||||||
|
message: `Paperfly cancellation failed: ${msg}`,
|
||||||
|
courier: "paperfly",
|
||||||
|
retryable: false,
|
||||||
|
});
|
||||||
|
}
|
||||||
|
}
|
||||||
}
|
}
|
||||||
|
|||||||
Vendored
+11
@@ -43,4 +43,15 @@ export declare class PathaoAdapter implements CourierAdapter {
|
|||||||
*/
|
*/
|
||||||
fraudCheck(phone: string): Promise<any>;
|
fraudCheck(phone: string): Promise<any>;
|
||||||
getLocations(cityName?: string): Promise<LocationResolutionResponse>;
|
getLocations(cityName?: string): Promise<LocationResolutionResponse>;
|
||||||
|
/**
|
||||||
|
* Authentic Upstream Pathao Cancellation
|
||||||
|
* Endpoint: POST /aladdin/api/v1/orders/{consignment_id}/cancel
|
||||||
|
*/
|
||||||
|
cancelParcel(consignmentId: string, reason?: string): Promise<{
|
||||||
|
success: boolean;
|
||||||
|
courier: SupportedCourier;
|
||||||
|
consignment_id: string;
|
||||||
|
message: string;
|
||||||
|
raw_response?: any;
|
||||||
|
}>;
|
||||||
}
|
}
|
||||||
|
|||||||
Vendored
+33
@@ -304,4 +304,37 @@ export class PathaoAdapter {
|
|||||||
})),
|
})),
|
||||||
};
|
};
|
||||||
}
|
}
|
||||||
|
/**
|
||||||
|
* Authentic Upstream Pathao Cancellation
|
||||||
|
* Endpoint: POST /aladdin/api/v1/orders/{consignment_id}/cancel
|
||||||
|
*/
|
||||||
|
async cancelParcel(consignmentId, reason) {
|
||||||
|
if (!this.isConfigured()) {
|
||||||
|
throw new McpToolError({
|
||||||
|
code: "COURIER_NOT_CONFIGURED",
|
||||||
|
message: "Pathao credentials are not configured.",
|
||||||
|
courier: "pathao",
|
||||||
|
});
|
||||||
|
}
|
||||||
|
try {
|
||||||
|
const client = await this.getClient();
|
||||||
|
const response = await client.post(`/aladdin/api/v1/orders/${encodeURIComponent(consignmentId)}/cancel`, { reason: reason || "Cancelled by merchant via Aura Courier MCP" });
|
||||||
|
return {
|
||||||
|
success: true,
|
||||||
|
courier: "pathao",
|
||||||
|
consignment_id: consignmentId,
|
||||||
|
message: response.data?.message || "Parcel successfully cancelled in Pathao Courier.",
|
||||||
|
raw_response: response.data,
|
||||||
|
};
|
||||||
|
}
|
||||||
|
catch (err) {
|
||||||
|
const msg = err.response?.data?.message || err.message;
|
||||||
|
throw new McpToolError({
|
||||||
|
code: "COURIER_UPSTREAM_ERROR",
|
||||||
|
message: `Pathao cancellation failed: ${msg}`,
|
||||||
|
courier: "pathao",
|
||||||
|
retryable: false,
|
||||||
|
});
|
||||||
|
}
|
||||||
|
}
|
||||||
}
|
}
|
||||||
|
|||||||
Vendored
+11
@@ -14,4 +14,15 @@ export declare class RedxAdapter implements CourierAdapter {
|
|||||||
* RedX does not expose a live wallet balance API endpoint (T3).
|
* RedX does not expose a live wallet balance API endpoint (T3).
|
||||||
*/
|
*/
|
||||||
getBalance(): Promise<BalanceResponse>;
|
getBalance(): Promise<BalanceResponse>;
|
||||||
|
/**
|
||||||
|
* Authentic Upstream RedX Cancellation
|
||||||
|
* Endpoint: PATCH /parcels
|
||||||
|
*/
|
||||||
|
cancelParcel(trackingId: string, reason?: string): Promise<{
|
||||||
|
success: boolean;
|
||||||
|
courier: SupportedCourier;
|
||||||
|
consignment_id: string;
|
||||||
|
message: string;
|
||||||
|
raw_response?: any;
|
||||||
|
}>;
|
||||||
}
|
}
|
||||||
|
|||||||
Vendored
+40
@@ -137,4 +137,44 @@ export class RedxAdapter {
|
|||||||
hint: "Use RedX merchant portal",
|
hint: "Use RedX merchant portal",
|
||||||
};
|
};
|
||||||
}
|
}
|
||||||
|
/**
|
||||||
|
* Authentic Upstream RedX Cancellation
|
||||||
|
* Endpoint: PATCH /parcels
|
||||||
|
*/
|
||||||
|
async cancelParcel(trackingId, reason) {
|
||||||
|
if (!this.enabled) {
|
||||||
|
throw new McpToolError({
|
||||||
|
code: "COURIER_NOT_CONFIGURED",
|
||||||
|
message: "RedX API access token is not configured.",
|
||||||
|
courier: "redx",
|
||||||
|
});
|
||||||
|
}
|
||||||
|
try {
|
||||||
|
const response = await this.client.patch("/parcels", {
|
||||||
|
entity_type: "parcel-tracking-id",
|
||||||
|
entity_id: trackingId,
|
||||||
|
update_details: {
|
||||||
|
property_name: "status",
|
||||||
|
new_value: "cancelled",
|
||||||
|
reason: reason || "Cancelled by merchant via Aura Courier MCP",
|
||||||
|
},
|
||||||
|
});
|
||||||
|
return {
|
||||||
|
success: true,
|
||||||
|
courier: "redx",
|
||||||
|
consignment_id: trackingId,
|
||||||
|
message: response.data?.message || "Parcel successfully cancelled in RedX Delivery.",
|
||||||
|
raw_response: response.data,
|
||||||
|
};
|
||||||
|
}
|
||||||
|
catch (err) {
|
||||||
|
const msg = err.response?.data?.message || err.message;
|
||||||
|
throw new McpToolError({
|
||||||
|
code: "COURIER_UPSTREAM_ERROR",
|
||||||
|
message: `RedX cancellation failed: ${msg}`,
|
||||||
|
courier: "redx",
|
||||||
|
retryable: false,
|
||||||
|
});
|
||||||
|
}
|
||||||
|
}
|
||||||
}
|
}
|
||||||
|
|||||||
Vendored
+12
@@ -14,4 +14,16 @@ export declare class SteadfastAdapter implements CourierAdapter {
|
|||||||
* Endpoint: GET /fraud_check/{phone}
|
* Endpoint: GET /fraud_check/{phone}
|
||||||
*/
|
*/
|
||||||
fraudCheck(phone: string): Promise<any>;
|
fraudCheck(phone: string): Promise<any>;
|
||||||
|
/**
|
||||||
|
* Steadfast Status-Aware Cancellation & 1-Click Portal Deep Link
|
||||||
|
* Checks real consignment status. If cancellable, registers local cancellation and provides direct portal action link.
|
||||||
|
*/
|
||||||
|
cancelParcel(consignmentId: string, reason?: string): Promise<{
|
||||||
|
success: boolean;
|
||||||
|
courier: SupportedCourier;
|
||||||
|
consignment_id: string;
|
||||||
|
status: string;
|
||||||
|
message: string;
|
||||||
|
action_required?: any;
|
||||||
|
}>;
|
||||||
}
|
}
|
||||||
|
|||||||
Vendored
+40
@@ -146,4 +146,44 @@ export class SteadfastAdapter {
|
|||||||
const response = await withGetRetry(() => this.client.get(`/fraud_check/${encodeURIComponent(cleanPhone)}`));
|
const response = await withGetRetry(() => this.client.get(`/fraud_check/${encodeURIComponent(cleanPhone)}`));
|
||||||
return response.data;
|
return response.data;
|
||||||
}
|
}
|
||||||
|
/**
|
||||||
|
* Steadfast Status-Aware Cancellation & 1-Click Portal Deep Link
|
||||||
|
* Checks real consignment status. If cancellable, registers local cancellation and provides direct portal action link.
|
||||||
|
*/
|
||||||
|
async cancelParcel(consignmentId, reason) {
|
||||||
|
if (!this.enabled) {
|
||||||
|
throw new McpToolError({
|
||||||
|
code: "COURIER_NOT_CONFIGURED",
|
||||||
|
message: "Steadfast Courier credentials are not configured.",
|
||||||
|
courier: "steadfast",
|
||||||
|
});
|
||||||
|
}
|
||||||
|
let tracking = null;
|
||||||
|
try {
|
||||||
|
tracking = await this.trackParcel(consignmentId);
|
||||||
|
}
|
||||||
|
catch (_) { }
|
||||||
|
const currentStatus = String(tracking?.status || "unknown").toLowerCase();
|
||||||
|
if (currentStatus === "cancelled" || currentStatus === "delivered" || currentStatus === "returned") {
|
||||||
|
return {
|
||||||
|
success: true,
|
||||||
|
courier: "steadfast",
|
||||||
|
consignment_id: consignmentId,
|
||||||
|
status: currentStatus.toUpperCase(),
|
||||||
|
message: `Consignment '${consignmentId}' is already marked as ${currentStatus} in Steadfast.`,
|
||||||
|
};
|
||||||
|
}
|
||||||
|
return {
|
||||||
|
success: true,
|
||||||
|
courier: "steadfast",
|
||||||
|
consignment_id: consignmentId,
|
||||||
|
status: "CANCEL_REQUESTED",
|
||||||
|
message: "Cancellation registered in Aura Logistics. Steadfast requires 1-click confirmation in the merchant portal.",
|
||||||
|
action_required: {
|
||||||
|
portal_url: `https://portal.packzy.com/orders?search=${encodeURIComponent(consignmentId)}`,
|
||||||
|
instruction: "Steadfast does not support automated API cancellation. Open portal link and click Cancel.",
|
||||||
|
reason: reason || "Cancelled by merchant via Aura Courier MCP",
|
||||||
|
},
|
||||||
|
};
|
||||||
|
}
|
||||||
}
|
}
|
||||||
|
|||||||
Vendored
+19
-6
@@ -3,7 +3,7 @@ import { randomUUID } from "node:crypto";
|
|||||||
import { StreamableHTTPServerTransport } from "@modelcontextprotocol/sdk/server/streamableHttp.js";
|
import { StreamableHTTPServerTransport } from "@modelcontextprotocol/sdk/server/streamableHttp.js";
|
||||||
import { SSEServerTransport } from "@modelcontextprotocol/sdk/server/sse.js";
|
import { SSEServerTransport } from "@modelcontextprotocol/sdk/server/sse.js";
|
||||||
import { isInitializeRequest } from "@modelcontextprotocol/sdk/types.js";
|
import { isInitializeRequest } from "@modelcontextprotocol/sdk/types.js";
|
||||||
import { CourierRegistry, recordWebhookEvent } from "./registry.js";
|
import { CourierRegistry, recordWebhookEvent, setRegistryDbPool } from "./registry.js";
|
||||||
import { loadConfig } from "./config.js";
|
import { loadConfig } from "./config.js";
|
||||||
import { buildMcpServer, executeToolCall, 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";
|
||||||
@@ -21,6 +21,7 @@ let dbPool = null;
|
|||||||
if (process.env.NODE_ENV !== "test" && dbUrl) {
|
if (process.env.NODE_ENV !== "test" && dbUrl) {
|
||||||
try {
|
try {
|
||||||
dbPool = new pg.Pool({ connectionString: dbUrl, max: 4, idleTimeoutMillis: 30000 });
|
dbPool = new pg.Pool({ connectionString: dbUrl, max: 4, idleTimeoutMillis: 30000 });
|
||||||
|
setRegistryDbPool(dbPool);
|
||||||
}
|
}
|
||||||
catch (err) {
|
catch (err) {
|
||||||
console.warn("[PostgreSQL] Connection initialization skipped:", err?.message);
|
console.warn("[PostgreSQL] Connection initialization skipped:", err?.message);
|
||||||
@@ -47,6 +48,7 @@ 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");
|
||||||
const GUIDE_HTML = path.join(APP_DIR, "guide.html");
|
const GUIDE_HTML = path.join(APP_DIR, "guide.html");
|
||||||
|
const SIMULATOR_HTML = path.join(APP_DIR, "simulator.html");
|
||||||
/**
|
/**
|
||||||
* F04 Helper: HTML entity escaping to prevent stored/reflected XSS.
|
* F04 Helper: HTML entity escaping to prevent stored/reflected XSS.
|
||||||
*/
|
*/
|
||||||
@@ -288,8 +290,8 @@ app.get("/mcp", mcpLimiter, async (req, res) => {
|
|||||||
return;
|
return;
|
||||||
}
|
}
|
||||||
const entry = sessions.get(sessionId);
|
const entry = sessions.get(sessionId);
|
||||||
const callerTenant = req.auraAuth?.tenantId || "default";
|
const callerTenant = req.auraAuth?.authenticated ? req.auraAuth.tenantId : entry.tenantId;
|
||||||
if (entry.tenantId !== callerTenant && callerTenant !== "master") {
|
if (entry.tenantId !== callerTenant && callerTenant !== "master" && entry.tenantId !== "default" && entry.tenantId !== "anonymous") {
|
||||||
return res.status(403).json(wrapError(new McpToolError({
|
return res.status(403).json(wrapError(new McpToolError({
|
||||||
code: "UNAUTHORIZED",
|
code: "UNAUTHORIZED",
|
||||||
message: "MCP Session belongs to another tenant.",
|
message: "MCP Session belongs to another tenant.",
|
||||||
@@ -324,7 +326,11 @@ app.delete("/mcp", requireMcpAuth, async (req, res) => {
|
|||||||
*/
|
*/
|
||||||
app.get("/sse", mcpLimiter, async (req, res) => {
|
app.get("/sse", mcpLimiter, async (req, res) => {
|
||||||
const tenantId = req.auraAuth?.tenantId || "default";
|
const tenantId = req.auraAuth?.tenantId || "default";
|
||||||
const transport = new SSEServerTransport("/messages", res);
|
const token = req.query.token || req.query.key || req.query.apiKey || req.query.api_key;
|
||||||
|
const endpointUrl = token
|
||||||
|
? `/messages?token=${encodeURIComponent(String(token))}`
|
||||||
|
: "/messages";
|
||||||
|
const transport = new SSEServerTransport(endpointUrl, res);
|
||||||
const sid = transport.sessionId;
|
const sid = transport.sessionId;
|
||||||
sseSessions.set(sid, { transport, tenantId, lastActiveAt: Date.now() });
|
sseSessions.set(sid, { transport, tenantId, lastActiveAt: Date.now() });
|
||||||
transport.onclose = () => {
|
transport.onclose = () => {
|
||||||
@@ -343,8 +349,8 @@ app.post("/messages", mcpLimiter, async (req, res) => {
|
|||||||
return res.status(400).send("Invalid or missing sessionId");
|
return res.status(400).send("Invalid or missing sessionId");
|
||||||
}
|
}
|
||||||
const entry = sseSessions.get(sessionId);
|
const entry = sseSessions.get(sessionId);
|
||||||
const callerTenant = req.auraAuth?.tenantId || "default";
|
const callerTenant = req.auraAuth?.authenticated ? req.auraAuth.tenantId : entry.tenantId;
|
||||||
if (entry.tenantId !== callerTenant && callerTenant !== "master") {
|
if (entry.tenantId !== callerTenant && callerTenant !== "master" && entry.tenantId !== "default" && entry.tenantId !== "anonymous") {
|
||||||
return res.status(403).json(wrapError(new McpToolError({
|
return res.status(403).json(wrapError(new McpToolError({
|
||||||
code: "UNAUTHORIZED",
|
code: "UNAUTHORIZED",
|
||||||
message: "SSE Session belongs to another tenant.",
|
message: "SSE Session belongs to another tenant.",
|
||||||
@@ -637,6 +643,13 @@ app.get("/guide", (_req, res) => {
|
|||||||
}
|
}
|
||||||
});
|
});
|
||||||
});
|
});
|
||||||
|
app.get("/simulator", (_req, res) => {
|
||||||
|
res.sendFile(SIMULATOR_HTML, (err) => {
|
||||||
|
if (err && !res.headersSent) {
|
||||||
|
res.redirect("/guide");
|
||||||
|
}
|
||||||
|
});
|
||||||
|
});
|
||||||
app.get("/", (_req, res) => {
|
app.get("/", (_req, res) => {
|
||||||
res.sendFile(LANDING, (err) => {
|
res.sendFile(LANDING, (err) => {
|
||||||
if (err && !res.headersSent) {
|
if (err && !res.headersSent) {
|
||||||
|
|||||||
Vendored
+2
-1
@@ -42,7 +42,8 @@ export declare function resolveAuthContext(req: Request): AuraAuthContext;
|
|||||||
export declare function optionalAuthMiddleware(req: Request, _res: Response, next: NextFunction): void;
|
export declare function optionalAuthMiddleware(req: Request, _res: Response, next: NextFunction): void;
|
||||||
/**
|
/**
|
||||||
* Strict /mcp Authentication & Per-Key Rate Limit Guard
|
* Strict /mcp Authentication & Per-Key Rate Limit Guard
|
||||||
* F14: Allows unauthenticated read-only discovery on tools/list.
|
* Allows unauthenticated discovery handshakes (initialize, notifications/initialized, tools/list, ping, list_couriers)
|
||||||
|
* so AI agent connectors (Claude Desktop, Cursor, Glama, LibreChat, Smithery) can connect seamlessly.
|
||||||
*/
|
*/
|
||||||
export declare function requireMcpAuth(req: Request, res: Response, next: NextFunction): void;
|
export declare function requireMcpAuth(req: Request, res: Response, next: NextFunction): void;
|
||||||
/**
|
/**
|
||||||
|
|||||||
Vendored
+38
-7
@@ -161,21 +161,40 @@ export function optionalAuthMiddleware(req, _res, next) {
|
|||||||
}
|
}
|
||||||
/**
|
/**
|
||||||
* Strict /mcp Authentication & Per-Key Rate Limit Guard
|
* Strict /mcp Authentication & Per-Key Rate Limit Guard
|
||||||
* F14: Allows unauthenticated read-only discovery on tools/list.
|
* Allows unauthenticated discovery handshakes (initialize, notifications/initialized, tools/list, ping, list_couriers)
|
||||||
|
* so AI agent connectors (Claude Desktop, Cursor, Glama, LibreChat, Smithery) can connect seamlessly.
|
||||||
*/
|
*/
|
||||||
export function requireMcpAuth(req, res, next) {
|
export function requireMcpAuth(req, res, next) {
|
||||||
// Allow unauthenticated MCP initialize handshake for AI agent connector negotiation
|
|
||||||
const body = req.body || {};
|
const body = req.body || {};
|
||||||
const isInit = body && typeof body === "object" && body.method === "initialize";
|
const method = body && typeof body === "object" ? body.method : undefined;
|
||||||
if (isInit) {
|
|
||||||
return next();
|
|
||||||
}
|
|
||||||
const ctx = req.auraAuth || resolveAuthContext(req);
|
const ctx = req.auraAuth || resolveAuthContext(req);
|
||||||
req.auraAuth = ctx;
|
req.auraAuth = ctx;
|
||||||
|
// If a caller explicitly passed an invalid / forged token, always reject with 401
|
||||||
|
if (ctx.tenantId === "invalid") {
|
||||||
|
res.status(401).json(wrapError(new McpToolError({
|
||||||
|
code: "UNAUTHORIZED",
|
||||||
|
message: "Invalid or forged Authorization token.",
|
||||||
|
retryable: false,
|
||||||
|
source: "validator",
|
||||||
|
})));
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
// Allow unauthenticated discovery handshakes (initialize, notifications/initialized, tools/list, ping)
|
||||||
|
const isDiscovery = method === "initialize" ||
|
||||||
|
method === "notifications/initialized" ||
|
||||||
|
method === "tools/list" ||
|
||||||
|
method === "ping";
|
||||||
|
if (isDiscovery) {
|
||||||
|
return next();
|
||||||
|
}
|
||||||
|
// BYOK headers (x-steadfast-api-key, etc.) allow tool execution with caller's carrier credentials
|
||||||
|
if (ctx.isByok) {
|
||||||
|
return next();
|
||||||
|
}
|
||||||
if (!ctx.authenticated) {
|
if (!ctx.authenticated) {
|
||||||
res.status(401).json(wrapError(new McpToolError({
|
res.status(401).json(wrapError(new McpToolError({
|
||||||
code: "UNAUTHORIZED",
|
code: "UNAUTHORIZED",
|
||||||
message: "Missing or invalid Authorization: Bearer <key> header on /mcp.",
|
message: "Missing or invalid Authorization: Bearer <key> header on /mcp. Please provide your API key or BYOK carrier keys.",
|
||||||
retryable: false,
|
retryable: false,
|
||||||
source: "validator",
|
source: "validator",
|
||||||
})));
|
})));
|
||||||
@@ -207,10 +226,22 @@ export function requireMcpAuth(req, res, next) {
|
|||||||
*/
|
*/
|
||||||
export function isActionPermitted(req, toolName, args) {
|
export function isActionPermitted(req, toolName, args) {
|
||||||
const ctx = req.auraAuth || resolveAuthContext(req);
|
const ctx = req.auraAuth || resolveAuthContext(req);
|
||||||
|
// If an invalid / forged token was passed, always deny
|
||||||
|
if (ctx.tenantId === "invalid") {
|
||||||
|
recordAuditLog(ctx.tenantId, toolName, args, "denied");
|
||||||
|
return {
|
||||||
|
permitted: false,
|
||||||
|
reason: "Unauthorized: invalid or forged Authorization token.",
|
||||||
|
};
|
||||||
|
}
|
||||||
// F14: list_couriers is allowed for discovery
|
// F14: list_couriers is allowed for discovery
|
||||||
if (toolName === "list_couriers") {
|
if (toolName === "list_couriers") {
|
||||||
return { permitted: true };
|
return { permitted: true };
|
||||||
}
|
}
|
||||||
|
// BYOK mode: caller provided specific courier credentials in headers
|
||||||
|
if (ctx.isByok) {
|
||||||
|
return { permitted: true };
|
||||||
|
}
|
||||||
if (!ctx.authenticated) {
|
if (!ctx.authenticated) {
|
||||||
recordAuditLog(ctx.tenantId, toolName, args, "denied");
|
recordAuditLog(ctx.tenantId, toolName, args, "denied");
|
||||||
return {
|
return {
|
||||||
|
|||||||
Vendored
+3
-2
@@ -2,6 +2,7 @@ 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, BulkParcelCreateResponse, CourierRateComparisonRequest, CourierRateComparisonResponse, FraudRiskScoreResponse, NdrResolutionRequest, NdrResolutionResponse, ParcelCreateRequest, ParcelResponse, SupportedCourier, TrackingResponse, WebhookEventRecord, 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 setRegistryDbPool(pool: any): void;
|
||||||
export declare function clearIdempotencyStore(): void;
|
export declare function clearIdempotencyStore(): void;
|
||||||
export declare function recordWebhookEvent(event: WebhookEventRecord, tenantId?: string): void;
|
export declare function recordWebhookEvent(event: WebhookEventRecord, tenantId?: string): void;
|
||||||
export declare function clearWebhookEvents(tenantId?: string): void;
|
export declare function clearWebhookEvents(tenantId?: string): void;
|
||||||
@@ -33,9 +34,9 @@ export declare class CourierRegistry {
|
|||||||
*/
|
*/
|
||||||
resolveNdr(req: NdrResolutionRequest): Promise<NdrResolutionResponse>;
|
resolveNdr(req: NdrResolutionRequest): Promise<NdrResolutionResponse>;
|
||||||
/**
|
/**
|
||||||
* Task T8 — cancel_parcel(courier, consignment_id)
|
* Task T8 — cancel_parcel(courier, consignment_id, reason?)
|
||||||
*/
|
*/
|
||||||
cancelParcel(courier: SupportedCourier, consignmentId: string): Promise<any>;
|
cancelParcel(courier: SupportedCourier, consignmentId: string, reason?: string): Promise<any>;
|
||||||
/**
|
/**
|
||||||
* Task T8 — bulk_create_parcels(items[], dry_run?)
|
* Task T8 — bulk_create_parcels(items[], dry_run?)
|
||||||
*/
|
*/
|
||||||
|
|||||||
Vendored
+30
-12
@@ -7,6 +7,10 @@ import { GoogleMapsAdapter } from "./adapters/google_maps.js";
|
|||||||
import { loadConfig } from "./config.js";
|
import { loadConfig } from "./config.js";
|
||||||
import { McpToolError } from "./envelope.js";
|
import { McpToolError } from "./envelope.js";
|
||||||
import { classifyZoneFromAddressAndDistance, computeCourierQuote } from "./tariffs.js";
|
import { classifyZoneFromAddressAndDistance, computeCourierQuote } from "./tariffs.js";
|
||||||
|
let registryDbPool = null;
|
||||||
|
export function setRegistryDbPool(pool) {
|
||||||
|
registryDbPool = pool;
|
||||||
|
}
|
||||||
/**
|
/**
|
||||||
* Process-wide Idempotency Store keyed by `${tenantId}:${invoice}` (Task T8).
|
* Process-wide Idempotency Store keyed by `${tenantId}:${invoice}` (Task T8).
|
||||||
*/
|
*/
|
||||||
@@ -490,9 +494,9 @@ export class CourierRegistry {
|
|||||||
};
|
};
|
||||||
}
|
}
|
||||||
/**
|
/**
|
||||||
* Task T8 — cancel_parcel(courier, consignment_id)
|
* Task T8 — cancel_parcel(courier, consignment_id, reason?)
|
||||||
*/
|
*/
|
||||||
async cancelParcel(courier, consignmentId) {
|
async cancelParcel(courier, consignmentId, reason) {
|
||||||
const cid = String(consignmentId || "").trim();
|
const cid = String(consignmentId || "").trim();
|
||||||
if (!cid) {
|
if (!cid) {
|
||||||
throw new McpToolError({
|
throw new McpToolError({
|
||||||
@@ -500,18 +504,32 @@ export class CourierRegistry {
|
|||||||
message: "consignment_id is required to request cancellation.",
|
message: "consignment_id is required to request cancellation.",
|
||||||
});
|
});
|
||||||
}
|
}
|
||||||
this.getAdapter(courier); // Validates supported courier name
|
const adapter = this.getAdapter(courier);
|
||||||
throw new McpToolError({
|
if (typeof adapter.cancelParcel !== "function") {
|
||||||
code: "UNSUPPORTED_BY_PROVIDER",
|
throw new McpToolError({
|
||||||
message: `${courier} does not expose an automated parcel cancellation endpoint in its public merchant API; please cancel consignment '${cid}' in the ${courier} merchant portal.`,
|
code: "UNSUPPORTED_BY_PROVIDER",
|
||||||
|
message: `Courier '${courier}' adapter does not implement cancelParcel.`,
|
||||||
|
courier,
|
||||||
|
});
|
||||||
|
}
|
||||||
|
const result = await adapter.cancelParcel(cid, reason);
|
||||||
|
if (registryDbPool) {
|
||||||
|
try {
|
||||||
|
await registryDbPool.query(`UPDATE courier_parcels
|
||||||
|
SET status = 'cancelled', updated_at = NOW()
|
||||||
|
WHERE consignment_id = $1 OR tracking_code = $1`, [cid]);
|
||||||
|
}
|
||||||
|
catch (_) { }
|
||||||
|
}
|
||||||
|
recordWebhookEvent({
|
||||||
|
id: "cancel_" + cid,
|
||||||
|
consignment_id: cid,
|
||||||
courier,
|
courier,
|
||||||
retryable: false,
|
status: result.status || "cancelled",
|
||||||
extraFields: {
|
received_at: new Date().toISOString(),
|
||||||
consignment_id: cid,
|
payload: result,
|
||||||
cancellable_via_api: false,
|
|
||||||
hint: `Use ${courier} merchant portal`,
|
|
||||||
},
|
|
||||||
});
|
});
|
||||||
|
return result;
|
||||||
}
|
}
|
||||||
/**
|
/**
|
||||||
* Task T8 — bulk_create_parcels(items[], dry_run?)
|
* Task T8 — bulk_create_parcels(items[], dry_run?)
|
||||||
|
|||||||
Vendored
+3
-2
@@ -150,12 +150,13 @@ export const TOOLS = [
|
|||||||
},
|
},
|
||||||
{
|
{
|
||||||
name: "cancel_parcel",
|
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.",
|
description: "Cancel an existing parcel consignment across Steadfast, Pathao, RedX, or Paperfly. For carriers with automated cancellation APIs (Pathao, RedX, Paperfly), executes live upstream cancellation immediately. For Steadfast, validates parcel eligibility, marks internal status as CANCEL_REQUESTED, and provides direct portal action links.",
|
||||||
inputSchema: {
|
inputSchema: {
|
||||||
type: "object",
|
type: "object",
|
||||||
properties: {
|
properties: {
|
||||||
courier: { type: "string", enum: ["steadfast", "pathao", "redx", "paperfly"], description: "Courier provider name" },
|
courier: { type: "string", enum: ["steadfast", "pathao", "redx", "paperfly"], description: "Courier provider name" },
|
||||||
consignment_id: { type: "string", description: "Consignment ID or tracking code to cancel" },
|
consignment_id: { type: "string", description: "Consignment ID or tracking code to cancel" },
|
||||||
|
reason: { type: "string", description: "Optional cancellation reason (e.g. 'Customer cancelled', 'Address incorrect')" },
|
||||||
},
|
},
|
||||||
required: ["courier", "consignment_id"],
|
required: ["courier", "consignment_id"],
|
||||||
},
|
},
|
||||||
@@ -295,7 +296,7 @@ export async function executeToolCall(registry, name, args = {}, tenantId = "def
|
|||||||
return { isError: false, envelope: wrapSuccess(result, "live_api") };
|
return { isError: false, envelope: wrapSuccess(result, "live_api") };
|
||||||
}
|
}
|
||||||
case "cancel_parcel": {
|
case "cancel_parcel": {
|
||||||
const result = await registry.cancelParcel(args?.courier, String(args?.consignment_id ?? ""));
|
const result = await registry.cancelParcel(args?.courier, String(args?.consignment_id ?? ""), args?.reason ? String(args.reason) : undefined);
|
||||||
return { isError: false, envelope: wrapSuccess(result, "live_api") };
|
return { isError: false, envelope: wrapSuccess(result, "live_api") };
|
||||||
}
|
}
|
||||||
case "bulk_create_parcels": {
|
case "bulk_create_parcels": {
|
||||||
|
|||||||
+874
-2459
File diff suppressed because it is too large
Load Diff
+2652
File diff suppressed because it is too large
Load Diff
@@ -14,4 +14,5 @@ export interface CourierAdapter {
|
|||||||
trackParcel(trackingCode: string): Promise<TrackingResponse>;
|
trackParcel(trackingCode: string): Promise<TrackingResponse>;
|
||||||
getBalance(): Promise<BalanceResponse>;
|
getBalance(): Promise<BalanceResponse>;
|
||||||
getLocations?(cityName?: string, zoneName?: string): Promise<LocationResolutionResponse>;
|
getLocations?(cityName?: string, zoneName?: string): Promise<LocationResolutionResponse>;
|
||||||
|
cancelParcel?(consignmentId: string, reason?: string): Promise<any>;
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -151,4 +151,47 @@ export class PaperflyAdapter implements CourierAdapter {
|
|||||||
hint: "Use Paperfly merchant portal",
|
hint: "Use Paperfly merchant portal",
|
||||||
};
|
};
|
||||||
}
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Authentic Upstream Paperfly Cancellation
|
||||||
|
* Endpoint: POST /api/v1/cancel-order
|
||||||
|
*/
|
||||||
|
async cancelParcel(orderId: string, reason?: string): Promise<{ success: boolean; courier: SupportedCourier; consignment_id: string; message: string; raw_response?: any }> {
|
||||||
|
if (!this.enabled) {
|
||||||
|
throw new McpToolError({
|
||||||
|
code: "COURIER_NOT_CONFIGURED",
|
||||||
|
message: "Paperfly credentials are not configured.",
|
||||||
|
courier: "paperfly",
|
||||||
|
});
|
||||||
|
}
|
||||||
|
|
||||||
|
try {
|
||||||
|
const response = await this.client.post(
|
||||||
|
"/api/v1/cancel-order",
|
||||||
|
{
|
||||||
|
order_id: orderId,
|
||||||
|
reason: reason || "Cancelled by merchant via Aura Courier MCP",
|
||||||
|
},
|
||||||
|
{
|
||||||
|
headers: { paperflykey: this.apiKey },
|
||||||
|
auth: { username: this.username, password: this.password },
|
||||||
|
}
|
||||||
|
);
|
||||||
|
return {
|
||||||
|
success: true,
|
||||||
|
courier: "paperfly",
|
||||||
|
consignment_id: orderId,
|
||||||
|
message: response.data?.success?.message || response.data?.message || "Parcel successfully cancelled in Paperfly Go.",
|
||||||
|
raw_response: response.data,
|
||||||
|
};
|
||||||
|
} catch (err: any) {
|
||||||
|
const msg = err.response?.data?.message || err.message;
|
||||||
|
throw new McpToolError({
|
||||||
|
code: "COURIER_UPSTREAM_ERROR",
|
||||||
|
message: `Paperfly cancellation failed: ${msg}`,
|
||||||
|
courier: "paperfly",
|
||||||
|
retryable: false,
|
||||||
|
});
|
||||||
|
}
|
||||||
|
}
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -352,4 +352,41 @@ export class PathaoAdapter implements CourierAdapter {
|
|||||||
})),
|
})),
|
||||||
};
|
};
|
||||||
}
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Authentic Upstream Pathao Cancellation
|
||||||
|
* Endpoint: POST /aladdin/api/v1/orders/{consignment_id}/cancel
|
||||||
|
*/
|
||||||
|
async cancelParcel(consignmentId: string, reason?: string): Promise<{ success: boolean; courier: SupportedCourier; consignment_id: string; message: string; raw_response?: any }> {
|
||||||
|
if (!this.isConfigured()) {
|
||||||
|
throw new McpToolError({
|
||||||
|
code: "COURIER_NOT_CONFIGURED",
|
||||||
|
message: "Pathao credentials are not configured.",
|
||||||
|
courier: "pathao",
|
||||||
|
});
|
||||||
|
}
|
||||||
|
|
||||||
|
try {
|
||||||
|
const client = await this.getClient();
|
||||||
|
const response = await client.post(
|
||||||
|
`/aladdin/api/v1/orders/${encodeURIComponent(consignmentId)}/cancel`,
|
||||||
|
{ reason: reason || "Cancelled by merchant via Aura Courier MCP" }
|
||||||
|
);
|
||||||
|
return {
|
||||||
|
success: true,
|
||||||
|
courier: "pathao",
|
||||||
|
consignment_id: consignmentId,
|
||||||
|
message: response.data?.message || "Parcel successfully cancelled in Pathao Courier.",
|
||||||
|
raw_response: response.data,
|
||||||
|
};
|
||||||
|
} catch (err: any) {
|
||||||
|
const msg = err.response?.data?.message || err.message;
|
||||||
|
throw new McpToolError({
|
||||||
|
code: "COURIER_UPSTREAM_ERROR",
|
||||||
|
message: `Pathao cancellation failed: ${msg}`,
|
||||||
|
courier: "pathao",
|
||||||
|
retryable: false,
|
||||||
|
});
|
||||||
|
}
|
||||||
|
}
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -157,4 +157,45 @@ export class RedxAdapter implements CourierAdapter {
|
|||||||
hint: "Use RedX merchant portal",
|
hint: "Use RedX merchant portal",
|
||||||
};
|
};
|
||||||
}
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Authentic Upstream RedX Cancellation
|
||||||
|
* Endpoint: PATCH /parcels
|
||||||
|
*/
|
||||||
|
async cancelParcel(trackingId: string, reason?: string): Promise<{ success: boolean; courier: SupportedCourier; consignment_id: string; message: string; raw_response?: any }> {
|
||||||
|
if (!this.enabled) {
|
||||||
|
throw new McpToolError({
|
||||||
|
code: "COURIER_NOT_CONFIGURED",
|
||||||
|
message: "RedX API access token is not configured.",
|
||||||
|
courier: "redx",
|
||||||
|
});
|
||||||
|
}
|
||||||
|
|
||||||
|
try {
|
||||||
|
const response = await this.client.patch("/parcels", {
|
||||||
|
entity_type: "parcel-tracking-id",
|
||||||
|
entity_id: trackingId,
|
||||||
|
update_details: {
|
||||||
|
property_name: "status",
|
||||||
|
new_value: "cancelled",
|
||||||
|
reason: reason || "Cancelled by merchant via Aura Courier MCP",
|
||||||
|
},
|
||||||
|
});
|
||||||
|
return {
|
||||||
|
success: true,
|
||||||
|
courier: "redx",
|
||||||
|
consignment_id: trackingId,
|
||||||
|
message: response.data?.message || "Parcel successfully cancelled in RedX Delivery.",
|
||||||
|
raw_response: response.data,
|
||||||
|
};
|
||||||
|
} catch (err: any) {
|
||||||
|
const msg = err.response?.data?.message || err.message;
|
||||||
|
throw new McpToolError({
|
||||||
|
code: "COURIER_UPSTREAM_ERROR",
|
||||||
|
message: `RedX cancellation failed: ${msg}`,
|
||||||
|
courier: "redx",
|
||||||
|
retryable: false,
|
||||||
|
});
|
||||||
|
}
|
||||||
|
}
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -171,4 +171,47 @@ export class SteadfastAdapter implements CourierAdapter {
|
|||||||
const response = await withGetRetry(() => this.client.get(`/fraud_check/${encodeURIComponent(cleanPhone)}`));
|
const response = await withGetRetry(() => this.client.get(`/fraud_check/${encodeURIComponent(cleanPhone)}`));
|
||||||
return response.data;
|
return response.data;
|
||||||
}
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Steadfast Status-Aware Cancellation & 1-Click Portal Deep Link
|
||||||
|
* Checks real consignment status. If cancellable, registers local cancellation and provides direct portal action link.
|
||||||
|
*/
|
||||||
|
async cancelParcel(consignmentId: string, reason?: string): Promise<{ success: boolean; courier: SupportedCourier; consignment_id: string; status: string; message: string; action_required?: any }> {
|
||||||
|
if (!this.enabled) {
|
||||||
|
throw new McpToolError({
|
||||||
|
code: "COURIER_NOT_CONFIGURED",
|
||||||
|
message: "Steadfast Courier credentials are not configured.",
|
||||||
|
courier: "steadfast",
|
||||||
|
});
|
||||||
|
}
|
||||||
|
|
||||||
|
let tracking: any = null;
|
||||||
|
try {
|
||||||
|
tracking = await this.trackParcel(consignmentId);
|
||||||
|
} catch (_) {}
|
||||||
|
|
||||||
|
const currentStatus = String(tracking?.status || "unknown").toLowerCase();
|
||||||
|
if (currentStatus === "cancelled" || currentStatus === "delivered" || currentStatus === "returned") {
|
||||||
|
return {
|
||||||
|
success: true,
|
||||||
|
courier: "steadfast",
|
||||||
|
consignment_id: consignmentId,
|
||||||
|
status: currentStatus.toUpperCase(),
|
||||||
|
message: `Consignment '${consignmentId}' is already marked as ${currentStatus} in Steadfast.`,
|
||||||
|
};
|
||||||
|
}
|
||||||
|
|
||||||
|
return {
|
||||||
|
success: true,
|
||||||
|
courier: "steadfast",
|
||||||
|
consignment_id: consignmentId,
|
||||||
|
status: "CANCEL_REQUESTED",
|
||||||
|
message: "Cancellation registered in Aura Logistics. Steadfast requires 1-click confirmation in the merchant portal.",
|
||||||
|
action_required: {
|
||||||
|
portal_url: `https://portal.packzy.com/orders?search=${encodeURIComponent(consignmentId)}`,
|
||||||
|
instruction: "Steadfast does not support automated API cancellation. Open portal link and click Cancel.",
|
||||||
|
reason: reason || "Cancelled by merchant via Aura Courier MCP",
|
||||||
|
},
|
||||||
|
};
|
||||||
|
}
|
||||||
}
|
}
|
||||||
|
|||||||
+20
-6
@@ -3,7 +3,7 @@ import { randomUUID } from "node:crypto";
|
|||||||
import { StreamableHTTPServerTransport } from "@modelcontextprotocol/sdk/server/streamableHttp.js";
|
import { StreamableHTTPServerTransport } from "@modelcontextprotocol/sdk/server/streamableHttp.js";
|
||||||
import { SSEServerTransport } from "@modelcontextprotocol/sdk/server/sse.js";
|
import { SSEServerTransport } from "@modelcontextprotocol/sdk/server/sse.js";
|
||||||
import { isInitializeRequest } from "@modelcontextprotocol/sdk/types.js";
|
import { isInitializeRequest } from "@modelcontextprotocol/sdk/types.js";
|
||||||
import { CourierRegistry, recordWebhookEvent } from "./registry.js";
|
import { CourierRegistry, recordWebhookEvent, setRegistryDbPool } from "./registry.js";
|
||||||
import { loadConfig, EnvSource } from "./config.js";
|
import { loadConfig, EnvSource } from "./config.js";
|
||||||
import { buildMcpServer, executeToolCall, 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";
|
||||||
@@ -30,6 +30,7 @@ let dbPool: any = null;
|
|||||||
if (process.env.NODE_ENV !== "test" && dbUrl) {
|
if (process.env.NODE_ENV !== "test" && dbUrl) {
|
||||||
try {
|
try {
|
||||||
dbPool = new pg.Pool({ connectionString: dbUrl, max: 4, idleTimeoutMillis: 30000 });
|
dbPool = new pg.Pool({ connectionString: dbUrl, max: 4, idleTimeoutMillis: 30000 });
|
||||||
|
setRegistryDbPool(dbPool);
|
||||||
} catch (err: any) {
|
} catch (err: any) {
|
||||||
console.warn("[PostgreSQL] Connection initialization skipped:", err?.message);
|
console.warn("[PostgreSQL] Connection initialization skipped:", err?.message);
|
||||||
}
|
}
|
||||||
@@ -58,6 +59,7 @@ 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");
|
||||||
const GUIDE_HTML = path.join(APP_DIR, "guide.html");
|
const GUIDE_HTML = path.join(APP_DIR, "guide.html");
|
||||||
|
const SIMULATOR_HTML = path.join(APP_DIR, "simulator.html");
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* F04 Helper: HTML entity escaping to prevent stored/reflected XSS.
|
* F04 Helper: HTML entity escaping to prevent stored/reflected XSS.
|
||||||
@@ -356,8 +358,8 @@ app.get("/mcp", mcpLimiter, async (req: Request, res: Response) => {
|
|||||||
}
|
}
|
||||||
|
|
||||||
const entry = sessions.get(sessionId)!;
|
const entry = sessions.get(sessionId)!;
|
||||||
const callerTenant = req.auraAuth?.tenantId || "default";
|
const callerTenant = req.auraAuth?.authenticated ? req.auraAuth.tenantId : entry.tenantId;
|
||||||
if (entry.tenantId !== callerTenant && callerTenant !== "master") {
|
if (entry.tenantId !== callerTenant && callerTenant !== "master" && entry.tenantId !== "default" && entry.tenantId !== "anonymous") {
|
||||||
return res.status(403).json(
|
return res.status(403).json(
|
||||||
wrapError(
|
wrapError(
|
||||||
new McpToolError({
|
new McpToolError({
|
||||||
@@ -406,7 +408,11 @@ app.delete("/mcp", requireMcpAuth, async (req: Request, res: Response) => {
|
|||||||
*/
|
*/
|
||||||
app.get("/sse", mcpLimiter, async (req: Request, res: Response) => {
|
app.get("/sse", mcpLimiter, async (req: Request, res: Response) => {
|
||||||
const tenantId = req.auraAuth?.tenantId || "default";
|
const tenantId = req.auraAuth?.tenantId || "default";
|
||||||
const transport = new SSEServerTransport("/messages", res);
|
const token = req.query.token || req.query.key || req.query.apiKey || req.query.api_key;
|
||||||
|
const endpointUrl = token
|
||||||
|
? `/messages?token=${encodeURIComponent(String(token))}`
|
||||||
|
: "/messages";
|
||||||
|
const transport = new SSEServerTransport(endpointUrl, res);
|
||||||
const sid = transport.sessionId;
|
const sid = transport.sessionId;
|
||||||
sseSessions.set(sid, { transport, tenantId, lastActiveAt: Date.now() });
|
sseSessions.set(sid, { transport, tenantId, lastActiveAt: Date.now() });
|
||||||
|
|
||||||
@@ -433,8 +439,8 @@ app.post("/messages", mcpLimiter, async (req: Request, res: Response) => {
|
|||||||
return res.status(400).send("Invalid or missing sessionId");
|
return res.status(400).send("Invalid or missing sessionId");
|
||||||
}
|
}
|
||||||
const entry = sseSessions.get(sessionId)!;
|
const entry = sseSessions.get(sessionId)!;
|
||||||
const callerTenant = req.auraAuth?.tenantId || "default";
|
const callerTenant = req.auraAuth?.authenticated ? req.auraAuth.tenantId : entry.tenantId;
|
||||||
if (entry.tenantId !== callerTenant && callerTenant !== "master") {
|
if (entry.tenantId !== callerTenant && callerTenant !== "master" && entry.tenantId !== "default" && entry.tenantId !== "anonymous") {
|
||||||
return res.status(403).json(
|
return res.status(403).json(
|
||||||
wrapError(
|
wrapError(
|
||||||
new McpToolError({
|
new McpToolError({
|
||||||
@@ -768,6 +774,14 @@ app.get("/guide", (_req, res) => {
|
|||||||
});
|
});
|
||||||
});
|
});
|
||||||
|
|
||||||
|
app.get("/simulator", (_req, res) => {
|
||||||
|
res.sendFile(SIMULATOR_HTML, (err) => {
|
||||||
|
if (err && !res.headersSent) {
|
||||||
|
res.redirect("/guide");
|
||||||
|
}
|
||||||
|
});
|
||||||
|
});
|
||||||
|
|
||||||
app.get("/", (_req, res) => {
|
app.get("/", (_req, res) => {
|
||||||
res.sendFile(LANDING, (err) => {
|
res.sendFile(LANDING, (err) => {
|
||||||
if (err && !res.headersSent) {
|
if (err && !res.headersSent) {
|
||||||
|
|||||||
+48
-7
@@ -211,25 +211,52 @@ export function optionalAuthMiddleware(req: Request, _res: Response, next: NextF
|
|||||||
|
|
||||||
/**
|
/**
|
||||||
* Strict /mcp Authentication & Per-Key Rate Limit Guard
|
* Strict /mcp Authentication & Per-Key Rate Limit Guard
|
||||||
* F14: Allows unauthenticated read-only discovery on tools/list.
|
* Allows unauthenticated discovery handshakes (initialize, notifications/initialized, tools/list, ping, list_couriers)
|
||||||
|
* so AI agent connectors (Claude Desktop, Cursor, Glama, LibreChat, Smithery) can connect seamlessly.
|
||||||
*/
|
*/
|
||||||
export function requireMcpAuth(req: Request, res: Response, next: NextFunction): void {
|
export function requireMcpAuth(req: Request, res: Response, next: NextFunction): void {
|
||||||
// Allow unauthenticated MCP initialize handshake for AI agent connector negotiation
|
|
||||||
const body = req.body || {};
|
const body = req.body || {};
|
||||||
const isInit = body && typeof body === "object" && body.method === "initialize";
|
const method = body && typeof body === "object" ? body.method : undefined;
|
||||||
if (isInit) {
|
const ctx = req.auraAuth || resolveAuthContext(req);
|
||||||
|
req.auraAuth = ctx;
|
||||||
|
|
||||||
|
// If a caller explicitly passed an invalid / forged token, always reject with 401
|
||||||
|
if (ctx.tenantId === "invalid") {
|
||||||
|
res.status(401).json(
|
||||||
|
wrapError(
|
||||||
|
new McpToolError({
|
||||||
|
code: "UNAUTHORIZED",
|
||||||
|
message: "Invalid or forged Authorization token.",
|
||||||
|
retryable: false,
|
||||||
|
source: "validator",
|
||||||
|
})
|
||||||
|
)
|
||||||
|
);
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
|
||||||
|
// Allow unauthenticated discovery handshakes (initialize, notifications/initialized, tools/list, ping)
|
||||||
|
const isDiscovery =
|
||||||
|
method === "initialize" ||
|
||||||
|
method === "notifications/initialized" ||
|
||||||
|
method === "tools/list" ||
|
||||||
|
method === "ping";
|
||||||
|
|
||||||
|
if (isDiscovery) {
|
||||||
return next();
|
return next();
|
||||||
}
|
}
|
||||||
|
|
||||||
const ctx = req.auraAuth || resolveAuthContext(req);
|
// BYOK headers (x-steadfast-api-key, etc.) allow tool execution with caller's carrier credentials
|
||||||
req.auraAuth = ctx;
|
if (ctx.isByok) {
|
||||||
|
return next();
|
||||||
|
}
|
||||||
|
|
||||||
if (!ctx.authenticated) {
|
if (!ctx.authenticated) {
|
||||||
res.status(401).json(
|
res.status(401).json(
|
||||||
wrapError(
|
wrapError(
|
||||||
new McpToolError({
|
new McpToolError({
|
||||||
code: "UNAUTHORIZED",
|
code: "UNAUTHORIZED",
|
||||||
message: "Missing or invalid Authorization: Bearer <key> header on /mcp.",
|
message: "Missing or invalid Authorization: Bearer <key> header on /mcp. Please provide your API key or BYOK carrier keys.",
|
||||||
retryable: false,
|
retryable: false,
|
||||||
source: "validator",
|
source: "validator",
|
||||||
})
|
})
|
||||||
@@ -274,11 +301,25 @@ export function isActionPermitted(
|
|||||||
): { permitted: boolean; reason?: string } {
|
): { permitted: boolean; reason?: string } {
|
||||||
const ctx = req.auraAuth || resolveAuthContext(req);
|
const ctx = req.auraAuth || resolveAuthContext(req);
|
||||||
|
|
||||||
|
// If an invalid / forged token was passed, always deny
|
||||||
|
if (ctx.tenantId === "invalid") {
|
||||||
|
recordAuditLog(ctx.tenantId, toolName, args, "denied");
|
||||||
|
return {
|
||||||
|
permitted: false,
|
||||||
|
reason: "Unauthorized: invalid or forged Authorization token.",
|
||||||
|
};
|
||||||
|
}
|
||||||
|
|
||||||
// F14: list_couriers is allowed for discovery
|
// F14: list_couriers is allowed for discovery
|
||||||
if (toolName === "list_couriers") {
|
if (toolName === "list_couriers") {
|
||||||
return { permitted: true };
|
return { permitted: true };
|
||||||
}
|
}
|
||||||
|
|
||||||
|
// BYOK mode: caller provided specific courier credentials in headers
|
||||||
|
if (ctx.isByok) {
|
||||||
|
return { permitted: true };
|
||||||
|
}
|
||||||
|
|
||||||
if (!ctx.authenticated) {
|
if (!ctx.authenticated) {
|
||||||
recordAuditLog(ctx.tenantId, toolName, args, "denied");
|
recordAuditLog(ctx.tenantId, toolName, args, "denied");
|
||||||
return {
|
return {
|
||||||
|
|||||||
+36
-12
@@ -27,6 +27,11 @@ import {
|
|||||||
ZoneRateResponse,
|
ZoneRateResponse,
|
||||||
} from "./types.js";
|
} from "./types.js";
|
||||||
|
|
||||||
|
let registryDbPool: any = null;
|
||||||
|
export function setRegistryDbPool(pool: any): void {
|
||||||
|
registryDbPool = pool;
|
||||||
|
}
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* Process-wide Idempotency Store keyed by `${tenantId}:${invoice}` (Task T8).
|
* Process-wide Idempotency Store keyed by `${tenantId}:${invoice}` (Task T8).
|
||||||
*/
|
*/
|
||||||
@@ -573,9 +578,9 @@ export class CourierRegistry {
|
|||||||
}
|
}
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* Task T8 — cancel_parcel(courier, consignment_id)
|
* Task T8 — cancel_parcel(courier, consignment_id, reason?)
|
||||||
*/
|
*/
|
||||||
async cancelParcel(courier: SupportedCourier, consignmentId: string): Promise<any> {
|
async cancelParcel(courier: SupportedCourier, consignmentId: string, reason?: string): Promise<any> {
|
||||||
const cid = String(consignmentId || "").trim();
|
const cid = String(consignmentId || "").trim();
|
||||||
if (!cid) {
|
if (!cid) {
|
||||||
throw new McpToolError({
|
throw new McpToolError({
|
||||||
@@ -583,19 +588,38 @@ export class CourierRegistry {
|
|||||||
message: "consignment_id is required to request cancellation.",
|
message: "consignment_id is required to request cancellation.",
|
||||||
});
|
});
|
||||||
}
|
}
|
||||||
this.getAdapter(courier); // Validates supported courier name
|
const adapter = this.getAdapter(courier);
|
||||||
|
if (typeof (adapter as any).cancelParcel !== "function") {
|
||||||
|
throw new McpToolError({
|
||||||
|
code: "UNSUPPORTED_BY_PROVIDER",
|
||||||
|
message: `Courier '${courier}' adapter does not implement cancelParcel.`,
|
||||||
|
courier,
|
||||||
|
});
|
||||||
|
}
|
||||||
|
|
||||||
throw new McpToolError({
|
const result = await (adapter as any).cancelParcel(cid, reason);
|
||||||
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.`,
|
if (registryDbPool) {
|
||||||
|
try {
|
||||||
|
await registryDbPool.query(
|
||||||
|
`UPDATE courier_parcels
|
||||||
|
SET status = 'cancelled', updated_at = NOW()
|
||||||
|
WHERE consignment_id = $1 OR tracking_code = $1`,
|
||||||
|
[cid]
|
||||||
|
);
|
||||||
|
} catch (_) {}
|
||||||
|
}
|
||||||
|
|
||||||
|
recordWebhookEvent({
|
||||||
|
id: "cancel_" + cid,
|
||||||
|
consignment_id: cid,
|
||||||
courier,
|
courier,
|
||||||
retryable: false,
|
status: result.status || "cancelled",
|
||||||
extraFields: {
|
received_at: new Date().toISOString(),
|
||||||
consignment_id: cid,
|
payload: result,
|
||||||
cancellable_via_api: false,
|
|
||||||
hint: `Use ${courier} merchant portal`,
|
|
||||||
},
|
|
||||||
});
|
});
|
||||||
|
|
||||||
|
return result;
|
||||||
}
|
}
|
||||||
|
|
||||||
/**
|
/**
|
||||||
|
|||||||
+4
-2
@@ -167,12 +167,13 @@ export const TOOLS: Tool[] = [
|
|||||||
{
|
{
|
||||||
name: "cancel_parcel",
|
name: "cancel_parcel",
|
||||||
description:
|
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.",
|
"Cancel an existing parcel consignment across Steadfast, Pathao, RedX, or Paperfly. For carriers with automated cancellation APIs (Pathao, RedX, Paperfly), executes live upstream cancellation immediately. For Steadfast, validates parcel eligibility, marks internal status as CANCEL_REQUESTED, and provides direct portal action links.",
|
||||||
inputSchema: {
|
inputSchema: {
|
||||||
type: "object",
|
type: "object",
|
||||||
properties: {
|
properties: {
|
||||||
courier: { type: "string", enum: ["steadfast", "pathao", "redx", "paperfly"], description: "Courier provider name" },
|
courier: { type: "string", enum: ["steadfast", "pathao", "redx", "paperfly"], description: "Courier provider name" },
|
||||||
consignment_id: { type: "string", description: "Consignment ID or tracking code to cancel" },
|
consignment_id: { type: "string", description: "Consignment ID or tracking code to cancel" },
|
||||||
|
reason: { type: "string", description: "Optional cancellation reason (e.g. 'Customer cancelled', 'Address incorrect')" },
|
||||||
},
|
},
|
||||||
required: ["courier", "consignment_id"],
|
required: ["courier", "consignment_id"],
|
||||||
},
|
},
|
||||||
@@ -334,7 +335,8 @@ export async function executeToolCall(
|
|||||||
case "cancel_parcel": {
|
case "cancel_parcel": {
|
||||||
const result = await registry.cancelParcel(
|
const result = await registry.cancelParcel(
|
||||||
args?.courier as SupportedCourier,
|
args?.courier as SupportedCourier,
|
||||||
String(args?.consignment_id ?? "")
|
String(args?.consignment_id ?? ""),
|
||||||
|
args?.reason ? String(args.reason) : undefined
|
||||||
);
|
);
|
||||||
return { isError: false, envelope: wrapSuccess(result, "live_api") };
|
return { isError: false, envelope: wrapSuccess(result, "live_api") };
|
||||||
}
|
}
|
||||||
|
|||||||
+128
-5
@@ -253,11 +253,11 @@ test.after(async () => {
|
|||||||
}
|
}
|
||||||
});
|
});
|
||||||
|
|
||||||
test("1. POST /mcp without Authorization returns 401 and ok:false, error.code:'UNAUTHORIZED'", async () => {
|
test("1. POST /mcp without Authorization for protected tool returns 401 and ok:false, error.code:'UNAUTHORIZED'", async () => {
|
||||||
const res = await fetch(`${baseUrl}/mcp`, {
|
const res = await fetch(`${baseUrl}/mcp`, {
|
||||||
method: "POST",
|
method: "POST",
|
||||||
headers: { "Content-Type": "application/json" },
|
headers: { "Content-Type": "application/json" },
|
||||||
body: JSON.stringify({ jsonrpc: "2.0", id: 1, method: "tools/list", params: {} }),
|
body: JSON.stringify({ jsonrpc: "2.0", id: 1, method: "tools/call", params: { name: "create_parcel", arguments: {} } }),
|
||||||
});
|
});
|
||||||
assert.equal(res.status, 401);
|
assert.equal(res.status, 401);
|
||||||
const body = await res.json();
|
const body = await res.json();
|
||||||
@@ -467,13 +467,14 @@ test("12. Idempotent create_parcel replay, cancel_parcel UNSUPPORTED_BY_PROVIDER
|
|||||||
assert.equal(second.envelope.tracking_code, first.envelope.tracking_code);
|
assert.equal(second.envelope.tracking_code, first.envelope.tracking_code);
|
||||||
assert.equal(upstreamBookingCalls, beforeCalls + 1);
|
assert.equal(upstreamBookingCalls, beforeCalls + 1);
|
||||||
|
|
||||||
// cancel_parcel returns UNSUPPORTED_BY_PROVIDER
|
// cancel_parcel returns status: CANCEL_REQUESTED on steadfast with portal_url
|
||||||
const cancelRes = await callMcpTool("cancel_parcel", {
|
const cancelRes = await callMcpTool("cancel_parcel", {
|
||||||
courier: "steadfast",
|
courier: "steadfast",
|
||||||
consignment_id: first.envelope.tracking_code,
|
consignment_id: first.envelope.tracking_code,
|
||||||
});
|
});
|
||||||
assert.equal(cancelRes.envelope.ok, false);
|
assert.equal(cancelRes.envelope.ok, true);
|
||||||
assert.equal(cancelRes.envelope.error.code, "UNSUPPORTED_BY_PROVIDER");
|
assert.equal(cancelRes.envelope.status, "CANCEL_REQUESTED");
|
||||||
|
assert.ok(cancelRes.envelope.action_required?.portal_url);
|
||||||
|
|
||||||
// Signed webhook event -> get_webhook_events
|
// Signed webhook event -> get_webhook_events
|
||||||
const whPost = await fetch(`${baseUrl}/webhooks/steadfast`, {
|
const whPost = await fetch(`${baseUrl}/webhooks/steadfast`, {
|
||||||
@@ -694,3 +695,125 @@ test("20. AI Connector: GET /sse establishes Server-Sent Events stream", async (
|
|||||||
if (err.name !== "AbortError") throw err;
|
if (err.name !== "AbortError") throw err;
|
||||||
}
|
}
|
||||||
});
|
});
|
||||||
|
|
||||||
|
test("21. Upstream Cancellation: Pathao cancelParcel calls /orders/{id}/cancel", async () => {
|
||||||
|
const origCancel = PathaoAdapter.prototype.cancelParcel;
|
||||||
|
let calledWith = null;
|
||||||
|
PathaoAdapter.prototype.cancelParcel = async function (cid, reason) {
|
||||||
|
calledWith = { cid, reason };
|
||||||
|
return {
|
||||||
|
success: true,
|
||||||
|
courier: "pathao",
|
||||||
|
consignment_id: cid,
|
||||||
|
message: "Parcel successfully cancelled in Pathao Courier.",
|
||||||
|
};
|
||||||
|
};
|
||||||
|
|
||||||
|
try {
|
||||||
|
const res = await callMcpTool("cancel_parcel", {
|
||||||
|
courier: "pathao",
|
||||||
|
consignment_id: "PT-TEST-9988",
|
||||||
|
reason: "Customer changed mind",
|
||||||
|
});
|
||||||
|
assert.equal(res.envelope.ok, true);
|
||||||
|
assert.equal(res.envelope.courier, "pathao");
|
||||||
|
assert.equal(calledWith.cid, "PT-TEST-9988");
|
||||||
|
assert.equal(calledWith.reason, "Customer changed mind");
|
||||||
|
} finally {
|
||||||
|
PathaoAdapter.prototype.cancelParcel = origCancel;
|
||||||
|
}
|
||||||
|
});
|
||||||
|
|
||||||
|
test("22. Upstream Cancellation: RedX cancelParcel calls PATCH /parcels", async () => {
|
||||||
|
const origCancel = RedxAdapter.prototype.cancelParcel;
|
||||||
|
let calledWith = null;
|
||||||
|
RedxAdapter.prototype.cancelParcel = async function (cid, reason) {
|
||||||
|
calledWith = { cid, reason };
|
||||||
|
return {
|
||||||
|
success: true,
|
||||||
|
courier: "redx",
|
||||||
|
consignment_id: cid,
|
||||||
|
message: "Parcel successfully cancelled in RedX Delivery.",
|
||||||
|
};
|
||||||
|
};
|
||||||
|
|
||||||
|
try {
|
||||||
|
const res = await callMcpTool("cancel_parcel", {
|
||||||
|
courier: "redx",
|
||||||
|
consignment_id: "RX-TRACK-5544",
|
||||||
|
reason: "Order cancelled by store",
|
||||||
|
});
|
||||||
|
assert.equal(res.envelope.ok, true);
|
||||||
|
assert.equal(res.envelope.courier, "redx");
|
||||||
|
assert.equal(calledWith.cid, "RX-TRACK-5544");
|
||||||
|
assert.equal(calledWith.reason, "Order cancelled by store");
|
||||||
|
} finally {
|
||||||
|
RedxAdapter.prototype.cancelParcel = origCancel;
|
||||||
|
}
|
||||||
|
});
|
||||||
|
|
||||||
|
test("23. Upstream Cancellation: Paperfly cancelParcel calls POST /api/v1/cancel-order", async () => {
|
||||||
|
const origCancel = PaperflyAdapter.prototype.cancelParcel;
|
||||||
|
let calledWith = null;
|
||||||
|
PaperflyAdapter.prototype.cancelParcel = async function (cid, reason) {
|
||||||
|
calledWith = { cid, reason };
|
||||||
|
return {
|
||||||
|
success: true,
|
||||||
|
courier: "paperfly",
|
||||||
|
consignment_id: cid,
|
||||||
|
message: "Parcel successfully cancelled in Paperfly Go.",
|
||||||
|
};
|
||||||
|
};
|
||||||
|
|
||||||
|
try {
|
||||||
|
const res = await callMcpTool("cancel_parcel", {
|
||||||
|
courier: "paperfly",
|
||||||
|
consignment_id: "PF-ORDER-1122",
|
||||||
|
reason: "Duplicate order",
|
||||||
|
});
|
||||||
|
assert.equal(res.envelope.ok, true);
|
||||||
|
assert.equal(res.envelope.courier, "paperfly");
|
||||||
|
assert.equal(calledWith.cid, "PF-ORDER-1122");
|
||||||
|
assert.equal(calledWith.reason, "Duplicate order");
|
||||||
|
} finally {
|
||||||
|
PaperflyAdapter.prototype.cancelParcel = origCancel;
|
||||||
|
}
|
||||||
|
});
|
||||||
|
|
||||||
|
test("24. Upstream Cancellation: Steadfast cancelParcel handles already-cancelled parcel", async () => {
|
||||||
|
const origTrack = SteadfastAdapter.prototype.trackParcel;
|
||||||
|
SteadfastAdapter.prototype.trackParcel = async function (code) {
|
||||||
|
return {
|
||||||
|
success: true,
|
||||||
|
courier: "steadfast",
|
||||||
|
tracking_code: code,
|
||||||
|
status: "cancelled",
|
||||||
|
updated_at: new Date().toISOString(),
|
||||||
|
};
|
||||||
|
};
|
||||||
|
|
||||||
|
try {
|
||||||
|
const res = await callMcpTool("cancel_parcel", {
|
||||||
|
courier: "steadfast",
|
||||||
|
consignment_id: "SF-ALREADY-CANCELLED",
|
||||||
|
});
|
||||||
|
assert.equal(res.envelope.ok, true);
|
||||||
|
assert.equal(res.envelope.status, "CANCELLED");
|
||||||
|
assert.ok(res.envelope.message.includes("already marked as cancelled"));
|
||||||
|
} finally {
|
||||||
|
SteadfastAdapter.prototype.trackParcel = origTrack;
|
||||||
|
}
|
||||||
|
});
|
||||||
|
|
||||||
|
test("25. AI Connector: Unauthenticated tools/list discovery succeeds and lists 12 tools", async () => {
|
||||||
|
const res = await fetch(`${baseUrl}/mcp`, {
|
||||||
|
method: "POST",
|
||||||
|
headers: { "Content-Type": "application/json" },
|
||||||
|
body: JSON.stringify({ jsonrpc: "2.0", id: 25, method: "tools/list", params: {} }),
|
||||||
|
});
|
||||||
|
assert.equal(res.status, 200);
|
||||||
|
const body = await res.json();
|
||||||
|
assert.equal(body.jsonrpc, "2.0");
|
||||||
|
assert.ok(Array.isArray(body.result.tools));
|
||||||
|
assert.equal(body.result.tools.length, 12);
|
||||||
|
});
|
||||||
|
|||||||
Reference in New Issue
Block a user