Commerce MCP

Enable AI agents and assistants to integrate seamlessly with Composable Commerce through standardized function calling.

Copy for LLM
View as Markdown

Commerce MCP is currently under development and may be subject to changes.

commercetools permits non-production use of Commerce MCP for development, evaluation, and testing purposes without charge, provided that the total number of tool invocations does not exceed 1 000 000 (one million) invocations in total.

Any use of Commerce MCP in a production environment or for any other commercial purpose requires a valid paid license or subscription.

Customers intending to move Commerce MCP into production must first secure the appropriate license by contacting their commercetools representative. commercetools will review usage as needed and may restrict, suspend, or terminate access if production use occurs without the required licensing.

With Commerce MCP, agents can perform tasks, including retrieving product information, managing carts and orders, and handling customer data, on your Composable Commerce Project.

You control which permissions your Commerce MCP server has on your Composable Commerce Project. You decide which API Client Commerce MCP uses and you configure which tools the MCP server is allowed to use. This gives you full control over the permissions your agent can have, whether it has read-only access or read-and-write access for advanced use cases.
This page describes how to set up your Commerce MCP server in Visual Studio Code and how to configure the transport protocol for it. Furthermore, you can control data transformation and enable logging for debugging purposes.
Find best practices and options for integrating Commerce MCP in agent frameworks and to extend it with custom tools.

Placeholder values

This document uses the following placeholders in examples. You should replace these placeholders with your respective values.

If you do not have an API Client, follow our Get your API Client guide.
PlaceholderReplace withFrom
{PROJECT_KEY}project_keyyour API Client
{CLIENT_ID}client_idyour API Client
{CLIENT_SECRET}secretyour API Client
{ACCESS_TOKEN}access_tokenan existing access token (when using auth_token authentication type)
{AUTH_URL}your Authorization URLRequest an access token using the Composable Commerce OAuth 2.0 service
{API_URL}your API URLHosts

Get started

This section describes how to set up and use Commerce MCP with Visual Studio Code in stdio mode. It requires you have Node.js 18 (or later) installed on your machine. You also need to have an API Client with the appropriate scopes for the tools you want to use. For this getting started guide, we recommend using an Admin Client with manage and view scopes enabled to see all available tools. Have the API Client credentials ready before proceeding. You need to replace the placeholder values given in this document with your respective values to access your Composable Commerce Project.

Add Commerce MCP server to Visual Studio Code

Add the following entry to the mcp.json file in your VS Code configuration:
Add Commerce MCP server to VS Codejson
{
  "servers": {
    "commerce-mcp": {
      "type": "stdio",
      "command": "npx",
      "args": [
        "-y",
        "@commercetools/commerce-mcp@latest",
        "--tools=all",
        "--isAdmin=true",
        "--dynamicToolLoadingThreshold=450",
        "--authType=client_credentials",
        "--clientId={CLIENT_ID}",
        "--clientSecret={CLIENT_SECRET}",
        "--authUrl={AUTH_URL}",
        "--projectKey={PROJECT_KEY}",
        "--apiUrl={API_URL}"
      ]
    }
  }
}

Replace the placeholders with your respective values.

You can now start the server right from the configuration file. If the status does not change to Running, open the Output panel in VS Code to see any error messages. If the server is running, you should see that Commerce MCP discovered a number of tools.

Use Commerce MCP's tools with VS Code Chat

You can now use the Composable Commerce tools in your VS Code chat using Agent mode.

Ask questions like:

  • What is the project key?
  • Which countries are configured in my project?

You can also create resources in your Composable Commerce project, for example:

  • Create a new inventory supply channel for Italy.

Verify in the Merchant Center that the channel has been created.

Next steps

If you have completed this guide to this point, you have successfully set up Commerce MCP running on your machine.

You can explore more advanced configurations in the following sections to configure Commerce MCP according to your needs. For example, you can set up Commerce MCP to run as a Streamable HTTP server for remote access. In the Best practices section, you can find recommendations on how to configure only the tools you want to enable for an agent. In the section Arguments and environment variables, you can find some explanations of the parameters you provided in the MCP server configuration.

Reference

Executable package

You can run Commerce MCP directly using npx without installing it globally:
npx -y @commercetools/commerce-mcp {list of arguments}

Find a list of the available arguments and environment variables that control the MCP server in the following section.

Arguments and environment variables

The following arguments can be provided as command-line parameters or as environment variables when invoking Commerce MCP.

Use command line argumentbash
npx -y @commercetools/commerce-mcp
  --tools=all
  --dynamicToolLoadingThreshold=50
  --clientId={CLIENT_ID}
  --clientSecret={CLIENT_SECRET}
  --projectKey={PROJECT_KEY}
  --authUrl={AUTH_URL}
  --apiUrl={API_URL}
Use environment variablebash
export DYNAMIC_TOOL_LOADING_THRESHOLD=50
npx -y @commercetools/commerce-mcp
  --tools=all
  --clientId={CLIENT_ID}
  --clientSecret={CLIENT_SECRET}
  --projectKey={PROJECT_KEY}
  --authUrl={AUTH_URL}
  --apiUrl={API_URL}
Command-line argumentEnvironment variableRequiredDescription or set value
toolsTOOLSRequiredThe tools to be used. To include multiple tools, use a comma-separated list without spaces.
authTypeAUTH_TYPERequiredThe authentication type to be used.
projectKeyPROJECT_KEYRequiredThe {PROJECT_KEY} of the Composable Commerce Project you want to use.
authUrlAUTH_URLRequiredThe {AUTH_URL} of your Project's authorization service.
apiUrlAPI_URLRequiredThe {API_URL} of your Project's API service.
accessTokenACCESS_TOKENRequired, if authType is auth_token.The access token to use for token authentication.
clientIdCLIENT_IDRequired, if authType is client_credentials.The {CLIENT_ID} to use for client credentials authentication.
clientSecretCLIENT_SECRETRequired, if authType is client_credentials.The {CLIENT_SECRET} to use for client credentials authentication.
remoteREMOTEOptionalSpecifies the transport protocol between MCP server and client. If true, Streamable HTTP is used, stdio if false.
statelessSTATELESSRequired, if remote is true.If true, the server will be stateless.
portPORTOptionalThe port number of the MCP server in remote mode. Defaults to port 8080.
isAdminIS_ADMINOptionalIf the server should be run with administrator privileges. Must be true if tools is set to all.
dynamicToolLoadingThresholdDYNAMIC_TOOL_LOADING_THRESHOLDOptionalThe number of tools to be injected. If the value exceeds the number of available tools then all available tools will be injected. For more information, see dynamic tool loading.
toolOutputFormatTOOL_OUTPUT_FORMATOptionalThe output format of the MCP server. Can be json or tabular. If not defined, tabular is used. See data transformation.
loggingLOGGINGOptionalIf true, the server runs in logging mode.
customerIdCUSTOMER_IDOptionalThe customerId to use in Customer-specific queries.
cartIdCART_IDOptionalThe cartId to use in Cart-specific queries.
storeKeySTORE_KEYOptionalThe storeKey to use in Store-specific queries.
businessUnitKeyBUSINESS_UNIT_KEYOptionalThe businessUnitKey to use in Business Unit-specific queries.

Available tools

Tools represent the operations on various Composable Commerce resources that Commerce MCP can perform. The Commerce MCP will try to find the tool that fits best to your natural language request. It can invoke these tools to interact with your Composable Commerce Project through the API Client you provide. The following table lists all available tools you can enable in your Commerce MCP server. In the Description column, you find links to the respective API endpoint used by Commerce MCP to perform the task. For better performance, Commerce MCP does not load all tools at once by default, it applies dynamic tool loading.

For best security and performance, you should configure your Commerce MCP server to only include specific tools required for your use case.

ToolDescription
allEnables all available tools, including read, create, and update operations. Requires setting --isAdmin=true.
all.readEnables all read-only tools.
bulk.createCreate entities in bulk.
bulk.updateUpdate entities in bulk.
business-unit.createCreate business unit
business-unit.readRead business unit
business-unit.updateUpdate business unit
cart.createCreate cart
cart.readRead cart information
cart.updateUpdate cart information
cart-discount.createCreate cart discount
cart-discount.readRead cart discount
cart-discount.updateUpdate cart discount
category.createCreate category
category.readRead category information
category.updateUpdate category
channel.createCreate channel
channel.readRead channel information
channel.updateUpdate channel information
custom-objects.createCreate custom objects
custom-objects.readRead custom objects
custom-objects.updateUpdate custom objects
customer.createCreate customer
customer.readRead customer information
customer.updateUpdate customer information
customer-group.createCreate customer group
customer-group.readRead customer group
customer-group.updateUpdate customer group
discount-code.createCreate discount code
discount-code.readRead discount code information
discount-code.updateUpdate discount code information
extensions.createCreate extensions
extensions.readRead extensions
extensions.updateUpdate extensions
inventory.createCreate inventory
inventory.readRead inventory information
inventory.updateUpdate inventory information
order.createCreate order (from cart, quote, import)
order.readRead order information
order.updateUpdate order information
payment.createCreate payment
payment.readRead payment
payment.updateUpdate payment
payment-intents.updateManage payment intents
payment-methods.createCreate payment method
payment-methods.readRead payment method
payment-methods.updateUpdate payment method
product-discount.createCreate product discount
product-discount.readRead product discount
product-discount.updateUpdate product discount
product-search.readSearch products
product-selection.createCreate product selection
product-selection.readRead product selection
product-selection.updateUpdate product selection
product-tailoring.createCreate product tailoring
product-tailoring.readRead product tailoring
product-tailoring.updateUpdate product tailoring
product-type.createCreate product type
product-type.readRead product type
product-type.updateUpdate product type
products.createCreate product information
products.readRead product information
products.updateUpdate product information
project.readRead project information
quote.createCreate quote
quote.readRead quote information
quote.updateUpdate quote information
quote-request.createCreate quote request
quote-request.readRead quote request
quote-request.updateUpdate quote request
recurring-orders.createCreate recurring order
recurring-orders.readRead recurring order
recurring-orders.updateUpdate recurring order
reviews.createCreate review
reviews.readRead review
reviews.updateUpdate review
shipping-methods.createCreate shipping method
shipping-methods.readRead shipping method
shipping-methods.updateUpdate shipping method
shopping-lists.createCreate shopping list
shopping-lists.readRead shopping list
shopping-lists.updateUpdate shopping list
staged-quote.createCreate staged quote
staged-quote.readRead staged quote
staged-quote.updateUpdate staged quote
standalone-price.createCreate standalone price
standalone-price.readRead standalone price
standalone-price.updateUpdate standalone price
store.createCreate store
store.readRead store
store.updateUpdate store
subscriptions.createCreate subscription
subscriptions.readRead subscription
subscriptions.updateUpdate subscription
tax-category.createCreate tax category
tax-category.readRead tax category
tax-category.updateUpdate tax category
transactions.createCreate transaction
transactions.readRead transaction
types.createCreate type
types.readRead type
types.updateUpdate type
zones.createCreate zone
zones.readRead zone
zones.updateUpdate zone

Dynamic tool loading

To optimize performance, Commerce MCP features an efficient loading strategy for the enabled tools called dynamic tool loading. Commerce MCP limits the number of tools loaded at once and only loads additional tools as needed. This strategy helps reduce the context usage when working with large numbers of tools.

Commerce MCP applies dynamic tool loading automatically when the number of enabled tools exceeds a configurable threshold. The threshold is 30 by default, but you can adjust this value if needed either by:

  • using the command-line argument --dynamicToolLoadingThreshold=50, or
  • setting the environment variable DYNAMIC_TOOL_LOADING_THRESHOLD=50.

Authentication types

Commerce MCP supports two types of authentication with the Composable Commerce API:

Choose the authentication type that best fits your use case and provide the corresponding credentials.

Client credentials authentication

Use argument --authType=client_credentials (or type: 'client_credentials' in TypeScript) and provide the API Client ID and secret using --clientId={CLIENT_ID} and --clientSecret={CLIENT_SECRET}.
Commerce MCP server configuration using client_credentials authenticationjson
{
  "servers": {
    "commerce-mcp": {
      "type": "stdio",
      "command": "npx",
      "args": [
        "-y",
        "@commercetools/commerce-mcp@latest",
        "--authType=client_credentials",
        "--clientId={CLIENT_ID}",
        "--clientSecret={CLIENT_SECRET}",
        "--authUrl={AUTH_URL}",
        "--projectKey={PROJECT_KEY}",
        "--apiUrl={API_URL}",
        "--tools=all.read"
      ]
    }
  }
}

Auth token authentication

Use argument --authType=auth_token (or type: 'auth_token' in TypeScript) and provide the existing access token using --accessToken={ACCESS_TOKEN}.
Commerce MCP server configuration using auth_token authenticationjson
{
  "servers": {
    "commerce-mcp": {
      "type": "stdio",
      "command": "npx",
      "args": [
        "-y",
        "@commercetools/commerce-mcp@latest",
        "--authType=auth_token",
        "--accessToken={ACCESS_TOKEN}",
        "--authUrl={AUTH_URL}",
        "--projectKey={PROJECT_KEY}",
        "--apiUrl={API_URL}",
        "--tools=all.read"
      ]
    }
  }
}

Transport protocol

Commerce MCP supports two transport protocols for communication between the MCP server and the client.

  • stdio: Use this for development and testing locally on your machine.
  • Streamable HTTP: Use this for remote deployments where your MCP server is hosted on a remote machine or in the cloud.

stdio

Setting up Commerce MCP with stdio transport allows you to run the MCP server locally and interact with it via standard input/output streams. Your configuration may differ based on the software used, but the following example illustrates the general setup within a JSON configuration file:
Set up Commerce MCP server with all available tools and stdio transportjson
{
  "commerce-mcp": {
    "type": "stdio",
    "command": "npx",
    "args": [
      "-y",
      "@commercetools/commerce-mcp@latest",
      "--tools=all",
      "--isAdmin=true",
      "--dynamicToolLoadingThreshold=450",
      "--authType=client_credentials",
      "--clientId={CLIENT_ID}",
      "--clientSecret={CLIENT_SECRET}",
      "--authUrl={AUTH_URL}",
      "--projectKey={PROJECT_KEY}",
      "--apiUrl={API_URL}"
    ]
  }
}

Streamable HTTP

Commerce MCP supports Streamable HTTP transport, allowing you to run the MCP server in a remote mode accessible over HTTP. This setup is useful for deploying the MCP server in cloud environments or on remote machines.

To run the Commerce MCP server in remote mode, add the following arguments to the command:

Set up Commerce MCP server with all available tools and Streamable HTTP transportbash
npx -y @commercetools/commerce-mcp \
  --remote=true \
  --stateless=true \
  --port=8888 \
  --tools=all \
  --isAdmin=true \
  --dynamicToolLoadingThreshold=450 \
  --authType=client_credentials \
  --clientId=CLIENT_ID \
  --clientSecret=CLIENT_SECRET \
  --projectKey=PROJECT_KEY \
  --authUrl=AUTH_URL \
  --apiUrl=API_URL \

Use with Claude Desktop

To use an Commerce MCP server running on port 8888, you configure Claude Desktop with the following:
Claude Desktop configuration to use Commerce MCP server running on port 8888json
{
  "mcpServers": {
    "commercetools": {
      "command": "npx",
      "args": ["mcp-remote", "http://localhost:8888/mcp"]
    }
  }
}

Data transformation

By default, Commerce MCP transforms data fetched from tools and resources before sending it back to the LLM. This transformation converts JSON data into tabular format, with minor modifications on booleans and property names. The transformed data format improves the quality of the data passed to the LLM, and in most cases reduces the token count. This might not work for large and deeply nested data structures. The following example shows the original JSON object together with its transformed tabular format:

Original JSON output from a tooljson
{
  "customer": {
    "customerID": "12",
    "firstName": "John",
    "lastName": "Doe",
    "isActive": true,
    "isGoldCustomer": false
  }
}
Transformed tabular outputtext
Customer
  Customer ID: 12
  First Name: John,
  Last Name: Doe,
  Is Active: Yes,
  Is Gold Customer: No
You can override this behaviour by passing the argument --toolOutputFormat=json or setting the TOOL_OUTPUT_FORMAT environment variable. This setting tells Commerce MCP to bypass this data transformation and to return the original JSON string instead.

Logging

Commerce MCP supports logging (as from @commercetools/commerce-mcp version 2.3.0) to stdout. The server logs the mode, the correlationId, and the sessionId when running a remote server in stateful mode.
You can enable logging by passing the --logging=true argument or setting the LOGGING environment variable to true.
Configure server with loggingbash
npx -y @commercetools/commerce-mcp \
  --tools=all \
  --authType=client_credentials \
  --clientId=CLIENT_ID \
  --clientSecret=CLIENT_SECRET \
  --projectKey=PROJECT_KEY \
  --authUrl=AUTH_URL \
  --apiUrl=API_URL \
  --remote=true \
  --stateless=true \
  --port=8888 \
  --logging=true # log to stdout

Best practices

Select specific tools

For optimal security and performance, you should only enable the specific tools required for your use case. To do so, modify the tools argument or TOOLS environment variable to include only the tools you need.
For example, to set up only read-only tools, use --tools=all.read. To specify individual tools, provide a comma-separated list, such as --tools=cart.read,order.read,products.create. Find a complete list of all available tools in section Available tools.
Set up Commerce MCP server with product-related tools onlyjson
{
  "commerce-mcp": {
    "type": "stdio",
    "command": "npx",
    "args": [
      "-y",
      "@commercetools/commerce-mcp@latest",
      "--tools=products.create,products.read,products.update",
      "--authType=client_credentials",
      "--clientId={CLIENT_ID}",
      "--clientSecret={CLIENT_SECRET}",
      "--authUrl={AUTH_URL}",
      "--projectKey={PROJECT_KEY}",
      "--apiUrl={API_URL}"
    ]
  }
}

Use administrator privileges only when necessary

Many examples on this page use the --isAdmin=true argument, which provides full access to all resources, settings, and operations in your Composable Commerce Project. This is useful during the exploration and experimentation phase, but should be used with caution in real-world scenarios. If not necessary, don't use --isAdmin=true to restrict access to only the tools specified in the --tools argument.

Commerce Agent

Commerce Agent allows agent frameworks to interact with Composable Commerce through function calling. It supports a subset of the commercetools API using the TypeScript SDK.
Commerce Agent requires Node 18 (or later). To get started, install @commercetools/commerce-agent:
npm install @commercetools/commerce-agent

Usage

Configure Commerce Agent with your API Client credentials. Your API Client must include scopes for each enabled action. For example, to enable products.read, the API Client must have the view_products scope.
The following examples use environment variables to load the credentials, which you can save after creating your API Client.
Additionally, you can define the actions available using the toolkit in configuration.
import { CommercetoolsCommerceAgent } from '@commercetools/commerce-agent/langchain';

const commercetoolsCommerceAgent = new CommercetoolsCommerceAgent({
  authConfig: {
    type: 'client_credentials',
    clientId: process.env.CLIENT_ID!,
    clientSecret: process.env.CLIENT_SECRET!,
    projectKey: process.env.PROJECT_KEY!,
    authUrl: process.env.AUTH_URL!,
    apiUrl: process.env.API_URL!,
  },
  configuration: {
    actions: {
      products: {
        read: true,
        create: true,
        update: true,
      },
      project: {
        read: true,
      },
    },
  },
});

Set up Streamable HTTP server locally with Express

You can also use the Streamable HTTP server with the Commerce Agent like an SDK and develop on it.

import {
  CommercetoolsCommerceAgent,
  CommercetoolsCommerceAgentStreamable,
} from '@commercetools/commerce-agent/modelcontextprotocol';
import express from 'express';

const expressApp = express();

async function agentServer(id: string) {
  // `id` is the session-id for`stateful` instance
  // that is the `stateless` option is set to false
  // console.log(id) -> f81d4fae-7dec-11d0-a765-00a0c91e6bf6
  return CommercetoolsCommerceAgent.create({
    authConfig: {
      type: 'client_credentials',
      clientId: process.env.CLIENT_ID!,
      clientSecret: process.env.CLIENT_SECRET!,
      projectKey: process.env.PROJECT_KEY!,
      authUrl: process.env.AUTH_URL!,
      apiUrl: process.env.API_URL!,
    },
    configuration: {
      actions: {
        products: {
          read: true,
        },
        cart: {
          read: true,
          create: true,
          update: true,
        },
        ...
      },
    },
  });
}

const serverStreamable = new CommercetoolsCommerceAgentStreamable({
  stateless: false, // make the MCP server stateless/stateful
  streamableHttpOptions: {
    sessionIdGenerator: undefined,
  },
  server: agentServer,
  app: expressApp, // optional express app instance
});

serverStreamable.listen(8888, function () {
  console.log('listening on 8888');
});
Without using the CommercetoolsCommerceAgent, you can directly use only the CommercetoolsCommerceAgentStreamable class.
import { CommercetoolsCommerceAgentStreamable } from '@commercetools/commerce-agent/modelcontextprotocol';
import express from 'express';

const expressApp = express();

const server = new CommercetoolsCommerceAgentStreamable({
  authConfig: {
    type: 'client_credentials',
    clientId: process.env.CLIENT_ID!,
    clientSecret: process.env.CLIENT_SECRET!,
    projectKey: process.env.PROJECT_KEY!,
    authUrl: process.env.AUTH_URL!,
    apiUrl: process.env.API_URL!,
  },
  configuration: {
    actions: {
      project: {
        read: true,
      },
      // other tools can go here
    },
  },

  stateless: false,
  streamableHttpOptions: {
    sessionIdGenerator: undefined,
  },
  app: expressApp,
});

server.listen(8888, function () {
  console.log('listening on 8888');
});

Tools

The toolkit integrates with LangChain and AI SDK by Vercel. Pass the tools to your agent executor:

import { AgentExecutor, createStructuredChatAgent } from 'langchain/agents';

const tools = commercetoolsCommerceAgent.getTools();

const agent = await createStructuredChatAgent({
  llm,
  tools,
  prompt,
});

const agentExecutor = new AgentExecutor({
  agent,
  tools,
});

Set up your own MCP server

You can also expose your own MCP server using CommercetoolsCommerceAgent:
import { CommercetoolsCommerceAgent } from '@commercetools/commerce-agent/modelcontextprotocol';
import { StdioServerTransport } from '@modelcontextprotocol/sdk/server/stdio.js';

const server = new CommercetoolsCommerceAgent({
  authConfig: {
    type: 'client_credentials',
    clientId: process.env.CLIENT_ID!,
    clientSecret: process.env.CLIENT_SECRET!,
    projectKey: process.env.PROJECT_KEY!,
    authUrl: process.env.AUTH_URL!,
    apiUrl: process.env.API_URL!,
  },
  configuration: {
    actions: {
      products: {
        read: true,
      },
      cart: {
        read: true,
        create: true,
        update: true,
      },
    },
  },
});

async function main() {
  const transport = new StdioServerTransport();
  await server.connect(transport);
  console.error('My custom commercetools MCP Server running on stdio');
}

main().catch((error) => {
  console.error('Fatal error in main():', error);
  process.exit(1);
});

Mastra

Just like the @commercetools/commerce-agent/langchain the @commercetools/commerce-agent/mastra essentials library can be used to execute multi-step commands/prompts.

Example

require('dotenv').config();
import { Agent } from '@mastra/core/agent';
import { CommercetoolsCommerceAgent } from '@commercetools/commerce-agent/mastra';

const commercetoolsCommerceAgent = new CommercetoolsCommerceAgent({
  authConfig: {
    type: 'client_credentials',
    clientId: process.env.CLIENT_ID!,
    clientSecret: process.env.CLIENT_SECRET!,
    authUrl: process.env.AUTH_URL!,
    projectKey: process.env.PROJECT_KEY!,
    apiUrl: process.env.API_URL!,
  },
  configuration: {
    actions: {
      products: {
        read: true,
        create: true,
        update: true,
      },
      'product-type': {
        read: true,
        create: true,
      },
    },
  },
});

const agent = new Agent({
  name: 'CommercetoolsAgent',
  instructions:
    'You are a helpful agent that can manage products and product types in commercetools. Use the available tools to help users with their commerce operations.',
  tools: commercetoolsCommerceAgent.getTools(),
});

(async () => {
  console.log('--- Starting Commercetools Mastra Agent Task Sequence ---');

  // Task 1: List all products
  const task1Prompt =
    'List all products in the commercetools project. This is the first step.';
  console.log(`\nExecuting: ${task1Prompt}`);
  const result1 = await agent.step({
    messages: [
      {
        role: 'user',
        content: task1Prompt,
      },
    ],
  });
  console.log('--- Response from "List all products" ---');
  console.log(result1.text);
  console.log(
    '--------------------------------------------------------------------------------'
  );

  // Task 2: List product types
  const task2Prompt = `Based on the products listed above, list all product types available in the project. I need this information to select a product type for creating a product in the next step.`;
  console.log(`\nExecuting: ${task2Prompt}`);
  const result2 = await agent.step({
    messages: [
      ...result1.messages,
      {
        role: 'user',
        content: task2Prompt,
      },
    ],
  });
  console.log('--- Response from "List product types" (Task 2) ---');
  console.log(result2.text);
  console.log(
    '--------------------------------------------------------------------------------'
  );

  // Task 3: Create a test product
  const productName = `Mastra Test Product ${Math.floor(Date.now() / 1000)}`;
  const productKey = `MASTRA-${Math.random().toString(36).substring(2, 9).toUpperCase()}`;
  const productSku = `MTP-${Math.random().toString(36).substring(2, 9).toUpperCase()}`;
  const productSlug = productName.toLowerCase().replace(/\s+/g, '-');

  const task3Prompt = `Based on the product types listed above, please create a new product with the following details:
- Name: "${productName}"
- Key: "${productKey}"
- Slug (en): "${productSlug}"
- SKU: "${productSku}"
- Description: "This product was created automatically by a Mastra AI agent."
- Ensure the product is published if possible during creation.

Please provide the ID of this newly created product in your response.`;
  console.log(`\nExecuting: ${task3Prompt}`);
  const result3 = await agent.step({
    messages: [
      ...result2.messages,
      {
        role: 'user',
        content: task3Prompt,
      },
    ],
  });
  console.log('--- Response from "Create test product" (Task 3) ---');
  console.log(result3.text);
  console.log(
    '--------------------------------------------------------------------------------'
  );

  // Task 4: Update the product
  const updateDescription =
    'This product was created and then updated automatically by a Mastra AI agent.';
  const task4Prompt = `Using the ID of the product that was just created (from the previous step), please update it.
Change its description to "${updateDescription}"`;
  console.log(`\nExecuting: ${task4Prompt}`);
  const result4 = await agent.step({
    messages: [
      ...result3.messages,
      {
        role: 'user',
        content: task4Prompt,
      },
    ],
  });
  console.log('--- Response from "Update the product" (Task 4) ---');
  console.log(result4.text);
  console.log(
    '--------------------------------------------------------------------------------'
  );

  console.log('\n--- Commercetools Mastra Agent Task Sequence Finished ---');
})().catch((error) => {
  console.error('An error occurred during the async execution:', error);
});

getTools()

The getTools() method returns the list of tools available to your agent.
const tools = commercetoolsCommerceAgent.getTools();

Custom Tools

The self-managed @commercetools/commerce-agent library includes support for custom tools. A list of custom tools implementations can be passed over and registered at runtime by the bootstrapping MCP server. This is useful when intended tools are not yet implemented, and gives you complete control and customization of how tools interact with the underlying LLM.

Usage

import { CommercetoolsCommerceAgent } from "@commercetools/commerce-agent/modelcontextprotocol";
import { StdioServerTransport } from "@modelcontextprotocol/sdk/server/stdio.js";

const server = await CommercetoolsCommerceAgent.create({
  authConfig: {...},
  configuration: {
    customTools: [
      {
        name: "Get Project",
        method: "get_project",
        description: `This tool will fetch information about a commercetools project.\n\n
          This tool will accept a project and fetch information about the provided key. \n\n
          `, // It is important that this description is well detailed and explicitly describes what this tool does and the parameters it receives/
        parameters: z.object({
          projectKey: z
            .string()
            .optional()
            .describe(
              "The key of the project to read. If not provided, the current project will be used."
            ),
        }),
        actions: {},
        execute: async (args: { projectKey: string }, api: ApiRoot) => {
          // already existing functions can be used here e.g
          // const response = await import('ctService').defaults.getProject('demo-project-key-a7fc1182');
          const response = await api.withProjectKey(args).get().execute();
          return JSON.stringify(response);
        },
      },
      ...
    ],
    actions: {...},
  },
});
...