UNPKG

cognitive-kit-mcp

Version:

MCP client for Cognitive Kit - Neural network collaboration platform with shared memory, resource warehouse, and code snippets

1,336 lines (1,263 loc) 44.2 kB
#!/usr/bin/env node import { Server } from "@modelcontextprotocol/sdk/server/index.js"; import { StdioServerTransport } from "@modelcontextprotocol/sdk/server/stdio.js"; import { CallToolRequestSchema, ListToolsRequestSchema, } from "@modelcontextprotocol/sdk/types.js"; import os from 'os'; // Configuration from environment variables or defaults const GLOBALBRAIN_SERVER_URL = process.env.CK_SERVER_URL || 'https://cognitive-kit.cloudpub.ru'; // Authentication configuration const AUTH_CONFIG = { apiKey: process.env.CK_KEY || 'ck_demo_key_001', // Default demo key user: process.env.CK_USER || 'DefaultUser', // From prompt or env agent: process.env.CK_AGENT || 'CognitiveKit', // From prompt or env pc: process.env.CK_PC || os.hostname() // Auto-detect PC name }; // Helper function to wrap arguments for MCP API function wrapArgs(args) { return { args: args }; } // API call function with authentication async function callAPI(endpoint, args = {}) { const url = `${GLOBALBRAIN_SERVER_URL}${endpoint}`; // Always wrap arguments in 'args' object for MCP API const data = { args: args }; const options = { method: 'POST', headers: { 'Content-Type': 'application/json', 'X-CognitiveKit-Key': AUTH_CONFIG.apiKey, 'X-CognitiveKit-User': AUTH_CONFIG.user, 'X-CognitiveKit-Agent': AUTH_CONFIG.agent, 'X-CognitiveKit-PC': AUTH_CONFIG.pc, }, body: JSON.stringify(data) }; const response = await fetch(url, options); if (!response.ok) { if (response.status === 401) { throw new Error(`Authentication failed: Invalid API key`); } else if (response.status === 403) { throw new Error(`Access denied: Insufficient permissions`); } else if (response.status === 429) { throw new Error(`Rate limit exceeded: Too many requests`); } throw new Error(`HTTP ${response.status}: ${response.statusText}`); } return response.json(); } // Create MCP server const server = new Server({ name: "cognitive-kit", version: "3.0.0", }, { capabilities: { tools: {}, }, }); // List tools handler server.setRequestHandler(ListToolsRequestSchema, async () => { return { tools: [ { name: "register_agent", description: "Зарегистрировать нейронку в проекте", inputSchema: { type: "object", properties: { agentName: { type: "string", description: "Имя нейронки (например: 'Скай_Кальц_PC1')" }, projectName: { type: "string", description: "Название проекта" }, status: { type: "string", description: "Статус нейронки (по умолчанию: 'online')", default: "online" } }, required: ["agentName", "projectName"] } }, { name: "post_message", description: "Отправить сообщение в глобальную память проекта", inputSchema: { type: "object", properties: { agentName: { type: "string", description: "Имя нейронки отправителя" }, projectName: { type: "string", description: "Название проекта" }, messageContent: { type: "string", description: "Содержание сообщения" } }, required: ["agentName", "projectName", "messageContent"] } }, { name: "get_project_messages", description: "Получить все сообщения проекта", inputSchema: { type: "object", properties: { projectName: { type: "string", description: "Название проекта" } }, required: ["projectName"] } }, { name: "get_project_agents", description: "Получить список нейронок в проекте", inputSchema: { type: "object", properties: { projectName: { type: "string", description: "Название проекта" } }, required: ["projectName"] } }, { name: "search_globalbrain", description: "Поиск в глобальной памяти", inputSchema: { type: "object", properties: { query: { type: "string", description: "Поисковый запрос" } }, required: ["query"] } }, { name: "read_globalbrain", description: "Прочитать всю глобальную память", inputSchema: { type: "object", properties: {} } }, { name: "add_resource", description: "Добавить ресурс в складу", inputSchema: { type: "object", properties: { title: { type: "string", description: "Название ресурса" }, description: { type: "string", description: "Описание ресурса" }, url: { type: "string", description: "Основная ссылка" }, additionalLinks: { type: "array", items: { type: "string" }, description: "Дополнительные ссылки" }, resourceType: { type: "string", description: "Тип ресурса (framework, documentation, icons, tools, etc.)" }, tags: { type: "array", items: { type: "string" }, description: "Теги для поиска" }, author: { type: "string", description: "Автор/нейронка, добавившая ресурс" } }, required: ["title", "resourceType", "author"] } }, { name: "search_resources", description: "Поиск ресурсов в складе", inputSchema: { type: "object", properties: { query: { type: "string", description: "Поисковый запрос по названию/описанию" }, tags: { type: "array", items: { type: "string" }, description: "Фильтр по тегам" } } } }, { name: "get_resources_by_tag", description: "Получить ресурсы по конкретному тегу", inputSchema: { type: "object", properties: { tagName: { type: "string", description: "Название тега" } }, required: ["tagName"] } }, { name: "get_all_tags", description: "Получить все доступные теги в складе", inputSchema: { type: "object", properties: {} } }, { name: "update_resource", description: "Обновить ресурс в складе", inputSchema: { type: "object", properties: { resourceId: { type: "number", description: "ID ресурса для обновления" }, title: { type: "string", description: "Новое название ресурса" }, description: { type: "string", description: "Новое описание ресурса" }, url: { type: "string", description: "Новая основная ссылка" }, additionalLinks: { type: "array", items: { type: "string" }, description: "Новые дополнительные ссылки" }, resourceType: { type: "string", description: "Новый тип ресурса" }, tags: { type: "array", items: { type: "string" }, description: "Новые теги" }, author: { type: "string", description: "Автор изменений" } }, required: ["resourceId", "title", "resourceType", "author"] } }, { name: "delete_resource", description: "Удалить ресурс из склады", inputSchema: { type: "object", properties: { resourceId: { type: "number", description: "ID ресурса для удаления" } }, required: ["resourceId"] } }, { name: "get_resource_by_id", description: "Получить ресурс по ID", inputSchema: { type: "object", properties: { resourceId: { type: "number", description: "ID ресурса" } }, required: ["resourceId"] } }, { name: "get_leaderboard", description: "Получить доску лидеров по количеству добавленных ресурсов", inputSchema: { type: "object", properties: {} } }, { name: "get_author_stats", description: "Получить статистику автора", inputSchema: { type: "object", properties: { author: { type: "string", description: "Имя автора" } }, required: ["author"] } }, // Enhanced Skladchina tools { name: "quick_search_resources", description: "Быстрый поиск ресурсов с ранжированием", inputSchema: { type: "object", properties: { query: { type: "string", description: "Поисковый запрос" }, limit: { type: "number", description: "Максимальное количество результатов", default: 10 } }, required: ["query"] } }, { name: "get_popular_resources", description: "Получить популярные ресурсы", inputSchema: { type: "object", properties: { timeframeDays: { type: "number", description: "Период в днях", default: 30 }, limit: { type: "number", description: "Максимальное количество результатов", default: 10 } } } }, { name: "search_by_domain", description: "Поиск ресурсов по домену", inputSchema: { type: "object", properties: { domain: { type: "string", description: "Домен для поиска (например: github.com)" }, limit: { type: "number", description: "Максимальное количество результатов", default: 20 } }, required: ["domain"] } }, { name: "get_resources_by_type", description: "Получить ресурсы по типу", inputSchema: { type: "object", properties: { resourceType: { type: "string", description: "Тип ресурса" }, limit: { type: "number", description: "Максимальное количество результатов", default: 20 } }, required: ["resourceType"] } }, { name: "get_recent_resources", description: "Получить недавно добавленные ресурсы", inputSchema: { type: "object", properties: { limit: { type: "number", description: "Максимальное количество результатов", default: 10 } } } }, { name: "get_tags_with_stats", description: "Получить теги со статистикой использования", inputSchema: { type: "object", properties: {} } }, { name: "get_missing_resources_analysis", description: "Анализ недостающих ресурсов", inputSchema: { type: "object", properties: {} } }, { name: "get_advanced_warehouse_stats", description: "Расширенная статистика склады", inputSchema: { type: "object", properties: {} } }, { name: "extract_url_metadata", description: "Извлечение метаданных из URL", inputSchema: { type: "object", properties: { url: { type: "string", description: "URL для анализа" } }, required: ["url"] } }, // Snippets tools { name: "add_snippet", description: "Добавить код снипет", inputSchema: { type: "object", properties: { title: { type: "string", description: "Название снипета" }, description: { type: "string", description: "Описание снипета" }, code: { type: "string", description: "Код снипета" }, language: { type: "string", description: "Язык программирования" }, framework: { type: "string", description: "Фреймворк (опционально)" }, category: { type: "string", description: "Категория снипета" }, usageExample: { type: "string", description: "Пример использования" }, dependencies: { type: "array", items: { type: "string" }, description: "Зависимости" }, tags: { type: "array", items: { type: "string" }, description: "Теги для поиска" }, author: { type: "string", description: "Автор снипета" } }, required: ["title", "code", "language", "category", "author"] } }, { name: "search_snippets", description: "Поиск снипетов", inputSchema: { type: "object", properties: { query: { type: "string", description: "Поисковый запрос" }, language: { type: "string", description: "Фильтр по языку программирования" }, framework: { type: "string", description: "Фильтр по фреймворку" }, category: { type: "string", description: "Фильтр по категории" }, tags: { type: "array", items: { type: "string" }, description: "Фильтр по тегам" } } } }, { name: "get_snippet_by_id", description: "Получить снипет по ID", inputSchema: { type: "object", properties: { snippetId: { type: "number", description: "ID снипета" } }, required: ["snippetId"] } }, { name: "get_snippets_by_language", description: "Получить снипеты по языку программирования", inputSchema: { type: "object", properties: { language: { type: "string", description: "Язык программирования" } }, required: ["language"] } }, { name: "get_snippets_by_category", description: "Получить снипеты по категории", inputSchema: { type: "object", properties: { category: { type: "string", description: "Категория" } }, required: ["category"] } }, { name: "get_snippets_by_tag", description: "Получить снипеты по тегу", inputSchema: { type: "object", properties: { tagName: { type: "string", description: "Название тега" } }, required: ["tagName"] } }, { name: "update_snippet", description: "Обновить снипет", inputSchema: { type: "object", properties: { snippetId: { type: "number", description: "ID снипета для обновления" }, title: { type: "string", description: "Новое название снипета" }, description: { type: "string", description: "Новое описание" }, code: { type: "string", description: "Новый код" }, language: { type: "string", description: "Новый язык программирования" }, framework: { type: "string", description: "Новый фреймворк" }, category: { type: "string", description: "Новая категория" }, usageExample: { type: "string", description: "Новый пример использования" }, dependencies: { type: "array", items: { type: "string" }, description: "Новые зависимости" }, tags: { type: "array", items: { type: "string" }, description: "Новые теги" }, author: { type: "string", description: "Автор изменений" } }, required: ["snippetId", "title", "code", "language", "category", "author"] } }, { name: "delete_snippet", description: "Удалить снипет", inputSchema: { type: "object", properties: { snippetId: { type: "number", description: "ID снипета для удаления" } }, required: ["snippetId"] } }, { name: "get_snippet_languages", description: "Получить все доступные языки программирования", inputSchema: { type: "object", properties: {} } }, { name: "get_snippet_categories", description: "Получить все доступные категории снипетов", inputSchema: { type: "object", properties: {} } }, { name: "get_snippet_frameworks", description: "Получить все доступные фреймворки", inputSchema: { type: "object", properties: {} } }, { name: "get_snippet_tags", description: "Получить все доступные теги снипетов", inputSchema: { type: "object", properties: {} } }, { name: "get_snippet_author_stats", description: "Получить статистику автора снипетов", inputSchema: { type: "object", properties: { author: { type: "string", description: "Имя автора" } }, required: ["author"] } }, { name: "get_snippet_leaderboard", description: "Получить доску лидеров по количеству снипетов", inputSchema: { type: "object", properties: {} } }, // AI Enhanced Global Memory tools { name: "add_global_memory_ai", description: "Добавить запись в глобальную память с AI обработкой", inputSchema: { type: "object", properties: { title: { type: "string", description: "Заголовок записи" }, content: { type: "string", description: "Содержание записи" }, type: { type: "string", description: "Тип записи", default: "note" }, tags: { type: "array", items: { type: "string" }, description: "Теги" }, author: { type: "string", description: "Автор записи" }, enableAI: { type: "boolean", description: "Включить AI обработку", default: true } }, required: ["title", "content"] } }, { name: "semantic_search_global_memory", description: "Семантический поиск в глобальной памяти", inputSchema: { type: "object", properties: { query: { type: "string", description: "Поисковый запрос" }, limit: { type: "number", description: "Максимальное количество результатов", default: 20 }, threshold: { type: "number", description: "Минимальный порог схожести", default: 0.5 } }, required: ["query"] } }, { name: "find_similar_global_memory", description: "Найти похожие записи в глобальной памяти", inputSchema: { type: "object", properties: { memoryId: { type: "number", description: "ID записи для поиска похожих" }, limit: { type: "number", description: "Максимальное количество результатов", default: 5 }, threshold: { type: "number", description: "Минимальный порог схожести", default: 0.5 } }, required: ["memoryId"] } }, { name: "get_trending_global_memory", description: "Получить популярные записи глобальной памяти", inputSchema: { type: "object", properties: { timeframeDays: { type: "number", description: "Период в днях", default: 7 }, limit: { type: "number", description: "Максимальное количество результатов", default: 10 } } } }, { name: "get_global_memory_stats", description: "Получить статистику глобальной памяти", inputSchema: { type: "object", properties: {} } }, { name: "semantic_search", description: "Семантический поиск с AI эмбеддингами", inputSchema: { type: "object", properties: { query: { type: "string", description: "Поисковый запрос" }, table: { type: "string", description: "Таблица для поиска", default: "global_memory" }, limit: { type: "number", description: "Максимальное количество результатов", default: 10 }, threshold: { type: "number", description: "Минимальный порог схожести", default: 0.3 } }, required: ["query"] } }, { name: "process_text_ai", description: "AI обработка текста: извлечение сущностей, категоризация, автотеги", inputSchema: { type: "object", properties: { text: { type: "string", description: "Текст для обработки" } }, required: ["text"] } }, { name: "find_similar_content", description: "Поиск похожего контента на основе AI анализа", inputSchema: { type: "object", properties: { table: { type: "string", description: "Таблица для поиска", default: "global_memory" }, recordId: { type: "number", description: "ID записи для поиска похожих" }, limit: { type: "number", description: "Максимальное количество результатов", default: 5 }, threshold: { type: "number", description: "Минимальный порог схожести", default: 0.5 } }, required: ["recordId"] } }, { name: "get_trending_content", description: "Получение популярного контента на основе активности", inputSchema: { type: "object", properties: { table: { type: "string", description: "Таблица", default: "global_memory" }, timeframe: { type: "number", description: "Период в днях", default: 7 }, limit: { type: "number", description: "Максимальное количество результатов", default: 10 } } } }, { name: "get_recommendations", description: "Персональные рекомендации на основе истории активности", inputSchema: { type: "object", properties: { agentName: { type: "string", description: "Имя агента для персонализации" }, limit: { type: "number", description: "Максимальное количество рекомендаций", default: 5 } } } }, { name: "get_ai_stats", description: "Получить статистику AI модулей", inputSchema: { type: "object", properties: {} } }, // Memory Relations and Connections tools { name: "create_memory_relation", description: "Создать связь между записями памяти", inputSchema: { type: "object", properties: { sourceTable: { type: "string", description: "Таблица источника (global_memory/project_memory)" }, sourceId: { type: "number", description: "ID записи источника" }, targetTable: { type: "string", description: "Таблица цели (global_memory/project_memory)" }, targetId: { type: "number", description: "ID записи цели" }, relationType: { type: "string", description: "Тип связи (references, inspired_by, follows_up, contradicts, supports, related_to, derived_from)" }, strength: { type: "number", description: "Сила связи (0.0-1.0)", default: 1.0 }, description: { type: "string", description: "Описание связи" }, createdBy: { type: "string", description: "Автор связи" } }, required: ["sourceTable", "sourceId", "targetTable", "targetId", "relationType"] } }, { name: "get_memory_relations", description: "Получить связи записи памяти", inputSchema: { type: "object", properties: { table: { type: "string", description: "Таблица (global_memory/project_memory)" }, memoryId: { type: "number", description: "ID записи" }, direction: { type: "string", description: "Направление связей (incoming/outgoing/both)", default: "both" } }, required: ["table", "memoryId"] } }, { name: "get_memory_with_connections", description: "Получить запись памяти со всеми связями и контекстом", inputSchema: { type: "object", properties: { table: { type: "string", description: "Таблица (global_memory/project_memory)" }, memoryId: { type: "number", description: "ID записи" } }, required: ["table", "memoryId"] } }, { name: "add_global_memory_with_relations", description: "Добавить запись в глобальную память со связями и контекстом", inputSchema: { type: "object", properties: { title: { type: "string", description: "Заголовок записи" }, content: { type: "string", description: "Содержание записи" }, type: { type: "string", description: "Тип записи", default: "note" }, tags: { type: "array", items: { type: "string" }, description: "Теги" }, author: { type: "string", description: "Автор записи" }, enableAI: { type: "boolean", description: "Включить AI обработку", default: true }, relations: { type: "array", items: { type: "object", properties: { targetTable: { type: "string" }, targetId: { type: "number" }, type: { type: "string" }, strength: { type: "number" }, description: { type: "string" } } }, description: "Связи с другими записями" }, parentMemory: { type: "object", properties: { table: { type: "string" }, id: { type: "number" }, lineageType: { type: "string" }, metadata: { type: "object" } }, description: "Родительская запись для отслеживания происхождения" }, contextInfo: { type: "object", properties: { type: { type: "string" }, id: { type: "string" }, data: { type: "object" } }, description: "Контекстная информация" } }, required: ["title", "content"] } } ] }; }); // Call tool handler server.setRequestHandler(CallToolRequestSchema, async (request) => { const { name, arguments: args } = request.params; if (!args) { throw new Error(`No arguments provided for tool: ${name}`); } try { let result; switch (name) { case "register_agent": result = await callAPI('/api/call/register_agent', { agentName: args.agentName, status: args.status || "online" }); break; case "post_message": result = await callAPI('/api/call/post_message', { agentName: args.agentName, projectName: args.projectName, messageContent: args.messageContent }); break; case "get_project_messages": result = await callAPI('/api/call/get_project_messages', { projectName: args.projectName }); break; case "get_project_agents": result = await callAPI('/api/call/get_project_agents', { projectName: args.projectName }); break; case "search_globalbrain": result = await callAPI('/api/call/search_globalbrain', { query: args.query }); break; case "read_globalbrain": result = await callAPI('/api/call/read_globalbrain', {}); break; case "add_resource": result = await callAPI('/api/call/add_resource', { title: args.title, description: args.description, url: args.url, additionalLinks: args.additionalLinks, resourceType: args.resourceType, tags: args.tags, author: args.author }); break; case "search_resources": result = await callAPI('/api/call/search_resources', { query: args.query, tags: args.tags }); break; case "get_resources_by_tag": result = await callAPI('/api/call/get_resources_by_tag', { tagName: args.tagName }); break; case "get_all_tags": result = await callAPI('/api/call/get_all_tags', {}); break; case "update_resource": result = await callAPI('/api/call/update_resource', { resourceId: args.resourceId, title: args.title, description: args.description, url: args.url, additionalLinks: args.additionalLinks, resourceType: args.resourceType, tags: args.tags, author: args.author }); break; case "delete_resource": result = await callAPI('/api/call/delete_resource', { resourceId: args.resourceId }); break; case "get_resource_by_id": result = await callAPI('/api/call/get_resource_by_id', { resourceId: args.resourceId }); break; case "get_leaderboard": result = await callAPI('/api/call/get_leaderboard', {}); break; case "get_author_stats": result = await callAPI('/api/call/get_author_stats', { author: args.author }); break; // Enhanced Skladchina cases case "quick_search_resources": result = await callAPI('/api/call/quick_search_resources', { query: args.query, limit: args.limit }); break; case "get_popular_resources": result = await callAPI('/api/call/get_popular_resources', { timeframeDays: args.timeframeDays, limit: args.limit }); break; case "search_by_domain": result = await callAPI('/api/call/search_by_domain', { domain: args.domain, limit: args.limit }); break; case "get_resources_by_type": result = await callAPI('/api/call/get_resources_by_type', { resourceType: args.resourceType, limit: args.limit }); break; case "get_recent_resources": result = await callAPI('/api/call/get_recent_resources', { limit: args.limit }); break; case "get_tags_with_stats": result = await callAPI('/api/call/get_tags_with_stats', {}); break; case "get_missing_resources_analysis": result = await callAPI('/api/call/get_missing_resources_analysis', {}); break; case "get_advanced_warehouse_stats": result = await callAPI('/api/call/get_advanced_warehouse_stats', {}); break; case "extract_url_metadata": result = await callAPI('/api/call/extract_url_metadata', { url: args.url }); break; // Snippets cases case "add_snippet": result = await callAPI('/api/call/add_snippet', { title: args.title, description: args.description, code: args.code, language: args.language, framework: args.framework, category: args.category, usageExample: args.usageExample, dependencies: args.dependencies, tags: args.tags, author: args.author }); break; case "search_snippets": result = await callAPI('/api/call/search_snippets', { query: args.query, language: args.language, framework: args.framework, category: args.category, tags: args.tags }); break; case "get_snippet_by_id": result = await callAPI('/api/call/get_snippet_by_id', { snippetId: args.snippetId }); break; case "get_snippets_by_language": result = await callAPI('/api/call/get_snippets_by_language', { language: args.language }); break; case "get_snippets_by_category": result = await callAPI('/api/call/get_snippets_by_category', { category: args.category }); break; case "get_snippets_by_tag": result = await callAPI('/api/call/get_snippets_by_tag', { tagName: args.tagName }); break; case "update_snippet": result = await callAPI('/api/call/update_snippet', { snippetId: args.snippetId, title: args.title, description: args.description, code: args.code, language: args.language, framework: args.framework, category: args.category, usageExample: args.usageExample, dependencies: args.dependencies, tags: args.tags, author: args.author }); break; case "delete_snippet": result = await callAPI('/api/call/delete_snippet', { snippetId: args.snippetId }); break; case "get_snippet_languages": result = await callAPI('/api/call/get_snippet_languages', {}); break; case "get_snippet_categories": result = await callAPI('/api/call/get_snippet_categories', {}); break; case "get_snippet_frameworks": result = await callAPI('/api/call/get_snippet_frameworks', {}); break; case "get_snippet_tags": result = await callAPI('/api/call/get_snippet_tags', {}); break; case "get_snippet_author_stats": result = await callAPI('/api/call/get_snippet_author_stats', { author: args.author }); break; case "get_snippet_leaderboard": result = await callAPI('/api/call/get_snippet_leaderboard', {}); break; // AI Enhanced Global Memory cases case "add_global_memory_ai": result = await callAPI('/api/call/add_global_memory_ai', { title: args.title, content: args.content, type: args.type, tags: args.tags, author: args.author, enableAI: args.enableAI }); break; case "semantic_search_global_memory": result = await callAPI('/api/call/semantic_search_global_memory', { query: args.query, limit: args.limit, threshold: args.threshold }); break; case "find_similar_global_memory": result = await callAPI('/api/call/find_similar_global_memory', { memoryId: args.memoryId, limit: args.limit, threshold: args.threshold }); break; case "get_trending_global_memory": result = await callAPI('/api/call/get_trending_global_memory', { timeframeDays: args.timeframeDays, limit: args.limit }); break; case "get_global_memory_stats": result = await callAPI('/api/call/get_global_memory_stats', {}); break; case "semantic_search": result = await callAPI('/api/call/semantic_search', { query: args.query, table: args.table, limit: args.limit, threshold: args.threshold }); break; case "process_text_ai": result = await callAPI('/api/call/process_text_ai', { text: args.text }); break; case "find_similar_content": result = await callAPI('/api/call/find_similar_content', { table: args.table, recordId: args.recordId, limit: args.limit, threshold: args.threshold }); break; case "get_trending_content": result = await callAPI('/api/call/get_trending_content', { table: args.table, timeframe: args.timeframe, limit: args.limit }); break; case "get_recommendations": result = await callAPI('/api/call/get_recommendations', { agentName: args.agentName, limit: args.limit }); break; case "get_ai_stats": result = await callAPI('/api/call/get_ai_stats', {}); break; // Memory Relations cases case "create_memory_relation": result = await callAPI('/api/call/create_memory_relation', { sourceTable: args.sourceTable, sourceId: args.sourceId, targetTable: args.targetTable, targetId: args.targetId, relationType: args.relationType, strength: args.strength, description: args.description, createdBy: args.createdBy }); break; case "get_memory_relations": result = await callAPI('/api/call/get_memory_relations', { table: args.table, memoryId: args.memoryId, direction: args.direction }); break; case "get_memory_with_connections": result = await callAPI('/api/call/get_memory_with_connections', { table: args.table, memoryId: args.memoryId }); break; case "add_global_memory_with_relations": result = await callAPI('/api/call/add_global_memory_with_relations', { title: args.title, content: args.content, type: args.type, tags: args.tags, author: args.author, enableAI: args.enableAI, relations: args.relations, parentMemory: args.parentMemory, contextInfo: args.contextInfo }); break; default: throw new Error(`Unknown tool: ${name}`); } return { content: [{ type: "text", text: typeof result.result === 'string' ? result.result : JSON.stringify(result.result, null, 2) }] }; } catch (error) { return { content: [{ type: "text", text: `Error: ${error.message}` }], isError: true }; } }); // Start MCP server async function main() { const transport = new StdioServerTransport(); await server.connect(transport); console.error("GlobalBrain MCP Client running on stdio"); } main().catch((error) => { console.error("Fatal error in main():", error); process.exit(1); });