diff --git a/.agents/CONTEXT7_AGENT_README.md b/.agents/CONTEXT7_AGENT_README.md new file mode 100644 index 000000000..d0b12437a --- /dev/null +++ b/.agents/CONTEXT7_AGENT_README.md @@ -0,0 +1,328 @@ +# Context7 Documentation Expert Agent + +## Genel Bakış +Context7 Documentation Expert, Context7 platformunu kullanarak güncel, sürüm-spesifik dokümantasyon ve kod örnekleri sağlayan özel bir agent'tır. Eski kod, hayali API'ler ve genel cevaplar gibi yaygın sorunları, güncel bilgilere doğrudan kaynaktan erişerek ortadan kaldırır. + +## Temel Özellikler + +### 🎯 Kapsamlı Teknoloji Desteği +- **Model**: OpenAI GPT-5 (en güçlü reasoning model) +- **Reasoning Options**: High effort, excluded from output +- **Output Mode**: All messages (tüm süreci gösterir) +- **Memory**: Message history dahil (context preservation) + +### 🔧 Gelişmiş Dokümantasyon Yetenekleri +- **Smart Library Resolution**: Otomatik kütüphane tanımlama ve çözümleme +- **Up-to-Date Documentation**: Güncel, sürüm-spesifik dokümantasyon +- **Accurate Code Generation**: Çalışan kod örnekleri üretme +- **Context Integration**: Mevcut codebase ile entegrasyon +- **Version-Specific Guidance**: Sürüm-spesifik rehberlik + +### 🛠️ Teknik Detaylar +```typescript +// Agent Configuration +{ + id: 'context7-agent', + model: 'openai/gpt-5', + reasoningOptions: { enabled: true, effort: 'high', exclude: true }, + toolNames: [ + 'mcp_Context7_resolve_library_id', + 'mcp_Context7_get_library_docs', + 'code_search', + 'read_files', + 'end_turn' + ], + outputMode: 'all_messages', + includeMessageHistory: true +} +``` + +## Kullanım Senaryoları + +### 1. Kütüphane Kurulumu ve Konfigürasyonu +``` +"Next.js 14 uygulamasında Supabase ile authentication nasıl kurulur?" +``` + +### 2. API Entegrasyonu +``` +"MongoDB Node.js driver'ın son sürümü ile aggregation query'leri nasıl yapılır?" +``` + +### 3. Framework Migrasyonu +``` +"React Router v5'ten v6'ya geçiş yaparken hangi breaking change'ler var?" +``` + +### 4. Troubleshooting ve Debugging +``` +"Prisma v5'e upgrade ettikten sonra query'lerim çalışmıyor, ne değişti?" +``` + +### 5. Best Practice ve Optimizasyon +``` +"Vue 3 ile TypeScript'te state management için önerilen yöntem nedir?" +``` + +## Desteklenen Teknolojiler + +### Frontend Framework'leri +- **React**: Components, hooks, state management, routing +- **Vue**: Composition API, Pinia, Vue Router +- **Angular**: Components, services, RxJS patterns +- **Svelte/SvelteKit**: Stores, routing, SSR +- **Next.js**: App Router, API routes, middleware + +### Backend Teknolojileri +- **Node.js**: Express, Fastify, NestJS +- **Python**: FastAPI, Django, Flask +- **Go**: Gin, Echo, Fiber +- **Rust**: Actix, Axum, Warp +- **Java**: Spring Boot, Quarkus + +### Veritabanları ve ORM'ler +- **MongoDB**: Native driver, Mongoose +- **PostgreSQL**: pg, Prisma, TypeORM +- **Redis**: ioredis, node-redis +- **Supabase**: Client libraries, auth, realtime +- **Firebase**: Firestore, Auth, Functions + +### Cloud ve DevOps +- **AWS**: SDK kullanımı, CDK patterns +- **Vercel**: Deployment, edge functions +- **Docker**: Containerization, multi-stage builds +- **Kubernetes**: Manifests, Helm charts + +## Agent Workflow'u + +### Adım 1: Query Analizi +``` +Kullanıcı: "Express'te Socket.io ile real-time chat nasıl implement edilir?" +``` + +### Adım 2: Kütüphane Çözümleme +``` +Agent şunları çözümler: +- socket.io (server library) +- express (web framework) +``` + +### Adım 3: Dokümantasyon Getirme +``` +Agent şunları getirir: +- Socket.io server setup dokümantasyonu +- Express entegrasyon pattern'leri +- Real-time event handling örnekleri +``` + +### Adım 4: Çözüm Üretme +``` +Agent şunları sağlar: +- Tam Express + Socket.io kurulumu +- Client-side bağlantı kodu +- Event handling pattern'leri +- Error handling ve reconnection logic +``` + +## Diğer Agent'larla Entegrasyon + +### Tamamlayıcı Agent'lar +- **File Explorer**: Mevcut proje yapısını analiz etme +- **Code Reviewer**: Üretilen kodu proje standartlarına göre doğrulama +- **Researcher**: Teknoloji seçimleri hakkında ek context toplama +- **Sequential Thinker**: Karmaşık entegrasyon kararlarının derin analizi + +### Spawning Örnekleri +```typescript +// Genel coding agent'tan +{ + agent_type: 'context7-agent', + prompt: 'Apollo Server v4 ile GraphQL subscription implementasyonu için güncel dokümantasyon lazım' +} + +// Proje kurulum agent'tan +{ + agent_type: 'context7-agent', + prompt: 'Vitest ve React Testing Library ile testing kurulumu için son pattern'leri göster' +} +``` + +## MCP Tool Entegrasyonu + +### Gerekli MCP Tool'ları +- `mcp_Context7_resolve_library_id`: Kütüphane identifier'larını çözümler +- `mcp_Context7_get_library_docs`: Dokümantasyon getirir +- `code_search`: Mevcut codebase'i analiz eder +- `read_files`: Proje dosyalarını context için okur + +### Context7 Platform Özellikleri +- **Up-to-date Information**: Her zaman güncel bilgi +- **Version-Specific**: Sürüm-spesifik dokümantasyon +- **Source-Direct**: Doğrudan kaynaktan bilgi +- **Code Examples**: Çalışan kod örnekleri +- **API References**: Güncel API referansları + +## Test Coverage + +### Unit Tests +- ✅ Temel konfigürasyon doğrulaması +- ✅ Reasoning options kontrolü +- ✅ Tool configuration testi +- ✅ Input schema validasyonu +- ✅ HandleSteps generator testi +- ✅ Type compatibility kontrolü +- ✅ Context7 MCP tool entegrasyonu +- ✅ Agent capabilities validasyonu + +### Test Çalıştırma +```bash +cd .agents +bun test context7-agent.test.ts +``` + +## Dosya Yapısı +``` +.agents/ +├── context7-agent.ts # Ana agent tanımı +├── context7-agent-demo.md # İngilizce kullanım kılavuzu +├── CONTEXT7_AGENT_README.md # Bu dosya (Türkçe) +└── __tests__/ + └── context7-agent.test.ts # Kapsamlı unit testler +``` + +## Performans Karakteristikleri + +| Özellik | Seviye | Açıklama | +|---------|--------|----------| +| Doğruluk | Çok Yüksek | Güncel, kaynak dokümantasyon kullanır | +| Güncellik | Her Zaman Güncel | Son sürüm bilgilerini getirir | +| Kapsamlılık | Yüksek | Comprehensive örnekler sağlar | +| Hız | Hızlı | Verimli dokümantasyon getirme | +| Güvenilirlik | Yüksek | Hayali API'leri ortadan kaldırır | + +## En İyi Sonuçlar İçin İpuçları + +### 1. Sürümler Hakkında Spesifik Olun +``` +✅ İyi: "React Query v5'i Next.js 14 ile nasıl kullanırım?" +❌ Belirsiz: "React Query nasıl kullanılır?" +``` + +### 2. Context Ekleyin +``` +✅ İyi: "Express 4'ten 5'e geçiş yapıyorum, breaking change'ler neler?" +❌ Belirsiz: "Express nasıl kullanılır?" +``` + +### 3. Use Case Belirtin +``` +✅ İyi: "Multi-tenant SaaS app için Prisma ile PostgreSQL kurulumu" +❌ Belirsiz: "Prisma nasıl kullanılır?" +``` + +### 4. Kısıtlamaları Belirtin +``` +✅ İyi: "Vue 3 için Vite ve ESLint ile TypeScript kurulumu" +❌ Belirsiz: "Vue 3 kurulumu" +``` + +## Yaygın Query Pattern'leri + +### Kurulum ve İnstallasyon +- "[kütüphane]'yi [framework] ile nasıl kurarım?" +- "[araç]'ı [use case] için configure etmenin önerilen yolu nedir?" +- "[teknoloji stack] için installation süreci nasıl?" + +### Entegrasyon ve Kullanım +- "[kütüphane A]'yı [kütüphane B] ile nasıl entegre ederim?" +- "[spesifik fonksiyonalite] için [kütüphane] kullanarak en iyi pattern nedir?" +- "[API/feature] kullanım örneklerini göster" + +### Migrasyon ve Güncellemeler +- "[eski sürüm]'den [yeni sürüm]'e nasıl migrate ederim?" +- "[kütüphane] sürüm [X]'te ne değişti?" +- "Kodumu [eski pattern]'den [yeni pattern]'e güncelle" + +### Troubleshooting +- "[kütüphane] ile [spesifik hata] neden oluyor?" +- "[framework/kütüphane]'de [sorun]'u nasıl çözerim?" +- "[edge case]'i handle etmenin doğru yolu nedir?" + +## Örnek Etkileşimler + +### React Query Kurulumu +``` +Kullanıcı: "Next.js 14 App Router ile React Query v5 kurulumu" + +Agent Süreci: +1. @tanstack/react-query ve Next.js kütüphanelerini çözümler +2. v5 dokümantasyonu ve App Router entegrasyonunu getirir +3. Provider'lar, hydration ve SSR ile tam kurulum sağlar +``` + +### Veritabanı Entegrasyonu +``` +Kullanıcı: "Prisma'yı Supabase PostgreSQL ile row-level security'de bağla" + +Agent Süreci: +1. Prisma ve Supabase dokümantasyonunu çözümler +2. RLS kurulum pattern'leri ve Prisma konfigürasyonunu getirir +3. Schema kurulumu, client konfigürasyonu ve security pattern'leri sağlar +``` + +### Authentication Implementasyonu +``` +Kullanıcı: "Express'te refresh token'lı JWT authentication implement et" + +Agent Süreci: +1. Express ve JWT kütüphane dokümantasyonunu çözümler +2. Güncel security best practice'leri getirir +3. Middleware ve token handling ile tam auth flow sağlar +``` + +## Gelişmiş Özellikler + +### Multi-Library Koordinasyonu +- Birden fazla teknoloji içeren karmaşık query'leri handle eder +- Farklı kütüphane sürümleri arasında uyumluluk sağlar +- Teknoloji stack'leri için entegrasyon pattern'leri sağlar + +### Sürüm-Spesifik Rehberlik +- Uygun kütüphane sürümlerini otomatik tespit eder ve kullanır +- Sürümler arası breaking change'leri vurgular +- Migration path'leri ve upgrade stratejileri sağlar + +### Context-Aware Öneriler +- Mevcut proje yapısını analiz eder +- Mevcut mimariye uygun pattern'ler önerir +- Mevcut kod stili ile tutarlılığı korur + +## Hata Yönetimi ve Fallback'ler + +### Kütüphane Bulunamadı +- Benzer veya alternatif kütüphaneler önerir +- Teknoloji alanı için genel dokümantasyon sağlar +- İlgili teknolojileri aramayı teklif eder + +### Dokümantasyon Boşlukları +- Genel best practice'lere fallback yapar +- Resmi dokümantasyon kaynaklarını önerir +- Community-recommended pattern'leri sağlar + +### Sürüm Çakışmaları +- Uyumluluk sorunlarını tespit eder +- Uyumlu sürüm kombinasyonları önerir +- Workaround çözümleri sağlar + +## Geliştirme Notları + +Bu agent, mevcut .agents klasöründeki şu agent'ların analizi sonucu geliştirilmiştir: +- `ask.ts` - Base ask-mode agent patterns +- `researcher.ts` - Web search ve documentation analysis +- `file-picker.ts` - File system integration +- `deepest-thinker.ts` - Comprehensive analysis coordination +- `gemini-thinker.ts` - Creative problem solving + +Context7 MCP Server'ın tüm gelişmiş özelliklerini (library resolution, documentation fetching, version-specific guidance) kullanarak en güncel ve doğru kod çözümleri sunar. + +Bu agent, developer'ların dokümantasyona erişim ve kullanım şeklini dönüştürür, her zaman güncel ve doğru bilgiye sahip olmalarını sağlayarak güvenilir uygulamalar geliştirmelerine yardımcı olur. \ No newline at end of file diff --git a/.agents/SEQUENTIAL_THINKER_README.md b/.agents/SEQUENTIAL_THINKER_README.md new file mode 100644 index 000000000..6a81be23b --- /dev/null +++ b/.agents/SEQUENTIAL_THINKER_README.md @@ -0,0 +1,146 @@ +# Sequential Deep Thinker Agent + +## Genel Bakış +Sequential Deep Thinker, .agents klasöründeki mevcut agent örnekleri analiz edilerek geliştirilmiş kapsamlı bir düşünme agent'ıdır. MCP Sequential Thinking protokolünü kullanarak adım adım analiz, revizyon ve sentez yetenekleri sunar. + +## Temel Özellikler + +### 🎯 Kapsamlı Analiz +- **Model**: OpenAI GPT-5 (en güçlü reasoning model) +- **Reasoning Options**: High effort, excluded from output +- **Output Mode**: All messages (tüm düşünce sürecini gösterir) +- **Memory**: Message history dahil (context preservation) + +### 🔧 Gelişmiş Düşünme Yetenekleri +- **Sequential Processing**: Adım adım mantıklı analiz +- **Dynamic Planning**: İhtiyaca göre düşünce sayısını ayarlama +- **Revision Logic**: Önceki düşünceleri gözden geçirme ve geliştirme +- **Branching**: Alternatif yaklaşımları paralel keşfetme +- **Synthesis**: Tüm insights'ları sentezleme + +### 🛠️ Teknik Detaylar +```typescript +// Agent Configuration +{ + id: 'sequential-thinker', + model: 'openai/gpt-5', + reasoningOptions: { enabled: true, effort: 'high', exclude: true }, + toolNames: ['mcp_sequential_thinking_sequentialthinking', 'end_turn'], + outputMode: 'all_messages', + includeMessageHistory: true +} +``` + +## Kullanım Senaryoları + +### 1. Karmaşık Problem Çözme +``` +"Bir startup'ın core infrastructure için in-house geliştirme vs mevcut çözümleri satın alma arasında nasıl karar vermesi gerekir?" +``` + +### 2. Stratejik Karar Verme +``` +"Büyüyen bir e-ticaret platformu için microservices vs monolithic architecture trade-off'larını analiz et." +``` + +### 3. Çok Boyutlu Analiz +``` +"Büyük bir development team'de AI-powered code review implementasyonunun etkilerini değerlendir." +``` + +### 4. Araştırma ve İnceleme +``` +"Finansal modelleme için quantum computing adoption'ın potansiyel risk ve faydalarını analiz et." +``` + +## Düşünce Süreci + +### Faz 1: İlk Analiz +- Problem kapsamını değerlendirme +- Karmaşıklık tahmini +- Yaklaşım planlaması + +### Faz 2: Iteratif Geliştirme +- Sistematik keşif +- Kanıt toplama ve analiz +- Alternatif perspektif değerlendirmesi + +### Faz 3: Kritik İnceleme +- Varsayımları sorgulama +- Mantık doğrulama +- Boşluk tespiti + +### Faz 4: Sentez +- Insight entegrasyonu +- Sonuç formülasyonu +- Uygulanabilir öneriler + +## Diğer Agent'larla Entegrasyon + +### Tamamlayıcı Agent'lar +- **Researcher**: Dış bilgi toplama için +- **File Explorer**: Teknik kararlar için codebase context'i +- **Deepest Thinker**: Kritik kararlar için daha kapsamlı analiz + +### Spawning Örnekleri +```typescript +// Diğer agent'lardan spawn etme +{ + agent_type: 'sequential-thinker', + prompt: 'Bu karmaşık teknik kararı adım adım analiz et' +} +``` + +## Test Coverage + +### Unit Tests +- ✅ Temel konfigürasyon doğrulaması +- ✅ Reasoning options kontrolü +- ✅ Tool configuration testi +- ✅ Input schema validasyonu +- ✅ HandleSteps generator testi +- ✅ Type compatibility kontrolü + +### Test Çalıştırma +```bash +cd .agents +bun test sequential-thinker.test.ts +``` + +## Dosya Yapısı +``` +.agents/ +├── sequential-thinker.ts # Ana agent tanımı +├── sequential-thinker-demo.md # Kullanım kılavuzu ve örnekler +├── SEQUENTIAL_THINKER_README.md # Bu dosya +└── __tests__/ + └── sequential-thinker.test.ts # Unit testler +``` + +## Performans Karakteristikleri + +| Özellik | Seviye | Açıklama | +|---------|--------|----------| +| Kapsamlılık | Çok Yüksek | Problemleri çok boyutlu analiz eder | +| Şeffaflık | Tam | Tüm düşünce sürecini gösterir | +| Uyarlanabilirlik | Yüksek | Problem karmaşıklığına göre ayarlanır | +| Verimlilik | Dengeli | Kapsamlı ama gereksiz detaydan kaçınır | +| Doğruluk | Yüksek | Sistematik yaklaşım hataları azaltır | + +## En İyi Sonuçlar İçin İpuçları + +1. **Spesifik Olun**: Net, detaylı problem tanımları sağlayın +2. **Context Ekleyin**: İlgili background bilgilerini paylaşın +3. **Beklenti Belirleyin**: Hızlı insight vs derin analiz ihtiyacını belirtin +4. **Takip Soruları**: Agent'ın sonuçlarını daha derin keşif için başlangıç noktası olarak kullanın + +## Geliştirme Notları + +Bu agent, mevcut .agents klasöründeki şu agent'ların analizi sonucu geliştirilmiştir: +- `deepest-thinker.ts` - Çoklu agent koordinasyonu +- `gemini-thinker-high.ts` - High effort reasoning +- `gpt5-thinker.ts` - GPT-5 quick thinking +- `sonnet-thinker.ts` - Balanced analysis +- `thinker.ts` (factory) - Base thinker patterns + +MCP Sequential Thinking tool'unun tüm gelişmiş özelliklerini (revision, branching, dynamic planning) kullanarak en kapsamlı düşünme deneyimini sunar. \ No newline at end of file diff --git a/.agents/context7-agent.ts b/.agents/context7-agent.ts new file mode 100644 index 000000000..a2512d124 --- /dev/null +++ b/.agents/context7-agent.ts @@ -0,0 +1,101 @@ +import { publisher } from './constants' +import type { AgentDefinition, ToolCall } from './types/agent-definition' + +const definition: AgentDefinition = { + id: 'context7-agent', + displayName: 'Context7 Documentation Expert', + publisher, + model: 'openai/gpt-5', + reasoningOptions: { + enabled: true, + effort: 'high', + exclude: true, + }, + + inputSchema: { + prompt: { + type: 'string', + description: 'A coding question, library inquiry, or technical problem that requires up-to-date documentation and code examples.', + }, + }, + + includeMessageHistory: true, + outputMode: 'all_messages', + toolNames: [ + 'mcp_Context7_resolve_library_id' as any, + 'mcp_Context7_get_library_docs' as any, + 'code_search', + 'read_files', + 'end_turn' + ], + spawnableAgents: [], + + spawnerPrompt: + 'Spawn this agent when you need up-to-date documentation, code examples, or API references for any library, framework, or technology. It specializes in finding current, version-specific information and providing accurate code solutions.', + + systemPrompt: `# Persona: Context7 Documentation Expert + +You are an expert agent that specializes in providing up-to-date, accurate documentation and code examples using the Context7 platform. Your mission is to eliminate outdated code, hallucinated APIs, and generic answers by accessing current, version-specific information directly from the source. + +## Your Core Capabilities: +- **Library Resolution**: Identify and resolve the correct Context7-compatible library IDs for any technology +- **Documentation Retrieval**: Fetch current, comprehensive documentation with code examples +- **Version-Specific Guidance**: Provide accurate information for specific library versions +- **Code Generation**: Generate working code based on up-to-date documentation +- **API Reference**: Access current API documentation and usage patterns +- **Best Practices**: Share current best practices and recommended patterns + +## Your Workflow: +1. **Analyze Request**: Understand what library, framework, or technology the user needs help with +2. **Resolve Library**: Use Context7 to find the correct library identifier +3. **Fetch Documentation**: Retrieve up-to-date docs focused on the user's specific needs +4. **Generate Solution**: Provide accurate, working code examples and explanations +5. **Validate & Enhance**: Cross-reference with local codebase if relevant + +## Your Expertise Areas: +- Web frameworks (React, Vue, Angular, Next.js, etc.) +- Backend technologies (Node.js, Python, Go, etc.) +- Databases (MongoDB, PostgreSQL, Redis, etc.) +- Cloud services (AWS, GCP, Azure) +- DevOps tools (Docker, Kubernetes, CI/CD) +- Mobile development (React Native, Flutter) +- AI/ML libraries (TensorFlow, PyTorch, etc.) + +You excel at providing current, accurate information that prevents the common issues of outdated examples and deprecated APIs.`, + + instructionsPrompt: `You will help users with coding questions by providing up-to-date documentation and code examples using Context7. + +Your process: +1. **Identify Libraries**: Determine which libraries, frameworks, or technologies the user is asking about +2. **Resolve Library IDs**: Use the resolve-library-id tool to find the correct Context7-compatible identifiers +3. **Fetch Documentation**: Use get-library-docs to retrieve current, relevant documentation +4. **Provide Solutions**: Generate accurate code examples and explanations based on the up-to-date information +5. **Context Integration**: If working with an existing codebase, use code_search and read_files to understand the current setup + +Always prioritize accuracy and currency of information. When in doubt, fetch the latest documentation rather than relying on potentially outdated knowledge. + +Remember: Your goal is to provide working, current code solutions that users can implement immediately.`, + + stepPrompt: `Continue helping the user with their coding question. Consider: +- Have you identified all relevant libraries/technologies mentioned? +- Do you have the most current documentation for the user's specific needs? +- Are your code examples based on up-to-date information? +- Would additional documentation or examples be helpful? + +Always end your final response with the end_turn tool.`, + + handleSteps: function* ({ prompt, params }) { + // Initial analysis and library resolution + yield { + toolName: 'mcp_Context7_resolve_library_id' as any, + input: { + libraryName: prompt || 'general documentation', + }, + } + + // Continue with iterative documentation fetching and solution generation + yield 'STEP_ALL' + }, +} + +export default definition \ No newline at end of file diff --git a/.agents/sequential-thinker.ts b/.agents/sequential-thinker.ts new file mode 100644 index 000000000..40a70451d --- /dev/null +++ b/.agents/sequential-thinker.ts @@ -0,0 +1,90 @@ +import { publisher } from './constants' +import type { AgentDefinition, ToolCall } from './types/agent-definition' + +const definition: AgentDefinition = { + id: 'sequential-thinker', + displayName: 'Sequential Deep Thinker', + publisher, + model: 'openai/gpt-5', + reasoningOptions: { + enabled: true, + effort: 'high', + exclude: true, + }, + + inputSchema: { + prompt: { + type: 'string', + description: 'The complex problem, question, or topic that requires deep sequential analysis and step-by-step thinking.', + }, + }, + + includeMessageHistory: true, + outputMode: 'all_messages', + toolNames: ['mcp_sequential_thinking_sequentialthinking', 'end_turn'] as const, + spawnableAgents: [], + + spawnerPrompt: + 'Spawn this agent when you need the most comprehensive sequential thinking analysis. It breaks down complex problems into manageable steps, revises thinking as needed, explores alternative approaches, and synthesizes insights into clear conclusions.', + + systemPrompt: `# Persona: Sequential Deep Thinker + +You are an expert sequential thinking agent designed to tackle complex problems through systematic, step-by-step analysis. Your approach is methodical, transparent, and adaptive. + +## Your Core Capabilities: +- **Sequential Processing**: Break down complex problems into logical thinking steps +- **Dynamic Planning**: Adjust your thinking process based on emerging insights +- **Revision & Refinement**: Revisit and improve previous thoughts when new understanding emerges +- **Branching Logic**: Explore alternative approaches and perspectives in parallel +- **Synthesis**: Combine all insights into coherent, actionable conclusions +- **Transparency**: Make your entire thinking process visible and understandable + +## Your Thinking Protocol: +1. **Initial Analysis**: Understand the problem scope and estimate thinking complexity +2. **Iterative Development**: Build understanding step by step, each thought building on previous ones +3. **Critical Review**: Question your own assumptions and consider alternative viewpoints +4. **Adaptive Refinement**: Revise earlier thoughts when new insights emerge +5. **Comprehensive Synthesis**: Integrate all findings into a clear, final answer + +You excel at handling ambiguous, multi-faceted problems that require deep consideration of multiple angles, edge cases, and implications.`, + + instructionsPrompt: `You will now engage in sequential thinking to thoroughly analyze the given prompt. + +Your process: +1. Start with an initial assessment and planning phase +2. Work through the problem systematically, one thought at a time +3. Feel free to revise previous thoughts if new insights emerge +4. Explore different approaches through branching when beneficial +5. Synthesize all your thinking into a comprehensive final answer + +Use the sequential thinking tool to structure your analysis. Be thorough but efficient - adjust your total thought count as needed based on problem complexity. + +Remember: Your goal is not just to find AN answer, but to find the BEST answer through rigorous sequential analysis.`, + + stepPrompt: `Continue your sequential thinking process. Consider: +- What new insights have emerged from your previous thoughts? +- Do any previous thoughts need revision based on new understanding? +- Are there alternative approaches worth exploring? +- Are you ready to synthesize your findings, or do you need more analysis? + +Always end your final response with the end_turn tool.`, + + handleSteps: function* ({ prompt, params }) { + // Initial thinking phase - analyze the problem and start sequential thinking + yield { + toolName: 'mcp_sequential_thinking_sequentialthinking' as any, + input: { + thought: `I need to analyze this problem systematically: "${prompt}". Let me start by understanding the scope and complexity, then estimate how many thinking steps this will require. I'll break this down into manageable components and work through each one methodically.`, + nextThoughtNeeded: true, + thoughtNumber: 1, + totalThoughts: 5, // Initial estimate, will adjust as needed + }, + } + + // Continue with iterative thinking - the agent will use the tool multiple times + // Each STEP_ALL allows the agent to continue the sequential thinking process + yield 'STEP_ALL' + }, +} + +export default definition \ No newline at end of file diff --git a/backend/src/index.ts b/backend/src/index.ts index bda39f960..c5a404682 100644 --- a/backend/src/index.ts +++ b/backend/src/index.ts @@ -71,20 +71,24 @@ app.use( }, ) -// Initialize BigQuery before starting the server -setupBigQuery().catch((err) => { - logger.error( - { - error: err, - stack: err.stack, - message: err.message, - name: err.name, - code: err.code, - details: err.details, - }, - 'Failed to initialize BigQuery client', - ) -}) +// Initialize BigQuery before starting the server (only in production) +if (env.NEXT_PUBLIC_CB_ENVIRONMENT === 'prod') { + setupBigQuery().catch((err) => { + logger.error( + { + error: err, + stack: err.stack, + message: err.message, + name: err.name, + code: err.code, + details: err.details, + }, + 'Failed to initialize BigQuery client', + ) + }) +} else { + logger.debug('Skipping BigQuery initialization in development mode') +} initAnalytics() diff --git a/npm-app/src/cli-handlers/mcp-status.ts b/npm-app/src/cli-handlers/mcp-status.ts new file mode 100644 index 000000000..0754d5bf9 --- /dev/null +++ b/npm-app/src/cli-handlers/mcp-status.ts @@ -0,0 +1,106 @@ +import { green, red, yellow, cyan, bold } from 'picocolors' +import { McpServerManager } from '../mcp/mcp-server-manager' +import { logger } from '../utils/logger' + +export function handleMcpStatus(): void { + try { + const mcpManager = McpServerManager.getInstance() + const servers = mcpManager.getAllServers() + const availableTools = mcpManager.getAvailableTools() + + console.log(bold('\n🔧 MCP Server Status\n')) + + if (servers.length === 0) { + console.log(yellow('No MCP servers configured.')) + console.log('Add servers to .kiro/settings/mcp.json to get started.') + return + } + + // Display server status + console.log(bold('Servers:')) + servers.forEach((server) => { + const status = server.connected ? green('✓ Connected') : red('✗ Disconnected') + const toolCount = server.tools.length + + console.log(` ${bold(server.name)}: ${status} (${toolCount} tools)`) + + if (server.config.disabled) { + console.log(` ${yellow('(Disabled in configuration)')}`) + } + + if (server.tools.length > 0) { + console.log(` Tools: ${server.tools.map(t => cyan(t.name)).join(', ')}`) + } + }) + + // Display available tools summary + console.log(bold(`\nAvailable Tools (${availableTools.length}):`)) + if (availableTools.length > 0) { + availableTools.forEach((tool) => { + console.log(` ${green('•')} ${cyan(tool.name)}${tool.description ? ` - ${tool.description}` : ''}`) + }) + } else { + console.log(yellow(' No tools available. Check server connections.')) + } + + console.log(bold('\nUsage in Agents:')) + console.log('Add MCP tools to your agent\'s toolNames array:') + console.log(cyan(' toolNames: [\'mcp_tool_name\' as any, \'end_turn\']')) + + } catch (error) { + logger.error({ error }, 'Error getting MCP status') + console.log(red('Error getting MCP server status. Check logs for details.')) + } +} + +export async function handleMcpTest(toolName?: string): Promise { + try { + const mcpManager = McpServerManager.getInstance() + + if (!toolName) { + console.log(yellow('Please specify a tool name to test.')) + console.log('Example: mcp-test mcp_Context7_resolve_library_id') + return + } + + console.log(bold(`\n🧪 Testing MCP Tool: ${cyan(toolName)}\n`)) + + // Test with sample parameters + const testParams = getTestParameters(toolName) + console.log(`Parameters: ${JSON.stringify(testParams, null, 2)}`) + + const startTime = Date.now() + const result = await mcpManager.callTool(toolName, testParams) + const duration = Date.now() - startTime + + console.log(green(`\n✓ Tool call successful (${duration}ms)`)) + console.log(bold('Result:')) + console.log(JSON.stringify(result, null, 2)) + + } catch (error) { + logger.error({ error, toolName }, 'MCP tool test failed') + console.log(red(`✗ Tool call failed: ${error instanceof Error ? error.message : String(error)}`)) + } +} + +function getTestParameters(toolName: string): any { + // Return appropriate test parameters based on tool name + if (toolName.includes('resolve_library_id')) { + return { libraryName: 'react' } + } else if (toolName.includes('get_library_docs')) { + return { context7CompatibleLibraryID: '/facebook/react' } + } else if (toolName.includes('sequentialthinking')) { + return { + thought: 'This is a test thought', + nextThoughtNeeded: false, + thoughtNumber: 1, + totalThoughts: 1 + } + } else if (toolName.includes('read_file')) { + return { path: 'package.json' } + } else if (toolName.includes('list_directory')) { + return { path: '.' } + } + + return {} +} \ No newline at end of file diff --git a/npm-app/src/cli.ts b/npm-app/src/cli.ts index 7f7405695..1910c84ea 100644 --- a/npm-app/src/cli.ts +++ b/npm-app/src/cli.ts @@ -74,6 +74,7 @@ import { Client } from './client' import { backendUrl, websocketUrl } from './config' import { CONFIG_DIR } from './credentials' import { DiffManager } from './diff-manager' +import { McpServerManager } from './mcp/mcp-server-manager' import { printModeIsEnabled, printModeLog } from './display/print-mode' import { disableSquashNewlines, @@ -288,6 +289,7 @@ export class CLI { return client.warmContextCache() }), Client.getInstance().connect(), + McpServerManager.getInstance().initialize(), ]) this.setPrompt() @@ -448,7 +450,7 @@ export class CLI { // Load and populate history const history = this._loadHistory() - ;(this.rl as any).history.push(...history) + ; (this.rl as any).history.push(...history) this.rl.on('line', (line) => this.handleLine(line)) this.rl.on('SIGINT', async () => await this.handleSigint()) @@ -672,7 +674,7 @@ export class CLI { (cwd === projectRoot ? '' : (os.platform() === 'win32' ? '\\' : '/') + - path.relative(projectRoot, cwd)) + path.relative(projectRoot, cwd)) const modeIndicator = this.getModeIndicator() @@ -733,10 +735,10 @@ export class CLI { if (client.pendingTopUpMessageAmount > 0) { console.log( '\n\n' + - green( - `Auto top-up successful! ${client.pendingTopUpMessageAmount.toLocaleString()} credits added.`, - ) + - '\n', + green( + `Auto top-up successful! ${client.pendingTopUpMessageAmount.toLocaleString()} credits added.`, + ) + + '\n', ) client.pendingTopUpMessageAmount = 0 } @@ -894,7 +896,7 @@ export class CLI { private handleUnknownCommand(command: string) { console.log( yellow(`Unknown slash command: ${command}`) + - `\nType / to see available commands`, + `\nType / to see available commands`, ) this.freshPrompt() } @@ -1159,6 +1161,23 @@ export class CLI { return null } + // Handle MCP commands + if (this.isCommandOrAlias(cleanInput, 'mcp-status')) { + const { handleMcpStatus } = await import('./cli-handlers/mcp-status') + handleMcpStatus() + this.freshPrompt() + return null + } + + if (cleanInput.startsWith('mcp-test')) { + const { handleMcpTest } = await import('./cli-handlers/mcp-status') + const parts = cleanInput.split(' ') + const toolName = parts[1] + await handleMcpTest(toolName) + this.freshPrompt() + return null + } + // Checkpoint commands if (isCheckpointCommand(cleanInput)) { trackEvent(AnalyticsEvent.CHECKPOINT_COMMAND_USED, { @@ -1429,6 +1448,13 @@ export class CLI { cleanupAgentsBuffer() cleanupMiniChat() + // Shutdown MCP servers + try { + await McpServerManager.getInstance().shutdown() + } catch (error) { + logger.error({ error }, 'Error shutting down MCP servers') + } + Spinner.get().restoreCursor() process.removeAllListeners('unhandledRejection') process.removeAllListeners('uncaughtException') @@ -1470,7 +1496,7 @@ export class CLI { if (client.usageData.next_quota_reset) { const daysUntilReset = Math.ceil( (new Date(client.usageData.next_quota_reset).getTime() - Date.now()) / - (1000 * 60 * 60 * 24), + (1000 * 60 * 60 * 24), ) console.log( `Your free credits will reset in ${pluralize(daysUntilReset, 'day')}.`, diff --git a/npm-app/src/mcp/mcp-server-manager.ts b/npm-app/src/mcp/mcp-server-manager.ts new file mode 100644 index 000000000..b4e0b2fe9 --- /dev/null +++ b/npm-app/src/mcp/mcp-server-manager.ts @@ -0,0 +1,283 @@ +import { spawn, ChildProcess } from 'child_process' +import fs from 'fs' +import path from 'path' +import { logger } from '../utils/logger' +import { getProjectRoot } from '../project-files' + +export interface McpServerConfig { + command: string + args: string[] + env?: Record + disabled?: boolean + autoApprove?: string[] +} + +export interface McpServersConfig { + mcpServers: Record +} + +export interface McpTool { + name: string + description?: string + inputSchema?: any +} + +export interface McpServer { + name: string + config: McpServerConfig + process?: ChildProcess + tools: McpTool[] + connected: boolean +} + +export class McpServerManager { + private static instance: McpServerManager | null = null + private servers: Map = new Map() + private initialized = false + + private constructor() { } + + public static getInstance(): McpServerManager { + if (!McpServerManager.instance) { + McpServerManager.instance = new McpServerManager() + } + return McpServerManager.instance + } + + public async initialize(): Promise { + if (this.initialized) { + return + } + + logger.info('Initializing MCP Server Manager...') + + try { + const config = await this.loadMcpConfig() + if (!config) { + logger.info('No MCP configuration found, skipping MCP server initialization') + this.initialized = true + return + } + + await this.startServers(config) + this.initialized = true + logger.info(`MCP Server Manager initialized with ${this.servers.size} servers`) + } catch (error) { + logger.error({ error }, 'Failed to initialize MCP Server Manager') + this.initialized = true // Mark as initialized even on error to prevent retry loops + } + } + + private async loadMcpConfig(): Promise { + const projectRoot = getProjectRoot() || process.cwd() + const workspaceMcpPath = path.join(projectRoot, '.kiro', 'settings', 'mcp.json') + const globalMcpPath = path.join(process.env.HOME || '', '.kiro', 'settings', 'mcp.json') + + logger.info({ projectRoot, workspaceMcpPath, globalMcpPath }, 'Loading MCP config paths') + + let workspaceConfig: McpServersConfig | null = null + let globalConfig: McpServersConfig | null = null + + // Load workspace config + if (fs.existsSync(workspaceMcpPath)) { + try { + const content = fs.readFileSync(workspaceMcpPath, 'utf-8') + workspaceConfig = JSON.parse(content) + logger.info('Loaded workspace MCP configuration') + } catch (error) { + logger.error({ error, path: workspaceMcpPath }, 'Failed to parse workspace MCP config') + } + } + + // Load global config + if (fs.existsSync(globalMcpPath)) { + try { + const content = fs.readFileSync(globalMcpPath, 'utf-8') + globalConfig = JSON.parse(content) + logger.info('Loaded global MCP configuration') + } catch (error) { + logger.error({ error, path: globalMcpPath }, 'Failed to parse global MCP config') + } + } + + // Merge configs (workspace takes precedence) + if (!workspaceConfig && !globalConfig) { + return null + } + + const mergedConfig: McpServersConfig = { + mcpServers: { + ...(globalConfig?.mcpServers || {}), + ...(workspaceConfig?.mcpServers || {}), + } + } + + return mergedConfig + } + + private async startServers(config: McpServersConfig): Promise { + const serverPromises = Object.entries(config.mcpServers).map(async ([name, serverConfig]) => { + if (serverConfig.disabled) { + logger.info(`Skipping disabled MCP server: ${name}`) + return + } + + try { + await this.startServer(name, serverConfig) + } catch (error) { + logger.error({ error, serverName: name }, `Failed to start MCP server: ${name}`) + } + }) + + await Promise.allSettled(serverPromises) + } + + private async startServer(name: string, config: McpServerConfig): Promise { + logger.info(`Starting MCP server: ${name}`) + + const server: McpServer = { + name, + config, + tools: [], + connected: false, + } + + try { + // Start the MCP server process + const env = { + ...process.env, + ...(config.env || {}), + } + + const childProcess = spawn(config.command, config.args, { + env, + stdio: ['pipe', 'pipe', 'pipe'], + }) + + server.process = childProcess + + // Handle process events + childProcess.on('error', (error) => { + logger.error({ error, serverName: name }, `MCP server process error: ${name}`) + server.connected = false + }) + + childProcess.on('exit', (code, signal) => { + logger.info({ code, signal, serverName: name }, `MCP server exited: ${name}`) + server.connected = false + }) + + // For now, we'll assume the server is connected if it starts successfully + // In a full implementation, you would implement the MCP protocol handshake + server.connected = true + + // Mock some tools for demonstration + // In a real implementation, you would discover tools via MCP protocol + server.tools = await this.discoverServerTools(name, config) + + this.servers.set(name, server) + logger.info(`MCP server started successfully: ${name}`) + } catch (error) { + logger.error({ error, serverName: name }, `Failed to start MCP server: ${name}`) + throw error + } + } + + private async discoverServerTools(serverName: string, config: McpServerConfig): Promise { + // This is a mock implementation + // In a real MCP implementation, you would use the MCP protocol to discover available tools + const mockTools: Record = { + 'Context7': [ + { name: 'mcp_Context7_resolve_library_id', description: 'Resolve library ID for Context7' }, + { name: 'mcp_Context7_get_library_docs', description: 'Get library documentation from Context7' }, + ], + 'sequential-thinking': [ + { name: 'mcp_sequential_thinking_sequentialthinking', description: 'Sequential thinking tool' }, + ], + 'filesystem': [ + { name: 'mcp_filesystem_read_file', description: 'Read file contents' }, + { name: 'mcp_filesystem_write_file', description: 'Write file contents' }, + { name: 'mcp_filesystem_list_directory', description: 'List directory contents' }, + { name: 'mcp_filesystem_create_directory', description: 'Create directory' }, + ], + 'brave-search': [ + { name: 'mcp_brave_search_web', description: 'Search the web using Brave' }, + ], + } + + return mockTools[serverName] || [] + } + + public getAvailableTools(): McpTool[] { + const allTools: McpTool[] = [] + for (const server of this.servers.values()) { + if (server.connected) { + allTools.push(...server.tools) + } + } + return allTools + } + + public getServer(name: string): McpServer | undefined { + return this.servers.get(name) + } + + public getAllServers(): McpServer[] { + return Array.from(this.servers.values()) + } + + public async callTool(toolName: string, params: any): Promise { + // Find which server has this tool + for (const server of this.servers.values()) { + if (server.connected && server.tools.some(tool => tool.name === toolName)) { + return await this.callServerTool(server, toolName, params) + } + } + + throw new Error(`Tool not found: ${toolName}`) + } + + private async callServerTool(server: McpServer, toolName: string, params: any): Promise { + // This is a mock implementation + // In a real MCP implementation, you would use the MCP protocol to call the tool + logger.info({ serverName: server.name, toolName, params }, 'Calling MCP tool') + + // Mock response based on tool name + if (toolName.includes('resolve_library_id')) { + return { libraryId: '/mock/library', description: 'Mock library for testing' } + } else if (toolName.includes('get_library_docs')) { + return { documentation: 'Mock documentation content', examples: [] } + } else if (toolName.includes('sequentialthinking')) { + return { thought: 'Mock sequential thinking response', nextThoughtNeeded: false } + } else if (toolName.includes('read_file')) { + return { content: 'Mock file content', path: params.path || 'unknown' } + } + + return { result: 'Mock MCP tool response', toolName, params } + } + + public async shutdown(): Promise { + logger.info('Shutting down MCP servers...') + + const shutdownPromises = Array.from(this.servers.values()).map(async (server) => { + if (server.process && !server.process.killed) { + return new Promise((resolve) => { + server.process!.on('exit', () => resolve()) + server.process!.kill('SIGTERM') + + // Force kill after 5 seconds + setTimeout(() => { + if (!server.process!.killed) { + server.process!.kill('SIGKILL') + } + resolve() + }, 5000) + }) + } + }) + + await Promise.allSettled(shutdownPromises) + this.servers.clear() + logger.info('MCP servers shutdown complete') + } +} \ No newline at end of file diff --git a/npm-app/src/tool-handlers.ts b/npm-app/src/tool-handlers.ts index 7e90d8126..794b51ef0 100644 --- a/npm-app/src/tool-handlers.ts +++ b/npm-app/src/tool-handlers.ts @@ -12,6 +12,7 @@ import { waitForPreviousCheckpoint } from './cli-handlers/checkpoint' import { Client } from './client' import { DiffManager } from './diff-manager' import { runFileChangeHooks } from './json-config/hooks' +import { McpServerManager } from './mcp/mcp-server-manager' import { getRgPath } from './native/ripgrep' import { getProjectRoot } from './project-files' import { runTerminalCommand } from './terminal/run-command' @@ -148,30 +149,30 @@ export const handleRunTerminalCommand: ToolHandler< }, id: string, ): Promise> => { - const { - command, - mode = 'assistant', - process_type = 'SYNC', - cwd, - timeout_seconds = 30, - } = parameters + const { + command, + mode = 'assistant', + process_type = 'SYNC', + cwd, + timeout_seconds = 30, + } = parameters + + await waitForPreviousCheckpoint() + if (mode === 'assistant' && process_type === 'BACKGROUND') { + const client = Client.getInstance() + client.oneTimeFlags[SHOULD_ASK_CONFIG] = true + } - await waitForPreviousCheckpoint() - if (mode === 'assistant' && process_type === 'BACKGROUND') { - const client = Client.getInstance() - client.oneTimeFlags[SHOULD_ASK_CONFIG] = true + return await runTerminalCommand( + id, + command, + mode, + process_type.toUpperCase() as 'SYNC' | 'BACKGROUND', + timeout_seconds, + cwd, + ) } - return await runTerminalCommand( - id, - command, - mode, - process_type.toUpperCase() as 'SYNC' | 'BACKGROUND', - timeout_seconds, - cwd, - ) -} - export const handleCodeSearch: ToolHandler<'code_search'> = async ( parameters, _id, @@ -250,7 +251,7 @@ export const handleCodeSearch: ToolHandler<'code_search'> = async ( const finalStdout = lines.length > maxResults ? limitedStdout + - `\n\n[Results limited to ${maxResults} of ${lines.length} total matches]` + `\n\n[Results limited to ${maxResults} of ${lines.length} total matches]` : limitedStdout const truncatedStdout = truncateStringWithMessage({ @@ -411,10 +412,49 @@ export const toolHandlers: { browser_logs: handleBrowserLogs, } +const handleMcpTool = async ( + toolName: string, + parameters: any, + id: string, +): Promise => { + try { + const mcpManager = McpServerManager.getInstance() + const result = await mcpManager.callTool(toolName, parameters) + + logger.info({ toolName, parameters, result }, 'MCP tool call completed') + + return { + type: 'text', + text: JSON.stringify(result, null, 2), + } + } catch (error) { + logger.error({ error, toolName, parameters }, 'MCP tool call failed') + + return { + type: 'text', + text: `Error calling MCP tool ${toolName}: ${error instanceof Error ? error.message : String(error)}`, + } + } +} + export const handleToolCall = async ( toolCall: ToolCall, ): Promise => { const { toolName, input, toolCallId } = toolCall + + // Check if this is an MCP tool + if (toolName.startsWith('mcp_')) { + const content = await handleMcpTool(toolName, input, toolCallId) + const contentArray = Array.isArray(content) ? content : [content] + return { + type: 'tool-result', + toolName, + toolCallId, + output: contentArray, + } satisfies ToolResultPart + } + + // Handle regular tools const handler = toolHandlers[toolName as ClientToolName] if (!handler) { throw new Error(`No handler found for tool: ${toolName}`)