npm package discovery and stats viewer.

Discover Tips

  • General search

    [free text search, go nuts!]

  • Package details

    pkg:[package-name]

  • User packages

    @[username]

Sponsor

Optimize Toolset

I’ve always been into building performant and accessible sites, but lately I’ve been taking it extremely seriously. So much so that I’ve been building a tool to help me optimize and monitor the sites that I build to make sure that I’m making an attempt to offer the best experience to those who visit them. If you’re into performant, accessible and SEO friendly sites, you might like it too! You can check it out at Optimize Toolset.

About

Hi, 👋, I’m Ryan Hefner  and I built this site for me, and you! The goal of this site was to provide an easy way for me to check the stats on my npm packages, both for prioritizing issues and updates, and to give me a little kick in the pants to keep up on stuff.

As I was building it, I realized that I was actually using the tool to build the tool, and figured I might as well put this out there and hopefully others will find it to be a fast and useful way to search and browse npm packages as I have.

If you’re interested in other things I’m working on, follow me on Twitter or check out the open source projects I’ve been publishing on GitHub.

I am also working on a Twitter bot for this site to tweet the most popular, newest, random packages from npm. Please follow that account now and it will start sending out packages soon–ish.

Open Software & Tools

This site wouldn’t be possible without the immense generosity and tireless efforts from the people who make contributions to the world and share their work via open source initiatives. Thank you 🙏

© 2026 – Pkg Stats / Ryan Hefner

@commercetools/tools-core

v0.0.2

Published

commercetools tool system core

Readme

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): commercetools-specific handler that adds API client management
  • Resource Layer: Concrete implementations for specific resources (Customer, Project, etc.)

Rationale: This separation allows the base handler to be reused for any API platform (Stripe, Shopify, etc.), while the commercetools layer provides platform-specific functionality.

2. Decorator-Based Discovery

Handlers can be automatically discovered using the @ToolHandler() decorator, which registers them in a global registry when the class is defined.

Rationale: Enables zero-configuration tool discovery, making it easy to add new tools without manual registration.

3. 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.

4. 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.

5. Function-Based and Class-Based Support

The architecture supports both:

  • Class-based: Full-featured handlers with inheritance and decorators
  • Function-based: Simple function wrappers for quick tool creation

Rationale: Provides flexibility for different use cases - complex tools benefit from classes, simple tools can use functions.

Package Components

packages/core/
├── src/
│   ├── handlers/
│   │   ├── base.handler.ts          # Generic base handler (API-agnostic)
│   │   └── commercetools.handler.ts # commercetools-specific handler
│   ├── decorators/
│   │   └── tool.decorator.ts        # @ToolHandler() decorator
│   ├── resources/
│   │   ├── customer/                # Customer resource handler
│   │   └── project/                 # Project resource handler
│   └── shared/
│       ├── types/                   # TypeScript interfaces
│       ├── client/                  # API client factories
│       └── 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
                     ▼
┌─────────────────────────────────────────────────────────┐
│         CommercetoolsResourceHandler                    │
│  • API client factory injection                         │
│  • getApiRoot() helper                                  │
│  • commercetools-specific configuration                 │
└────────────────────┬────────────────────────────────────┘
                     │
                     │ extends
                     ▼
┌─────────────────────────────────────────────────────────┐
│              CustomerHandler / ProjectHandler           │
│  • Resource-specific CRUD implementation                │
│  • Resource metadata & schemas                          │
│  • @ToolHandler() decorator                             │
└────────────────────┬────────────────────────────────────┘
                     │
                     │ registered via
                     ▼
┌─────────────────────────────────────────────────────────┐
│              Decorator Registry                         │
│  • getDecoratorRegisteredHandlers()                     │
└────────────────────┬────────────────────────────────────┘
                     │
                     │ used by
                     ▼
┌─────────────────────────────────────────────────────────┐
│                    MCP Server                           │
│  • Tool registration                                    │
│  • Request handling                                     │
└─────────────────────────────────────────────────────────┘

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,
        {
          description: toolDef.description,
          inputSchema: toolDef.inputSchema as any,
        },
        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',
  allowedTools: ['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,
        {
          description: toolDef.description,
          inputSchema: toolDef.inputSchema as any,
        },
        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;
}

Key Design Patterns

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

  2. Strategy Pattern: IApiClientFactory allows different API client creation strategies to be injected.

  3. Decorator Pattern: @ToolHandler() decorator adds registration behavior to handler classes.

  4. Factory Pattern: ApiClientFactory creates API clients based on configuration.

  5. Dependency Injection: Handlers accept factories in constructors, enabling testability and flexibility.