#
tokens: 16576/50000 16/16 files
lines: off (toggle) GitHub
raw markdown copy
# Directory Structure

```
├── .gitignore
├── package-lock.json
├── package.json
├── README.md
├── src
│   ├── index.ts
│   ├── mcp
│   │   └── memoryBankMcp.ts
│   ├── templates
│   │   ├── .byterules
│   │   ├── activeContext.md
│   │   ├── productContext.md
│   │   ├── progress.md
│   │   ├── projectbrief.md
│   │   ├── systemPatterns.md
│   │   └── techContext.md
│   └── utils
│       ├── cursorRulesGenerator.ts
│       ├── fileManager.ts
│       └── gemini.ts
└── tsconfig.json
```

# Files

--------------------------------------------------------------------------------
/.gitignore:
--------------------------------------------------------------------------------

```
# Node.js
node_modules/
npm-debug.log
yarn-debug.log
yarn-error.log

# Derleme ve dağıtım
dist/
build/
*.tsbuildinfo

# Çevre değişkenleri
.env
.env.local
.env.development.local
.env.test.local
.env.production.local

# Memory Bank verileri
memory-bank/
memory-bank-export/
memory-bank-export.json

# Editör ve IDE
.vscode/
.idea/
*.swp
*.swo

# İşletim sistemi
.DS_Store
Thumbs.db

# Log dosyaları
logs/
*.log
npm-debug.log*
yarn-debug.log*
yarn-error.log* 
```

--------------------------------------------------------------------------------
/src/templates/.byterules:
--------------------------------------------------------------------------------

```
# Memory Bank Document Orchestration Rules

## Document Types and Purposes

### 1. Project Brief (projectbrief.md)
- **Purpose**: Acts as the project's foundation document defining key objectives
- **When to Update**: At project initiation and when scope changes
- **Structure**:
  - Project Vision & Goals
  - Key Stakeholders
  - Success Metrics
  - Constraints & Limitations
  - Timeline Overview
- **Commands**:
  - `update_document projectbrief` - Update project brief details
  - `query_memory_bank "project goals"` - Find project goal information

### 2. Product Context (productContext.md)
- **Purpose**: Details product functionality, user experience, and market position
- **When to Update**: When features change or market requirements shift
- **Structure**:
  - User Personas
  - Feature List & Priorities
  - User Stories
  - Competitive Analysis
  - Product Roadmap
- **Commands**:
  - `update_document productContext` - Update product information
  - `query_memory_bank "features"` - Find feature-related information

### 3. System Patterns (systemPatterns.md)
- **Purpose**: Documents system architecture and design decisions
- **When to Update**: When architectural decisions are made or changed
- **Structure**:
  - System Architecture
  - Component Diagrams
  - Design Patterns Used
  - Integration Points
  - Data Flow
- **Commands**:
  - `update_document systemPatterns` - Update system architecture information
  - `query_memory_bank "architecture"` - Find architecture information

### 4. Tech Context (techContext.md)
- **Purpose**: Technical details, stack choices, and tooling decisions
- **When to Update**: When technology decisions are made or changed
- **Structure**:
  - Technology Stack
  - Development Environment
  - Deployment Process
  - Performance Considerations
  - Technical Debt
- **Commands**:
  - `update_document techContext` - Update technology information
  - `query_memory_bank "stack"` - Find technology stack information

### 5. Active Context (activeContext.md)
- **Purpose**: Current tasks, open questions, and active development
- **When to Update**: Daily or when switching focus areas
- **Structure**:
  - Current Sprint Goals
  - Active Tasks
  - Blockers & Challenges
  - Decisions Needed
  - Next Actions
- **Commands**:
  - `update_document activeContext` - Update current work information
  - `query_memory_bank "current tasks"` - Find information about active work

### 6. Progress (progress.md)
- **Purpose**: Progress tracking and milestone documentation
- **When to Update**: After completing tasks or reaching milestones
- **Structure**:
  - Milestones Achieved
  - Current Progress Status
  - Sprint/Cycle History
  - Learnings & Adjustments
  - Next Milestones
- **Commands**:
  - `update_document progress` - Update project progress information
  - `query_memory_bank "milestone"` - Find milestone information

## Document Workflow Processes

### Project Initialization
1. Create project brief with clear goals
2. Define product context based on brief
3. Establish initial system patterns
4. Document technology decisions
5. Set up initial active context and progress tracking

### Feature Development Cycle
1. Update active context with new feature details
2. Reference system patterns for implementation guidance
3. Document technical decisions in tech context
4. Update progress when feature is completed
5. Ensure product context reflects new capabilities

### Project Review Process
1. Review progress against project brief goals
2. Validate system patterns match implementation
3. Update product context with feedback/learnings
4. Document technical challenges in tech context
5. Set new goals in active context

## Best Practices

### Document Maintenance
- Keep documents concise and focused
- Use markdown formatting for readability
- Include diagrams where appropriate (store in resources/)
- Link between documents when referencing related content
- Update documents regularly based on the workflow process

### Collaboration Guidelines
- Review document changes with team members
- Hold regular sync meetings to update active context
- Use version control for tracking document history
- Maintain changelog entries in progress.md
- Cross-reference documents to maintain consistency

## Command Reference
- `initialize_memory_bank` - Create a new Memory Bank structure
- `update_document <docType>` - Update specific document content
- `query_memory_bank <query>` - Search across all documents
- `export_memory_bank` - Export current Memory Bank state

## Document Integration Flow
Project Brief → Product Context → System Patterns → Tech Context → Active Context → Progress

Follow this integration flow to ensure proper document orchestration and maintain project coherence.

```

--------------------------------------------------------------------------------
/README.md:
--------------------------------------------------------------------------------

```markdown
# Memory Bank MCP

<div align="center">
  <img src="https://github.com/tuncer-byte/byte/blob/main/media/icons/icon-white.png" height="128">
  <h1>Memory Bank MCP</h1>
  <p>
    <b>Structured project knowledge management for LLMs via Model Context Protocol (MCP)</b>
  </p>
</div>

<a href="https://glama.ai/mcp/servers/@tuncer-byte/memory-bank-MCP">
  <img width="380" height="200" src="https://glama.ai/mcp/servers/@tuncer-byte/memory-bank-MCP/badge" alt="Memory Bank MCP server" />
</a>

---

> **Note:** This is not a traditional Node.js application. Memory Bank MCP is an **MCP server**—a component in the [Model Context Protocol](https://modelcontextprotocol.io/introduction) ecosystem. It exposes project knowledge to LLM-powered agents and tools using a standardized protocol, enabling seamless integration with AI clients (e.g., Claude Desktop, IDEs, or custom LLM agents).

---

## What is Model Context Protocol (MCP)?

MCP is an open protocol that standardizes how applications provide context to LLMs. Think of MCP like a USB-C port for AI: it provides a universal way to connect AI models to data sources and tools, both locally and remotely. MCP enables:

- **Plug-and-play integrations** between LLMs, data, and tools
- **Switching between LLM providers** with minimal friction
- **Secure, modular architecture** for building AI workflows

Learn more: [MCP Introduction](https://modelcontextprotocol.io/introduction)

## About Memory Bank MCP

Memory Bank MCP is an **MCP server** that helps teams create, manage, and access structured project documentation. It generates and maintains interconnected Markdown documents capturing all aspects of project knowledge, from high-level goals to technical details and daily progress. It is designed to be accessed by MCP-compatible clients and LLM agents.

## Features

- **AI-Generated Documentation**: Uses Gemini API to generate and update project documentation
- **Structured Knowledge System**: Maintains six core document types in a hierarchical structure
- **MCP Server**: Implements the Model Context Protocol for integration with LLM agents and tools
- **Customizable Storage**: Choose where your Memory Bank directory is created
- **Document Templates**: Pre-defined templates for project brief, product context, system patterns, etc.
- **AI-Assisted Updates**: Update documents manually or regenerate them with AI
- **Advanced Querying**: Search across all documents with context-aware relevance ranking

## Installation

```bash
# Clone the repository
git clone https://github.com/tuncer-byte/memory-bank-mcp.git
cd memory-bank-mcp

# Install dependencies
npm install

# (Optional) Create .env file with your Gemini API key
echo "GEMINI_API_KEY=your_api_key_here" > .env
```

## Usage

> **Note:** Memory Bank MCP is intended to be run as an MCP server, not as a standalone app. You typically launch it as part of an MCP workflow, and connect to it from an MCP-compatible client (such as Claude Desktop or your own LLM agent).

### Development Mode

```bash
npm run dev
```

### Production Mode

```bash
npm run build
npm run start
```

### MCP Integration

To connect Memory Bank MCP to your MCP client, add the following to your `mcp.json` configuration:

```json
{
  "memoryBank": {
    "command": "node",
    "args": ["/path/to/memory-bank-mcp/dist/index.js"],
    "env": {
      "GEMINI_API_KEY": "your_gemini_api_key_here"
    }
  }
}
```

Replace `/path/to/memory-bank-mcp/dist/index.js` with the absolute path to your built file, and add your Gemini API key if needed.

---

## MCP Tools Exposed by Memory Bank

Memory Bank MCP provides the following tools via the Model Context Protocol:

### `initialize_memory_bank`

Creates a new Memory Bank structure with all document templates.

**Parameters:**
- `goal` (string): Project goal description (min 10 characters)
- `geminiApiKey` (string, optional): Gemini API key for document generation
- `location` (string, optional): Absolute path where memory-bank folder will be created

**Example:**
```javascript
await callTool({
  name: "initialize_memory_bank",
  arguments: {
    goal: "Building a self-documenting AI-powered software development assistant",
    location: "/Users/username/Documents/projects/ai-assistant"
  }
});
```

### `update_document`

Updates a specific document in the Memory Bank.

**Parameters:**
- `documentType` (enum): One of: `projectbrief`, `productContext`, `systemPatterns`, `techContext`, `activeContext`, `progress`
- `content` (string, optional): New content for the document
- `regenerate` (boolean, default: false): Whether to regenerate the document using AI

**Example:**
```javascript
await callTool({
  name: "update_document",
  arguments: {
    documentType: "projectbrief",
    content: "# Project Brief\n\n## Purpose\nTo develop an advanced and user-friendly AI..."
  }
});
```

### `query_memory_bank`

Searches across all documents with context-aware relevance ranking.

**Parameters:**
- `query` (string): Search query (min 5 characters)

**Example:**
```javascript
await callTool({
  name: "query_memory_bank",
  arguments: {
    query: "system architecture components"
  }
});
```

### `export_memory_bank`

Exports all Memory Bank documents.

**Parameters:**
- `format` (enum, default: "folder"): Export format, either "json" or "folder"
- `outputPath` (string, optional): Custom output path for the export

**Example:**
```javascript
await callTool({
  name: "export_memory_bank",
  arguments: {
    format: "json",
    outputPath: "/Users/username/Documents/exports"
  }
});
```

## Document Types

Memory Bank organizes project knowledge into six core document types:

1. **Project Brief** (`projectbrief.md`): Core document defining project objectives, scope, and vision
2. **Product Context** (`productContext.md`): Documents product functionality from a user perspective
3. **System Patterns** (`systemPatterns.md`): Establishes system architecture and component relationships
4. **Tech Context** (`techContext.md`): Specifies technology stack and implementation details
5. **Active Context** (`activeContext.md`): Tracks current tasks, open issues, and development focus
6. **Progress** (`progress.md`): Documents completed work, milestones, and project history

## License

MIT
```

--------------------------------------------------------------------------------
/tsconfig.json:
--------------------------------------------------------------------------------

```json
{
  "compilerOptions": {
    "target": "ES2022",
    "module": "NodeNext",
    "moduleResolution": "NodeNext",
    "esModuleInterop": true,
    "outDir": "./dist",
    "rootDir": "./src",
    "strict": true,
    "declaration": true,
    "resolveJsonModule": true
  },
  "include": ["src/**/*"],
  "exclude": ["node_modules", "**/*.test.ts"]
} 
```

--------------------------------------------------------------------------------
/src/index.ts:
--------------------------------------------------------------------------------

```typescript
import { startServer } from './mcp/memoryBankMcp.js';

// Ana fonksiyon
async function main() {
  console.log('Memory Bank MCP uygulaması başlatılıyor...');
  
  try {
    // MCP sunucusunu başlat
    await startServer();
  } catch (error) {
    console.error('Hata:', error);
    process.exit(1);
  }
}

// Uygulamayı başlat
main().catch(error => {
  console.error('Kritik hata:', error);
  process.exit(1);
}); 
```

--------------------------------------------------------------------------------
/src/templates/projectbrief.md:
--------------------------------------------------------------------------------

```markdown
# Project Brief

## Project Purpose
{{projectPurpose}}

## Core Objectives
{{projectGoals}}

## Target Audience
{{targetAudience}}

## Key Features
{{keyFeatures}}

## Success Criteria
{{successCriteria}}

## Timeline
{{timeline}}

## Project Scope
{{projectScope}}

## Stakeholders
{{stakeholders}}

## Dependencies
{{dependencies}}

## Constraints
{{constraints}}

---
*This document was created by AI on {{date}} and serves as the foundation for all Memory Bank documentation.* 
```

--------------------------------------------------------------------------------
/src/templates/productContext.md:
--------------------------------------------------------------------------------

```markdown
# Product Context

## Market Analysis
{{marketAnalysis}}

## Competitive Landscape
{{competitiveAnalysis}}

## User Stories
{{userStories}}

## Requirements
{{requirements}}

## Workflows
{{workflows}}

## Product Roadmap
{{roadmap}}

## Problem Statement
{{problemStatement}}

## Solution Overview
{{solutionOverview}}

## User Experience Goals
{{uxGoals}}

## Business Model
{{businessModel}}

---
*This document was created by AI on {{date}} and outlines why this project exists and how it should work.* 
```

--------------------------------------------------------------------------------
/src/templates/activeContext.md:
--------------------------------------------------------------------------------

```markdown
# Active Context

## Current Sprint
{{currentSprint}}

## Ongoing Tasks
{{ongoingTasks}}

## Known Issues
{{knownIssues}}

## Priorities
{{priorities}}

## Next Steps
{{nextSteps}}

## Meeting Notes
{{meetingNotes}}

## Recent Decisions
{{recentDecisions}}

## Blockers
{{blockers}}

## Resource Allocation
{{resourceAllocation}}

## Risk Assessment
{{riskAssessment}}

## Current Focus Areas
{{currentFocusAreas}}

---
*This document was created by AI on {{date}} and is updated regularly to reflect the current state of the project.* 
```

--------------------------------------------------------------------------------
/src/templates/progress.md:
--------------------------------------------------------------------------------

```markdown
# Progress Report

## Completed Tasks
{{completedTasks}}

## Milestones
{{milestones}}

## Test Results
{{testResults}}

## Performance Metrics
{{performanceMetrics}}

## Feedback
{{feedback}}

## Changelog
{{changelog}}

## Quality Assurance Results
{{qaResults}}

## User Adoption Metrics
{{userAdoption}}

## Lessons Learned
{{lessonsLearned}}

## Time Tracking
{{timeTracking}}

## Achievement Highlights
{{achievementHighlights}}

---
*This document was created by AI on {{date}} and is updated regularly to track the project's progress and outcomes.* 
```

--------------------------------------------------------------------------------
/src/templates/systemPatterns.md:
--------------------------------------------------------------------------------

```markdown
# System Patterns

## Architectural Design
{{architectureDesign}}

## Data Models
{{dataModels}}

## API Definitions
{{apiDefinitions}}

## Component Structure
{{componentStructure}}

## Integration Points
{{integrationPoints}}

## Scalability Strategy
{{scalabilityStrategy}}

## Security Architecture
{{securityArchitecture}}

## Design Patterns
{{designPatterns}}

## Technical Debt
{{technicalDebt}}

## System Constraints
{{systemConstraints}}

## Performance Considerations
{{performanceConsiderations}}

---
*This document was created by AI on {{date}} and documents the system architecture and key technical decisions.* 
```

--------------------------------------------------------------------------------
/src/templates/techContext.md:
--------------------------------------------------------------------------------

```markdown
# Technology Context

## Technologies Used
{{technologiesUsed}}

## Development Tools
{{developmentTools}}

## Development Environment
{{developmentEnvironment}}

## Testing Strategy
{{testingStrategy}}

## Deployment Process
{{deploymentProcess}}

## Continuous Integration
{{continuousIntegration}}

## Infrastructure
{{infrastructure}}

## Third-Party Dependencies
{{thirdPartyDependencies}}

## Configuration Management
{{configManagement}}

## Monitoring & Logging
{{monitoringLogging}}

## Backup & Recovery
{{backupRecovery}}

---
*This document was created by AI on {{date}} and covers the technical foundation of the project.* 
```

--------------------------------------------------------------------------------
/package.json:
--------------------------------------------------------------------------------

```json
{
  "name": "memory-bank-mcp",
  "version": "1.0.0",
  "description": "MCP tabanlı Memory Bank: metin tabanlı bilgileri depolama ve erişim aracı",
  "main": "dist/index.js",
  "type": "module",
  "scripts": {
    "build": "tsc",
    "start": "node dist/index.js",
    "dev": "ts-node src/index.ts"
  },
  "dependencies": {
    "@google/generative-ai": "^0.2.0",
    "@modelcontextprotocol/sdk": "^1.8.0",
    "dotenv": "^16.3.1",
    "zod": "^3.22.4",
    "fs-extra": "^11.2.0"
  },
  "devDependencies": {
    "@types/fs-extra": "^11.0.4",
    "@types/node": "^20.10.5",
    "ts-node": "^10.9.2",
    "typescript": "^5.3.3"
  },
  "keywords": ["mcp", "memory-bank", "gemini", "ai"],
  "author": "",
  "license": "MIT"
} 
```

--------------------------------------------------------------------------------
/src/utils/gemini.ts:
--------------------------------------------------------------------------------

```typescript
import { GoogleGenerativeAI, HarmBlockThreshold, HarmCategory } from '@google/generative-ai';
import dotenv from 'dotenv';
import fs from 'fs-extra';
import path from 'path';


// Load environment variables
dotenv.config();

// Default API key placeholder - replace with your actual API key
const DEFAULT_API_KEY = 'YOUR_DEFAULT_API_KEY';

// Initialize API key
let apiKey = process.env.GEMINI_API_KEY;

console.log('Checking for Gemini API key...');
if (!apiKey) {
  console.error('GEMINI_API_KEY environment variable is not defined.');
  
  try {
    const envPath = path.resolve(process.cwd(), '.env');
    if (!fs.existsSync(envPath)) {
      fs.writeFileSync(envPath, `GEMINI_API_KEY=${DEFAULT_API_KEY}`, 'utf-8');
      console.log('Created .env file with default API key.');
    }
  } catch (err) {
    console.error('Failed to create .env file:', err);
  }
  
  apiKey = DEFAULT_API_KEY;
  console.log('Using default API key.');
}

if (apiKey === 'your_gemini_api_key_here' || apiKey === 'YOUR_DEFAULT_API_KEY') {
  console.warn('GEMINI_API_KEY is set to the example value. Please set a valid API key in your .env file.');
  throw new Error('Invalid API key. Please set a valid GEMINI_API_KEY in your .env file.');
}

console.log('Gemini API key found.');

// Initialize Gemini client
let genAI: GoogleGenerativeAI;
try {
  genAI = new GoogleGenerativeAI(apiKey);
  console.log('Gemini client created successfully.');
} catch (error) {
  console.error('Failed to create Gemini client:', error);
  throw new Error(`Gemini client creation failed: ${error}`);
}

const safetySettings = [
  {
    category: HarmCategory.HARM_CATEGORY_HARASSMENT,
    threshold: HarmBlockThreshold.BLOCK_MEDIUM_AND_ABOVE,
  },
  {
    category: HarmCategory.HARM_CATEGORY_HATE_SPEECH,
    threshold: HarmBlockThreshold.BLOCK_MEDIUM_AND_ABOVE,
  },
  {
    category: HarmCategory.HARM_CATEGORY_SEXUALLY_EXPLICIT,
    threshold: HarmBlockThreshold.BLOCK_MEDIUM_AND_ABOVE,
  },
  {
    category: HarmCategory.HARM_CATEGORY_DANGEROUS_CONTENT,
    threshold: HarmBlockThreshold.BLOCK_MEDIUM_AND_ABOVE,
  },
];

export async function generateContent(prompt: string): Promise<string> {
  try {
    const model = genAI.getGenerativeModel({ model: 'gemini-2.0-flash' });
    
    const result = await model.generateContent({
      contents: [{ role: 'user', parts: [{ text: prompt }] }],
      safetySettings,
      generationConfig: {
        temperature: 0.7,
        topK: 40,
        topP: 0.95,
        maxOutputTokens: 8192,
      },
    });

    const response = result.response;
    return response.text();
  } catch (error) {
    console.error('Gemini API error:', error);
    throw new Error(`Error generating document content: ${error}`);
  }
}

export async function fillTemplate(templatePath: string, values: Record<string, string>): Promise<string> {
  try {
    let templateContent = await fs.readFile(templatePath, 'utf-8');
    
    Object.entries(values).forEach(([key, value]) => {
      const regex = new RegExp(`{{${key}}}`, 'g');
      templateContent = templateContent.replace(regex, value);
    });
    
    return templateContent;
  } catch (error) {
    console.error('Template filling error:', error);
    throw new Error(`Error filling template: ${error}`);
  }
}

export async function generateAllDocuments(goal: string): Promise<Record<string, string>> {
  const currentDate = new Date().toLocaleDateString('tr-TR');
  
  const basePrompt = `
You are a project documentation expert. You will create comprehensive documentation for the following project:

PROJECT PURPOSE: ${goal}

Create the following documents for this project:
`;

  const documentTypes = {
    projectbrief: `
1. Project Brief (projectbrief.md):
   - Explain the general purpose and vision of the project
   - List the main objectives
   - Define the target audience
   - Specify key features
   - Determine success criteria
   - Present a realistic timeline`,
    
    productContext: `
2. Product Context (productContext.md):
   - Conduct market analysis
   - Evaluate competitive landscape
   - Write user stories
   - List requirements
   - Explain workflows
   - Define product roadmap`,
    
    systemPatterns: `
3. System Patterns (systemPatterns.md):
   - Explain architectural design
   - Define data models
   - Specify API definitions
   - Show component structure
   - List integration points
   - Explain scalability strategy`,
    
    techContext: `
4. Technology Context (techContext.md):
   - List technologies used
   - Specify software development tools
   - Define development environment
   - Explain testing strategy
   - Define deployment process
   - Explain continuous integration approach`,
    
    activeContext: `
5. Active Context (activeContext.md):
   - Explain current sprint goals
   - List ongoing tasks
   - Specify known issues
   - Define priorities
   - Explain next steps
   - Add meeting notes`,
    
    progress: `
6. Progress Report (progress.md):
   - List completed tasks
   - Specify milestones
   - Report test results
   - Show performance metrics
   - Summarize feedback
   - Maintain a changelog`
  };
  

  const results: Record<string, string> = {};

  for (const [docType, docPrompt] of Object.entries(documentTypes)) {
    console.log(`Creating ${docType} document...`);
    
    const fullPrompt = `${basePrompt}${docPrompt}\n\nPlease create content only for the "${docType}" document. Use Markdown format with section headers marked by ##. At the end of the document, add the note "Created on ${currentDate}".`;
    
    const content = await generateContent(fullPrompt);
    results[docType] = content;
  }

  return results;
}
```

--------------------------------------------------------------------------------
/src/utils/cursorRulesGenerator.ts:
--------------------------------------------------------------------------------

```typescript
/**
 * Utility functions for generating Cursor rules
 *
 * Note: This module dynamically imports the gemini.js module when necessary
 * to generate AI-powered content for cursor rules.
 */

/**
 * Generates cursor rules content based on project purpose
 * @param purpose Project purpose description
 * @returns Generated cursor rules content
 */
export async function generateCursorRules(purpose: string): Promise<string> {
  // Format current date in English locale
  const currentDate = new Date().toLocaleDateString("en-US");

  // Project type detection based on user's purpose
  const projectType = detectProjectType(purpose);

  // AI ile içerik oluştur
  try {
    console.log("Attempting to generate cursor rules with AI...");
    const mainRulesContent = await generateMainCursorRulesWithAI(
      purpose,
      currentDate,
      projectType
    );
    console.log("Successfully generated cursor rules with AI");
    return mainRulesContent;
  } catch (error) {
    console.error("Error generating cursor rules with AI:", error);
    
    // Hata detayı için log ekleyelim
    if (error instanceof Error) {
      console.error("Error details:", error.message);
      if (error.stack) {
        console.error("Error stack:", error.stack);
      }
      
      // Kullanıcıya daha açıklayıcı hata mesajı göster
      throw new Error(`AI ile içerik oluşturulamadı: ${error.message}`);
    }
    
    // Genel hata durumunda
    throw new Error("AI ile içerik oluşturulamadı. Lütfen daha sonra tekrar deneyin.");
  }
}

/**
 * Detects project type based on user's purpose
 */
function detectProjectType(purpose: string): string {
  const purposeLower = purpose.toLowerCase();

  if (
    purposeLower.includes("frontend") ||
    purposeLower.includes("web") ||
    purposeLower.includes("site") ||
    purposeLower.includes("ui")
  ) {
    return "frontend";
  }

  if (
    purposeLower.includes("backend") ||
    purposeLower.includes("api") ||
    purposeLower.includes("service")
  ) {
    return "backend";
  }

  if (
    purposeLower.includes("mobile") ||
    purposeLower.includes("android") ||
    purposeLower.includes("ios")
  ) {
    return "mobile";
  }

  if (
    purposeLower.includes("fullstack") ||
    purposeLower.includes("full-stack")
  ) {
    return "fullstack";
  }

  if (
    purposeLower.includes("data") ||
    purposeLower.includes("analytics") ||
    purposeLower.includes("ml") ||
    purposeLower.includes("ai")
  ) {
    return "data";
  }

  if (
    purposeLower.includes("devops") ||
    purposeLower.includes("infrastructure") ||
    purposeLower.includes("cloud")
  ) {
    return "devops";
  }

  return "general";
}

/**
 * Generates the main cursor rules content using Gemini API
 */
async function generateMainCursorRulesWithAI(
  purpose: string,
  currentDate: string,
  projectType: string
): Promise<string> {
  const frontmatter = `---
description: Main development guidelines for the ${purpose} project
globs: **/*
alwaysApply: true
---`;

  try {
    console.log("Dynamically importing gemini.js module...");
    const { generateContent } = await import("./gemini.js");
    console.log("Successfully imported gemini.js module");

    const prompt = `
As a software development expert, you are creating Cursor rules for the ${purpose} project.

PROJECT DETAILS:
- PURPOSE: ${purpose}
- TYPE: ${projectType}
- DATE: ${currentDate}

FORMAT REQUIREMENTS:
1. Start with a clear and concise main title
2. Use hierarchical markdown headings (## for main sections, ### for subsections)
3. Use numbered lists for step-by-step instructions
4. Use bullet points for important notes and guidelines
5. Include language-specific code blocks for all examples
6. Provide good and bad examples with explanatory comments
7. Use bold and italic formatting to emphasize important points
8. Include a footer with "Powered by tuncer-byte" and GitHub reference

CONTENT REQUIREMENTS:
1. PROJECT OVERVIEW:
   - Detailed project purpose and objectives
   - Technical goals and success criteria
   - Recommended technology stack with version numbers
   - Architectural patterns and design decisions

2. CODE STRUCTURE AND ORGANIZATION:
   - Detailed file/folder structure for ${projectType} projects
   - Comprehensive naming conventions with examples
   - Module organization and dependency management
   - State management patterns (if applicable)

3. CODING STANDARDS:
   - Language-specific best practices
   - Error handling and logging strategies
   - Performance optimization techniques
   - Security implementation guidelines
   - Code review checklist

4. DEVELOPMENT WORKFLOW:
   - Git workflow with branch naming rules
   - Commit message format with examples
   - PR template and review process
   - CI/CD pipeline configuration
   - Environment management

5. TESTING REQUIREMENTS:
   - Test pyramid implementation
   - Framework setup and configuration
   - Test coverage goals and metrics
   - Mocking and test data strategies
   - E2E testing approach

6. DOCUMENTATION STANDARDS:
   - Code documentation templates
   - API documentation format
   - README structure and content
   - Architectural decision records
   - Deployment documentation

7. QUALITY ASSURANCE:
   - Code quality metrics
   - Static analysis tools
   - Performance monitoring
   - Security scanning
   - Accessibility guidelines

8. FILE ORGANIZATION:
   - Explain the purpose of each directory
   - Provide examples of correct file placement

9. ONBOARDING PROCESS:
   - Step-by-step guide for new developers
   - Required development environment setup
   - Access management and permissions
   - Communication channels and protocols

10. DEPLOYMENT STRATEGY:
    - Environment configuration
    - Release process
    - Rollback procedures
    - Monitoring and alerting setup

Include specific, practical examples that directly apply to ${projectType} development.
Each guideline should be actionable and specific.
End with a footer containing "Powered by tuncer-byte" and GitHub reference.
`;

    console.log("Sending request to Gemini API...");
    const aiGeneratedContent = await generateContent(prompt);
    console.log("Successfully received response from Gemini API");

    return `${frontmatter}

${aiGeneratedContent}

---
*Powered by tuncer-byte*
*GitHub: @tuncer-byte*`;
  } catch (error) {
    console.error("Error generating cursor rules with AI:", error);

    // Daha açıklayıcı hata mesajı
    if (error instanceof Error) {
      if (error.message.includes("GEMINI_API_KEY")) {
        throw new Error(
          "Gemini API anahtarı bulunamadı. Lütfen .env dosyasında GEMINI_API_KEY değişkenini tanımlayın."
        );
      } else if (
        error.message.includes("network") ||
        error.message.includes("fetch")
      ) {
        throw new Error(
          "Gemini API ile iletişim kurulamadı. Lütfen internet bağlantınızı kontrol edin."
        );
      }
    }

    // Orijinal hatayı yeniden fırlat
    throw error;
  }
}

```

--------------------------------------------------------------------------------
/src/utils/fileManager.ts:
--------------------------------------------------------------------------------

```typescript
import fs from 'fs-extra';
import path from 'path';

/**
 * Creates the Memory Bank directory structure
 * @param outputDir Output directory (must already exist)
 */
export async function createMemoryBankStructure(outputDir: string): Promise<void> {
  try {
    console.log(`Creating Memory Bank structure in existing directory: ${outputDir}`);
    
    // Verify directory exists
    if (!await fs.pathExists(outputDir)) {
      console.warn(`Directory does not exist: ${outputDir}, will create it`);
      await fs.ensureDir(outputDir);
    }
    
    // No subdirectories needed - using a flat structure for simplicity
    console.log(`Using flat structure for Memory Bank in "${outputDir}"`);
    
    // Create a README.md file with component descriptions
    const readmePath = path.join(outputDir, 'README.md');
    const readmeContent = `# Memory Bank

This directory serves as a structured repository for your project information and notes.

## Directory Structure
- **resources**: Images, diagrams, and other resources
- **temp**: Temporary files and drafts
- **archive**: Archived documents
- **references**: Reference materials and documentation

## Core Documents
- **projectbrief.md**: Project goals, scope, and vision
- **productContext.md**: Product features, user stories, and market context
- **systemPatterns.md**: System architecture, design patterns, and component structure
- **techContext.md**: Technology stack, frameworks, and technical specifications
- **activeContext.md**: Active tasks, current sprint, and in-progress work
- **progress.md**: Progress tracking, milestones, and project history

## Document Management
This Memory Bank uses a structured approach to organize project knowledge. Each document serves a specific purpose in the project lifecycle and should be maintained according to the rules specified in the \`.byterules\` file.

See the \`.byterules\` file for detailed guidelines on how to maintain and update these documents.
`;
    try {
      await fs.writeFile(readmePath, readmeContent, 'utf-8');
      console.log(`README file created at: ${readmePath}`);
    } catch (error) {
      const err = error as any;
      console.error(`Error creating README file: ${err.code} - ${err.message}`);
      // Continue without README
    }
    
    console.log(`Memory Bank structure successfully created in "${outputDir}".`);
  } catch (error) {
    console.error(`Error creating directory structure at ${outputDir}:`, error);
    if (error instanceof Error) {
      throw new Error(`Failed to create Memory Bank structure: ${error.message} (Code: ${(error as any).code || 'UNKNOWN'})`);
    } else {
      throw new Error(`Failed to create Memory Bank structure: Unknown error`);
    }
  }
}

/**
 * Saves document content to a specific file
 * @param content File content
 * @param filePath File path
 */
export async function saveDocument(content: string, filePath: string): Promise<void> {
  try {
    // Ensure directory exists
    await fs.ensureDir(path.dirname(filePath));
    
    // Write file
    await fs.writeFile(filePath, content, 'utf-8');
    
    console.log(`Document saved: ${filePath}`);
  } catch (error) {
    console.error('Error saving document:', error);
    throw new Error(`Failed to save document: ${error}`);
  }
}

/**
 * Reads document content
 * @param filePath File path
 * @returns File content
 */
export async function readDocument(filePath: string): Promise<string> {
  try {
    // Check if file exists
    if (!await fs.pathExists(filePath)) {
      throw new Error(`Document not found: ${filePath}`);
    }
    
    // Read file
    const content = await fs.readFile(filePath, 'utf-8');
    
    return content;
  } catch (error) {
    console.error('Error reading document:', error);
    throw new Error(`Failed to read document: ${error}`);
  }
}

/**
 * Reads all documents from a directory
 * @param directoryPath Directory path
 * @returns Object containing file paths and contents
 */
export async function readAllDocuments(directoryPath: string): Promise<Record<string, string>> {
  try {
    // Check if directory exists
    if (!await fs.pathExists(directoryPath)) {
      throw new Error(`Directory not found: ${directoryPath}`);
    }
    
    // List all files
    const files = await fs.readdir(directoryPath);
    
    // Filter only markdown files
    const markdownFiles = files.filter(file => file.endsWith('.md'));
    
    // Read each file
    const results: Record<string, string> = {};
    
    for (const file of markdownFiles) {
      const filePath = path.join(directoryPath, file);
      const content = await fs.readFile(filePath, 'utf-8');
      
      // Use filename as key (without extension)
      const fileName = path.basename(file, path.extname(file));
      results[fileName] = content;
    }
    
    return results;
  } catch (error) {
    console.error('Error reading documents:', error);
    throw new Error(`Failed to read documents: ${error}`);
  }
}

/**
 * Exports Memory Bank documents
 * @param sourceDir Source directory
 * @param format Export format ('folder' or 'json')
 * @param outputPath Output file path
 * @returns Path to the exported content
 */
export async function exportMemoryBank(sourceDir: string, format: string = 'folder', outputPath: string): Promise<string> {
  try {
    // Check if source directory exists
    if (!await fs.pathExists(sourceDir)) {
      throw new Error(`Source directory not found: ${sourceDir}`);
    }
    
    const exportDir = path.dirname(outputPath);
    await fs.ensureDir(exportDir);
    
    if (format === 'folder') {
      // Export as folder (copy entire directory structure)
      const exportFolderPath = path.join(exportDir, path.basename(sourceDir));
      await fs.copy(sourceDir, exportFolderPath);
      console.log(`Memory Bank folder exported to "${exportFolderPath}".`);
      return exportFolderPath;
    } else if (format === 'json') {
      // Export as JSON
      const documents = await readAllDocuments(sourceDir);
      
      // Add metadata
      const exportData = {
        exportDate: new Date().toISOString(),
        memoryBank: documents
      };
      
      const jsonFilePath = outputPath.endsWith('.json') ? outputPath : `${outputPath}.json`;
      await fs.writeFile(jsonFilePath, JSON.stringify(exportData, null, 2), 'utf-8');
      console.log(`Memory Bank data exported to "${jsonFilePath}" in JSON format.`);
      return jsonFilePath;
    } else {
      throw new Error(`Unsupported format: ${format}. Use 'folder' or 'json'.`);
    }
  } catch (error) {
    console.error('Error exporting:', error);
    throw new Error(`Failed to export Memory Bank: ${error}`);
  }
}

/**
 * Reads the .byterules file and returns its content
 * @param directory Directory where .byterules file is located
 * @returns Content of .byterules file
 */
export async function readByteRules(directory: string): Promise<string> {
  try {
    const byteRulesPath = path.join(directory, '.byterules');
    
    // Check if file exists
    if (!await fs.pathExists(byteRulesPath)) {
      throw new Error('ByteRules file not found. Memory Bank may not be properly initialized.');
    }
    
    // Read file
    const content = await fs.readFile(byteRulesPath, 'utf-8');
    
    return content;
  } catch (error) {
    console.error('Error reading ByteRules:', error);
    throw new Error(`Failed to read ByteRules: ${error}`);
  }
}

/**
 * Gets document workflow information based on document type
 * @param directory Directory where .byterules file is located
 * @param documentType Type of document to get workflow for
 * @returns Workflow information for the document
 */
export async function getDocumentWorkflow(directory: string, documentType: string): Promise<{
  purpose: string;
  updateTiming: string;
  structure: string[];
  commands: string[];
}> {
  try {
    // Get byterules content
    const byteRulesContent = await readByteRules(directory);
    
    // Extract section for the specific document type
    const regex = new RegExp(`###\\s*\\d+\\.\\s*${documentType.replace(/Context/g, ' Context')}\\s*\\([\\w\\.]+\\)[\\s\\S]*?(?=###\\s*\\d+\\.\\s*|##\\s*|$)`, 'i');
    const match = byteRulesContent.match(regex);
    
    if (!match) {
      return {
        purpose: `Information about ${documentType} document`,
        updateTiming: 'As needed',
        structure: ['No specific structure defined'],
        commands: [`update_document ${documentType.toLowerCase()}`]
      };
    }
    
    // Parse section content
    const sectionContent = match[0];
    
    // Extract purpose
    const purposeMatch = sectionContent.match(/\*\*Purpose\*\*:\s*(.*?)(?=\n)/);
    const purpose = purposeMatch ? purposeMatch[1].trim() : `Information about ${documentType}`;
    
    // Extract when to update
    const updateMatch = sectionContent.match(/\*\*When to Update\*\*:\s*(.*?)(?=\n)/);
    const updateTiming = updateMatch ? updateMatch[1].trim() : 'As needed';
    
    // Extract structure
    const structureMatch = sectionContent.match(/\*\*Structure\*\*:[\s\S]*?(?=\*\*|$)/);
    const structure = structureMatch 
      ? structureMatch[0]
          .replace(/\*\*Structure\*\*:\s*/, '')
          .trim()
          .split('\n')
          .map(line => line.replace(/^\s*-\s*/, '').trim())
          .filter(line => line.length > 0)
      : ['No specific structure defined'];
    
    // Extract commands
    const commandsMatch = sectionContent.match(/\*\*Commands\*\*:[\s\S]*?(?=\*\*|$)/);
    const commands = commandsMatch 
      ? commandsMatch[0]
          .replace(/\*\*Commands\*\*:\s*/, '')
          .trim()
          .split('\n')
          .map(line => line.replace(/^\s*-\s*`(.*?)`.*/, '$1').trim())
          .filter(line => line.length > 0)
      : [`update_document ${documentType.toLowerCase()}`];
    
    return {
      purpose,
      updateTiming,
      structure,
      commands
    };
  } catch (error) {
    console.error('Error getting document workflow:', error);
    return {
      purpose: `Information about ${documentType} document`,
      updateTiming: 'As needed',
      structure: ['No specific structure defined'],
      commands: [`update_document ${documentType.toLowerCase()}`]
    };
  }
}

/**
 * Creates a structured template for a document based on ByteRules
 * @param directory Directory where .byterules file is located
 * @param documentType Type of document to create template for
 * @returns Structured template content
 */
export async function createDocumentTemplate(directory: string, documentType: string): Promise<string> {
  try {
    // Get workflow info
    const workflow = await getDocumentWorkflow(directory, documentType);
    
    // Build template
    let template = `# ${documentType.replace(/([A-Z])/g, ' $1').trim()}\n\n`;
    template += `> ${workflow.purpose}\n\n`;
    template += `> Last Updated: ${new Date().toISOString().split('T')[0]}\n\n`;
    
    // Add sections based on structure
    for (const section of workflow.structure) {
      template += `## ${section}\n\n_Add content here_\n\n`;
    }
    
    // Add reference to update timing
    template += `---\n\n**Note:** This document should be updated ${workflow.updateTiming.toLowerCase()}.\n`;
    
    return template;
  } catch (error) {
    console.error('Error creating document template:', error);
    
    // Return basic template on error
    return `# ${documentType.replace(/([A-Z])/g, ' $1').trim()}\n\nLast Updated: ${new Date().toISOString().split('T')[0]}\n\n## Content\n\n_Add content here_\n`;
  }
}

/**
 * Analyzes document consistency with ByteRules guidelines
 * @param directory Directory where documents are located
 * @returns Analysis results with recommendations
 */
export async function analyzeDocumentConsistency(directory: string): Promise<{
  documentType: string;
  status: 'good' | 'needs-update';
  recommendation: string;
}[]> {
  try {
    // Get all documents
    const documents = await readAllDocuments(directory);
    const results = [];
    
    // Analyze each document
    for (const [docName, content] of Object.entries(documents)) {
      // Skip non-standard documents
      if (!['projectbrief', 'productContext', 'systemPatterns', 'techContext', 'activeContext', 'progress'].includes(docName)) {
        continue;
      }
      
      // Get workflow info
      const workflow = await getDocumentWorkflow(directory, docName);
      
      // Check for required sections
      const missingSections = [];
      for (const section of workflow.structure) {
        const sectionRegex = new RegExp(`##\\s*${section}`, 'i');
        if (!sectionRegex.test(content)) {
          missingSections.push(section);
        }
      }
      
      // Check if document was updated recently (within last 30 days)
      const lastUpdatedMatch = content.match(/Last Updated:\s*(\d{4}-\d{2}-\d{2})/);
      let needsUpdate = false;
      
      if (lastUpdatedMatch) {
        const lastUpdated = new Date(lastUpdatedMatch[1]);
        const thirtyDaysAgo = new Date();
        thirtyDaysAgo.setDate(thirtyDaysAgo.getDate() - 30);
        needsUpdate = lastUpdated < thirtyDaysAgo;
      } else {
        needsUpdate = true; // No update date found
      }
      
      let recommendation = '';
      let status: 'good' | 'needs-update' = 'good';
      
      if (missingSections.length > 0) {
        recommendation = `Missing sections: ${missingSections.join(', ')}`;
        status = 'needs-update';
      } else if (needsUpdate) {
        recommendation = 'Document may need updating (last update over 30 days ago)';
        status = 'needs-update';
      } else {
        recommendation = 'Document follows the structure defined in ByteRules';
      }
      
      results.push({
        documentType: docName,
        status,
        recommendation
      });
    }
    
    return results;
  } catch (error) {
    console.error('Error analyzing documents:', error);
    throw new Error(`Failed to analyze documents: ${error}`);
  }
}
```

--------------------------------------------------------------------------------
/src/mcp/memoryBankMcp.ts:
--------------------------------------------------------------------------------

```typescript
import { McpServer } from '@modelcontextprotocol/sdk/server/mcp.js';
import { StdioServerTransport } from '@modelcontextprotocol/sdk/server/stdio.js';
import { z } from 'zod';
import path from 'path';
import fs from 'fs-extra';
import os from 'os';
import { generateAllDocuments } from '../utils/gemini.js';
import { 
  createMemoryBankStructure, 
  saveDocument, 
  readDocument, 
  readAllDocuments, 
  exportMemoryBank 
} from '../utils/fileManager.js';
import { generateCursorRules } from '../utils/cursorRulesGenerator.js';

// Create MCP server
const server = new McpServer({
  name: 'Memory Bank MCP',
  version: '1.0.0'
});

// Import URL and fileURLToPath for ESM compatible __dirname alternative
import { fileURLToPath } from 'url';
import { dirname } from 'path';

// Helper function to get the workspace root directory
const getWorkspaceRootDir = () => {
  // Try to get VS Code workspace folder from environment variables
  // This is more reliable than process.cwd() in VS Code environment
  if (process.env.VSCODE_WORKSPACE_FOLDER) {
    console.log(`Using VS Code workspace folder: ${process.env.VSCODE_WORKSPACE_FOLDER}`);
    return process.env.VSCODE_WORKSPACE_FOLDER;
  }
  
  // If not in VS Code or env var not available, try to determine from current file path
  // ESM compatible version of __dirname
  const __filename = fileURLToPath(import.meta.url);
  const __dirname = dirname(__filename);
  
  const currentFilePath = __dirname;
  console.log(`Current file directory: ${currentFilePath}`);
  
  // Try to find the workspace root by looking for package.json
  let dir = currentFilePath;
  while (dir !== path.parse(dir).root) {
    if (fs.existsSync(path.join(dir, 'package.json'))) {
      console.log(`Found workspace root at: ${dir}`);
      return dir;
    }
    dir = path.dirname(dir);
  }
  
  // Fallback to current working directory with warning
  console.warn(`Could not determine workspace root, falling back to CWD: ${process.cwd()}`);
  return process.cwd();
};

// Default document directory path - initialize to null, will be set during initialization
let MEMORY_BANK_DIR: string | null = null;

// Initialize Memory Bank - create new document structure
server.tool(
  'initialize_memory_bank',
  {
    goal: z.string().min(10, 'Project goal must be at least 10 characters'),
    geminiApiKey: z.string().optional().describe('Gemini API key (optional)'),
    location: z.string().describe('Absolute path where memory-bank folder will be created')
  },
  async ({ goal, geminiApiKey, location }) => {
    try {
      // Diagnostics: Log environment info
      console.log(`Current working directory: ${process.cwd()}`);
      console.log(`Node version: ${process.version}`);
      console.log(`Platform: ${process.platform}`);
      
      // Determine where to create the memory-bank directory
      let baseDir;
      let memoryBankDir;
      
      if (location) {
        // Use user-specified location as the base directory
        if (path.isAbsolute(location)) {
          // If absolute path is provided, use it directly as base directory
          baseDir = location;
        } else {
          // If relative path is provided, resolve against current working directory
          baseDir = path.resolve(process.cwd(), location);
        }
        console.log(`Using user specified base location: ${baseDir}`);
      } else {
        // If no location provided, use current working directory as base
        baseDir = process.cwd();
        console.log(`No location specified, using current directory as base: ${baseDir}`);
      }
      
      // Create memory-bank directory inside the base directory
      memoryBankDir = path.join(baseDir, 'memory-bank');
      console.log(`Will create Memory Bank structure at: ${memoryBankDir}`);
      
      // Ensure parent directory exists if needed
      const parentDir = path.dirname(memoryBankDir);
      try {
        await fs.ensureDir(parentDir);
        console.log(`Ensured parent directory exists: ${parentDir}`);
      } catch (error) {
        console.error(`Error ensuring parent directory: ${error}`);
        throw new Error(`Cannot create or access parent directory: ${error}`);
      }
      
      // Set global memory bank directory
      MEMORY_BANK_DIR = memoryBankDir;
      
      console.log(`Will create Memory Bank at: ${MEMORY_BANK_DIR}`);
      
      // Ensure memory-bank directory exists before passing to createMemoryBankStructure
      try {
        await fs.ensureDir(MEMORY_BANK_DIR);
        console.log(`Created Memory Bank root directory: ${MEMORY_BANK_DIR}`);
      } catch (error) {
        console.error(`Error creating Memory Bank directory: ${error}`);
        throw new Error(`Cannot create Memory Bank directory: ${error}`);
      }

      // Temporarily set the API key if provided
      if (geminiApiKey) {
        process.env.GEMINI_API_KEY = geminiApiKey;
      }

      // First, set up the .byterules file before creating other files
      // This ensures the byterules file is in place before other operations
      const byterulesDest = path.join(MEMORY_BANK_DIR, '.byterules');
      
      try {
        // Debug: List all search paths we're going to try
        console.log('Searching for .byterules template file...');
        
        // Get the ESM compatible dirname
        const __filename = fileURLToPath(import.meta.url);
        const __dirname = dirname(__filename);
        console.log(`Current file directory: ${__dirname}`);
        
        // Try multiple possible locations for the .byterules file
        const possiblePaths = [
          path.join(process.cwd(), 'src', 'templates', '.byterules'),          // From current working dir
          path.join(__dirname, '..', 'templates', '.byterules'),               // From mcp dir to templates
          path.join(__dirname, '..', '..', 'src', 'templates', '.byterules'),  // From mcp dir up two levels
          path.join(process.cwd(), 'templates', '.byterules'),                 // Direct templates folder
          path.join(process.cwd(), '.byterules')                               // Root of project
        ];
        
        // Manually create .byterules content as fallback
        const defaultByterules = `# Memory Bank Document Orchestration Standard

## Directory Validation

Before any operation (create/update/reference/review), ensure you are in the correct project root directory. Specifically:

- A valid Memory Bank system **must contain** this \`.byterules\` file at its root.
- If this file is missing, halt operations and **navigate to the correct directory** using:

\`\`\`bash
cd /your/project/root
\`\`\`

Failing to validate the directory can lead to misplaced or inconsistent documentation.

---

## System Overview

Memory Bank is a structured documentation system designed to maintain project knowledge in an organized, accessible format. This \`.byterules\` file serves as the standard guide for how the system works across all projects.

## Standard Document Types

### 1. Project Brief (projectbrief.md)
- **Purpose**: Core document that defines project objectives, scope, and vision
- **When to Use**: Reference when making any major project decisions
- **Workflow Step**: Start here; all other documents derive from this foundation
- **Critical For**: Maintaining alignment with business goals throughout development

### 2. Product Context (productContext.md)
- **Purpose**: Documents product functionality from a user perspective
- **When to Use**: When designing features and establishing requirements
- **Workflow Step**: Second document in sequence, expands on project brief goals
- **Critical For**: Ensuring user needs drive technical decisions

### 3. System Patterns (systemPatterns.md)
- **Purpose**: Establishes system architecture and component relationships
- **When to Use**: During system design and when making integration decisions
- **Workflow Step**: Third document, translates product needs to technical design
- **Critical For**: Maintaining a coherent and scalable technical architecture

### 4. Tech Context (techContext.md)
- **Purpose**: Specifies technology stack and implementation details
- **When to Use**: During development and when onboarding technical team members
- **Workflow Step**: Fourth document, makes concrete technology choices
- **Critical For**: Technical consistency and efficient development

### 5. Active Context (activeContext.md)
- **Purpose**: Tracks current tasks, open issues, and development focus
- **When to Use**: Daily, during planning sessions, and when switching tasks
- **Workflow Step**: Fifth document, operationalizes the technical approach
- **Critical For**: Day-to-day execution and short-term planning

### 6. Progress (progress.md)
- **Purpose**: Documents completed work, milestones, and project history
- **When to Use**: After completing significant work or during reviews
- **Workflow Step**: Ongoing document that records the project journey
- **Critical For**: Tracking accomplishments and learning from experience

## Standard Workflows

### Documentation Sequence
Always follow this sequence for document creation and reference:
1. **Project Brief** → Foundation of all project decisions
2. **Product Context** → User-focused requirements and features
3. **System Patterns** → Architecture and component design
4. **Tech Context** → Technology choices and implementation guidelines
5. **Active Context** → Current work and immediate focus
6. **Progress** → Historical record and milestone tracking

### Document Lifecycle Management
Each document follows a standard lifecycle:
1. **Creation**: Establish initial content based on project needs
2. **Reference**: Use document for planning and decision-making
3. **Update**: Revise when relevant factors change
4. **Review**: Periodically validate for accuracy and completeness
5. **Archive**: Maintain as historical reference when superseded

## Best Practices

### Document Quality Standards
- **Clarity**: Write in clear, concise language
- **Completeness**: Include all relevant information
- **Consistency**: Use consistent terminology across documents
- **Structure**: Follow standardized document formats
- **Granularity**: Balance detail with readability
- **Traceability**: Link related concepts across documents

### Document Integration Principles
- **Vertical Traceability**: Ensure business goals trace to technical implementation
- **Horizontal Consistency**: Maintain alignment across documents at the same level
- **Change Impact Analysis**: Update related documents when one changes
- **Decision Recording**: Document the reasoning behind significant decisions


`;
        
        // Try each path and use the first one that exists
        let bytesRulesFound = false;
        
        for (const testPath of possiblePaths) {
          console.log(`Checking path: ${testPath}`);
          
          if (await fs.pathExists(testPath)) {
            console.log(`✓ Found .byterules at: ${testPath}`);
            await fs.copy(testPath, byterulesDest);
            console.log(`Standard .byterules file copied to: ${byterulesDest}`);
            bytesRulesFound = true;
            break;
          } else {
            console.log(`✗ Not found at: ${testPath}`);
          }
        }
        
        // If no .byterules file found, create one with the default content
        if (!bytesRulesFound) {
          console.log('No .byterules template found, creating default');
          await fs.writeFile(byterulesDest, defaultByterules, 'utf-8');
          console.log(`Default .byterules file created at: ${byterulesDest}`);
        }
        
      } catch (error) {
        console.error(`Error setting up .byterules file: ${error}`);
        throw new Error(`Failed to set up .byterules file: ${error}`);
      }
      
      // Now create the full structure
      await createMemoryBankStructure(MEMORY_BANK_DIR);

      // Generate document contents
      const documentContents = await generateAllDocuments(goal);

      // Save each document
      for (const [docType, content] of Object.entries(documentContents)) {
        const filePath = path.join(MEMORY_BANK_DIR, `${docType}.md`);
        await saveDocument(content, filePath);
      }

      return {
        content: [
          { 
            type: 'text', 
            text: `✅ Memory Bank successfully created!\n\nLocation: ${MEMORY_BANK_DIR}\n\nGenerated Documents:\n- projectbrief.md\n- productContext.md\n- systemPatterns.md\n- techContext.md\n- activeContext.md\n- progress.md\n- .byterules` 
          }
        ]
      };
    } catch (error) {
      console.error('Error creating Memory Bank:', error);
      return {
        content: [{ type: 'text', text: `❌ Error: ${error instanceof Error ? error.message : String(error)}` }],
        isError: true
      };
    }
  }
);

// Update document
server.tool(
  'update_document',
  {
    documentType: z.enum(['projectbrief', 'productContext', 'systemPatterns', 'techContext', 'activeContext', 'progress']),
    content: z.string().optional(),
    regenerate: z.boolean().default(false)
  },
  async ({ documentType, content, regenerate }) => {
    try {
      // Check if Memory Bank directory is initialized
      if (!MEMORY_BANK_DIR) {
        throw new Error('Memory Bank not initialized. Please use initialize_memory_bank tool first.');
      }

      const filePath = path.join(MEMORY_BANK_DIR, `${documentType}.md`);

      // Check if file exists
      if (!await fs.pathExists(filePath)) {
        // Create file if it doesn't exist
        await fs.ensureFile(filePath);
        await fs.writeFile(filePath, `# ${documentType}\n\n`, 'utf-8');
      }

      if (regenerate) {
        // Read existing document
        const currentContent = await readDocument(filePath);
        
        // Always use en-US locale for date formatting to ensure English output
        const dateOptions = { year: 'numeric', month: 'long', day: 'numeric' };
        const englishDate = new Date().toLocaleDateString('en-US');
        
        // TODO: Generate new content with Gemini (example for now)
        const newContent = `${currentContent}\n\n## Update\nThis document was regenerated on ${englishDate}.`;
        
        // Save document
        await saveDocument(newContent, filePath);
      } else if (content) {
        // Save provided content
        await saveDocument(content, filePath);
      } else {
        throw new Error('Content must be provided or regenerate=true');
      }

      // Always use English for all response messages
      return {
        content: [{ 
          type: 'text', 
          text: `✅ "${documentType}.md" document successfully updated!` 
        }]
      };
    } catch (error) {
      console.error('Error updating document:', error);
      // Ensure error messages are also in English
      const errorMessage = error instanceof Error ? error.message : String(error);
      return {
        content: [{ type: 'text', text: `❌ Error: ${errorMessage}` }],
        isError: true
      };
    }
  }
);

// Query Memory Bank
server.tool(
  'query_memory_bank',
  {
    query: z.string().min(5, 'Query must be at least 5 characters')
  },
  async ({ query }) => {
    try {
      // Check if Memory Bank has been initialized
      if (!MEMORY_BANK_DIR) {
        return {
          content: [{ type: 'text', text: `ℹ️ Memory Bank not initialized. Please use 'initialize_memory_bank' tool first.` }]
        };
      }

      // Check if Memory Bank directory exists on disk
      if (!await fs.pathExists(MEMORY_BANK_DIR)) {
        return {
          content: [{ type: 'text', text: `ℹ️ Memory Bank directory (${MEMORY_BANK_DIR}) not found on disk. Please use 'initialize_memory_bank' tool first.` }]
        };
      }

      // Read all documents
      const documents = await readAllDocuments(MEMORY_BANK_DIR);
      
      // Advanced search function
      const searchResults = performAdvancedSearch(query, documents);
      
      if (searchResults.length === 0) {
        return {
          content: [{ type: 'text', text: `ℹ️ No results found for query "${query}".` }]
        };
      }
      
      // Format results
      const formattedResults = searchResults.map(result => {
        return `📄 **${result.documentType}**:\n${result.snippet}\n`;
      }).join('\n');
      
      return {
        content: [{ 
          type: 'text', 
          text: `🔍 Results for query "${query}":\n\n${formattedResults}` 
        }]
      };
    } catch (error) {
      console.error('Error querying Memory Bank:', error);
      return {
        content: [{ type: 'text', text: `❌ Error: ${error instanceof Error ? error.message : String(error)}` }],
        isError: true
      };
    }
  }
);

// Advanced search functionality
interface SearchResult {
  documentType: string;
  relevanceScore: number;
  snippet: string;
}

function performAdvancedSearch(query: string, documents: Record<string, string>): SearchResult[] {
  const results: SearchResult[] = [];
  const queryTerms = query.toLowerCase().split(/\s+/).filter(term => term.length > 2);
  
  // Search in each document
  for (const [docType, content] of Object.entries(documents)) {
    // Split document into sections and paragraphs
    const sections = content.split(/\n#{2,3}\s+/).filter(Boolean);
    
    for (const section of sections) {
      // Extract title and content
      const titleMatch = section.match(/^([^\n]+)/);
      const title = titleMatch ? titleMatch[1].trim() : '';
      
      // Evaluate each paragraph
      const paragraphs = section.split(/\n\n+/);
      
      for (const paragraph of paragraphs) {
        // Calculate relevance score
        const relevanceScore = calculateRelevanceScore(query, queryTerms, paragraph);
        
        // Add results above threshold
        if (relevanceScore > 0.3) {
          // Extract relevant snippet
          const snippet = extractRelevantSnippet(paragraph, queryTerms, title);
          
          results.push({
            documentType: docType,
            relevanceScore,
            snippet
          });
        }
      }
    }
  }
  
  // Sort results by relevance and return top 5
  return results
    .sort((a, b) => b.relevanceScore - a.relevanceScore)
    .slice(0, 5);
}

function calculateRelevanceScore(query: string, queryTerms: string[], text: string): number {
  const lowerText = text.toLowerCase();
  
  // Exact match check (highest score)
  if (lowerText.includes(query.toLowerCase())) {
    return 1.0;
  }
  
  // Term-based matching
  let matchCount = 0;
  for (const term of queryTerms) {
    if (lowerText.includes(term)) {
      matchCount++;
    }
  }
  
  // Term match ratio
  const termMatchRatio = queryTerms.length > 0 ? matchCount / queryTerms.length : 0;
  
  // Proximity factor calculation
  let proximityFactor = 0;
  if (matchCount >= 2) {
    // Calculate proximity between matching terms
    // (This is a simplified approach)
    proximityFactor = 0.2;
  }
  
  return termMatchRatio * 0.8 + proximityFactor;
}

function extractRelevantSnippet(text: string, queryTerms: string[], sectionTitle: string): string {
  const lowerText = text.toLowerCase();
  const MAX_SNIPPET_LENGTH = 150;
  
  // Find best match
  let bestPosition = 0;
  let bestTermCount = 0;
  
  // Query for each character in the document
  for (let i = 0; i < lowerText.length; i++) {
    let termCount = 0;
    for (const term of queryTerms) {
      if (lowerText.substring(i, i + 100).includes(term)) {
        termCount++;
      }
    }
    
    if (termCount > bestTermCount) {
      bestTermCount = termCount;
      bestPosition = i;
    }
  }
  
  // Create snippet around best match
  let startPos = Math.max(0, bestPosition - 30);
  let endPos = Math.min(text.length, bestPosition + MAX_SNIPPET_LENGTH - 30);
  
  // Adjust to word boundaries
  while (startPos > 0 && text[startPos] !== ' ' && text[startPos] !== '\n') {
    startPos--;
  }
  
  while (endPos < text.length && text[endPos] !== ' ' && text[endPos] !== '\n') {
    endPos++;
  }
  
  let snippet = text.substring(startPos, endPos).trim();
  
  // Add ellipsis to indicate truncation
  if (startPos > 0) {
    snippet = '...' + snippet;
  }
  
  if (endPos < text.length) {
    snippet = snippet + '...';
  }
  
  // Add title
  if (sectionTitle) {
    return `**${sectionTitle}**: ${snippet}`;
  }
  
  return snippet;
}

// Export Memory Bank
server.tool(
  'export_memory_bank',
  {
    format: z.enum(['json', 'folder']).default('folder').describe('Export format'),
    outputPath: z.string().optional()
  },
  async ({ format, outputPath }) => {
    try {
      // Check if Memory Bank has been initialized
      if (!MEMORY_BANK_DIR) {
        return {
          content: [{ type: 'text', text: `ℹ️ Memory Bank not initialized. Please use 'initialize_memory_bank' tool first.` }]
        };
      }
      
      // Check if Memory Bank directory exists on disk
      if (!await fs.pathExists(MEMORY_BANK_DIR)) {
        return {
          content: [{ type: 'text', text: `ℹ️ Memory Bank directory (${MEMORY_BANK_DIR}) not found on disk. Please use 'initialize_memory_bank' tool first.` }]
        };
      }

      // Ensure we have an absolute path for the output
      const defaultOutputPath = path.resolve(path.join(process.cwd(), 'memory-bank-export'));
      const targetOutputPath = outputPath ? path.resolve(outputPath) : defaultOutputPath;
      
      console.log(`Exporting Memory Bank from ${MEMORY_BANK_DIR} to ${targetOutputPath}`);
      
      // Call exportMemoryBank function
      const exportResult = await exportMemoryBank(MEMORY_BANK_DIR, format, targetOutputPath);
      
      // Create message based on format type
      const formatMessage = format === 'json' ? 'JSON file' : 'folder';
      
      return {
        content: [{ 
          type: 'text', 
          text: `✅ Memory Bank successfully exported as ${formatMessage}: ${exportResult}` 
        }]
      };
    } catch (error) {
      console.error('Error exporting Memory Bank:', error);
      return {
        content: [{ type: 'text', text: `❌ Error: ${error instanceof Error ? error.message : String(error)}` }],
        isError: true
      };
    }
  }
);

// Create Cursor Rules
server.tool(
  'create_cursor_rules',
  {
    projectPurpose: z.string()
      .min(10, 'Proje amacı en az 10 karakter olmalıdır')
      .describe('Proje amacını detaylı bir şekilde açıklayan bir metin giriniz. Bu metin projenin temel hedeflerini ve kapsamını belirleyecektir.'),
    location: z.string()
      .describe('Absolute path where cursor-rules will be created')
  },
  async ({ projectPurpose, location }) => {
    try {
      // Diagnostics: Log environment info
      console.log(`Current working directory: ${process.cwd()}`);
      console.log(`Node version: ${process.version}`);
      console.log(`Platform: ${process.platform}`);
      
      // Determine where to create the .cursor directory
      let baseDir;
      
      if (location) {
        // Use user-specified location as the base directory
        if (path.isAbsolute(location)) {
          // If absolute path is provided, use it directly as base directory
          baseDir = location;
        } else {
          // If relative path is provided, resolve against current working directory
          baseDir = path.resolve(process.cwd(), location);
        }
        console.log(`Using user specified base location: ${baseDir}`);
      } else {
        // If no location provided, use current working directory as base
        baseDir = process.cwd();
        console.log(`No location specified, using current directory as base: ${baseDir}`);
      }
      
      // Create .cursor directory in the base directory
      const cursorDir = path.join(baseDir, '.cursor');
      console.log(`Will create Cursor Rules at: ${cursorDir}`);
      
      // Ensure parent directory exists if needed
      const parentDir = path.dirname(cursorDir);
      try {
        await fs.ensureDir(parentDir);
        console.log(`Ensured parent directory exists: ${parentDir}`);
      } catch (error) {
        console.error(`Error ensuring parent directory: ${error}`);
        throw new Error(`Cannot create or access parent directory: ${error}`);
      }
      
      // Ensure .cursor directory exists
      try {
        await fs.ensureDir(cursorDir);
        console.log(`Created .cursor directory: ${cursorDir}`);
      } catch (error) {
        console.error(`Error creating .cursor directory: ${error}`);
        throw new Error(`Cannot create .cursor directory: ${error}`);
      }
      
      // Create the cursor-rules.mdc file
      const cursorRulesPath = path.join(cursorDir, 'cursor-rules.mdc');
      console.log(`Will create cursor-rules.mdc at: ${cursorRulesPath}`);
      
      // Generate content for the rules file based on project purpose
      console.log(`Generating cursor rules content for purpose: ${projectPurpose}`);
      try {
        const cursorRulesContent = await generateCursorRules(projectPurpose);
        
        // Save the file
        try {
          await fs.writeFile(cursorRulesPath, cursorRulesContent, 'utf-8');
          console.log(`Created cursor-rules.mdc at: ${cursorRulesPath}`);
        } catch (error) {
          console.error(`Error creating cursor-rules.mdc file: ${error}`);
          throw new Error(`Cannot create cursor-rules.mdc file: ${error}`);
        }
        
        return {
          content: [{ 
            type: 'text', 
            text: `✅ Cursor Rules successfully created!\n\nLocation: ${cursorRulesPath}` 
          }]
        };
      } catch (ruleGenError) {
        console.error(`Error generating cursor rules content: ${ruleGenError}`);
        
        // Detaylı hata mesajı oluştur
        let errorMessage = 'Error generating Cursor Rules content: ';
        if (ruleGenError instanceof Error) {
          errorMessage += ruleGenError.message;
          
          // API key ile ilgili hata mesajlarını daha açıklayıcı hale getir
          if (ruleGenError.message.includes('GEMINI_API_KEY') || ruleGenError.message.includes('API key')) {
            errorMessage += '\n\nÖnemli: Bu özellik Gemini API kullanıyor. Lütfen .env dosyasında geçerli bir GEMINI_API_KEY tanımladığınızdan emin olun.';
          }
        } else {
          errorMessage += String(ruleGenError);
        }
        
        throw new Error(errorMessage);
      }
    } catch (error) {
      console.error('Error creating Cursor Rules:', error);
      return {
        content: [{ type: 'text', text: `❌ Error: ${error instanceof Error ? error.message : String(error)}` }],
        isError: true
      };
    }
  }
);

// Read document contents - provides as resource
server.resource(
  'memory_bank_document',
  'memory-bank://{documentType}',
  async (uri) => {
    try {
      // First check if Memory Bank has been initialized
      if (!MEMORY_BANK_DIR) {
        throw new Error('Memory Bank not initialized. Please use initialize_memory_bank tool first.');
      }
      
      const documentType = uri.pathname.split('/').pop();
      const validDocumentTypes = ['projectbrief', 'productContext', 'systemPatterns', 'techContext', 'activeContext', 'progress'];
      
      if (!documentType || !validDocumentTypes.includes(documentType)) {
        throw new Error(`Invalid document type: ${documentType}`);
      }
      
      const filePath = path.join(MEMORY_BANK_DIR, `${documentType}.md`);
      
      // Check if file exists
      if (!await fs.pathExists(filePath)) {
        // Create file if it doesn't exist
        await fs.ensureFile(filePath);
        await fs.writeFile(filePath, `# ${documentType}\n\nThis document has not been created yet.`, 'utf-8');
      }
      
      const content = await readDocument(filePath);
      
      return {
        contents: [{
          uri: uri.href,
          text: content
        }]
      };
    } catch (error) {
      console.error('Error reading document:', error);
      throw error;
    }
  }
);

// Export MCP server
export default server;

// Direct execution function
export async function startServer(): Promise<void> {
  const transport = new StdioServerTransport();
  
  try {
    console.log('Starting Memory Bank MCP server...');
    await server.connect(transport);
    console.log('Memory Bank MCP server successfully started!');
  } catch (error) {
    console.error('Error starting server:', error);
    process.exit(1);
  }
} 
```