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>;
Behavior2/5

Does the description disclose side effects, auth requirements, rate limits, or destructive behavior?

With no annotations provided, the description carries the full burden of behavioral disclosure but only states the basic action. It doesn't mention whether this is a read-only operation, potential rate limits, authentication needs, error conditions, or response format (e.g., pagination, data structure). For a tool with zero annotation coverage, this is a significant gap in transparency.

Agents need to know what a tool does to the world before calling it. Descriptions should go beyond structured annotations to explain consequences.

Conciseness5/5

Is the description appropriately sized, front-loaded, and free of redundancy?

The description is a single, efficient sentence with zero wasted words. It's front-loaded with the core purpose and appropriately sized for the tool's complexity, making it easy to parse quickly.

Shorter descriptions cost fewer tokens and are easier for agents to parse. Every sentence should earn its place.

Completeness2/5

Given the tool's complexity, does the description cover enough for an agent to succeed on first attempt?

Given no annotations and no output schema, the description is incomplete for a retrieval tool. It lacks details on behavioral traits (e.g., read-only nature, error handling), response format, or usage distinctions from siblings. While concise, it doesn't provide enough context for an agent to fully understand how to invoke and interpret results.

Complex tools with many parameters or behaviors need more documentation. Simple tools need less. This dimension scales expectations accordingly.

Parameters3/5

Does the description clarify parameter syntax, constraints, interactions, or defaults beyond what the schema provides?

The input schema has 100% description coverage, with clear documentation for both parameters (collectionId and limit). The description adds no additional semantic context beyond what the schema provides, such as example values or constraints not in the schema. This meets the baseline score of 3 when schema coverage is high.

Input schemas describe structure but not intent. Descriptions should explain non-obvious parameter relationships and valid value ranges.

Purpose4/5

Does the description clearly state what the tool does and how it differs from similar tools?

The description clearly states the verb ('Get') and resource ('products from a specific collection'), making the purpose immediately understandable. However, it doesn't explicitly differentiate from sibling tools like 'get-products' or 'get-products-by-ids', which would require more specific language about collection-based filtering versus other retrieval methods.

Agents choose between tools based on descriptions. A clear purpose with a specific verb and resource helps agents select the right tool.

Usage Guidelines2/5

Does the description explain when to use this tool, when not to, or what alternatives exist?

The description provides no guidance on when to use this tool versus alternatives like 'get-products' or 'get-products-by-ids'. It mentions 'specific collection' but doesn't clarify prerequisites, exclusions, or comparative contexts with sibling tools, leaving the agent to infer usage scenarios.

Agents often have multiple tools that could apply. Explicit usage guidance like "use X instead of Y when Z" prevents misuse.

Install Server

Other Tools

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