Skip to main content
Glama
amir-bengherbi

Shopify MCP Server

get-products-by-collection

Retrieve products from a Shopify collection using its ID to manage inventory and display items. Specify a limit to control the number of products returned.

Instructions

Get products from a specific collection

Input Schema

TableJSON Schema
NameRequiredDescriptionDefault
collectionIdYesID of the collection to get products from
limitNoMaximum number of products to return

Implementation Reference

  • src/index.ts:134-163 (registration)
    Registration of the MCP tool 'get-products-by-collection', including input schema (collectionId, limit) and handler function that instantiates ShopifyClient and calls loadProductsByCollectionId
    server.tool(
      "get-products-by-collection",
      "Get products from a specific collection",
      {
        collectionId: z
          .string()
          .describe("ID of the collection to get products from"),
        limit: z
          .number()
          .optional()
          .default(10)
          .describe("Maximum number of products to return"),
      },
      async ({ collectionId, limit }) => {
        const client = new ShopifyClient();
        try {
          const products = await client.loadProductsByCollectionId(
            SHOPIFY_ACCESS_TOKEN,
            MYSHOPIFY_DOMAIN,
            collectionId,
            limit
          );
          const formattedProducts = products.products.map(formatProduct);
          return {
            content: [{ type: "text", text: formattedProducts.join("\n") }],
          };
        } catch (error) {
          return handleError("Failed to retrieve products from collection", error);
        }
      }
  • Implementation of loadProductsByCollectionId in ShopifyClient class, executes GraphQL query to fetch products from a Shopify collection by ID, handles pagination, returns formatted products with currency
    async loadProductsByCollectionId(
      accessToken: string,
      shop: string,
      collectionId: string,
      limit: number = 10,
      afterCursor?: string
    ): Promise<LoadProductsResponse> {
      const myshopifyDomain = await this.getMyShopifyDomain(accessToken, shop);
    
      const graphqlQuery = gql`
        {
          shop {
            currencyCode
          }
          collection(id: "gid://shopify/Collection/${collectionId}") {
            products(
              first: ${limit}${afterCursor ? `, after: "${afterCursor}"` : ""}
            ) {
              edges {
                node {
                  ${productFragment}
                }
              }
              pageInfo {
                hasNextPage
                endCursor
              }
            }
          }
        }
      `;
    
      const res = await this.shopifyGraphqlRequest<{
        data: {
          shop: {
            currencyCode: string;
          };
          collection: {
            products: {
              edges: Array<{
                node: ProductNode;
              }>;
              pageInfo: {
                hasNextPage: boolean;
                endCursor: string;
              };
            };
          };
        };
      }>({
        url: `https://${myshopifyDomain}/admin/api/${this.SHOPIFY_API_VERSION}/graphql.json`,
        accessToken,
        query: graphqlQuery,
      });
    
      const data = res.data.data;
      const edges = data.collection.products.edges;
      const products = edges.map((edge) => edge.node);
      const pageInfo = data.collection.products.pageInfo;
      const next = pageInfo.hasNextPage ? pageInfo.endCursor : undefined;
      const currencyCode = data.shop.currencyCode;
    
      return { products, next, currencyCode };
    }
  • Helper function formatProduct used in the tool handler to format product data for text output
    function formatProduct(product: ProductNode): string {
      return `
      Product: ${product.title} 
      description: ${product.description} 
      handle: ${product.handle}
      variants: ${product.variants.edges
        .map(
          (variant) => `variant.title: ${variant.node.title}
        variant.id: ${variant.node.id}
        variant.price: ${variant.node.price}
        variant.sku: ${variant.node.sku}
        variant.inventoryPolicy: ${variant.node.inventoryPolicy}
        `
        )
        .join(", ")}
      `;
    }
  • Type signature for loadProductsByCollectionId method in ShopifyClientPort interface, defines input/output types (uses LoadProductsResponse which includes products: ProductNode[], next cursor, currencyCode)
    loadProductsByCollectionId(
      accessToken: string,
      myshopifyDomain: string,
      collectionId: string,
      limit?: number,
      afterCursor?: string
    ): Promise<LoadProductsResponse>;

Latest Blog Posts

MCP directory API

We provide all the information about MCP servers via our MCP API.

curl -X GET 'https://glama.ai/api/mcp/v1/servers/amir-bengherbi/shopify-mcp-server'

If you have feedback or need assistance with the MCP directory API, please join our Discord server