@commercetools/tools-core
v0.0.9
Published
commercetools tool system core
Downloads
1,556
Keywords
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): Uses the factory’s client to build the Platform API root (viacreateApiBuilderFromCtpClientfrom@commercetools/platform-sdk). Use for customers, project, orders, etc. - Checkout Layer (
CheckoutResourceHandler): Uses the same factory client to build the Checkout API root (viacreateApiBuilderFromCtpClientfrom@commercetools/checkout-sdkwith 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 withgetDecoratorRegisteredHandlers()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 exportsComponent 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,
{
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',
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,
{
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
Template Method Pattern:
BaseResourceHandler.execute()defines the algorithm structure, while subclasses implement specific CRUD operations.Strategy Pattern:
IApiClientFactoryexposesgetClient(configuration, authToken)and allows different client creation strategies to be injected (e.g. the defaultApiClientFactorythat usesCommercetoolsAPIClient).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
createApiBuilderFromCtpClientfrom the corresponding SDK.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.Factory Pattern:
ApiClientFactorycreates the Client viaCommercetoolsAPIClient; handlers then build Platform or Checkout API roots from that client.Dependency Injection: Handlers accept an optional
IApiClientFactoryin their constructor, enabling testability and custom client implementations.
