import { Tool } from '@modelcontextprotocol/sdk/types.js';
import { SFExpressClient } from '../sf-express-client.js';
import {
TrackShipmentRequestSchema,
TrackShipmentRequest,
SFExpressError
} from '../types.js';
export const trackShipmentTool: Tool = {
name: 'sf_express_track_shipment',
description: 'Track the status and route information of SF Express shipments using waybill numbers or order IDs.',
inputSchema: {
type: 'object',
properties: {
trackingType: {
type: 'string',
enum: ['1', '2'],
description: 'Tracking type: 1-Track by waybill number, 2-Track by order ID'
},
trackingNumber: {
type: 'array',
description: 'List of tracking numbers (waybill numbers or order IDs)',
items: {
type: 'string',
description: 'Waybill number or order ID'
},
minItems: 1,
maxItems: 100
},
methodType: {
type: 'string',
enum: ['1', '2'],
description: 'Query method: 1-Standard query, 2-Detailed query (optional)'
}
},
required: ['trackingType', 'trackingNumber']
}
};
export async function handleTrackShipment(
args: any,
client: SFExpressClient
): Promise<any> {
try {
// Validate input using Zod schema
const validatedRequest = TrackShipmentRequestSchema.parse(args);
// Call SF Express API
const results = await client.trackShipment(validatedRequest);
// Format the response
const formattedResults = results.map(result => ({
waybillNo: result.waybillNo,
orderId: result.orderId,
trackingHistory: result.routes.map(route => ({
timestamp: route.acceptTime,
location: route.acceptAddress,
status: route.opCode,
description: route.remark || 'Package processed',
statusCode: route.opCode
})).sort((a, b) => new Date(b.timestamp).getTime() - new Date(a.timestamp).getTime())
}));
return {
success: true,
data: {
trackingType: validatedRequest.trackingType === '1' ? 'waybill' : 'orderId',
totalResults: formattedResults.length,
shipments: formattedResults,
message: `Successfully tracked ${formattedResults.length} shipment(s)`
}
};
} catch (error) {
if (error instanceof SFExpressError) {
return {
success: false,
error: {
code: error.errorCode || 'TRACK_SHIPMENT_ERROR',
message: error.message,
details: error.details
}
};
}
// Handle Zod validation errors
if (error.name === 'ZodError') {
return {
success: false,
error: {
code: 'VALIDATION_ERROR',
message: 'Invalid input parameters',
details: error.errors
}
};
}
return {
success: false,
error: {
code: 'UNKNOWN_ERROR',
message: 'An unexpected error occurred while tracking the shipment',
details: error instanceof Error ? error.message : 'Unknown error'
}
};
}
}