import { Tool } from '@modelcontextprotocol/sdk/types.js';
import { SFExpressClient } from '../sf-express-client.js';
import {
QueryRoutesRequestSchema,
QueryRoutesRequest,
SFExpressError
} from '../types.js';
export const queryRoutesTool: Tool = {
name: 'sf_express_query_routes',
description: 'Query available shipping routes, services, and pricing between origin and destination locations.',
inputSchema: {
type: 'object',
properties: {
originCode: {
type: 'string',
description: 'Origin area code (e.g., "010" for Beijing, "021" for Shanghai)'
},
destCode: {
type: 'string',
description: 'Destination area code (e.g., "010" for Beijing, "021" for Shanghai)'
},
cargoWeight: {
type: 'number',
description: 'Total cargo weight in kg (optional, used for pricing calculation)',
minimum: 0
}
},
required: ['originCode', 'destCode']
}
};
export async function handleQueryRoutes(
args: any,
client: SFExpressClient
): Promise<any> {
try {
// Validate input using Zod schema
const validatedRequest = QueryRoutesRequestSchema.parse(args);
// Call SF Express API
const result = await client.queryRoutes(validatedRequest);
// Format the response with enhanced information
const formattedServices = result.availableServices.map(service => ({
serviceCode: service.expressType,
serviceName: service.serviceName,
pricing: {
standardCost: service.standardCost,
additionalCostPerKg: service.additionalCost,
currency: service.currency,
weightLimit: service.limitedWeight
},
estimatedCost: validatedRequest.cargoWeight && service.standardCost
? calculateEstimatedCost(
validatedRequest.cargoWeight,
service.standardCost,
service.additionalCost || 0,
service.limitedWeight || 1
)
: null
}));
return {
success: true,
data: {
route: {
from: result.originCode,
to: result.destCode,
cargoWeight: validatedRequest.cargoWeight
},
availableServices: formattedServices,
totalServices: formattedServices.length,
message: `Found ${formattedServices.length} available service(s) for this route`
}
};
} catch (error) {
if (error instanceof SFExpressError) {
return {
success: false,
error: {
code: error.errorCode || 'QUERY_ROUTES_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 querying routes',
details: error instanceof Error ? error.message : 'Unknown error'
}
};
}
}
/**
* Calculate estimated shipping cost based on weight and pricing structure
*/
function calculateEstimatedCost(
weight: number,
baseCost: number,
additionalCostPerKg: number,
weightLimit: number
): number {
if (weight <= weightLimit) {
return baseCost;
} else {
const additionalWeight = weight - weightLimit;
return baseCost + (additionalWeight * additionalCostPerKg);
}
}