#!/usr/bin/env node
/**
* Matrix Pattern MCP Server
* Advanced pattern management and synchronization server for Claude applications
*/
import { Server } from '@modelcontextprotocol/sdk/server/index.js';
import { StdioServerTransport } from '@modelcontextprotocol/sdk/server/stdio.js';
import {
CallToolRequestSchema,
ErrorCode,
ListToolsRequestSchema,
McpError,
} from '@modelcontextprotocol/sdk/types.js';
import fs from 'fs-extra';
import path from 'path';
import { fileURLToPath } from 'url';
import { v4 as uuidv4 } from 'uuid';
import { z } from 'zod';
const __filename = fileURLToPath(import.meta.url);
const __dirname = path.dirname(__filename);
const PROJECT_ROOT = path.dirname(__dirname);
// Configuration paths
const CONFIG_PATH = path.join(PROJECT_ROOT, '.matrix_pattern', 'config.json');
const MATRIX_DIR = path.join(PROJECT_ROOT, '.matrix_pattern', 'matrix');
const METADATA_DIR = path.join(PROJECT_ROOT, '.matrix_pattern', 'metadata');
const HORIZONTALS_DIR = path.join(METADATA_DIR, 'horizontals');
const SYNC_REPORTS_DIR = path.join(METADATA_DIR, 'sync-reports');
// Initialize server
const server = new Server(
{
name: 'matrix-pattern-mcp-server',
version: '1.0.0',
},
{
capabilities: {
tools: {},
},
}
);
// Load configuration
let config = {};
try {
config = await fs.readJson(CONFIG_PATH);
} catch (error) {
console.error('Warning: Could not load configuration file:', error.message);
config = {
matrix_pattern: {
version: '1.0.0',
initialized: false,
config: {
max_patterns: 1000,
auto_cleanup: true
},
directories: {
matrix: '.matrix_pattern/matrix',
metadata: '.matrix_pattern/metadata',
horizontals: '.matrix_pattern/metadata/horizontals',
sync_reports: '.matrix_pattern/metadata/sync-reports'
}
}
};
}
// Validation schemas
const CellIdSchema = z.object({
row: z.string().min(1),
column: z.string().min(1)
});
const CellDataSchema = z.object({
content: z.string(),
metadata: z.record(z.any()).optional()
});
const CreateCellSchema = z.object({
cellId: CellIdSchema,
data: CellDataSchema
});
const ReadCellSchema = z.object({
cellId: CellIdSchema
});
const SyncHorizontalSchema = z.object({
sourceRow: z.string().min(1),
targetRow: z.string().min(1),
columns: z.array(z.string()).optional()
});
const SyncVerticalSchema = z.object({
column: z.string().min(1),
fromRow: z.string().min(1),
toRow: z.string().min(1)
});
const ListVerticalsSchema = z.object({
column: z.string().min(1)
});
const ListHorizontalsSchema = z.object({
row: z.string().min(1)
});
const ReadHorizontalInstructionsSchema = z.object({
row: z.string().min(1)
});
// Utility functions
async function ensureDirectories() {
const dirs = [MATRIX_DIR, METADATA_DIR, HORIZONTALS_DIR, SYNC_REPORTS_DIR];
for (const dir of dirs) {
await fs.ensureDir(dir);
}
}
function getCellPath(cellId) {
return path.join(MATRIX_DIR, `${cellId.row}_${cellId.column}.json`);
}
function getHorizontalMetadataPath(row) {
return path.join(HORIZONTALS_DIR, `${row}.json`);
}
async function cellExists(cellId) {
return await fs.pathExists(getCellPath(cellId));
}
async function createSyncReport(type, operation, details) {
const timestamp = new Date().toISOString();
const reportId = uuidv4();
const report = {
id: reportId,
type,
operation,
timestamp,
details,
status: 'completed'
};
const reportDir = path.join(SYNC_REPORTS_DIR, type);
await fs.ensureDir(reportDir);
const reportPath = path.join(reportDir, `${reportId}.json`);
await fs.writeJson(reportPath, report, { spaces: 2 });
return report;
}
// Tool implementations
async function handleMatrixCreateCell(args) {
try {
const { cellId, data } = CreateCellSchema.parse(args);
await ensureDirectories();
// Check if cell already exists (forward-only constraint)
if (await cellExists(cellId)) {
throw new McpError(
ErrorCode.InvalidRequest,
`Cell ${cellId.row}:${cellId.column} already exists. Matrix Pattern System enforces forward-only constraint.`
);
}
// Create cell data with metadata
const cellData = {
id: cellId,
content: data.content,
metadata: {
...data.metadata,
created: new Date().toISOString(),
version: 1,
row: cellId.row,
column: cellId.column
}
};
const cellPath = getCellPath(cellId);
await fs.writeJson(cellPath, cellData, { spaces: 2 });
return {
content: [
{
type: 'text',
text: `Successfully created cell ${cellId.row}:${cellId.column}`,
},
],
};
} catch (error) {
if (error instanceof z.ZodError) {
throw new McpError(ErrorCode.InvalidParams, `Validation error: ${error.message}`);
}
throw new McpError(ErrorCode.InternalError, `Failed to create cell: ${error.message}`);
}
}
async function handleMatrixReadCell(args) {
try {
const { cellId } = ReadCellSchema.parse(args);
const cellPath = getCellPath(cellId);
if (!await fs.pathExists(cellPath)) {
throw new McpError(
ErrorCode.InvalidRequest,
`Cell ${cellId.row}:${cellId.column} does not exist`
);
}
const cellData = await fs.readJson(cellPath);
return {
content: [
{
type: 'text',
text: JSON.stringify(cellData, null, 2),
},
],
};
} catch (error) {
if (error instanceof z.ZodError) {
throw new McpError(ErrorCode.InvalidParams, `Validation error: ${error.message}`);
}
throw new McpError(ErrorCode.InternalError, `Failed to read cell: ${error.message}`);
}
}
async function handleMatrixSyncHorizontal(args) {
try {
const { sourceRow, targetRow, columns } = SyncHorizontalSchema.parse(args);
await ensureDirectories();
// Get all cells in source row
const matrixFiles = await fs.readdir(MATRIX_DIR);
const sourceCells = matrixFiles
.filter(file => file.startsWith(`${sourceRow}_`) && file.endsWith('.json'))
.map(file => {
const match = file.match(/^(.+)_(.+)\.json$/);
return match ? { row: match[1], column: match[2] } : null;
})
.filter(Boolean);
if (sourceCells.length === 0) {
throw new McpError(
ErrorCode.InvalidRequest,
`No cells found in source row ${sourceRow}`
);
}
// Filter by columns if specified
const cellsToSync = columns
? sourceCells.filter(cell => columns.includes(cell.column))
: sourceCells;
const syncResults = [];
for (const cellId of cellsToSync) {
const sourcePath = getCellPath(cellId);
const targetCellId = { row: targetRow, column: cellId.column };
const targetPath = getCellPath(targetCellId);
// Skip if target cell already exists (forward-only constraint)
if (await fs.pathExists(targetPath)) {
syncResults.push({
cell: `${targetRow}:${cellId.column}`,
status: 'skipped',
reason: 'Cell already exists (forward-only constraint)'
});
continue;
}
try {
const sourceData = await fs.readJson(sourcePath);
const targetData = {
...sourceData,
id: targetCellId,
metadata: {
...sourceData.metadata,
row: targetRow,
synced_from: `${sourceRow}:${cellId.column}`,
synced_at: new Date().toISOString()
}
};
await fs.writeJson(targetPath, targetData, { spaces: 2 });
syncResults.push({
cell: `${targetRow}:${cellId.column}`,
status: 'synced',
source: `${sourceRow}:${cellId.column}`
});
} catch (cellError) {
syncResults.push({
cell: `${targetRow}:${cellId.column}`,
status: 'error',
error: cellError.message
});
}
}
// Create sync report
await createSyncReport('horizontal', 'sync', {
sourceRow,
targetRow,
columns: columns || 'all',
results: syncResults
});
return {
content: [
{
type: 'text',
text: `Horizontal sync completed from ${sourceRow} to ${targetRow}. Results: ${JSON.stringify(syncResults, null, 2)}`,
},
],
};
} catch (error) {
if (error instanceof z.ZodError) {
throw new McpError(ErrorCode.InvalidParams, `Validation error: ${error.message}`);
}
throw new McpError(ErrorCode.InternalError, `Failed to sync horizontal: ${error.message}`);
}
}
async function handleMatrixSyncVertical(args) {
try {
const { column, fromRow, toRow } = SyncVerticalSchema.parse(args);
await ensureDirectories();
const sourceCellId = { row: fromRow, column };
const targetCellId = { row: toRow, column };
const sourcePath = getCellPath(sourceCellId);
const targetPath = getCellPath(targetCellId);
if (!await fs.pathExists(sourcePath)) {
throw new McpError(
ErrorCode.InvalidRequest,
`Source cell ${fromRow}:${column} does not exist`
);
}
// Skip if target cell already exists (forward-only constraint)
if (await fs.pathExists(targetPath)) {
await createSyncReport('vertical', 'sync', {
column,
fromRow,
toRow,
status: 'skipped',
reason: 'Target cell already exists (forward-only constraint)'
});
return {
content: [
{
type: 'text',
text: `Vertical sync skipped: Target cell ${toRow}:${column} already exists (forward-only constraint)`,
},
],
};
}
const sourceData = await fs.readJson(sourcePath);
const targetData = {
...sourceData,
id: targetCellId,
metadata: {
...sourceData.metadata,
row: toRow,
synced_from: `${fromRow}:${column}`,
synced_at: new Date().toISOString(),
sync_type: 'vertical'
}
};
await fs.writeJson(targetPath, targetData, { spaces: 2 });
// Create sync report
await createSyncReport('vertical', 'sync', {
column,
fromRow,
toRow,
status: 'completed'
});
return {
content: [
{
type: 'text',
text: `Successfully synced cell from ${fromRow}:${column} to ${toRow}:${column}`,
},
],
};
} catch (error) {
if (error instanceof z.ZodError) {
throw new McpError(ErrorCode.InvalidParams, `Validation error: ${error.message}`);
}
throw new McpError(ErrorCode.InternalError, `Failed to sync vertical: ${error.message}`);
}
}
async function handleMatrixListVerticals(args) {
try {
const { column } = ListVerticalsSchema.parse(args);
// Get all cells in the specified column
const matrixFiles = await fs.readdir(MATRIX_DIR);
const columnCells = matrixFiles
.filter(file => file.endsWith(`_${column}.json`))
.map(file => {
const match = file.match(/^(.+)_(.+)\.json$/);
return match ? match[1] : null;
})
.filter(Boolean)
.sort();
const cellDetails = [];
for (const row of columnCells) {
try {
const cellPath = getCellPath({ row, column });
const cellData = await fs.readJson(cellPath);
cellDetails.push({
row,
column,
created: cellData.metadata?.created,
synced_from: cellData.metadata?.synced_from
});
} catch (error) {
cellDetails.push({
row,
column,
error: `Failed to read cell: ${error.message}`
});
}
}
return {
content: [
{
type: 'text',
text: `Vertical cells in column ${column}:\n${JSON.stringify(cellDetails, null, 2)}`,
},
],
};
} catch (error) {
if (error instanceof z.ZodError) {
throw new McpError(ErrorCode.InvalidParams, `Validation error: ${error.message}`);
}
throw new McpError(ErrorCode.InternalError, `Failed to list verticals: ${error.message}`);
}
}
async function handleMatrixListHorizontals(args) {
try {
const { row } = ListHorizontalsSchema.parse(args);
// Get all cells in the specified row
const matrixFiles = await fs.readdir(MATRIX_DIR);
const rowCells = matrixFiles
.filter(file => file.startsWith(`${row}_`) && file.endsWith('.json'))
.map(file => {
const match = file.match(/^(.+)_(.+)\.json$/);
return match ? match[2] : null;
})
.filter(Boolean)
.sort();
const cellDetails = [];
for (const column of rowCells) {
try {
const cellPath = getCellPath({ row, column });
const cellData = await fs.readJson(cellPath);
cellDetails.push({
row,
column,
created: cellData.metadata?.created,
synced_from: cellData.metadata?.synced_from
});
} catch (error) {
cellDetails.push({
row,
column,
error: `Failed to read cell: ${error.message}`
});
}
}
return {
content: [
{
type: 'text',
text: `Horizontal cells in row ${row}:\n${JSON.stringify(cellDetails, null, 2)}`,
},
],
};
} catch (error) {
if (error instanceof z.ZodError) {
throw new McpError(ErrorCode.InvalidParams, `Validation error: ${error.message}`);
}
throw new McpError(ErrorCode.InternalError, `Failed to list horizontals: ${error.message}`);
}
}
async function handleMatrixReadHorizontalInstructions(args) {
try {
const { row } = ReadHorizontalInstructionsSchema.parse(args);
const metadataPath = getHorizontalMetadataPath(row);
if (!await fs.pathExists(metadataPath)) {
// Return default instructions if no custom metadata exists
const defaultInstructions = {
row,
instructions: `Default instructions for horizontal row ${row}`,
sync_strategy: 'merge',
conflict_resolution: config.matrix_pattern?.sync?.horizontal?.conflict_resolution || 'manual',
last_updated: new Date().toISOString()
};
return {
content: [
{
type: 'text',
text: JSON.stringify(defaultInstructions, null, 2),
},
],
};
}
const instructions = await fs.readJson(metadataPath);
return {
content: [
{
type: 'text',
text: JSON.stringify(instructions, null, 2),
},
],
};
} catch (error) {
if (error instanceof z.ZodError) {
throw new McpError(ErrorCode.InvalidParams, `Validation error: ${error.message}`);
}
throw new McpError(ErrorCode.InternalError, `Failed to read horizontal instructions: ${error.message}`);
}
}
// Register tools
server.setRequestHandler(ListToolsRequestSchema, async () => {
return {
tools: [
{
name: 'matrix_create_cell',
description: 'Create a new cell in the matrix pattern system',
inputSchema: {
type: 'object',
properties: {
cellId: {
type: 'object',
properties: {
row: { type: 'string', description: 'Row identifier' },
column: { type: 'string', description: 'Column identifier' }
},
required: ['row', 'column'],
description: 'Cell coordinates'
},
data: {
type: 'object',
properties: {
content: { type: 'string', description: 'Cell content' },
metadata: { type: 'object', description: 'Optional metadata' }
},
required: ['content'],
description: 'Cell data'
}
},
required: ['cellId', 'data']
}
},
{
name: 'matrix_read_cell',
description: 'Read a cell from the matrix pattern system',
inputSchema: {
type: 'object',
properties: {
cellId: {
type: 'object',
properties: {
row: { type: 'string', description: 'Row identifier' },
column: { type: 'string', description: 'Column identifier' }
},
required: ['row', 'column'],
description: 'Cell coordinates'
}
},
required: ['cellId']
}
},
{
name: 'matrix_sync_horizontal',
description: 'Synchronize patterns horizontally between rows',
inputSchema: {
type: 'object',
properties: {
sourceRow: { type: 'string', description: 'Source row identifier' },
targetRow: { type: 'string', description: 'Target row identifier' },
columns: {
type: 'array',
items: { type: 'string' },
description: 'Optional: specific columns to sync'
}
},
required: ['sourceRow', 'targetRow']
}
},
{
name: 'matrix_sync_vertical',
description: 'Synchronize patterns vertically between rows in a column',
inputSchema: {
type: 'object',
properties: {
column: { type: 'string', description: 'Column identifier' },
fromRow: { type: 'string', description: 'Source row identifier' },
toRow: { type: 'string', description: 'Target row identifier' }
},
required: ['column', 'fromRow', 'toRow']
}
},
{
name: 'matrix_list_verticals',
description: 'List all cells in a vertical column',
inputSchema: {
type: 'object',
properties: {
column: { type: 'string', description: 'Column identifier' }
},
required: ['column']
}
},
{
name: 'matrix_list_horizontals',
description: 'List all cells in a horizontal row',
inputSchema: {
type: 'object',
properties: {
row: { type: 'string', description: 'Row identifier' }
},
required: ['row']
}
},
{
name: 'matrix_read_horizontal_instructions',
description: 'Read horizontal synchronization instructions for a row',
inputSchema: {
type: 'object',
properties: {
row: { type: 'string', description: 'Row identifier' }
},
required: ['row']
}
}
]
};
});
// Register tool handlers
server.setRequestHandler(CallToolRequestSchema, async (request) => {
const { name, arguments: args } = request.params;
try {
switch (name) {
case 'matrix_create_cell':
return await handleMatrixCreateCell(args);
case 'matrix_read_cell':
return await handleMatrixReadCell(args);
case 'matrix_sync_horizontal':
return await handleMatrixSyncHorizontal(args);
case 'matrix_sync_vertical':
return await handleMatrixSyncVertical(args);
case 'matrix_list_verticals':
return await handleMatrixListVerticals(args);
case 'matrix_list_horizontals':
return await handleMatrixListHorizontals(args);
case 'matrix_read_horizontal_instructions':
return await handleMatrixReadHorizontalInstructions(args);
default:
throw new McpError(ErrorCode.MethodNotFound, `Unknown tool: ${name}`);
}
} catch (error) {
if (error instanceof McpError) {
throw error;
}
throw new McpError(ErrorCode.InternalError, `Tool execution failed: ${error.message}`);
}
});
// Start server
async function main() {
try {
await ensureDirectories();
const transport = new StdioServerTransport();
await server.connect(transport);
console.error('Matrix Pattern MCP Server started successfully');
} catch (error) {
console.error('Failed to start Matrix Pattern MCP Server:', error);
process.exit(1);
}
}
// Handle process termination
process.on('SIGINT', async () => {
console.error('Received SIGINT, shutting down gracefully...');
await server.close();
process.exit(0);
});
process.on('SIGTERM', async () => {
console.error('Received SIGTERM, shutting down gracefully...');
await server.close();
process.exit(0);
});
// CLI mode detection - only start server if not in CLI mode
const isCliMode = process.env.CLI_MODE === 'true' ||
process.argv.some(arg => arg.includes('cli.js')) ||
process.argv[1]?.includes('matrix-pattern');
if (!isCliMode && import.meta.url === `file://${process.argv[1]}`) {
main().catch((error) => {
console.error('Fatal error:', error);
process.exit(1);
});
}
// Export server and main function for CLI usage
export { server, main, config };