amazon-seller-mcp
Version:
Model Context Protocol (MCP) client for Amazon Selling Partner API
177 lines • 6.16 kB
JavaScript
/**
* Listings API client for Amazon Selling Partner API
*/
// Third-party dependencies
import { z } from 'zod';
// Internal imports
import { BaseApiClient } from './base-client.js';
/**
* Listings API client for Amazon Selling Partner API
*/
export class ListingsClient extends BaseApiClient {
/**
* API version
*/
apiVersion = 'listings/2021-08-01';
/**
* Create a new ListingsClient instance
*
* @param authConfig Authentication configuration
*/
constructor(authConfig) {
super(authConfig);
}
/**
* Get listings
*
* @param params Parameters for retrieving listings
* @returns Promise resolving to the listings result
*/
async getListings(params = {}) {
const { sku, includedData, pageSize, nextToken } = params;
// Build query parameters
const query = {};
if (sku) {
query.sku = sku;
}
if (includedData && includedData.length > 0) {
query.includedData = includedData;
}
if (pageSize) {
query.pageSize = Math.min(100, Math.max(1, pageSize)); // Ensure pageSize is between 1 and 100
}
if (nextToken) {
query.nextToken = nextToken;
}
// Add seller ID and marketplace ID
query.sellerId = 'SELLER_ID'; // This should be retrieved from auth config in a real implementation
query.marketplaceIds = this.config.marketplaceId;
// Make API request
const requestOptions = {
method: 'GET',
path: `/${this.apiVersion}/items`,
query: query,
};
// Use cache for listings (1 minute TTL)
const cacheKey = `listings:${query.sellerId}:${this.config.marketplaceId}:${sku || 'all'}:${JSON.stringify(includedData)}:${nextToken || 'first'}`;
return this.withCache(cacheKey, async () => {
const response = await this.request(requestOptions);
return response.data.payload;
}, 60 // 1 minute TTL
);
}
/**
* Get a single listing by SKU
*
* @param sku Seller SKU
* @param includedData List of included data sets
* @returns Promise resolving to the listing
*/
async getListing(sku, includedData) {
const result = await this.getListings({ sku, includedData });
if (!result.listings || result.listings.length === 0) {
throw new Error(`Listing with SKU ${sku} not found`);
}
return result.listings[0];
}
/**
* Create or update a listing
*
* @param params Parameters for creating or updating a listing
* @returns Promise resolving to the submission result
*/
async putListing(params) {
const { sku, productType, attributes, requirements, fulfillmentAvailability } = params;
// Validate listing data
this.validateListingData(params);
// Build request body
const requestBody = {
productType,
attributes,
requirements,
fulfillmentAvailability,
};
// Make API request
const requestOptions = {
method: 'PUT',
path: `/${this.apiVersion}/items/${sku}`,
query: {
marketplaceIds: this.config.marketplaceId,
},
data: requestBody,
};
const response = await this.request(requestOptions);
// Clear cache for this SKU
this.clearCache(`listings:*:${this.config.marketplaceId}:${sku}:*`);
return response.data.payload;
}
/**
* Delete a listing
*
* @param params Parameters for deleting a listing
* @returns Promise resolving to the submission result
*/
async deleteListing(params) {
const { sku, issueLocale } = params;
// Build query parameters
const query = {
marketplaceIds: this.config.marketplaceId,
};
if (issueLocale) {
query.issueLocale = issueLocale;
}
// Make API request
const requestOptions = {
method: 'DELETE',
path: `/${this.apiVersion}/items/${sku}`,
query,
};
const response = await this.request(requestOptions);
// Clear cache for this SKU
this.clearCache(`listings:*:${this.config.marketplaceId}:${sku}:*`);
return response.data.payload;
}
/**
* Validate listing data
*
* @param params Listing parameters to validate
* @throws Error if validation fails
*/
validateListingData(params) {
// Define validation schema using zod
const listingSchema = z.object({
sku: z.string().min(1, 'SKU is required'),
productType: z.string().min(1, 'Product type is required'),
attributes: z.record(z.unknown()).refine((attrs) => Object.keys(attrs).length > 0, {
message: 'At least one attribute is required',
}),
requirements: z
.array(z.object({
type: z.string().min(1, 'Requirement type is required'),
value: z.string().min(1, 'Requirement value is required'),
}))
.optional(),
fulfillmentAvailability: z
.array(z.object({
fulfillmentChannelCode: z.string().min(1, 'Fulfillment channel code is required'),
quantity: z.number().int().min(0, 'Quantity must be a non-negative integer'),
}))
.optional(),
});
try {
// Validate against schema
listingSchema.parse(params);
}
catch (error) {
if (error instanceof z.ZodError) {
// Format validation errors
const formattedErrors = error.errors
.map((err) => `${err.path.join('.')}: ${err.message}`)
.join(', ');
throw new Error(`Listing validation failed: ${formattedErrors}`);
}
throw error;
}
}
}
//# sourceMappingURL=listings-client.js.map