Skip to content

Latest commit

 

History

History
468 lines (359 loc) · 9.32 KB

File metadata and controls

468 lines (359 loc) · 9.32 KB

Architecture Documentation

Project Structure

The MCP Server for Creem.io is organized into modular components for maintainability and scalability.

mcp-server-creem/
├── src/
│   ├── index.ts                 # Main entry point (40 lines)
│   ├── server.ts                # Server configuration (55 lines)
│   ├── client.ts                # Creem API client (83 lines)
│   ├── types.ts                 # TypeScript definitions (183 lines)
│   └── tools/
│       ├── definitions.ts       # Tool schemas (431 lines)
│       └── handlers.ts          # Tool implementations (322 lines)
├── build/                       # Compiled JavaScript (generated)
├── node_modules/                # Dependencies
└── [documentation files]

Module Breakdown

1. Entry Point (index.ts)

Purpose: Application initialization and startup

Responsibilities:

  • Read environment variables
  • Validate API key
  • Initialize Creem client
  • Start MCP server

Key Functions:

  • main() - Main entry point

Dependencies:

  • client.ts - For API client
  • server.ts - For server creation

2. Server Configuration (server.ts)

Purpose: MCP server setup and request handling

Responsibilities:

  • Create MCP server instance
  • Register request handlers
  • Connect to transport layer

Key Functions:

  • createServer(creem) - Initialize server with handlers
  • startServer(server, testMode, baseURL) - Start and connect server

Dependencies:

  • @modelcontextprotocol/sdk - MCP framework
  • tools/definitions.ts - Tool schemas
  • tools/handlers.ts - Tool implementations

3. API Client (client.ts)

Purpose: HTTP communication with Creem API

Responsibilities:

  • Manage API authentication
  • Handle HTTP requests (GET, POST, DELETE)
  • Error interception and formatting
  • Base URL management (test/production)

Key Class:

class CreemClient {
  constructor(config: CreemConfig)
  get<T>(endpoint, params?): Promise<T>
  post<T>(endpoint, data?): Promise<T>
  delete<T>(endpoint): Promise<T>
  getBaseURL(): string
  isTestMode(): boolean
}

Dependencies:

  • axios - HTTP client
  • types.ts - Type definitions

4. Type Definitions (types.ts)

Purpose: TypeScript type safety

Key Types:

  • CreemConfig - Client configuration
  • Product - Product entity
  • Customer - Customer entity
  • Subscription - Subscription entity
  • Checkout - Checkout session
  • License - License key
  • Discount - Discount code
  • Transaction - Payment transaction
  • Request/Response types for API operations

No Dependencies

5. Tool Definitions (tools/definitions.ts)

Purpose: MCP tool schemas and metadata

Structure:

export const tools: Tool[] = [
  {
    name: 'tool_name',
    description: 'What the tool does',
    inputSchema: {
      type: 'object',
      properties: { /* parameters */ },
      required: [ /* required params */ ]
    }
  },
  // ... more tools
];

Contains:

  • 20+ tool definitions
  • Input schema for each tool
  • Parameter descriptions
  • Validation rules

Dependencies:

  • @modelcontextprotocol/sdk/types - Tool type definition

6. Tool Handlers (tools/handlers.ts)

Purpose: Business logic for each tool

Key Function:

handleToolCall(name, args, creem): Promise<ToolResponse>

Implementation Pattern:

async function handleXyz(args, creem) {
  // 1. Extract and validate parameters
  // 2. Make API call(s)
  // 3. Format response
  // 4. Return formatted data
}

Handlers for:

  • Product operations (3 handlers)
  • Checkout operations (2 handlers)
  • Customer operations (3 handlers)
  • Subscription operations (4 handlers)
  • License operations (3 handlers)
  • Discount operations (3 handlers)
  • Transaction operations (1 handler)

Dependencies:

  • client.ts - API communication
  • types.ts - Type definitions

Data Flow

Tool Execution Flow

User Request
    ↓
Claude/AI Assistant
    ↓
MCP Protocol
    ↓
server.ts (CallToolRequestSchema handler)
    ↓
tools/handlers.ts (handleToolCall)
    ↓
Specific handler function
    ↓
client.ts (HTTP request)
    ↓
Creem API (https://api.creem.io)
    ↓
Response back through chain
    ↓
User receives formatted result

Example: Creating a Product

// 1. User asks Claude to create a product
"Create a product called Pro Plan for $29/month"

// 2. Claude calls the tool
{
  name: "create_product",
  arguments: {
    name: "Pro Plan",
    price: 2900,
    billing_type: "recurring",
    billing_period: "every-month"
  }
}

// 3. Server routes to handler
server.ts  handleToolCall("create_product", args, creem)

// 4. Handler executes
handlers.ts  handleCreateProduct(args, creem)

// 5. API call
client.ts  post("/v1/products", productData)

// 6. Response formatted and returned
{
  content: [{
    type: "text",
    text: JSON.stringify(product, null, 2)
  }]
}

Error Handling

Error Flow

Error occurs
    ↓
Caught by handler or client
    ↓
formatError(error) in handlers.ts
    ↓
Returned with isError: true
    ↓
User sees error message

Error Types

  1. Validation Errors - Invalid parameters
  2. API Errors - Creem API responses (401, 404, etc.)
  3. Network Errors - Connection failures
  4. Unknown Tool Errors - Tool not found

Configuration

Environment Variables

CREEM_API_KEY     // Required - API authentication
CREEM_TEST_MODE   // Optional - "true" for test mode

Mode Switching

// Test Mode
baseURL = "https://test-api.creem.io"

// Production Mode
baseURL = "https://api.creem.io"

Extension Points

Adding a New Tool

  1. Add schema to tools/definitions.ts:
{
  name: 'new_tool',
  description: 'Tool description',
  inputSchema: { /* schema */ }
}
  1. Add handler to tools/handlers.ts:
async function handleNewTool(args, creem) {
  // Implementation
}
  1. Add case in handleToolCall switch:
case 'new_tool':
  return await handleNewTool(args, creem);

Adding a New API Method

Add to client.ts:

async patch<T>(endpoint: string, data?: any): Promise<T> {
  const response = await this.client.patch<T>(endpoint, data);
  return response.data;
}

Adding New Types

Add to types.ts:

export interface NewEntity {
  id: string;
  // ... fields
}

Testing Strategy

Manual Testing

  1. Set CREEM_TEST_MODE=true
  2. Use test API key
  3. Build: npm run build
  4. Configure Claude Desktop
  5. Test each tool

Test Scenarios

  • Product creation and retrieval
  • Checkout session generation
  • Subscription management
  • License activation/validation
  • Error handling

Performance Considerations

Response Times

  • Typical API call: < 500ms
  • Pagination for large lists
  • Async operations throughout

Memory Usage

  • Minimal footprint
  • No data caching
  • Stateless operations

Security

API Key Protection

  • Stored in environment variables
  • Never logged or exposed
  • HTTPS for all communications

Request Validation

  • Input schemas validate parameters
  • Type safety via TypeScript
  • Error messages sanitized

Future Improvements

Potential Enhancements

  1. Caching Layer - Cache product/customer data
  2. Batch Operations - Multiple operations in one call
  3. Webhook Tools - Manage webhooks via tools
  4. Analytics - Usage tracking and reporting
  5. Rate Limiting - Client-side rate limit handling

Code Quality

  • Unit tests for handlers
  • Integration tests with Creem API
  • Code coverage metrics
  • Linting and formatting

Dependencies

Production Dependencies

{
  "@modelcontextprotocol/sdk": "^1.0.4",
  "axios": "^1.7.2",
  "zod": "^3.23.8"
}

Development Dependencies

{
  "@types/node": "^22.10.2",
  "typescript": "^5.7.2"
}

Build Process

Compilation

npm run build

Process:

  1. TypeScript compiler reads tsconfig.json
  2. Compiles src/**/*.ts to build/**/*.js
  3. Generates .d.ts declaration files
  4. Creates source maps

Output Structure

build/
├── index.js              # Entry point (executable)
├── index.d.ts            # Type declarations
├── server.js
├── server.d.ts
├── client.js
├── client.d.ts
├── types.js
├── types.d.ts
└── tools/
    ├── definitions.js
    ├── definitions.d.ts
    ├── handlers.js
    └── handlers.d.ts

Maintenance

Code Organization Principles

  1. Separation of Concerns - Each module has one responsibility
  2. DRY (Don't Repeat Yourself) - Shared logic in helpers
  3. Type Safety - Full TypeScript coverage
  4. Modularity - Easy to add/modify tools
  5. Documentation - Inline comments and external docs

Version Control

  • Semantic versioning (MAJOR.MINOR.PATCH)
  • CHANGELOG.md for release notes
  • Git tags for releases

Troubleshooting

Common Issues

  1. Build Failures - Check TypeScript version
  2. API Errors - Verify API key and mode
  3. Tool Not Found - Check tool name matches definition
  4. Type Errors - Update type definitions

Debug Mode

# Run with debugging
npm run dev

# Check server output
console.error messages show mode and URL

Last Updated: November 10, 2025
Version: 1.0.0