@commercetools/tools-core

中文文档
0.7.1发布于 2026/11/09UNLICENSEDTypeScriptESM + CJS近 30 天下载 1万

commercetools tool system core

原始使用文档
文档目录7 节
  1. Design Document
  2. Design Decisions
  3. Package Components
  4. Component Relationships
  5. Usage Examples
  6. Tool Titles and MCP Annotations
  7. Key Design Patterns

commercetools core MCP tools

This package exposes the commercetools resources in the form of MCP (Model Context Protocol) tools that can be used across multiple MCP projects.

This docs describes the detailed design decisions, steps to integrate the exposed tools into an existing project and various usage examples depending on the project design choice.

Design Document

-- to be added --

Design Decisions

1. Layered Architecture

The package follows a layered architecture pattern with clear separation of concerns:

  • Base Layer (BaseResourceHandler): Generic, API-agnostic handler that provides tool routing, validation, and naming conventions.
  • Platform Layer (CommercetoolsResourceHandler): Uses the factory’s client to build the Platform API root (via createApiBuilderFromCtpClient from @commercetools/platform-sdk). Use for customers, project, orders, etc.
  • Checkout Layer (CheckoutResourceHandler): Uses the same factory client to build the Checkout API root (via createApiBuilderFromCtpClient from @commercetools/checkout-sdk with a checkout base URL). Use for payment-intents, transactions.
  • Resource Layer: Concrete implementations for specific resources (CustomerHandler, PaymentIntentsHandler, etc.).

Rationale: This separation allows the base handler to be reused for any API platform (Stripe, Shopify, etc.). The commercetools layer is split so that resources can use either the Platform API or the Checkout API as needed; both use the same low-level client from the factory.

2. Handler Registration: Decorators or Direct Instantiation

Tool handler classes can be registered in either of two ways:

  • Decorator-based: Apply @ToolHandler() to a class that extends a base handler (e.g. CustomerHandler). When the class is defined, it is registered in a global registry. Retrieve all registered handlers with getDecoratorRegisteredHandlers() and pass them to your MCP server.
  • Direct instantiation: Create handler instances yourself (e.g. new CustomerHandler(), new PaymentIntentsHandler(factory)) and pass that array of instances to your MCP server. No decorator or registry is involved.

You can mix both: use decorators for some handlers and explicitly instantiate others, then combine the arrays when building the server.

Rationale: Decorators enable zero-configuration discovery; direct instantiation gives full control over constructor arguments (e.g. custom IApiClientFactory) and avoids global state.

3. Client and API Root Separation

The low-level client (from @commercetools/ts-client) is created and returned by the factory; API roots (Platform or Checkout) are built inside the handlers. The factory exposes getClient(configuration, authToken); handlers call it and then use createApiBuilderFromCtpClient from the appropriate SDK (platform-sdk or checkout-sdk) to build the root they need.

Rationale: One client instance can back both Platform and Checkout APIs; handlers own which API they use.

4. Dependency Injection

API client factories are injectable, allowing for:

  • Easy testing with mock factories
  • Custom API client implementations
  • Different authentication strategies

Rationale: Improves testability and flexibility while maintaining a clean API.

5. Schema-Based Validation

All tool parameters are validated using Zod schemas defined in the handler metadata.

Rationale: Type-safe parameter validation with clear error messages and automatic TypeScript type inference.

6. Function-Based and Class-Based Support

The architecture supports both:

  • Class-based: Full-featured handlers (e.g. CustomerHandler, PaymentIntentsHandler). Register them via decorators (@ToolHandler() + getDecoratorRegisteredHandlers()) or by direct instantiation (e.g. new CustomerHandler()) and passing the instances to your server.
  • Function-based: Simple function wrappers for quick tool creation (e.g. createCustomerHandler() that returns a handler instance).

Rationale: Provides flexibility for different use cases - complex tools benefit from classes, simple tools can use functions; classes can be registered either through the decorator registry or by direct instantiation.

Package Components

packages/core/
├── src/
│   ├── handlers/
│   │   ├── base.handler.ts          # Generic base handler (API-agnostic)
│   │   ├── commercetools.handler.ts # Platform API handler (builds root from client)
│   │   └── checkout.handler.ts      # Checkout API handler (payment-intents, transactions)
│   ├── decorators/
│   │   └── tool.decorator.ts        # @ToolHandler() decorator
│   ├── resources/
│   │   ├── customer/                # Customer resource handler
│   │   ├── project/                 # Project resource handler
│   │   ├── payment-intents/         # Checkout API resource
│   │   ├── transactions/            # Checkout API resource
│   │   └── ...                      # Other resources
│   └── shared/
│       ├── types/                   # TypeScript interfaces (e.g. IApiClientFactory)
│       ├── client/
│       │   └── client.base.ts       # CommercetoolsAPIClient + ApiClientFactory
│       └── errors/                  # Error handling
└── index.ts                         # Public API exports

Component Relationships

┌────────────────────────────────────────────────────────┐
│                    ToolExecutionContext                │
│  (authToken, configuration, toolName, parameters)      │
└────────────────────┬───────────────────────────────────┘
                     │
                     ▼
┌─────────────────────────────────────────────────────────┐
│              BaseResourceHandler<TConfig>               │
│  • Tool routing & validation                            │
│  • Schema validation                                    │
│  • Tool name generation                                 │
│  • Abstract CRUD methods                                │
└────────────────────┬────────────────────────────────────┘
                     │
                     │ extends
         ┌───────────┴───────────┐
         ▼                       ▼
┌─────────────────────┐  ┌─────────────────────────────┐
│ CommercetoolsResource│  │   CheckoutResourceHandler   │
│      Handler         │  │  • getClient() from factory │
│  • getClient() from  │  │  • getApiRoot() = checkout- │
│    factory           │  │    sdk createApiBuilder…  │
│  • getApiRoot() =    │  │  • payment-intents,         │
│    platform-sdk      │  │    transactions            │
│    createApiBuilder… │  └──────────────┬──────────────┘
│  • customers,        │                 │
│    project, etc.     │                 │ extends
└──────────┬───────────┘                 │
           │ extends                     │
           ▼                             ▼
┌─────────────────────┐  ┌─────────────────────────────┐
│ CustomerHandler /    │  │ PaymentIntentsHandler /     │
│ ProjectHandler /…   │  │ TransactionsHandler         │
└──────────┬───────────┘  └──────────────┬──────────────┘
           │                             │
           └─────────────┬───────────────┘
                         │ registered via
                         ▼
           ┌─────────────────────────────┐
           │     Decorator Registry      │
           │ getDecoratorRegistered…()   │
           └──────────────┬──────────────┘
                          │ used by
                          ▼
           ┌─────────────────────────────┐
           │        MCP Server            │
           └─────────────────────────────┘

Usage Examples

1. Custom Tools Using Base Handler (Class-Based)

Create a custom tool for any API platform:

import { z } from 'zod';
import {
  BaseResourceHandler,
  type ResourceMetadata,
  type ToolExecutionContext,
} from '@commercetools/tools-core';

// Define your custom configuration type
interface CustomApiConfig {
  apiKey: string;
  baseUrl: string;
}

// Create a custom handler
class ProductHandler extends BaseResourceHandler<CustomApiConfig> {
  protected readonly metadata: ResourceMetadata = {
    namespace: 'product',
    description: 'Manage products in custom API',
    toolNamePrefix: 'mcp_custom_',
    schemas: {
      read: z.object({
        id: z.string().describe('Product ID'),
      }),
      create: z.object({
        name: z.string(),
        price: z.number(),
      }),
      update: z.object({
        id: z.string(),
        name: z.string().optional(),
        price: z.number().optional(),
      }),
      delete: z.object({
        id: z.string(),
      }),
    },
  };

  async read(context: ToolExecutionContext<CustomApiConfig>): Promise<unknown> {
    const { id } = context.parameters as { id: string };
    const { apiKey, baseUrl } = context.configuration;

    // Make API call using your custom API client
    const response = await fetch(`${baseUrl}/products/${id}`, {
      headers: { Authorization: `Bearer ${apiKey}` },
    });

    return response.json();
  }

  async create(
    context: ToolExecutionContext<CustomApiConfig>
  ): Promise<unknown> {
    const params = context.parameters as { name: string; price: number };
    const { apiKey, baseUrl } = context.configuration;

    const response = await fetch(`${baseUrl}/products`, {
      method: 'POST',
      headers: {
        Authorization: `Bearer ${apiKey}`,
        'Content-Type': 'application/json',
      },
      body: JSON.stringify(params),
    });

    return response.json();
  }

  async update(
    context: ToolExecutionContext<CustomApiConfig>
  ): Promise<unknown> {
    // Implementation similar to create
    return {};
  }

  async delete(
    context: ToolExecutionContext<CustomApiConfig>
  ): Promise<unknown> {
    // Implementation
    return {};
  }

  // other custom functions can go here
}

// Use in MCP server
import { createMCPServer } from './mcp.server';

const server = createMCPServer(
  'auth-token',
  { apiKey: 'key', baseUrl: 'https://api.example.com' },
  [new ProductHandler()]
);

2. Custom Tools Using Base Handler (Function-Based)

For simpler tools, use a function-based approach:

import { z } from 'zod';
import {
  BaseResourceHandler,
  type ToolExecutionContext,
  type ResourceMetadata,
} from '@commercetools/tools-core';

interface CustomConfig {
  apiKey: string;
}

// Create handler instance with function-based CRUD operations
function createProductHandler(): BaseResourceHandler<CustomConfig> {
  return new (class extends BaseResourceHandler<CustomConfig> {
    protected readonly metadata: ResourceMetadata = {
      namespace: 'product',
      description: 'Manage products',
      toolNamePrefix: 'mcp_custom_',
      schemas: {
        read: z.object({ id: z.string() }),
        create: z.object({ name: z.string(), price: z.number() }),
        update: z.object({ id: z.string(), name: z.string().optional() }),
        delete: z.object({ id: z.string() }),
      },
    };

    async read(context: ToolExecutionContext<CustomConfig>) {
      const { id } = context.parameters as { id: string };
      // Your API call logic
      return { id, name: 'Product' };
    }

    async create(context: ToolExecutionContext<CustomConfig>) {
      return { created: true };
    }

    async update(context: ToolExecutionContext<CustomConfig>) {
      return { updated: true };
    }

    async delete(context: ToolExecutionContext<CustomConfig>) {
      return { deleted: true };
    }
  })();
}

// Use in MCP server
const server = createMCPServer('auth-token', { apiKey: 'key' }, [
  createProductHandler(),
]);

3. commercetools Core Tools (Class-Based with Decorator)

Extend the commercetools handler and use the decorator:

import {
  CustomerHandler as BaseCustomerHandler,
  ToolHandler,
  getDecoratorRegisteredHandlers,
} from '@commercetools/tools-core';

// Simply extend and decorate - automatically registered!
@ToolHandler()
export class CustomerHandler extends BaseCustomerHandler {
  // Optionally override methods for custom behavior
  override getToolDefinition(
    operation: 'read' | 'create' | 'update' | 'delete'
  ) {
    const base = super.getToolDefinition(operation);
    return {
      ...base,
      description: `Custom: ${base.description}`,
    };
  }
}

// In your MCP server setup
import { createMCPServer } from './mcp.server';
import { getDecoratorRegisteredHandlers } from '@commercetools/tools-core';

// Import handlers to trigger decorator registration
import './handlers/customer.handler';
import './handlers/project.handler';

// Get all registered handlers
const handlers = getDecoratorRegisteredHandlers();

const server = createMCPServer(authToken, configuration, handlers);

4. Commercetools Core Tools (Function-Based)

Create commercetools handlers using functions:

import {
  CustomerHandler,
  ProjectHandler,
  BaseResourceHandler,
  type Configuration,
  type IApiClientFactory,
  type ToolExecutionContext,
} from '@commercetools/tools-core';
import { McpServer } from '@modelcontextprotocol/sdk/server/mcp.js';

// Create handler instance with custom factory
function createCustomerHandler(
  apiClientFactory?: IApiClientFactory<Configuration>
) {
  return new CustomerHandler(apiClientFactory);
}

// Create MCP server with function-based handlers
export function createMCPServer(
  authToken: string,
  configuration: Configuration,
  handlers: BaseResourceHandler<Configuration>[] = []
): McpServer {
  const server = new McpServer({
    name: 'commercetools-mcp-server',
    version: '1.0.0',
  });

  // Use function-created handlers
  const customerHandler = createCustomerHandler();
  const projectHandler = new ProjectHandler();

  const allHandlers =
    handlers.length > 0 ? handlers : [customerHandler, projectHandler];

  // Register each handler's tools
  for (const handler of allHandlers) {
    const toolDefinitions = handler.getAllToolDefinitions();

    for (const toolDef of toolDefinitions) {
      server.registerTool(
        toolDef.name,
        {
          title: toolDef.title,
          description: toolDef.description,
          inputSchema: toolDef.inputSchema as any,
          annotations: toolDef.annotations,
        },
        async (args: any): Promise<any> => {
          const context: ToolExecutionContext<Configuration> = {
            authToken,
            configuration,
            toolName: toolDef.name,
            parameters: args,
          };

          try {
            const result = await handler.execute(context);
            return {
              content: [
                {
                  type: 'text' as const,
                  text: JSON.stringify(result),
                },
              ],
            };
          } catch (e) {
            console.error(e);
            throw e;
          }
        }
      );
    }
  }

  return server;
}

// Usage
const server = createMCPServer(process.env.AUTH_TOKEN!, {
  projectKey: 'my-project',
  correlationId: 'my-correlation-id',
  tools: ['customer', 'project'],
});

5. Complete MCP Server Example (Combining Both Approaches)

import { McpServer } from '@modelcontextprotocol/sdk/server/mcp.js';
import {
  BaseResourceHandler,
  CustomerHandler,
  ProjectHandler,
  getDecoratorRegisteredHandlers,
  type ToolExecutionContext,
  type Configuration,
} from '@commercetools/tools-core';

// Function to create MCP server with both decorator and manual handlers
export function createMCPServer(
  authToken: string,
  configuration: Configuration
): McpServer {
  const server = new McpServer({
    name: 'commercetools-mcp-server',
    version: '1.0.0',
  });

  // Get decorator-registered handlers (class-based with @ToolHandler())
  const decoratorHandlers = getDecoratorRegisteredHandlers();

  // Create function-based handlers
  const functionHandlers: BaseResourceHandler<Configuration>[] = [
    new CustomerHandler(),
    new ProjectHandler(),
  ];

  // Combine all handlers
  const allHandlers = [...decoratorHandlers, ...functionHandlers];

  // Register tools from all handlers
  for (const handler of allHandlers) {
    const toolDefinitions = handler.getAllToolDefinitions();

    for (const toolDef of toolDefinitions) {
      server.registerTool(
        toolDef.name,
        {
          title: toolDef.title,
          description: toolDef.description,
          inputSchema: toolDef.inputSchema as any,
          annotations: toolDef.annotations,
        },
        async (args: any) => {
          const context: ToolExecutionContext<Configuration> = {
            authToken,
            configuration,
            toolName: toolDef.name,
            parameters: args,
          };

          try {
            const result = await handler.execute(context);
            return {
              content: [
                {
                  type: 'text' as const,
                  text: JSON.stringify(result, null, 2),
                },
              ],
            };
          } catch (error) {
            return {
              content: [
                {
                  type: 'text' as const,
                  text: `Error: ${
                    error instanceof Error ? error.message : String(error)
                  }`,
                },
              ],
              isError: true,
            };
          }
        }
      );
    }
  }

  return server;
}

Tool Titles and MCP Annotations

Every tool definition carries a human-readable title and a full MCP annotations object (title, readOnlyHint, destructiveHint, openWorldHint) alongside name, description and inputSchema, so an MCP client can tell read_orders from update_orders when deciding what to run without asking the user.

Both are derived from the tool name rather than stored per tool, by src/utils/tool-annotations.ts. A verb table maps the verb of a tool name to its effect on the environment — read, additive, or destructive — and the title and annotations follow from it. A tool added later is annotated automatically, with no second place to update.

Two name shapes are accepted, so the same table serves servers that rename the tools this package defines: verb_resource (read_orders), which is how every tool here is named, and resource.verb (orders.read). Either end of the name is considered, and whichever segment matches a known verb wins.

import {
  deriveToolAnnotations,
  deriveToolAnnotationsOrConservative,
} from '@commercetools/tools-core';

deriveToolAnnotations('read_orders');
// { title: 'Read Orders', readOnlyHint: true, destructiveHint: false, openWorldHint: false }

deriveToolAnnotations('update_orders');
// { title: 'Update Orders', readOnlyHint: false, destructiveHint: true, openWorldHint: false }

// The `resource.verb` shape resolves to the same effect.
deriveToolAnnotations('orders.read');
// { title: 'Orders Read', readOnlyHint: true, destructiveHint: false, openWorldHint: false }

Two entry points, split by call site:

  • deriveToolAnnotations throws on an unrecognised verb. Use it on build paths — schema emitters, code generators — so CI fails rather than publishing a guessed safety hint.
  • deriveToolAnnotationsOrConservative falls back to readOnlyHint: false / destructiveHint: true and reports the fallback through an optional callback so it can be logged. Use it on the serving path, where one unknown tool must not take tools/list down for a whole tenant.

Notes on the classifications:

  • All update_* tools are destructive. commercetools update actions remove line items and overwrite fields rather than only adding.
  • create_* and replicate_carts are additive — they bring a new resource into existence and leave the rest alone.
  • openWorldHint is false everywhere. Each tool acts on a single commercetools project through a scoped token, which is a closed domain in the sense the MCP spec means.
  • idempotentHint is omitted. Writes are guarded by optimistic-concurrency versions, so a repeated call is rejected rather than absorbed; the spec's default of false is the honest answer.
  • writeHint is not in the MCP spec, and is never emitted. The spec expresses a write as readOnlyHint: false.

If you disagree with a classification, VERB_EFFECTS in src/utils/tool-annotations.ts is the only place to change it.

Key Design Patterns

  1. Template Method Pattern: BaseResourceHandler.execute() defines the algorithm structure, while subclasses implement specific CRUD operations.

  2. Strategy Pattern: IApiClientFactory exposes getClient(configuration, authToken) and allows different client creation strategies to be injected (e.g. the default ApiClientFactory that uses CommercetoolsAPIClient).

  3. Client / API root separation: The factory returns only the low-level Client. Handlers obtain that client and build the appropriate API root (Platform or Checkout) using createApiBuilderFromCtpClient from the corresponding SDK.

  4. Decorator Pattern: @ToolHandler() decorator adds registration behavior to handler classes. Handlers can alternatively be registered by direct instantiation (e.g. new CustomerHandler()) without using the decorator or registry.

  5. Factory Pattern: ApiClientFactory creates the Client via CommercetoolsAPIClient; handlers then build Platform or Checkout API roots from that client.

  6. Dependency Injection: Handlers accept an optional IApiClientFactory in their constructor, enabling testability and custom client implementations.

版本与发布记录

@commercetools/tools-core 共发布 28 个版本,首次发布于 2026/01/26;过去 12 个月发布了 28 个版本。

版本发布日期距今
0.7.1latest2026/11/091 天前
0.6.22026/10/1525 天前
0.6.12026/10/1526 天前
0.0.140.0-lts2026/10/1427 天前
0.6.02026/10/1427 天前
0.5.02026/09/301 个月前

关于 @commercetools/tools-core 的常见问题

@commercetools/tools-core 是什么?

commercetools tool system core

如何安装 @commercetools/tools-core?

在项目目录运行 npm install @commercetools/tools-core,或使用 pnpm add / yarn add / bun add。

@commercetools/tools-core 支持 TypeScript 吗?

支持。包内自带 TypeScript 类型声明(package.json 声明了 types 入口),安装后即可获得类型提示,无需再安装 @types 包。

@commercetools/tools-core 支持 ESM 还是 CommonJS?

同时提供 ES Module 与 CommonJS 入口,import 和 require() 都可以使用,打包工具会自动选择合适的版本。

@commercetools/tools-core 需要什么版本的 Node.js?

package.json 的 engines 字段要求 Node.js >=22。版本不符时 npm 默认只给出警告,开启 engine-strict 后会拒绝安装。

@commercetools/tools-core 可以商用吗?

@commercetools/tools-core 使用 UNLICENSED 许可。作者声明为 UNLICENSED,即不授予公开使用许可(与公共领域的 Unlicense 不同)。使用前需获得作者授权。以上为概括,不构成法律意见,请以许可原文为准。

@commercetools/tools-core 的下载量有多少?

根据 npm 官方下载统计,@commercetools/tools-core 在 2026/10/11 – 2026/11/09 这 30 天内被下载 10,306 次,日均约 344 次。下载量会把 CI 构建、镜像同步和作为其他包依赖的安装一并计入,适合横向比较热度,不能直接等同于使用人数。

@commercetools/tools-core 还在维护吗?

最新版本 0.7.1 发布于 2026/11/09(1 天前);至今共发布 28 个版本,其中过去 12 个月发布了 28 个;首次发布于 2026/01/26。发布频率只是参考信号:功能稳定的工具可能很少需要更新,建议结合源码仓库的 issue 和提交记录判断。