aiagentmarket 3.0.47 → 3.0.49

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (80) hide show
  1. package/bin/aiagent-base +1 -1
  2. package/lib/mcp-server/dist/bluelamp-system.js +1 -1
  3. package/lib/mcp-server/dist/crypto-utils.js +1 -1
  4. package/lib/mcp-server/dist/database-version.js +1 -1
  5. package/lib/mcp-server/dist/index.js +1 -1
  6. package/lib/mcp-server/dist/plugins/base-plugin.js +1 -1
  7. package/lib/mcp-server/dist/plugins/services/leonardo-plugin.js +1 -1
  8. package/lib/mcp-server/dist/plugins/services/portal-api-client.js +1 -1
  9. package/lib/mcp-server/dist/plugins/services/portal-plugin.js +1 -1
  10. package/lib/mcp-server/dist/secure-mcp-server.js +1 -1
  11. package/lib/mcp-server/dist/security/EncryptionKeyManager.js +1 -0
  12. package/lib/mcp-server/dist/security/InteractiveLogin.js +1 -1
  13. package/lib/mcp-server/dist/security/PortalAuthClient.js +1 -1
  14. package/lib/mcp-server/dist/security/SimpleAuthManager.js +1 -1
  15. package/lib/mcp-server/dist/security/SlotAuthClient.js +1 -1
  16. package/lib/mcp-server/dist/security/TokenManager.js +1 -1
  17. package/lib/mcp-server/dist/types/common.js +1 -0
  18. package/lib/mcp-server/package.json +12 -1
  19. package/lib/mcp-server/scripts/create-release.sh +158 -0
  20. package/lib/mcp-server/scripts/install.sh +167 -0
  21. package/package.json +2 -2
  22. package/scripts/build.js +1 -1
  23. package/scripts/configure-aiagent-tools.js +2 -0
  24. package/scripts/generate-aiagent-links.js +1 -1
  25. package/lib/agents//343/203/226/343/203/253/343/203/274/343/203/251/343/203/263/343/203/227.md +0 -105
  26. package/lib/mcp-server/dist/bluelamp-system.d.ts +0 -29
  27. package/lib/mcp-server/dist/bluelamp-system.d.ts.map +0 -1
  28. package/lib/mcp-server/dist/bluelamp-system.js.map +0 -1
  29. package/lib/mcp-server/dist/crypto-utils.d.ts +0 -33
  30. package/lib/mcp-server/dist/crypto-utils.d.ts.map +0 -1
  31. package/lib/mcp-server/dist/crypto-utils.js.map +0 -1
  32. package/lib/mcp-server/dist/database-version.d.ts +0 -72
  33. package/lib/mcp-server/dist/database-version.d.ts.map +0 -1
  34. package/lib/mcp-server/dist/database-version.js.map +0 -1
  35. package/lib/mcp-server/dist/index.d.ts +0 -3
  36. package/lib/mcp-server/dist/index.d.ts.map +0 -1
  37. package/lib/mcp-server/dist/index.js.map +0 -1
  38. package/lib/mcp-server/dist/plugins/base-plugin.d.ts +0 -245
  39. package/lib/mcp-server/dist/plugins/base-plugin.d.ts.map +0 -1
  40. package/lib/mcp-server/dist/plugins/base-plugin.js.map +0 -1
  41. package/lib/mcp-server/dist/plugins/plugin-manager.d.ts +0 -173
  42. package/lib/mcp-server/dist/plugins/plugin-manager.d.ts.map +0 -1
  43. package/lib/mcp-server/dist/plugins/plugin-manager.js.map +0 -1
  44. package/lib/mcp-server/dist/plugins/services/leonardo-plugin.d.ts +0 -124
  45. package/lib/mcp-server/dist/plugins/services/leonardo-plugin.d.ts.map +0 -1
  46. package/lib/mcp-server/dist/plugins/services/leonardo-plugin.js.map +0 -1
  47. package/lib/mcp-server/dist/plugins/services/leonardo-prompt-parser.d.ts +0 -205
  48. package/lib/mcp-server/dist/plugins/services/leonardo-prompt-parser.d.ts.map +0 -1
  49. package/lib/mcp-server/dist/plugins/services/leonardo-prompt-parser.js.map +0 -1
  50. package/lib/mcp-server/dist/plugins/services/portal-api-client.d.ts +0 -104
  51. package/lib/mcp-server/dist/plugins/services/portal-api-client.d.ts.map +0 -1
  52. package/lib/mcp-server/dist/plugins/services/portal-api-client.js.map +0 -1
  53. package/lib/mcp-server/dist/plugins/services/portal-plugin.d.ts +0 -131
  54. package/lib/mcp-server/dist/plugins/services/portal-plugin.d.ts.map +0 -1
  55. package/lib/mcp-server/dist/plugins/services/portal-plugin.js.map +0 -1
  56. package/lib/mcp-server/dist/secure-mcp-server.d.ts +0 -68
  57. package/lib/mcp-server/dist/secure-mcp-server.d.ts.map +0 -1
  58. package/lib/mcp-server/dist/secure-mcp-server.js.map +0 -1
  59. package/lib/mcp-server/dist/security/ApiKeyManager.d.ts +0 -29
  60. package/lib/mcp-server/dist/security/ApiKeyManager.d.ts.map +0 -1
  61. package/lib/mcp-server/dist/security/ApiKeyManager.js.map +0 -1
  62. package/lib/mcp-server/dist/security/InteractiveLogin.d.ts +0 -47
  63. package/lib/mcp-server/dist/security/InteractiveLogin.d.ts.map +0 -1
  64. package/lib/mcp-server/dist/security/InteractiveLogin.js.map +0 -1
  65. package/lib/mcp-server/dist/security/PortalAuthClient.d.ts +0 -65
  66. package/lib/mcp-server/dist/security/PortalAuthClient.d.ts.map +0 -1
  67. package/lib/mcp-server/dist/security/PortalAuthClient.js.map +0 -1
  68. package/lib/mcp-server/dist/security/SimpleAuthManager.d.ts +0 -73
  69. package/lib/mcp-server/dist/security/SimpleAuthManager.d.ts.map +0 -1
  70. package/lib/mcp-server/dist/security/SimpleAuthManager.js.map +0 -1
  71. package/lib/mcp-server/dist/security/SlotAuthClient.d.ts +0 -47
  72. package/lib/mcp-server/dist/security/SlotAuthClient.d.ts.map +0 -1
  73. package/lib/mcp-server/dist/security/SlotAuthClient.js.map +0 -1
  74. package/lib/mcp-server/dist/security/TokenManager.d.ts +0 -61
  75. package/lib/mcp-server/dist/security/TokenManager.d.ts.map +0 -1
  76. package/lib/mcp-server/dist/security/TokenManager.js.map +0 -1
  77. package/lib/mcp-server/package-lock.json +0 -1788
  78. package/lib/mcp-server/package-release.json +0 -32
  79. package/lib/mcp-server/tsconfig.json +0 -32
  80. package/lib/mcp-server/tsconfig.production.json +0 -33
@@ -1 +1 @@
1
- "use strict";var __createBinding=this&&this.__createBinding||(Object.create?function(e,t,r,n){void 0===n&&(n=r);var o=Object.getOwnPropertyDescriptor(t,r);o&&!("get"in o?!t.__esModule:o.writable||o.configurable)||(o={enumerable:!0,get:function(){return t[r]}}),Object.defineProperty(e,n,o)}:function(e,t,r,n){void 0===n&&(n=r),e[n]=t[r]}),__setModuleDefault=this&&this.__setModuleDefault||(Object.create?function(e,t){Object.defineProperty(e,"default",{enumerable:!0,value:t})}:function(e,t){e.default=t}),__importStar=this&&this.__importStar||function(){var e=function(t){return e=Object.getOwnPropertyNames||function(e){var t=[];for(var r in e)Object.prototype.hasOwnProperty.call(e,r)&&(t[t.length]=r);return t},e(t)};return function(t){if(t&&t.__esModule)return t;var r={};if(null!=t)for(var n=e(t),o=0;o<n.length;o++)"default"!==n[o]&&__createBinding(r,t,n[o]);return __setModuleDefault(r,t),r}}(),__importDefault=this&&this.__importDefault||function(e){return e&&e.__esModule?e:{default:e}};Object.defineProperty(exports,"__esModule",{value:!0}),exports.SecureMCPServer=void 0;const dotenv_1=__importDefault(require("dotenv")),path_1=__importDefault(require("path")),envPath=path_1.default.join(process.cwd(),".env.local");dotenv_1.default.config({path:envPath});const index_js_1=require("@modelcontextprotocol/sdk/server/index.js"),stdio_js_1=require("@modelcontextprotocol/sdk/server/stdio.js"),types_js_1=require("@modelcontextprotocol/sdk/types.js"),crypto_utils_js_1=require("./crypto-utils.js"),fs=__importStar(require("fs")),os=__importStar(require("os")),plugin_manager_js_1=require("./plugins/plugin-manager.js");class SecureMCPServer{constructor(){this.cacheTimeout=3e5,this.server=new index_js_1.Server({name:"secure-bluelamp-mcp",version:"3.0.0"},{capabilities:{tools:{}}}),this.validTokens=new Set,this.promptCache=new Map,this.encryptionKey=process.env.BLUELAMP_ENCRYPTION_KEY||"demo-encryption-password-2024",this.keywordMapping=new Map([["orchestrator","AIエージェント"],["requirements-engineer","要件定義エンジニア"],["ui-ux-designer","UI/UXデザイナー"],["data-modeling-engineer","データモデリングエンジニア"],["system-architect","システムアーキテクト"],["implementation-consultant","実装コンサルタント"],["environment-setup","環境構築"],["prototype-implementation","プロトタイプ実装"],["implementation-agent","実装エージェント"],["debug-agent","デバッグエージェント"],["deploy-specialist","デプロイスペシャリスト"],["page-creator","ページクリエイター"],["refactoring-engineer","リファクタリングエンジニア"],["ai-friendliness-diagnostic","AI親和性診断"]]),this.logFilePath=path_1.default.join(os.tmpdir(),`bluelamp-debug-${Date.now()}.log`),this.debugLog(`BlueLamp MCP Server starting - Log file: ${this.logFilePath}`),this.initializeTokensSync(),this.setupHandlers()}debugLog(e,t){const r=(new Date).toISOString(),n=t?`[${r}] ${e}\n${JSON.stringify(t,null,2)}\n`:`[${r}] ${e}\n`;try{fs.appendFileSync(this.logFilePath,n),console.error(`[DEBUG] ${e}`,t||"")}catch(e){}}initializeTokensSync(){try{const e=process.env.BLUELAMP_TOKEN;e&&this.validTokens.add(e),this.loadCLITokenFromFile(),this.validTokens.add("secure-token-2024"),this.debugLog(`Total valid tokens: ${this.validTokens.size}`)}catch(e){this.validTokens.add("secure-token-2024"),this.debugLog("Token initialization error:",e)}}loadCLITokenFromFile(){this.loadCLITokenAsync()}async loadCLITokenAsync(){try{const e=await Promise.resolve().then(()=>__importStar(require("path"))),__dirname=(await Promise.resolve().then(()=>__importStar(require("url"))),e.dirname(__filename)),t=e.dirname(e.dirname(e.dirname(__dirname))),r=e.join(t,"lib/mcp-server/dist/security"),module=require(`${r}/SimpleAuthManager.js`),n=await module.SimpleAuthManager.getToken();n&&n.startsWith("cli_")&&(this.validTokens.add(n),this.debugLog(`Loaded CLI token from SimpleAuthManager: ${n.substring(0,20)}...`))}catch(e){this.debugLog("CLI token loading error:",e)}}async getSystemToken(){try{const e=process.env.BLUELAMP_TOKEN;if(e&&this.validTokens.has(e))return e;const t=await Promise.resolve().then(()=>__importStar(require("path"))),__dirname=(await Promise.resolve().then(()=>__importStar(require("url"))),t.dirname(__filename)),r=t.dirname(t.dirname(t.dirname(__dirname))),n=t.join(r,"lib/mcp-server/dist/security");try{const module=require(`${n}/SimpleAuthManager.js`),e=await module.SimpleAuthManager.getToken();if(e&&e.startsWith("cli_"))return e}catch(e){this.debugLog("Failed to load token from SimpleAuthManager:",e)}for(const e of this.validTokens)if(e.startsWith("cli_"))return e;return"secure-token-2024"}catch(e){return this.debugLog("System token retrieval error:",e),"secure-token-2024"}}setupHandlers(){this.server.setRequestHandler(types_js_1.ListToolsRequestSchema,async()=>{const e=[{name:"inject_knowledge",description:"Inject specialized knowledge from Portal API",inputSchema:{type:"object",properties:{keyword:{type:"string",description:"Keyword to search for specialized knowledge"},context:{type:"string",description:"Additional context"},level:{type:"string",description:"Knowledge detail level"}},required:["keyword","context"]}},{name:"save_knowledge",description:"Save knowledge to encrypted storage",inputSchema:{type:"object",properties:{knowledge:{type:"string",description:"Knowledge content to save (encrypted)"},identifier:{type:"string",description:"Unique identifier for the knowledge"},token:{type:"string",description:"Authentication token for access"}},required:["knowledge","identifier","token"]}},{name:"list_prompts",description:"List available encrypted prompt templates",inputSchema:{type:"object",properties:{token:{type:"string",description:"Authentication token for access"},category:{type:"string",description:"Filter by category (optional)"}},required:["token"]}},{name:"delegate_to_agent",description:"Delegate task to specialized sub-agent with knowledge injection",inputSchema:{type:"object",properties:{agentName:{type:"string",description:"Name of the target agent"},token:{type:"string",description:"Authentication token for access"}},required:["agentName","token"]}},{name:"get_debug_log_path",description:"Get the path to the debug log file",inputSchema:{type:"object",properties:{},required:[]}}];let t=[];try{plugin_manager_js_1.pluginManager&&(t=plugin_manager_js_1.pluginManager.getAvailableTools(),this.debugLog(`プラグインツール取得完了: ${t.length}個`))}catch(e){this.debugLog("プラグインツール取得エラー",e)}const r=[...e,...t];return this.debugLog(`全ツール数: ${r.length} (基本: ${e.length}, プラグイン: ${t.length})`),{tools:r}}),this.server.setRequestHandler(types_js_1.CallToolRequestSchema,async e=>{const{name:t,arguments:r}=e.params;this.debugLog(`Tool called: ${t}`),this.debugLog("Tool args:",r);try{switch(t){case"inject_knowledge":return this.debugLog("Calling handleInjectKnowledge"),await this.handleInjectKnowledge(r);case"save_knowledge":return await this.handleSaveKnowledge(r);case"list_prompts":return await this.handleListPrompts(r);case"delegate_to_agent":return await this.handleDelegateToAgent(r);case"get_debug_log_path":return{content:[{type:"text",text:JSON.stringify({success:!0,logPath:this.logFilePath,message:`Debug log is being written to: ${this.logFilePath}`})}]};default:const e=await this.handlePluginTool(t,r);if(e)return e;throw new types_js_1.McpError(types_js_1.ErrorCode.MethodNotFound,`Unknown tool: ${t}`)}}catch(e){if(e instanceof types_js_1.McpError)throw e;throw new types_js_1.McpError(types_js_1.ErrorCode.InternalError,`Tool execution failed: ${t}: ${e}`)}})}validateToken(e){return this.validTokens.has(e)}async fetchFromPortalAPI(e,t){try{const r=`${process.env.BLUELAMP_PORTAL_API_URL||"https://aiagentmarket-backend-6clpzmy5pa-an.a.run.app"}/api/cli/prompts/knowledge-injection/${encodeURIComponent(e)}`;this.debugLog("Portal API request:",{url:r,token:t.substring(0,20)+"...",keyword:e});const n=new AbortController,o=setTimeout(()=>n.abort(),3e4),s=process.env.BLUELAMP_SLOT_NUMBER||"1",i=await fetch(r,{method:"GET",headers:{"X-CLI-Token":t,"X-Current-Slot":s,"Content-Type":"application/json","User-Agent":"BlueLamp-MCP-Server/1.0"},signal:n.signal});if(clearTimeout(o),this.debugLog(`Portal API response status: ${i.status}`),!i.ok){if(this.debugLog(`Portal API error: ${i.status} ${i.statusText}`),401===i.status)return this.debugLog("Authentication failed - token may be invalid"),null;if(404===i.status)return this.debugLog(`Knowledge not found for keyword: ${e}`),null;throw new Error(`Portal API error: ${i.status} ${i.statusText}`)}const a=await i.json();return this.debugLog("Portal API JSON response:",a),a&&a.success&&a.data&&a.data.content?a.data.content:(this.debugLog("Empty response from Portal API"),null)}catch(e){return null}}async handleInjectKnowledge(e){this.debugLog("Received args:",e),this.debugLog(`Valid tokens: ${Array.from(this.validTokens).map(e=>e.substring(0,30)+"...").join(", ")}`);let t=await this.getSystemToken();if(this.debugLog(`Using system token: ${t?.substring(0,30)}...`),!t||!this.validateToken(t))return this.debugLog("System authentication failed"),{content:[{type:"text",text:JSON.stringify({success:!1,error:"System authentication failed",code:"SYSTEM_AUTH_ERROR"})}]};try{const r=`${e.keyword}:${e.level}`,n=this.promptCache.get(r);let o,s="unknown";if(n&&Date.now()-n.timestamp<this.cacheTimeout)o=n.content,s=n.source||"cache";else{const n=path_1.default.join(process.cwd(),"lib/knowledge","encrypted",`${e.keyword}.enc`);if(fs.existsSync(n))try{o=crypto_utils_js_1.CryptoUtils.decryptFile(n,this.encryptionKey),s="local"}catch(r){const n=await this.fetchFromPortalAPI(e.keyword,t);if(!n)return{content:[{type:"text",text:JSON.stringify({success:!1,error:`Portal APIから知識を取得できませんでした: ${e.keyword}`,code:"KNOWLEDGE_NOT_FOUND"})}]};o=n,s="api"}else{this.debugLog(`Fetching from Portal API for keyword: ${e.keyword}`);const r=await this.fetchFromPortalAPI(e.keyword,t);if(this.debugLog("Portal API result:",{keyword:e.keyword,resultExists:!!r,resultType:typeof r,resultLength:r?r.length:0}),!r)return this.debugLog(`Portal API returned null for keyword: ${e.keyword}`),{content:[{type:"text",text:JSON.stringify({success:!1,error:`専門知識が見つかりませんでした: ${e.keyword}`,code:"KNOWLEDGE_NOT_FOUND"})}]};o=r,s="api"}this.promptCache.set(r,{content:o,timestamp:Date.now(),source:s})}const i=this.buildResponse(o,t);return{content:[{type:"text",text:JSON.stringify({success:!0,result:i,keyword:e.keyword,token:t.substring(0,20)+"...",cached:"cache"===s,source:s,timestamp:(new Date).toISOString()})}]}}catch(e){return{content:[{type:"text",text:JSON.stringify({success:!1,error:`知識注入処理中にエラーが発生しました: ${e}`,code:"INJECTION_ERROR"})}]}}}buildResponse(e,t){return this.debugLog(`buildResponse called with content length: ${e?e.length:0}`),{content:[{type:"text",text:e}]}}async handleSaveKnowledge(e){if(!this.validateToken(e.token))return{content:[{type:"text",text:JSON.stringify({success:!1,error:"Invalid authentication token",code:"AUTH_ERROR"})}]};try{const t=path_1.default.join(process.cwd(),"lib/knowledge","encrypted");fs.existsSync(t)||fs.mkdirSync(t,{recursive:!0});const r=path_1.default.join(t,`${e.identifier}.enc`);return crypto_utils_js_1.CryptoUtils.encryptFile(e.knowledge,r,this.encryptionKey),{content:[{type:"text",text:JSON.stringify({success:!0,message:"Knowledge saved successfully",outputPath:r,size:fs.statSync(r).size})}]}}catch(e){return{content:[{type:"text",text:JSON.stringify({success:!1,error:`Knowledge save failed: ${e}`,code:"SAVE_ERROR"})}]}}}async handleListPrompts(e){if(!this.validateToken(e.token))return{content:[{type:"text",text:JSON.stringify({success:!1,error:"Invalid authentication token",code:"AUTH_ERROR"})}]};try{const t=path_1.default.join(process.cwd(),"lib/knowledge","encrypted"),r=path_1.default.join(t,"prompt-registry.json");if(!fs.existsSync(r))return{content:[{type:"text",text:JSON.stringify({success:!1,error:"Prompt registry not found",code:"REGISTRY_NOT_FOUND"})}]};const n=JSON.parse(fs.readFileSync(r,"utf8"));let o=n.prompts;return e.category&&(o=o.filter(t=>t.category===e.category)),{content:[{type:"text",text:JSON.stringify({success:!0,totalCount:o.length,prompts:o,categories:n.categories,lastUpdated:n.lastUpdated})}]}}catch(e){return{content:[{type:"text",text:JSON.stringify({success:!1,error:`Failed to list prompts: ${e}`,code:"LIST_ERROR"})}]}}}async handleDelegateToAgent(e){if(!this.validateToken(e.token))return{content:[{type:"text",text:JSON.stringify({success:!1,error:"Invalid authentication token",code:"AUTH_ERROR"})}]};try{const t=path_1.default.join(process.cwd(),"lib/knowledge","agents",`${e.agentName}.agent`);if(!fs.existsSync(t))return{content:[{type:"text",text:JSON.stringify({success:!1,error:`Agent script not found: ${e.agentName}`,code:"AGENT_NOT_FOUND"})}]};const r=JSON.parse(fs.readFileSync(t,"utf8")),n=path_1.default.join(process.cwd(),"lib/knowledge","encrypted"),o=path_1.default.join(n,`${e.agentName}.enc`),s=fs.existsSync(o);return{content:[{type:"text",text:JSON.stringify({success:!0,agentName:e.agentName,agentData:r,hasKnowledge:s,knowledgeSize:s?fs.statSync(o).size:0})}]}}catch(e){return{content:[{type:"text",text:JSON.stringify({success:!1,error:`Agent delegation failed: ${e}`,code:"DELEGATION_ERROR"})}]}}}startCacheCleanup(){}async handlePluginTool(e,t){try{if(!plugin_manager_js_1.pluginManager)return null;if(!plugin_manager_js_1.pluginManager.getAvailableTools().find(t=>t.name===e))return null;this.debugLog(`プラグインツール実行: ${e}`,t);const r={userId:"current_user",service:"leonardo",apiKey:void 0,settings:{}};let n="leonardo";e.startsWith("leonardo_")&&(n="leonardo");const o=await plugin_manager_js_1.pluginManager.executePlugin(n,e,t,r);if(o.success)return this.debugLog(`プラグインツール実行成功: ${e}`),{content:o.content,_meta:o.metadata};throw this.debugLog(`プラグインツール実行失敗: ${e}`,o.error),new types_js_1.McpError(types_js_1.ErrorCode.InternalError,`プラグインツール実行エラー: ${o.error}`)}catch(t){if(this.debugLog(`プラグインツール処理エラー: ${e}`,t),t instanceof types_js_1.McpError)throw t;throw new types_js_1.McpError(types_js_1.ErrorCode.InternalError,`プラグイン処理中にエラーが発生しました: ${t.message}`)}}async run(){try{await plugin_manager_js_1.pluginManager.initialize(),this.debugLog("プラグインマネージャー初期化完了")}catch(e){this.debugLog("プラグインマネージャー初期化エラー",e)}const e=new stdio_js_1.StdioServerTransport;await this.server.connect(e),this.startCacheCleanup()}}exports.SecureMCPServer=SecureMCPServer,require.main===module&&(new SecureMCPServer).run().catch(()=>{});
1
+ "use strict";var __createBinding=this&&this.__createBinding||(Object.create?function(e,t,r,n){void 0===n&&(n=r);var o=Object.getOwnPropertyDescriptor(t,r);o&&!("get"in o?!t.__esModule:o.writable||o.configurable)||(o={enumerable:!0,get:function(){return t[r]}}),Object.defineProperty(e,n,o)}:function(e,t,r,n){void 0===n&&(n=r),e[n]=t[r]}),__setModuleDefault=this&&this.__setModuleDefault||(Object.create?function(e,t){Object.defineProperty(e,"default",{enumerable:!0,value:t})}:function(e,t){e.default=t}),__importStar=this&&this.__importStar||function(){var e=function(t){return e=Object.getOwnPropertyNames||function(e){var t=[];for(var r in e)Object.prototype.hasOwnProperty.call(e,r)&&(t[t.length]=r);return t},e(t)};return function(t){if(t&&t.__esModule)return t;var r={};if(null!=t)for(var n=e(t),o=0;o<n.length;o++)"default"!==n[o]&&__createBinding(r,t,n[o]);return __setModuleDefault(r,t),r}}(),__importDefault=this&&this.__importDefault||function(e){return e&&e.__esModule?e:{default:e}};Object.defineProperty(exports,"__esModule",{value:!0}),exports.SecureMCPServer=void 0;const dotenv_1=__importDefault(require("dotenv")),path_1=__importDefault(require("path")),envPath=path_1.default.join(process.cwd(),".env.local");dotenv_1.default.config({path:envPath});const index_js_1=require("@modelcontextprotocol/sdk/server/index.js"),stdio_js_1=require("@modelcontextprotocol/sdk/server/stdio.js"),types_js_1=require("@modelcontextprotocol/sdk/types.js"),crypto_utils_js_1=require("./crypto-utils.js"),fs=__importStar(require("fs")),os=__importStar(require("os")),plugin_manager_js_1=require("./plugins/plugin-manager.js"),EncryptionKeyManager_js_1=require("./security/EncryptionKeyManager.js");class SecureMCPServer{constructor(){this.cacheTimeout=3e5,this.server=new index_js_1.Server({name:"secure-bluelamp-mcp",version:"3.0.0"},{capabilities:{tools:{}}}),this.validTokens=new Set,this.promptCache=new Map,this.encryptionKey=EncryptionKeyManager_js_1.EncryptionKeyManager.getEncryptionKey(),this.keywordMapping=new Map([["orchestrator","AIエージェント"],["requirements-engineer","要件定義エンジニア"],["ui-ux-designer","UI/UXデザイナー"],["data-modeling-engineer","データモデリングエンジニア"],["system-architect","システムアーキテクト"],["implementation-consultant","実装コンサルタント"],["environment-setup","環境構築"],["prototype-implementation","プロトタイプ実装"],["implementation-agent","実装エージェント"],["debug-agent","デバッグエージェント"],["deploy-specialist","デプロイスペシャリスト"],["page-creator","ページクリエイター"],["refactoring-engineer","リファクタリングエンジニア"],["ai-friendliness-diagnostic","AI親和性診断"]]),this.logFilePath=path_1.default.join(os.tmpdir(),`bluelamp-debug-${Date.now()}.log`),this.debugLog(`BlueLamp MCP Server starting - Log file: ${this.logFilePath}`),this.initializeTokensSync(),this.setupHandlers()}debugLog(e,t){const r=(new Date).toISOString(),n=t?`[${r}] ${e}\n${JSON.stringify(t,null,2)}\n`:`[${r}] ${e}\n`;try{fs.appendFileSync(this.logFilePath,n),console.error(`[DEBUG] ${e}`,t||"")}catch(e){}}initializeTokensSync(){try{const e=process.env.BLUELAMP_TOKEN;e&&this.validTokens.add(e),this.loadCLITokenFromFile(),this.validTokens.add("secure-token-2024"),this.debugLog(`Total valid tokens: ${this.validTokens.size}`)}catch(e){this.validTokens.add("secure-token-2024"),this.debugLog("Token initialization error:",e)}}loadCLITokenFromFile(){this.loadCLITokenAsync()}async loadCLITokenAsync(){try{const e=await Promise.resolve().then(()=>__importStar(require("path"))),__dirname=(await Promise.resolve().then(()=>__importStar(require("url"))),e.dirname(__filename)),t=e.dirname(e.dirname(e.dirname(__dirname))),r=e.join(t,"lib/mcp-server/dist/security"),module=require(`${r}/SimpleAuthManager.js`),n=await module.SimpleAuthManager.getToken();n&&n.startsWith("cli_")&&(this.validTokens.add(n),this.debugLog(`Loaded CLI token from SimpleAuthManager: ${n.substring(0,20)}...`))}catch(e){this.debugLog("CLI token loading error:",e)}}async getSystemToken(){try{const e=process.env.BLUELAMP_TOKEN;if(e&&this.validTokens.has(e))return e;const t=await Promise.resolve().then(()=>__importStar(require("path"))),__dirname=(await Promise.resolve().then(()=>__importStar(require("url"))),t.dirname(__filename)),r=t.dirname(t.dirname(t.dirname(__dirname))),n=t.join(r,"lib/mcp-server/dist/security");try{const module=require(`${n}/SimpleAuthManager.js`),e=await module.SimpleAuthManager.getToken();if(e&&e.startsWith("cli_"))return e}catch(e){this.debugLog("Failed to load token from SimpleAuthManager:",e)}for(const e of this.validTokens)if(e.startsWith("cli_"))return e;return"secure-token-2024"}catch(e){return this.debugLog("System token retrieval error:",e),"secure-token-2024"}}setupHandlers(){this.server.setRequestHandler(types_js_1.ListToolsRequestSchema,async()=>{const e=[{name:"inject_knowledge",description:"Inject specialized knowledge from Portal API",inputSchema:{type:"object",properties:{keyword:{type:"string",description:"Keyword to search for specialized knowledge"},context:{type:"string",description:"Additional context"},level:{type:"string",description:"Knowledge detail level"}},required:["keyword","context"]}},{name:"save_knowledge",description:"Save knowledge to encrypted storage",inputSchema:{type:"object",properties:{knowledge:{type:"string",description:"Knowledge content to save (encrypted)"},identifier:{type:"string",description:"Unique identifier for the knowledge"},token:{type:"string",description:"Authentication token for access"}},required:["knowledge","identifier","token"]}},{name:"list_prompts",description:"List available encrypted prompt templates",inputSchema:{type:"object",properties:{token:{type:"string",description:"Authentication token for access"},category:{type:"string",description:"Filter by category (optional)"}},required:["token"]}},{name:"get_debug_log_path",description:"Get the path to the debug log file",inputSchema:{type:"object",properties:{},required:[]}}];let t=[];try{plugin_manager_js_1.pluginManager&&(t=plugin_manager_js_1.pluginManager.getAvailableTools(),this.debugLog(`プラグインツール取得完了: ${t.length}個`))}catch(e){this.debugLog("プラグインツール取得エラー",e)}const r=[...e,...t];return this.debugLog(`全ツール数: ${r.length} (基本: ${e.length}, プラグイン: ${t.length})`),{tools:r}}),this.server.setRequestHandler(types_js_1.CallToolRequestSchema,async e=>{const{name:t,arguments:r}=e.params;this.debugLog(`Tool called: ${t}`),this.debugLog("Tool args:",r);try{switch(t){case"inject_knowledge":return this.debugLog("Calling handleInjectKnowledge"),await this.handleInjectKnowledge(r);case"save_knowledge":return await this.handleSaveKnowledge(r);case"list_prompts":return await this.handleListPrompts(r);case"get_debug_log_path":return{content:[{type:"text",text:JSON.stringify({success:!0,logPath:this.logFilePath,message:`Debug log is being written to: ${this.logFilePath}`})}]};default:const e=await this.handlePluginTool(t,r||{});if(e)return e;throw new types_js_1.McpError(types_js_1.ErrorCode.MethodNotFound,`Unknown tool: ${t}`)}}catch(e){if(e instanceof types_js_1.McpError)throw e;throw new types_js_1.McpError(types_js_1.ErrorCode.InternalError,`Tool execution failed: ${t}: ${e}`)}})}validateToken(e){return this.validTokens.has(e)}async fetchFromPortalAPI(e,t){try{const r=`${process.env.BLUELAMP_PORTAL_API_URL||"https://aiagentmarket-backend-6clpzmy5pa-an.a.run.app"}/api/cli/prompts/knowledge-injection/${encodeURIComponent(e)}`;this.debugLog("Portal API request:",{url:r,token:t.substring(0,20)+"...",keyword:e});const n=new AbortController,o=setTimeout(()=>n.abort(),3e4),s=process.env.BLUELAMP_SLOT_NUMBER||"1",i=await fetch(r,{method:"GET",headers:{"X-CLI-Token":t,"X-Current-Slot":s,"Content-Type":"application/json","User-Agent":"BlueLamp-MCP-Server/1.0"},signal:n.signal});if(clearTimeout(o),this.debugLog(`Portal API response status: ${i.status}`),!i.ok){if(this.debugLog(`Portal API error: ${i.status} ${i.statusText}`),401===i.status)return this.debugLog("Authentication failed - token may be invalid"),null;if(404===i.status)return this.debugLog(`Knowledge not found for keyword: ${e}`),null;throw new Error(`Portal API error: ${i.status} ${i.statusText}`)}const a=await i.json();return this.debugLog("Portal API JSON response:",a),a&&a.success&&a.data&&a.data.content?a.data.content:(this.debugLog("Empty response from Portal API"),null)}catch(e){if(e&&"object"==typeof e){const t=e;if("ENOTFOUND"===t.code||"TIMEOUT"===t.code||"AbortError"===t.name)return null}return null}}async handleInjectKnowledge(e){this.debugLog("Received args:",e),this.debugLog(`Valid tokens: ${Array.from(this.validTokens).map(e=>e.substring(0,30)+"...").join(", ")}`);let t=await this.getSystemToken();if(this.debugLog(`Using system token: ${t?.substring(0,30)}...`),!t||!this.validateToken(t))return this.debugLog("System authentication failed"),{content:[{type:"text",text:JSON.stringify({success:!1,error:"System authentication failed",code:"SYSTEM_AUTH_ERROR"})}]};try{const r=`${e.keyword}:${e.level}`,n=this.promptCache.get(r);let o,s="unknown";if(n&&Date.now()-n.timestamp<this.cacheTimeout)o=n.content,s=n.source||"cache";else{const n=path_1.default.join(process.cwd(),"lib/knowledge","encrypted",`${e.keyword}.enc`);if(fs.existsSync(n))try{o=crypto_utils_js_1.CryptoUtils.decryptFile(n,this.encryptionKey),s="local"}catch(r){const n=await this.fetchFromPortalAPI(e.keyword,t);if(!n)return{content:[{type:"text",text:JSON.stringify({success:!1,error:`Portal APIから知識を取得できませんでした: ${e.keyword}`,code:"KNOWLEDGE_NOT_FOUND"})}]};o=n,s="api"}else{this.debugLog(`Fetching from Portal API for keyword: ${e.keyword}`);const r=await this.fetchFromPortalAPI(e.keyword,t);if(this.debugLog("Portal API result:",{keyword:e.keyword,resultExists:!!r,resultType:typeof r,resultLength:r?r.length:0}),!r)return this.debugLog(`Portal API returned null for keyword: ${e.keyword}`),{content:[{type:"text",text:JSON.stringify({success:!1,error:`専門知識が見つかりませんでした: ${e.keyword}`,code:"KNOWLEDGE_NOT_FOUND"})}]};o=r,s="api"}this.promptCache.set(r,{content:o,timestamp:Date.now(),source:s})}const i=this.buildResponse(o,t);return{content:[{type:"text",text:JSON.stringify({success:!0,result:i,keyword:e.keyword,token:t.substring(0,20)+"...",cached:"cache"===s,source:s,timestamp:(new Date).toISOString()})}]}}catch(e){return{content:[{type:"text",text:JSON.stringify({success:!1,error:`知識注入処理中にエラーが発生しました: ${e}`,code:"INJECTION_ERROR"})}]}}}buildResponse(e,t){return this.debugLog(`buildResponse called with content length: ${e?e.length:0}`),{content:[{type:"text",text:e}]}}async handleSaveKnowledge(e){if(!this.validateToken(e.token))return{content:[{type:"text",text:JSON.stringify({success:!1,error:"Invalid authentication token",code:"AUTH_ERROR"})}]};try{const t=path_1.default.join(process.cwd(),"lib/knowledge","encrypted");fs.existsSync(t)||fs.mkdirSync(t,{recursive:!0});const r=path_1.default.join(t,`${e.identifier}.enc`);return crypto_utils_js_1.CryptoUtils.encryptFile(e.knowledge,r,this.encryptionKey),{content:[{type:"text",text:JSON.stringify({success:!0,message:"Knowledge saved successfully",outputPath:r,size:fs.statSync(r).size})}]}}catch(e){return{content:[{type:"text",text:JSON.stringify({success:!1,error:`Knowledge save failed: ${e}`,code:"SAVE_ERROR"})}]}}}async handleListPrompts(e){if(!this.validateToken(e.token))return{content:[{type:"text",text:JSON.stringify({success:!1,error:"Invalid authentication token",code:"AUTH_ERROR"})}]};try{const t=path_1.default.join(process.cwd(),"lib/knowledge","encrypted"),r=path_1.default.join(t,"prompt-registry.json");if(!fs.existsSync(r))return{content:[{type:"text",text:JSON.stringify({success:!1,error:"Prompt registry not found",code:"REGISTRY_NOT_FOUND"})}]};const n=JSON.parse(fs.readFileSync(r,"utf8"));let o=n.prompts;return e.category&&(o=o.filter(t=>t.category===e.category)),{content:[{type:"text",text:JSON.stringify({success:!0,totalCount:o.length,prompts:o,categories:n.categories,lastUpdated:n.lastUpdated})}]}}catch(e){return{content:[{type:"text",text:JSON.stringify({success:!1,error:`Failed to list prompts: ${e}`,code:"LIST_ERROR"})}]}}}startCacheCleanup(){}async handlePluginTool(e,t){try{if(!plugin_manager_js_1.pluginManager)return null;if(!plugin_manager_js_1.pluginManager.getAvailableTools().find(t=>t.name===e))return null;this.debugLog(`プラグインツール実行: ${e}`,t);const r={userId:"current_user",service:"leonardo",apiKey:void 0,settings:{}};let n="leonardo";e.startsWith("leonardo_")&&(n="leonardo");const o=await plugin_manager_js_1.pluginManager.executePlugin(n,e,t,r);if(o.success&&o.content)return this.debugLog(`プラグインツール実行成功: ${e}`),{content:o.content.map(e=>({type:e.type,text:e.text||""})),_meta:o.metadata};throw this.debugLog(`プラグインツール実行失敗: ${e}`,o.error),new types_js_1.McpError(types_js_1.ErrorCode.InternalError,`プラグインツール実行エラー: ${o.error}`)}catch(t){if(this.debugLog(`プラグインツール処理エラー: ${e}`,t),t instanceof types_js_1.McpError)throw t;const r=t instanceof Error?t.message:String(t);throw new types_js_1.McpError(types_js_1.ErrorCode.InternalError,`プラグイン処理中にエラーが発生しました: ${r}`)}}async run(){try{await plugin_manager_js_1.pluginManager.initialize(),this.debugLog("プラグインマネージャー初期化完了")}catch(e){this.debugLog("プラグインマネージャー初期化エラー",e)}const e=new stdio_js_1.StdioServerTransport;await this.server.connect(e),this.startCacheCleanup()}}exports.SecureMCPServer=SecureMCPServer,process.on("uncaughtException",e=>{const t=`[${(new Date).toISOString()}] UNCAUGHT_EXCEPTION: ${e.message}\n${e.stack||""}\n`,r=require("path").join(require("os").tmpdir(),"bluelamp-mcp-errors.log");try{require("fs").appendFileSync(r,t)}catch{}(e.message.includes("EADDRINUSE")||e.message.includes("FATAL"))&&process.exit(1)}),process.on("unhandledRejection",(e,t)=>{const r=`[${(new Date).toISOString()}] UNHANDLED_REJECTION: ${e instanceof Error?e.message:String(e)}\n`,n=require("path").join(require("os").tmpdir(),"bluelamp-mcp-errors.log");try{require("fs").appendFileSync(n,r)}catch{}}),require.main===module&&(new SecureMCPServer).run().catch(e=>{const t=require("path").join(require("os").tmpdir(),"bluelamp-mcp-errors.log"),r=`[${(new Date).toISOString()}] STARTUP_ERROR: ${e.message}\n`;try{require("fs").appendFileSync(t,r)}catch{}process.exit(1)});
@@ -0,0 +1 @@
1
+ "use strict";var __createBinding=this&&this.__createBinding||(Object.create?function(e,t,r,n){void 0===n&&(n=r);var a=Object.getOwnPropertyDescriptor(t,r);a&&!("get"in a?!t.__esModule:a.writable||a.configurable)||(a={enumerable:!0,get:function(){return t[r]}}),Object.defineProperty(e,n,a)}:function(e,t,r,n){void 0===n&&(n=r),e[n]=t[r]}),__setModuleDefault=this&&this.__setModuleDefault||(Object.create?function(e,t){Object.defineProperty(e,"default",{enumerable:!0,value:t})}:function(e,t){e.default=t}),__importStar=this&&this.__importStar||function(){var e=function(t){return e=Object.getOwnPropertyNames||function(e){var t=[];for(var r in e)Object.prototype.hasOwnProperty.call(e,r)&&(t[t.length]=r);return t},e(t)};return function(t){if(t&&t.__esModule)return t;var r={};if(null!=t)for(var n=e(t),a=0;a<n.length;a++)"default"!==n[a]&&__createBinding(r,t,n[a]);return __setModuleDefault(r,t),r}}();Object.defineProperty(exports,"__esModule",{value:!0}),exports.EncryptionKeyManager=void 0;const fs=__importStar(require("fs")),path=__importStar(require("path")),os=__importStar(require("os")),crypto=__importStar(require("crypto"));class EncryptionKeyManager{static getEncryptionKey(){return process.env.BLUELAMP_ENCRYPTION_KEY||(this.cachedKey||(this.cachedKey=this.loadOrGenerateKey()),this.cachedKey)}static loadOrGenerateKey(){if(fs.existsSync(this.BLUELAMP_DIR)||fs.mkdirSync(this.BLUELAMP_DIR,{recursive:!0,mode:448}),fs.existsSync(this.KEY_FILE_PATH))try{const e=fs.readFileSync(this.KEY_FILE_PATH,"utf8").trim();if(this.validateKeyFormat(e))return e;console.warn("[EncryptionKeyManager] Invalid key format, regenerating...")}catch(e){console.warn("[EncryptionKeyManager] Failed to read key file, regenerating...")}return this.generateAndSaveKey()}static generateAndSaveKey(){const e=crypto.randomBytes(this.KEY_LENGTH).toString("hex");try{fs.writeFileSync(this.KEY_FILE_PATH,e,{encoding:"utf8",mode:384}),"win32"!==process.platform&&fs.chmodSync(this.KEY_FILE_PATH,384),console.log("[EncryptionKeyManager] New encryption key generated and saved.")}catch(e){console.error("[EncryptionKeyManager] Failed to save key file:",e)}return e}static validateKeyFormat(e){return/^[a-f0-9]{64}$/i.test(e)}static getKeyFilePath(){return this.KEY_FILE_PATH}static clearCache(){this.cachedKey=null}}exports.EncryptionKeyManager=EncryptionKeyManager,EncryptionKeyManager.BLUELAMP_DIR=path.join(os.homedir(),".bluelamp"),EncryptionKeyManager.KEY_FILE_PATH=path.join(EncryptionKeyManager.BLUELAMP_DIR,".encryption-key"),EncryptionKeyManager.KEY_LENGTH=32,EncryptionKeyManager.cachedKey=null;