Skip to main content
Glama
amir-bengherbi

Shopify MCP Server

get-products-by-ids

Retrieve specific products from a Shopify store by providing their unique IDs, enabling targeted product data access for inventory management or display purposes.

Instructions

Get products by their IDs

Input Schema

TableJSON Schema
NameRequiredDescriptionDefault
productIdsYesArray of product IDs to retrieve

Implementation Reference

  • src/index.ts:166-190 (registration)
    MCP tool registration for 'get-products-by-ids', including input schema (productIds: array of strings) and handler logic that delegates to ShopifyClient.loadProductsByIds, formats output with formatProduct, handles errors.
    server.tool(
      "get-products-by-ids",
      "Get products by their IDs",
      {
        productIds: z
          .array(z.string())
          .describe("Array of product IDs to retrieve"),
      },
      async ({ productIds }) => {
        const client = new ShopifyClient();
        try {
          const products = await client.loadProductsByIds(
            SHOPIFY_ACCESS_TOKEN,
            MYSHOPIFY_DOMAIN,
            productIds
          );
          const formattedProducts = products.products.map(formatProduct);
          return {
            content: [{ type: "text", text: formattedProducts.join("\n") }],
          };
        } catch (error) {
          return handleError("Failed to retrieve products by IDs", error);
        }
      }
    );
  • Core implementation fetching products by IDs via Shopify GraphQL 'nodes' query with productFragment, filters valid Products, returns products array and shop currencyCode.
    async loadProductsByIds(
      accessToken: string,
      shop: string,
      productIds: string[]
    ): Promise<LoadProductsResponse> {
      const myshopifyDomain = await this.getMyShopifyDomain(accessToken, shop);
    
      const graphqlQuery = gql`
        {
          shop {
            currencyCode
          }
          nodes(ids: ${JSON.stringify(productIds)}) {
            __typename
            ... on Product {
              ${productFragment}
            }
          }
        }
      `;
    
      const res = await this.shopifyGraphqlRequest<{
        data: {
          shop: {
            currencyCode: string;
          };
          nodes: Array<
            | ({
                __typename: string;
              } & ProductNode)
            | null
          >;
        };
      }>({
        url: `https://${myshopifyDomain}/admin/api/${this.SHOPIFY_API_VERSION}/graphql.json`,
        accessToken,
        query: graphqlQuery,
      });
    
      const data = res.data.data;
    
      const products = data.nodes.filter(
        (
          node
        ): node is {
          __typename: string;
        } & ProductNode => node?.__typename === "Product"
      );
      const currencyCode = data.shop.currencyCode;
    
      return { products, currencyCode };
    }
  • Helper function to format a ProductNode into a human-readable string with title, description, handle, and detailed variants.
    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 definition for ProductNode, the structure of product data returned and used in formatting.
    export type ProductNode = {
      id: string;
      handle: string;
      title: string;
      description: string;
      publishedAt: string;
      updatedAt: string;
      options: ProductOption[];
      images: {
        edges: {
          node: ProductImage;
        }[];
      };
      variants: {
        edges: {
          node: ProductVariant;
        }[];
      };
    };
  • Helper function to handle and format errors in tool responses, used in the tool handler.
    function handleError(
      defaultMessage: string,
      error: unknown
    ): {
      content: { type: "text"; text: string }[];
      isError: boolean;
    } {
      let errorMessage = defaultMessage;
      if (error instanceof CustomError) {
        errorMessage = `${defaultMessage}: ${error.message}`;
      }
      return {
        content: [{ type: "text", text: errorMessage }],
        isError: true,
      };
    }
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 cover critical aspects like whether this is a read-only operation, error handling, rate limits, authentication needs, or what happens with invalid IDs, leaving significant gaps.

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 extremely concise with a single, direct sentence that front-loads the core functionality. There is no wasted language, making it efficient and easy to parse.

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 the lack of annotations and output schema, the description is incomplete. It doesn't explain return values, error conditions, or behavioral nuances needed for a tool that retrieves data by IDs, failing to compensate for the missing structured information.

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?

Schema description coverage is 100%, so the schema fully documents the single parameter 'productIds'. The description adds no additional meaning beyond what the schema provides, such as format examples or constraints, meeting the baseline for high coverage.

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 by their IDs'), making the purpose immediately understandable. However, it doesn't differentiate from sibling tools like 'get-products' or 'get-products-by-collection', which would require more specificity to earn a 5.

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-collection'. It lacks context about prerequisites, limitations, or typical use cases, offering only basic functional information.

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