Skip to content

pangialernios/claude-gemini-mcp

Folders and files

NameName
Last commit message
Last commit date

Latest commit

 

History

1 Commit
 
 
 
 
 
 
 
 
 
 
 
 
 
 

Repository files navigation

Claude-Gemini MCP with Context Management

An advanced MCP (Model Context Protocol) server that enables seamless collaboration between Claude and Gemini with intelligent persistent context management.

✨ Key Features

🤖 AI Collaboration

  • Multi-round conversations between Claude and Gemini
  • Consensus detection to identify areas of agreement
  • Intelligent synthesis of different AI perspectives
  • Direct Gemini querying for specific questions

🧠 Persistent Context Management

  • Session continuity - conversations remember previous discussions
  • Intelligent context injection - relevant history automatically included
  • Explicit context APIs - full developer control over what gets remembered
  • Active recall suggestions - proactive recommendations based on past interactions

🔒 Security & Privacy

  • AES-256 encryption for all stored context data
  • Automatic sensitive data masking (API keys, PII, credentials, etc.)
  • Session-based access control with UUID validation
  • Configurable data retention and expiry policies
  • Local storage only - no external dependencies

🎛️ Developer Control

  • 6 context management tools for fine-grained control
  • Flexible configuration via environment variables
  • Tag-based organization for context categorization
  • Relevance scoring for intelligent context retrieval

Quick Start

1. Installation

git clone <repository-url>
cd claude-gemini-mcp
npm install

2. Configuration

cp .env.example .env
# Add your Gemini API key and optional settings

3. Build and Start

npm run build
npm start

4. Claude Code Integration

Run this command from the project root directory:

claude mcp add --scope user claude-gemini node $(pwd)/dist/index.js

Environment Configuration

# Required: Get your API key from https://aistudio.google.com/app/apikey
GEMINI_API_KEY=your_gemini_api_key_here

# Optional: Model selection (default: gemini-2.5-flash)
GEMINI_MODEL=gemini-2.5-flash

# Context Management Settings
CONTEXT_DB_PATH=./data/context.db                    # Database location
CONTEXT_ENCRYPTION_KEY=your_64_char_hex_key         # Encryption key
CONTEXT_MAX_ENTRIES=1000                            # Max entries per session
CONTEXT_DEFAULT_EXPIRY_DAYS=30                      # Default expiry
ENABLE_CONTEXT_LOGGING=true                         # Operation logging

Available Tools

Core Collaboration

collaborate

Enhanced collaborative conversation with persistent context.

await collaborate({
  prompt: "How should we optimize this API endpoint?",
  claudeResponse: "I suggest implementing caching...",
  sessionId: "optional-existing-session",           // For continuity
  useContext: true,                                 // Enable context (default)
  contextTags: ["api", "optimization", "caching"]  // Filter relevant context
});

query_gemini

Direct query to Gemini for specific questions.

await query_gemini({
  prompt: "What are the latest best practices for React state management?"
});

Context Management

create_session

Create a new context session for organized conversations.

const session = await create_session({
  userId: "developer-123",
  projectId: "mobile-app-redesign"
});

add_to_context

Store important information for future reference.

await add_to_context({
  sessionId: session.sessionId,
  data: {
    decision: "Use Redux Toolkit for state management",
    rationale: "Better DevTools and reduced boilerplate",
    alternatives: ["Zustand", "Valtio", "React Context"]
  },
  tags: ["decision", "state-management", "redux"],
  key: "state-management-decision"
});

get_context_summary

Get an overview of your session's context.

const summary = await get_context_summary({
  sessionId: session.sessionId
});
// Returns: totalEntries, recentEntries, tags, summary, tokenCount

get_relevant_context

Retrieve specific context entries.

const relevantContext = await get_relevant_context({
  sessionId: session.sessionId,
  tags: ["api", "performance"],
  limit: 5
});

clear_context

Clean up context data with flexible scoping.

await clear_context({
  sessionId: session.sessionId,
  scope: "expired"  // "session", "expired", or "all"
});

tag_context

Add metadata tags to existing context entries.

await tag_context({
  sessionId: session.sessionId,
  entryId: "context-entry-id",
  tags: ["reviewed", "approved", "production-ready"]
});

Usage Patterns

Project-Based Workflow

// 1. Start a project session
const session = await create_session({
  projectId: "ecommerce-checkout-redesign"
});

// 2. Add project requirements
await add_to_context({
  sessionId: session.sessionId,
  data: {
    requirements: ["Mobile-first design", "One-click checkout", "Guest checkout"],
    constraints: ["PCI compliance", "Existing payment gateway", "2-second load time"]
  },
  tags: ["requirements", "constraints", "project-start"]
});

// 3. Collaborate with context awareness
const designResult = await collaborate({
  prompt: "Design the new checkout flow",
  claudeResponse: "Based on the requirements for mobile-first design...",
  sessionId: session.sessionId,
  contextTags: ["requirements", "design"]
});

// 4. Continue iterating with full context
const implementationResult = await collaborate({
  prompt: "How do we implement the one-click checkout?",
  claudeResponse: "Building on our design discussion...",
  sessionId: session.sessionId  // Previous context automatically included
});

Research and Decision Making

// Research session with context accumulation
const researchSession = await create_session({
  projectId: "database-migration-research"
});

// Accumulate research findings
await add_to_context({
  sessionId: researchSession.sessionId,
  data: {
    database: "PostgreSQL",
    pros: ["ACID compliance", "JSON support", "Strong ecosystem"],
    cons: ["Learning curve", "Resource usage"],
    benchmarks: { reads: "15k qps", writes: "8k qps" }
  },
  tags: ["research", "postgresql", "benchmarks"]
});

// Make informed decisions with full research context
const decision = await collaborate({
  prompt: "Should we migrate from MySQL to PostgreSQL?",
  claudeResponse: "Let me analyze this migration decision...",
  sessionId: researchSession.sessionId,
  contextTags: ["research", "decision", "migration"]
});

Development

Scripts

npm run dev      # Development mode with auto-reload
npm run build    # Build TypeScript to JavaScript
npm run start    # Start production server
npm run clean    # Clean build directory
npm run rebuild  # Clean and rebuild

Project Structure

src/
├── context/           # Context management system
│   ├── storage.ts     # SQLite + encryption layer
│   ├── manager.ts     # High-level context operations
│   └── security.ts    # Data masking and security
├── tools/             # MCP tools
│   ├── conversation.ts    # Enhanced collaboration tool
│   ├── context-tools.ts   # Context management APIs
│   └── gemini-query.ts    # Direct Gemini queries
├── gemini/            # Gemini client
│   └── client.ts      # API wrapper
├── types.ts           # TypeScript interfaces
├── server.ts          # MCP server implementation
└── index.ts           # Entry point

Security Features

Automatic Data Protection

The system automatically detects and masks sensitive information:

  • API keys and tokens (any pattern like api_key=...)
  • JWT tokens
  • GitHub tokens (ghp_, gho_)
  • Google API keys (AIza...)
  • AWS access keys (AKIA...)
  • Email addresses
  • Credit card numbers
  • Phone numbers
  • IP addresses
  • Database connection strings

Access Control

  • Session isolation: Each session has its own encrypted context
  • UUID validation: Only valid session IDs are accepted
  • Configurable expiry: Auto-cleanup of old context data
  • Audit logging: Track all context operations (configurable)

Privacy by Design

  • Local storage only: No external services or cloud dependencies
  • Encryption at rest: All context data encrypted with AES-256
  • Opt-in storage: Context can be disabled entirely
  • Safe summaries: Context summaries don't leak sensitive details

Architecture

Context Storage

SQLite Database (AES-256 Encrypted)
├── Sessions Table
│   ├── Session metadata and lifecycle
│   └── Encrypted summaries
├── Context Entries Table
│   ├── Encrypted data with relevance scoring
│   ├── Tag-based categorization
│   └── Configurable expiry timestamps
└── Indexes for performance
    ├── Session-based lookups
    ├── Time-based queries
    └── Relevance scoring

Security Pipeline

Input Data → Sensitive Data Detection → Encryption → Storage
                     ↓
            [REDACTED] markers replace sensitive content

Context Management Flow

User Input → Context Retrieval → Enhanced Prompt → AI Collaboration → Context Storage
     ↑                                                                        ↓
     └─── Active Recall Suggestions ←─── Analysis ←─── Results Storage ←─────┘

Troubleshooting

Common Issues

"GEMINI_API_KEY environment variable is required"

  • Get your API key from Google AI Studio
  • Add it to your .env file: GEMINI_API_KEY=your_key_here

"Failed to encrypt/decrypt data"

  • Generate a 64-character hex string for CONTEXT_ENCRYPTION_KEY
  • Use: node -e "console.log(require('crypto').randomBytes(32).toString('hex'))"
  • Without this key, data won't persist across server restarts

Context not working between sessions

  • Verify the data directory exists and is writable
  • Check that the same encryption key is used consistently
  • Ensure the database file path is accessible

Performance issues

  • Reduce CONTEXT_MAX_ENTRIES (default: 1000)
  • Set shorter CONTEXT_DEFAULT_EXPIRY_DAYS (default: 30)
  • Use clear_context with scope: "expired" regularly

Large memory usage

  • Context data is cached in memory for performance
  • Use shorter expiry times for development
  • Consider restarting the server periodically for long-running sessions

Roadmap

✅ Current (v2.0.0)

  • ✅ Persistent context management with encryption
  • ✅ Enhanced AI collaboration with context awareness
  • ✅ Comprehensive security and privacy measures
  • ✅ Full developer control via explicit APIs

🚧 Phase 2: AI-Powered Context (Planned)

  • 🔄 Intelligent context summarization
  • 🔄 Cost-aware context management
  • 🔄 Advanced relevance algorithms
  • 🔄 Context decay and freshness scoring

📋 Phase 3: Advanced Features (Future)

  • 📅 Hierarchical context organization
  • 📅 Cross-session context linking
  • 📅 Collaborative multi-user contexts
  • 📅 Advanced collaboration modes
  • 📅 Plugin system for custom context processors

License

MIT License - see LICENSE file for details.

Support

  • 📚 Documentation: Check this README and inline code comments
  • 🐛 Issues: GitHub Issues for bugs and feature requests
  • 💬 Discussions: GitHub Discussions for questions and ideas

Claude-Gemini MCP v2.0 - Intelligent AI collaboration with persistent memory. 🤖🧠✨

About

An advanced MCP (Model Context Protocol) server that enables seamless collaboration between Claude and Gemini with intelligent persistent context management.

Topics

Resources

Stars

Watchers

Forks

Releases

No releases published

Packages

 
 
 

Contributors