agentic-flow 1.0.0

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 (383) hide show
  1. package/.claude/agents/MIGRATION_SUMMARY.md +222 -0
  2. package/.claude/agents/README.md +89 -0
  3. package/.claude/agents/analysis/code-analyzer.md +209 -0
  4. package/.claude/agents/analysis/code-review/analyze-code-quality.md +180 -0
  5. package/.claude/agents/architecture/system-design/arch-system-design.md +156 -0
  6. package/.claude/agents/base-template-generator.md +42 -0
  7. package/.claude/agents/consensus/README.md +253 -0
  8. package/.claude/agents/consensus/byzantine-coordinator.md +63 -0
  9. package/.claude/agents/consensus/crdt-synchronizer.md +997 -0
  10. package/.claude/agents/consensus/gossip-coordinator.md +63 -0
  11. package/.claude/agents/consensus/performance-benchmarker.md +851 -0
  12. package/.claude/agents/consensus/quorum-manager.md +823 -0
  13. package/.claude/agents/consensus/raft-manager.md +63 -0
  14. package/.claude/agents/consensus/security-manager.md +622 -0
  15. package/.claude/agents/core/coder.md +211 -0
  16. package/.claude/agents/core/planner.md +116 -0
  17. package/.claude/agents/core/researcher.md +136 -0
  18. package/.claude/agents/core/reviewer.md +272 -0
  19. package/.claude/agents/core/tester.md +266 -0
  20. package/.claude/agents/data/ml/data-ml-model.md +193 -0
  21. package/.claude/agents/development/backend/dev-backend-api.md +142 -0
  22. package/.claude/agents/devops/ci-cd/ops-cicd-github.md +164 -0
  23. package/.claude/agents/documentation/api-docs/docs-api-openapi.md +174 -0
  24. package/.claude/agents/flow-nexus/app-store.md +88 -0
  25. package/.claude/agents/flow-nexus/authentication.md +69 -0
  26. package/.claude/agents/flow-nexus/challenges.md +81 -0
  27. package/.claude/agents/flow-nexus/neural-network.md +88 -0
  28. package/.claude/agents/flow-nexus/payments.md +83 -0
  29. package/.claude/agents/flow-nexus/sandbox.md +76 -0
  30. package/.claude/agents/flow-nexus/swarm.md +76 -0
  31. package/.claude/agents/flow-nexus/user-tools.md +96 -0
  32. package/.claude/agents/flow-nexus/workflow.md +84 -0
  33. package/.claude/agents/github/code-review-swarm.md +538 -0
  34. package/.claude/agents/github/github-modes.md +173 -0
  35. package/.claude/agents/github/issue-tracker.md +319 -0
  36. package/.claude/agents/github/multi-repo-swarm.md +553 -0
  37. package/.claude/agents/github/pr-manager.md +191 -0
  38. package/.claude/agents/github/project-board-sync.md +509 -0
  39. package/.claude/agents/github/release-manager.md +367 -0
  40. package/.claude/agents/github/release-swarm.md +583 -0
  41. package/.claude/agents/github/repo-architect.md +398 -0
  42. package/.claude/agents/github/swarm-issue.md +573 -0
  43. package/.claude/agents/github/swarm-pr.md +428 -0
  44. package/.claude/agents/github/sync-coordinator.md +452 -0
  45. package/.claude/agents/github/workflow-automation.md +635 -0
  46. package/.claude/agents/goal/agent.md +816 -0
  47. package/.claude/agents/goal/goal-planner.md +73 -0
  48. package/.claude/agents/optimization/README.md +250 -0
  49. package/.claude/agents/optimization/benchmark-suite.md +665 -0
  50. package/.claude/agents/optimization/load-balancer.md +431 -0
  51. package/.claude/agents/optimization/performance-monitor.md +672 -0
  52. package/.claude/agents/optimization/resource-allocator.md +674 -0
  53. package/.claude/agents/optimization/topology-optimizer.md +808 -0
  54. package/.claude/agents/payments/agentic-payments.md +126 -0
  55. package/.claude/agents/sparc/architecture.md +472 -0
  56. package/.claude/agents/sparc/pseudocode.md +318 -0
  57. package/.claude/agents/sparc/refinement.md +525 -0
  58. package/.claude/agents/sparc/specification.md +276 -0
  59. package/.claude/agents/specialized/mobile/spec-mobile-react-native.md +226 -0
  60. package/.claude/agents/sublinear/consensus-coordinator.md +338 -0
  61. package/.claude/agents/sublinear/matrix-optimizer.md +185 -0
  62. package/.claude/agents/sublinear/pagerank-analyzer.md +299 -0
  63. package/.claude/agents/sublinear/performance-optimizer.md +368 -0
  64. package/.claude/agents/sublinear/trading-predictor.md +246 -0
  65. package/.claude/agents/swarm/README.md +190 -0
  66. package/.claude/agents/swarm/adaptive-coordinator.md +396 -0
  67. package/.claude/agents/swarm/hierarchical-coordinator.md +256 -0
  68. package/.claude/agents/swarm/mesh-coordinator.md +392 -0
  69. package/.claude/agents/templates/automation-smart-agent.md +205 -0
  70. package/.claude/agents/templates/coordinator-swarm-init.md +90 -0
  71. package/.claude/agents/templates/github-pr-manager.md +177 -0
  72. package/.claude/agents/templates/implementer-sparc-coder.md +259 -0
  73. package/.claude/agents/templates/memory-coordinator.md +187 -0
  74. package/.claude/agents/templates/migration-plan.md +746 -0
  75. package/.claude/agents/templates/orchestrator-task.md +139 -0
  76. package/.claude/agents/templates/performance-analyzer.md +199 -0
  77. package/.claude/agents/templates/sparc-coordinator.md +183 -0
  78. package/.claude/agents/test-neural.md +14 -0
  79. package/.claude/agents/testing/unit/tdd-london-swarm.md +244 -0
  80. package/.claude/agents/testing/validation/production-validator.md +395 -0
  81. package/.claude/commands/agents/README.md +10 -0
  82. package/.claude/commands/agents/agent-capabilities.md +21 -0
  83. package/.claude/commands/agents/agent-coordination.md +28 -0
  84. package/.claude/commands/agents/agent-spawning.md +28 -0
  85. package/.claude/commands/agents/agent-types.md +26 -0
  86. package/.claude/commands/analysis/COMMAND_COMPLIANCE_REPORT.md +54 -0
  87. package/.claude/commands/analysis/README.md +9 -0
  88. package/.claude/commands/analysis/bottleneck-detect.md +162 -0
  89. package/.claude/commands/analysis/performance-bottlenecks.md +59 -0
  90. package/.claude/commands/analysis/performance-report.md +25 -0
  91. package/.claude/commands/analysis/token-efficiency.md +45 -0
  92. package/.claude/commands/analysis/token-usage.md +25 -0
  93. package/.claude/commands/automation/README.md +9 -0
  94. package/.claude/commands/automation/auto-agent.md +122 -0
  95. package/.claude/commands/automation/self-healing.md +106 -0
  96. package/.claude/commands/automation/session-memory.md +90 -0
  97. package/.claude/commands/automation/smart-agents.md +73 -0
  98. package/.claude/commands/automation/smart-spawn.md +25 -0
  99. package/.claude/commands/automation/workflow-select.md +25 -0
  100. package/.claude/commands/claude-flow-help.md +103 -0
  101. package/.claude/commands/claude-flow-memory.md +107 -0
  102. package/.claude/commands/claude-flow-swarm.md +205 -0
  103. package/.claude/commands/coordination/README.md +9 -0
  104. package/.claude/commands/coordination/agent-spawn.md +25 -0
  105. package/.claude/commands/coordination/init.md +44 -0
  106. package/.claude/commands/coordination/orchestrate.md +43 -0
  107. package/.claude/commands/coordination/spawn.md +45 -0
  108. package/.claude/commands/coordination/swarm-init.md +85 -0
  109. package/.claude/commands/coordination/task-orchestrate.md +25 -0
  110. package/.claude/commands/flow-nexus/app-store.md +124 -0
  111. package/.claude/commands/flow-nexus/challenges.md +120 -0
  112. package/.claude/commands/flow-nexus/login-registration.md +65 -0
  113. package/.claude/commands/flow-nexus/neural-network.md +134 -0
  114. package/.claude/commands/flow-nexus/payments.md +116 -0
  115. package/.claude/commands/flow-nexus/sandbox.md +83 -0
  116. package/.claude/commands/flow-nexus/swarm.md +87 -0
  117. package/.claude/commands/flow-nexus/user-tools.md +152 -0
  118. package/.claude/commands/flow-nexus/workflow.md +115 -0
  119. package/.claude/commands/github/README.md +11 -0
  120. package/.claude/commands/github/code-review-swarm.md +514 -0
  121. package/.claude/commands/github/code-review.md +25 -0
  122. package/.claude/commands/github/github-modes.md +147 -0
  123. package/.claude/commands/github/github-swarm.md +121 -0
  124. package/.claude/commands/github/issue-tracker.md +292 -0
  125. package/.claude/commands/github/issue-triage.md +25 -0
  126. package/.claude/commands/github/multi-repo-swarm.md +519 -0
  127. package/.claude/commands/github/pr-enhance.md +26 -0
  128. package/.claude/commands/github/pr-manager.md +170 -0
  129. package/.claude/commands/github/project-board-sync.md +471 -0
  130. package/.claude/commands/github/release-manager.md +338 -0
  131. package/.claude/commands/github/release-swarm.md +544 -0
  132. package/.claude/commands/github/repo-analyze.md +25 -0
  133. package/.claude/commands/github/repo-architect.md +367 -0
  134. package/.claude/commands/github/swarm-issue.md +482 -0
  135. package/.claude/commands/github/swarm-pr.md +285 -0
  136. package/.claude/commands/github/sync-coordinator.md +301 -0
  137. package/.claude/commands/github/workflow-automation.md +442 -0
  138. package/.claude/commands/hive-mind/README.md +17 -0
  139. package/.claude/commands/hive-mind/hive-mind-consensus.md +8 -0
  140. package/.claude/commands/hive-mind/hive-mind-init.md +18 -0
  141. package/.claude/commands/hive-mind/hive-mind-memory.md +8 -0
  142. package/.claude/commands/hive-mind/hive-mind-metrics.md +8 -0
  143. package/.claude/commands/hive-mind/hive-mind-resume.md +8 -0
  144. package/.claude/commands/hive-mind/hive-mind-sessions.md +8 -0
  145. package/.claude/commands/hive-mind/hive-mind-spawn.md +21 -0
  146. package/.claude/commands/hive-mind/hive-mind-status.md +8 -0
  147. package/.claude/commands/hive-mind/hive-mind-stop.md +8 -0
  148. package/.claude/commands/hive-mind/hive-mind-wizard.md +8 -0
  149. package/.claude/commands/hive-mind/hive-mind.md +27 -0
  150. package/.claude/commands/hooks/README.md +11 -0
  151. package/.claude/commands/hooks/overview.md +58 -0
  152. package/.claude/commands/hooks/post-edit.md +117 -0
  153. package/.claude/commands/hooks/post-task.md +112 -0
  154. package/.claude/commands/hooks/pre-edit.md +113 -0
  155. package/.claude/commands/hooks/pre-task.md +111 -0
  156. package/.claude/commands/hooks/session-end.md +118 -0
  157. package/.claude/commands/hooks/setup.md +103 -0
  158. package/.claude/commands/memory/README.md +9 -0
  159. package/.claude/commands/memory/memory-persist.md +25 -0
  160. package/.claude/commands/memory/memory-search.md +25 -0
  161. package/.claude/commands/memory/memory-usage.md +25 -0
  162. package/.claude/commands/memory/neural.md +47 -0
  163. package/.claude/commands/memory/usage.md +46 -0
  164. package/.claude/commands/monitoring/README.md +9 -0
  165. package/.claude/commands/monitoring/agent-metrics.md +25 -0
  166. package/.claude/commands/monitoring/agents.md +44 -0
  167. package/.claude/commands/monitoring/real-time-view.md +25 -0
  168. package/.claude/commands/monitoring/status.md +46 -0
  169. package/.claude/commands/monitoring/swarm-monitor.md +25 -0
  170. package/.claude/commands/optimization/README.md +9 -0
  171. package/.claude/commands/optimization/auto-topology.md +62 -0
  172. package/.claude/commands/optimization/cache-manage.md +25 -0
  173. package/.claude/commands/optimization/parallel-execute.md +25 -0
  174. package/.claude/commands/optimization/parallel-execution.md +50 -0
  175. package/.claude/commands/optimization/topology-optimize.md +25 -0
  176. package/.claude/commands/pair/README.md +261 -0
  177. package/.claude/commands/pair/commands.md +546 -0
  178. package/.claude/commands/pair/config.md +510 -0
  179. package/.claude/commands/pair/examples.md +512 -0
  180. package/.claude/commands/pair/modes.md +348 -0
  181. package/.claude/commands/pair/session.md +407 -0
  182. package/.claude/commands/pair/start.md +209 -0
  183. package/.claude/commands/sparc/analyzer.md +52 -0
  184. package/.claude/commands/sparc/architect.md +53 -0
  185. package/.claude/commands/sparc/ask.md +97 -0
  186. package/.claude/commands/sparc/batch-executor.md +54 -0
  187. package/.claude/commands/sparc/code.md +89 -0
  188. package/.claude/commands/sparc/coder.md +54 -0
  189. package/.claude/commands/sparc/debug.md +83 -0
  190. package/.claude/commands/sparc/debugger.md +54 -0
  191. package/.claude/commands/sparc/designer.md +53 -0
  192. package/.claude/commands/sparc/devops.md +109 -0
  193. package/.claude/commands/sparc/docs-writer.md +80 -0
  194. package/.claude/commands/sparc/documenter.md +54 -0
  195. package/.claude/commands/sparc/innovator.md +54 -0
  196. package/.claude/commands/sparc/integration.md +83 -0
  197. package/.claude/commands/sparc/mcp.md +117 -0
  198. package/.claude/commands/sparc/memory-manager.md +54 -0
  199. package/.claude/commands/sparc/optimizer.md +54 -0
  200. package/.claude/commands/sparc/orchestrator.md +132 -0
  201. package/.claude/commands/sparc/post-deployment-monitoring-mode.md +83 -0
  202. package/.claude/commands/sparc/refinement-optimization-mode.md +83 -0
  203. package/.claude/commands/sparc/researcher.md +54 -0
  204. package/.claude/commands/sparc/reviewer.md +54 -0
  205. package/.claude/commands/sparc/security-review.md +80 -0
  206. package/.claude/commands/sparc/sparc-modes.md +174 -0
  207. package/.claude/commands/sparc/sparc.md +111 -0
  208. package/.claude/commands/sparc/spec-pseudocode.md +80 -0
  209. package/.claude/commands/sparc/supabase-admin.md +348 -0
  210. package/.claude/commands/sparc/swarm-coordinator.md +54 -0
  211. package/.claude/commands/sparc/tdd.md +54 -0
  212. package/.claude/commands/sparc/tester.md +54 -0
  213. package/.claude/commands/sparc/tutorial.md +79 -0
  214. package/.claude/commands/sparc/workflow-manager.md +54 -0
  215. package/.claude/commands/sparc.md +166 -0
  216. package/.claude/commands/stream-chain/pipeline.md +121 -0
  217. package/.claude/commands/stream-chain/run.md +70 -0
  218. package/.claude/commands/swarm/README.md +15 -0
  219. package/.claude/commands/swarm/analysis.md +95 -0
  220. package/.claude/commands/swarm/development.md +96 -0
  221. package/.claude/commands/swarm/examples.md +168 -0
  222. package/.claude/commands/swarm/maintenance.md +102 -0
  223. package/.claude/commands/swarm/optimization.md +117 -0
  224. package/.claude/commands/swarm/research.md +136 -0
  225. package/.claude/commands/swarm/swarm-analysis.md +8 -0
  226. package/.claude/commands/swarm/swarm-background.md +8 -0
  227. package/.claude/commands/swarm/swarm-init.md +19 -0
  228. package/.claude/commands/swarm/swarm-modes.md +8 -0
  229. package/.claude/commands/swarm/swarm-monitor.md +8 -0
  230. package/.claude/commands/swarm/swarm-spawn.md +19 -0
  231. package/.claude/commands/swarm/swarm-status.md +8 -0
  232. package/.claude/commands/swarm/swarm-strategies.md +8 -0
  233. package/.claude/commands/swarm/swarm.md +27 -0
  234. package/.claude/commands/swarm/testing.md +131 -0
  235. package/.claude/commands/training/README.md +9 -0
  236. package/.claude/commands/training/model-update.md +25 -0
  237. package/.claude/commands/training/neural-patterns.md +74 -0
  238. package/.claude/commands/training/neural-train.md +25 -0
  239. package/.claude/commands/training/pattern-learn.md +25 -0
  240. package/.claude/commands/training/specialization.md +63 -0
  241. package/.claude/commands/truth/start.md +143 -0
  242. package/.claude/commands/verify/check.md +50 -0
  243. package/.claude/commands/verify/start.md +128 -0
  244. package/.claude/commands/workflows/README.md +9 -0
  245. package/.claude/commands/workflows/development.md +78 -0
  246. package/.claude/commands/workflows/research.md +63 -0
  247. package/.claude/commands/workflows/workflow-create.md +25 -0
  248. package/.claude/commands/workflows/workflow-execute.md +25 -0
  249. package/.claude/commands/workflows/workflow-export.md +25 -0
  250. package/.claude/helpers/checkpoint-manager.sh +251 -0
  251. package/.claude/helpers/github-safe.js +106 -0
  252. package/.claude/helpers/github-setup.sh +28 -0
  253. package/.claude/helpers/quick-start.sh +19 -0
  254. package/.claude/helpers/setup-mcp.sh +18 -0
  255. package/.claude/helpers/standard-checkpoint-hooks.sh +179 -0
  256. package/.claude/mcp.json +13 -0
  257. package/.claude/settings-backup.json +130 -0
  258. package/.claude/settings-optimized.json +116 -0
  259. package/.claude/settings-simple.json +78 -0
  260. package/.claude/settings.json +114 -0
  261. package/.claude/settings.local.json +14 -0
  262. package/README.md +1280 -0
  263. package/dist/agents/claudeAgent.js +73 -0
  264. package/dist/agents/claudeFlowAgent.js +115 -0
  265. package/dist/agents/codeReviewAgent.js +34 -0
  266. package/dist/agents/dataAgent.js +34 -0
  267. package/dist/agents/directApiAgent.js +260 -0
  268. package/dist/agents/webResearchAgent.js +35 -0
  269. package/dist/cli/mcp.js +135 -0
  270. package/dist/cli-proxy.js +246 -0
  271. package/dist/cli.js +158 -0
  272. package/dist/config/claudeFlow.js +67 -0
  273. package/dist/config/tools.js +33 -0
  274. package/dist/coordination/parallelSwarm.js +226 -0
  275. package/dist/examples/multi-agent-orchestration.js +45 -0
  276. package/dist/examples/parallel-swarm-deployment.js +171 -0
  277. package/dist/examples/use-goal-planner.js +52 -0
  278. package/dist/health.js +46 -0
  279. package/dist/index-with-proxy.js +101 -0
  280. package/dist/index.js +167 -0
  281. package/dist/mcp/claudeFlowSdkServer.js +202 -0
  282. package/dist/mcp/fastmcp/servers/claude-flow-sdk.js +198 -0
  283. package/dist/mcp/fastmcp/servers/http-streaming-updated.js +421 -0
  284. package/dist/mcp/fastmcp/servers/poc-stdio.js +82 -0
  285. package/dist/mcp/fastmcp/servers/stdio-full.js +421 -0
  286. package/dist/mcp/fastmcp/tools/agent/add-agent.js +107 -0
  287. package/dist/mcp/fastmcp/tools/agent/add-command.js +117 -0
  288. package/dist/mcp/fastmcp/tools/agent/execute.js +56 -0
  289. package/dist/mcp/fastmcp/tools/agent/list.js +82 -0
  290. package/dist/mcp/fastmcp/tools/agent/parallel.js +63 -0
  291. package/dist/mcp/fastmcp/tools/memory/retrieve.js +38 -0
  292. package/dist/mcp/fastmcp/tools/memory/search.js +41 -0
  293. package/dist/mcp/fastmcp/tools/memory/store.js +56 -0
  294. package/dist/mcp/fastmcp/tools/swarm/init.js +41 -0
  295. package/dist/mcp/fastmcp/tools/swarm/orchestrate.js +47 -0
  296. package/dist/mcp/fastmcp/tools/swarm/spawn.js +40 -0
  297. package/dist/mcp/fastmcp/types/index.js +2 -0
  298. package/dist/proxy/anthropic-to-openrouter.js +246 -0
  299. package/dist/router/providers/anthropic.js +89 -0
  300. package/dist/router/providers/onnx-local-optimized.js +167 -0
  301. package/dist/router/providers/onnx-local.js +294 -0
  302. package/dist/router/providers/onnx-phi4.js +190 -0
  303. package/dist/router/providers/onnx.js +242 -0
  304. package/dist/router/providers/openrouter.js +242 -0
  305. package/dist/router/router.js +283 -0
  306. package/dist/router/test-integration.js +140 -0
  307. package/dist/router/test-onnx-benchmark.js +145 -0
  308. package/dist/router/test-onnx-integration.js +128 -0
  309. package/dist/router/test-onnx-local.js +37 -0
  310. package/dist/router/test-onnx.js +148 -0
  311. package/dist/router/test-openrouter.js +121 -0
  312. package/dist/router/test-phi4.js +137 -0
  313. package/dist/router/types.js +2 -0
  314. package/dist/utils/agentLoader.js +106 -0
  315. package/dist/utils/cli.js +128 -0
  316. package/dist/utils/logger.js +41 -0
  317. package/dist/utils/mcpCommands.js +214 -0
  318. package/dist/utils/model-downloader.js +182 -0
  319. package/dist/utils/retry.js +54 -0
  320. package/docs/.claude-flow/metrics/agent-metrics.json +1 -0
  321. package/docs/.claude-flow/metrics/performance.json +9 -0
  322. package/docs/.claude-flow/metrics/task-metrics.json +10 -0
  323. package/docs/CHANGELOG.md +155 -0
  324. package/docs/CLAUDE.md +352 -0
  325. package/docs/COMPLETE_VALIDATION_SUMMARY.md +405 -0
  326. package/docs/INDEX.md +183 -0
  327. package/docs/LICENSE +21 -0
  328. package/docs/ONNX_CLI_USAGE.md +344 -0
  329. package/docs/ONNX_ENV_VARS.md +564 -0
  330. package/docs/ONNX_INTEGRATION.md +422 -0
  331. package/docs/ONNX_OPTIMIZATION_GUIDE.md +665 -0
  332. package/docs/ONNX_OPTIMIZATION_SUMMARY.md +374 -0
  333. package/docs/ONNX_VS_CLAUDE_QUALITY.md +442 -0
  334. package/docs/OPENROUTER_DEPLOYMENT.md +495 -0
  335. package/docs/architecture/EXECUTIVE_SUMMARY.md +310 -0
  336. package/docs/architecture/IMPROVEMENT_PLAN.md +11 -0
  337. package/docs/architecture/INTEGRATION-STATUS.md +290 -0
  338. package/docs/architecture/MULTI_MODEL_ROUTER_PLAN.md +620 -0
  339. package/docs/architecture/QUICK_WINS.md +333 -0
  340. package/docs/architecture/README.md +15 -0
  341. package/docs/architecture/RESEARCH_SUMMARY.md +652 -0
  342. package/docs/archived/FASTMCP_COMPLETE.md +428 -0
  343. package/docs/archived/FASTMCP_INTEGRATION_STATUS.md +288 -0
  344. package/docs/archived/FLOW-NEXUS-COMPLETE.md +269 -0
  345. package/docs/archived/INTEGRATION_CONFIRMED.md +351 -0
  346. package/docs/archived/ONNX_FINAL_REPORT.md +312 -0
  347. package/docs/archived/ONNX_IMPLEMENTATION_COMPLETE.md +215 -0
  348. package/docs/archived/ONNX_IMPLEMENTATION_SUMMARY.md +197 -0
  349. package/docs/archived/ONNX_SUCCESS_REPORT.md +271 -0
  350. package/docs/archived/OPENROUTER_PROXY_COMPLETE.md +494 -0
  351. package/docs/archived/PACKAGE-COMPLETE.md +138 -0
  352. package/docs/archived/README.md +27 -0
  353. package/docs/archived/RESEARCH_COMPLETE.txt +335 -0
  354. package/docs/archived/SDK-SETUP-COMPLETE.md +252 -0
  355. package/docs/guides/ALTERNATIVE_LLM_MODELS.md +524 -0
  356. package/docs/guides/DOCKER_AGENT_USAGE.md +352 -0
  357. package/docs/guides/IMPLEMENTATION_EXAMPLES.md +960 -0
  358. package/docs/guides/NPM-PUBLISH.md +218 -0
  359. package/docs/guides/README.md +17 -0
  360. package/docs/guides/agent-sdk.md +234 -0
  361. package/docs/integrations/CLAUDE_AGENTS_INTEGRATION.md +356 -0
  362. package/docs/integrations/CLAUDE_FLOW_INTEGRATION.md +535 -0
  363. package/docs/integrations/FASTMCP_CLI_INTEGRATION.md +503 -0
  364. package/docs/integrations/FLOW-NEXUS-INTEGRATION.md +319 -0
  365. package/docs/integrations/README.md +18 -0
  366. package/docs/integrations/fastmcp-implementation-plan.md +2516 -0
  367. package/docs/integrations/fastmcp-poc-integration.md +198 -0
  368. package/docs/router/ONNX_PHI4_RESEARCH.md +220 -0
  369. package/docs/router/ONNX_RUNTIME_INTEGRATION_PLAN.md +866 -0
  370. package/docs/router/PHI4_HYPEROPTIMIZATION_PLAN.md +2488 -0
  371. package/docs/router/README.md +552 -0
  372. package/docs/router/ROUTER_CONFIG_REFERENCE.md +577 -0
  373. package/docs/router/ROUTER_USER_GUIDE.md +865 -0
  374. package/docs/validation/DOCKER_MCP_VALIDATION.md +358 -0
  375. package/docs/validation/DOCKER_OPENROUTER_VALIDATION.md +443 -0
  376. package/docs/validation/FINAL_SYSTEM_VALIDATION.md +458 -0
  377. package/docs/validation/FINAL_VALIDATION_SUMMARY.md +409 -0
  378. package/docs/validation/MCP_CLI_TOOLS_VALIDATION.md +266 -0
  379. package/docs/validation/MODEL_VALIDATION_REPORT.md +386 -0
  380. package/docs/validation/OPENROUTER_VALIDATION_COMPLETE.md +382 -0
  381. package/docs/validation/README.md +20 -0
  382. package/docs/validation/ROUTER_VALIDATION.md +311 -0
  383. package/package.json +140 -0
@@ -0,0 +1,2516 @@
1
+ # FastMCP Implementation Plan for Agentic-Flow
2
+
3
+ ## Executive Summary
4
+
5
+ This document outlines a comprehensive plan to integrate the **fastmcp** TypeScript framework into agentic-flow, enhancing the Model Context Protocol (MCP) server infrastructure with improved performance, real-time streaming capabilities via HTTP transport, and optional security features.
6
+
7
+ ### Current State
8
+ - **Architecture**: 4 MCP servers (claude-flow-sdk in-process, claude-flow, flow-nexus, agentic-payments as subprocesses)
9
+ - **Tools**: 203+ MCP tools across multiple domains
10
+ - **Implementation**: Custom MCP implementation using `@anthropic-ai/claude-agent-sdk` and `@modelcontextprotocol/sdk`
11
+ - **Transport**: Primarily stdio for local/subprocess communication
12
+ - **Deployment**: Local, Docker, and cloud environments
13
+
14
+ ### Target State
15
+ - **Framework**: fastmcp TypeScript framework for standardized MCP server implementation
16
+ - **Transport**: Dual support for stdio (local) and HTTP streaming (network/cloud)
17
+ - **Security**: Optional authentication, authorization, and rate limiting layers
18
+ - **Performance**: Reduced boilerplate, improved tooling, better debugging
19
+ - **Maintainability**: Standardized patterns across all MCP servers
20
+
21
+ ### Benefits
22
+ 1. **Developer Experience**: Simplified tool definition with Zod schema validation
23
+ 2. **Performance**: Built-in optimizations, streaming support, progress notifications
24
+ 3. **Security**: Session-based authentication, tool-level authorization, rate limiting
25
+ 4. **Observability**: Enhanced logging, typed server events, health-check endpoints
26
+ 5. **Flexibility**: Support for both stdio and HTTP transports with automatic CORS
27
+ 6. **Testing**: Built-in CLI tools for development and debugging (`npx fastmcp dev`)
28
+
29
+ ---
30
+
31
+ ## 1. Research Summary
32
+
33
+ ### FastMCP Overview
34
+
35
+ FastMCP (v3.19.0+) is a TypeScript framework built on top of `@modelcontextprotocol/sdk` that eliminates boilerplate and provides intuitive APIs for building MCP servers.
36
+
37
+ **Key Features:**
38
+ - Simple tool, resource, and prompt definition
39
+ - Schema validation support (Zod, ArkType, Valibot, Standard Schema)
40
+ - Session-based authentication with tool-level access control
41
+ - Multiple transport types: stdio, HTTP streaming (SSE deprecated)
42
+ - Stateless mode for serverless deployments
43
+ - Progress notifications and streaming output
44
+ - Typed server events and prompt auto-completion
45
+ - CORS enabled by default
46
+ - Health-check endpoints
47
+ - Built-in development CLI
48
+
49
+ **Package Info:**
50
+ - **npm**: `npm install fastmcp`
51
+ - **GitHub**: https://github.com/punkpeye/fastmcp
52
+ - **Documentation**: https://gofastmcp.com/
53
+ - **Usage**: 382+ projects in npm registry
54
+
55
+ ### Transport Mechanisms
56
+
57
+ #### 1. Stdio Transport (Default)
58
+ - **Use Case**: Local command-line tools, desktop applications (Claude Desktop)
59
+ - **Communication**: Standard input/output streams
60
+ - **Advantages**: Simple, lightweight, perfect for subprocess communication
61
+ - **Current Match**: Aligns with current agentic-flow subprocess servers
62
+
63
+ #### 2. HTTP Streaming Transport (Recommended for Web)
64
+ - **Use Case**: Network-based deployments, multiple clients, cloud services
65
+ - **Communication**: Streamable HTTP with optional SSE for server-to-client streaming
66
+ - **Advantages**: Bidirectional communication, scalable, web-friendly
67
+ - **Target Use**: Flow-nexus cloud features, remote agent coordination
68
+
69
+ #### 3. SSE Transport (Deprecated)
70
+ - **Status**: Maintained for backward compatibility only
71
+ - **Recommendation**: Use HTTP streaming for all new projects
72
+ - **Migration Path**: Clients can fall back from HTTP to SSE for old servers
73
+
74
+ ### Security Features
75
+
76
+ #### Authentication
77
+ ```typescript
78
+ const server = new FastMCP({
79
+ name: "Secure Server",
80
+ authenticate: async (req) => {
81
+ const apiKey = req.headers.get('x-api-key');
82
+ if (!apiKey || apiKey !== process.env.API_KEY) {
83
+ throw new Response('Unauthorized', { status: 401 });
84
+ }
85
+ return { userId: 'user-123', role: 'admin' };
86
+ }
87
+ });
88
+ ```
89
+
90
+ #### Tool-Level Authorization
91
+ ```typescript
92
+ server.addTool({
93
+ name: "admin-dashboard",
94
+ canAccess: (auth) => auth.role === 'admin',
95
+ execute: async () => { /* ... */ }
96
+ });
97
+ ```
98
+
99
+ #### Rate Limiting
100
+ - TypeScript version: Middleware pattern support (not built-in like Python version)
101
+ - Python version: Built-in token bucket algorithms, per-client identification
102
+ - Implementation: Custom middleware or third-party libraries (express-rate-limit)
103
+
104
+ #### OAuth Support
105
+ - Built-in OAuth discovery endpoints
106
+ - Supports MCP Specification 2025-03-26 and 2025-06-18
107
+
108
+ ### Comparison: Current vs FastMCP
109
+
110
+ | Feature | Current Implementation | FastMCP Implementation |
111
+ |---------|----------------------|----------------------|
112
+ | **Tool Definition** | Manual SDK calls with verbose handlers | Simple `addTool()` with Zod schemas |
113
+ | **Schema Validation** | Custom validation logic | Built-in Zod/ArkType/Valibot support |
114
+ | **Authentication** | Not implemented | Session-based with tool-level control |
115
+ | **Transport** | Stdio only | Stdio + HTTP streaming |
116
+ | **Progress Reporting** | Not available | Built-in progress notifications |
117
+ | **Streaming** | Not available | Built-in streaming output |
118
+ | **Development Tools** | Manual testing | `npx fastmcp dev` and `npx fastmcp inspect` |
119
+ | **Error Handling** | Custom error handling | Standardized error responses |
120
+ | **Type Safety** | Partial | Full TypeScript support |
121
+ | **CORS** | Manual setup | Enabled by default |
122
+ | **Health Checks** | Not available | Built-in health-check endpoint |
123
+ | **Session Management** | Not available | Built-in session support |
124
+ | **OAuth** | Not implemented | Built-in OAuth discovery |
125
+
126
+ ---
127
+
128
+ ## 2. Technical Architecture
129
+
130
+ ### 2.1 Architecture Overview
131
+
132
+ ```
133
+ ┌─────────────────────────────────────────────────────────────┐
134
+ │ Agentic-Flow Core │
135
+ │ │
136
+ │ ┌─────────────┐ ┌─────────────┐ ┌─────────────┐ │
137
+ │ │ Goal Planner│ │ Orchestrator│ │ Agent SDK │ │
138
+ │ └──────┬──────┘ └──────┬──────┘ └──────┬──────┘ │
139
+ │ │ │ │ │
140
+ │ └─────────────────┴─────────────────┘ │
141
+ │ │ │
142
+ └───────────────────────────┼──────────────────────────────────┘
143
+
144
+ ┌───────▼────────┐
145
+ │ MCP Gateway │
146
+ │ (FastMCP Hub) │
147
+ └───────┬────────┘
148
+
149
+ ┌───────────────────┼───────────────────┐
150
+ │ │ │
151
+ ┌────▼─────┐ ┌─────▼──────┐ ┌─────▼──────┐
152
+ │ In-Process│ │ Subprocess │ │ HTTP │
153
+ │ FastMCP │ │ FastMCP │ │ FastMCP │
154
+ │ Servers │ │ Servers │ │ Servers │
155
+ └────┬─────┘ └─────┬──────┘ └─────┬──────┘
156
+ │ │ │
157
+ ┌────▼─────┐ ┌─────▼──────┐ ┌─────▼──────┐
158
+ │ claude- │ │ claude- │ │ flow-nexus │
159
+ │ flow-sdk │ │ flow │ │ (cloud) │
160
+ │ │ │ agentic- │ │ │
161
+ │ (stdio) │ │ payments │ │ (HTTP) │
162
+ └──────────┘ │ (stdio) │ └────────────┘
163
+ └────────────┘
164
+
165
+ Transport Layer:
166
+ ━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━
167
+
168
+ ┌──────────────────┐ ┌──────────────────┐ ┌──────────────────┐
169
+ │ Stdio Transport │ │ HTTP Streaming │ │ SSE (Legacy) │
170
+ │ │ │ │ │ │
171
+ │ • stdin/stdout │ │ • Bidirectional │ │ • Server→Client │
172
+ │ • Local process │ │ • Network │ │ • Deprecated │
173
+ │ • Claude Desktop│ │ • Multi-client │ │ • Backward compat│
174
+ │ • Subprocess │ │ • Cloud ready │ │ • Migration only│
175
+ └──────────────────┘ └──────────────────┘ └──────────────────┘
176
+
177
+ Security Layer (Optional):
178
+ ━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━
179
+
180
+ ┌─────────────────────────────────────────────────────────────┐
181
+ │ Authentication │ Authorization │ Rate Limiting │
182
+ │ ─────────────── │ ───────────── │ ──────────── │
183
+ │ • API Key │ • Tool-level │ • Per-client │
184
+ │ • Bearer Token │ • Role-based │ • Per-tool │
185
+ │ • OAuth 2.0 │ • Custom logic │ • Token bucket │
186
+ │ • Session-based │ • canAccess() │ • Middleware │
187
+ └─────────────────────────────────────────────────────────────┘
188
+ ```
189
+
190
+ ### 2.2 Server Migration Plan
191
+
192
+ #### Phase 1: In-Process Server (claude-flow-sdk)
193
+ **Current**: Uses `@anthropic-ai/claude-agent-sdk` with custom tool definitions
194
+ **Target**: FastMCP with stdio transport, no authentication needed (in-process)
195
+
196
+ ```typescript
197
+ // Before (current)
198
+ import { createSdkMcpServer, tool } from '@anthropic-ai/claude-agent-sdk';
199
+ import { z } from 'zod';
200
+
201
+ export const claudeFlowSdkServer = createSdkMcpServer({
202
+ name: 'claude-flow-sdk',
203
+ version: '1.0.0',
204
+ tools: [
205
+ tool('memory_store', '...', { key: z.string(), ... }, async (args) => { ... })
206
+ ]
207
+ });
208
+
209
+ // After (FastMCP)
210
+ import { FastMCP } from 'fastmcp';
211
+ import { z } from 'zod';
212
+
213
+ const server = new FastMCP({
214
+ name: 'claude-flow-sdk',
215
+ version: '1.0.0'
216
+ });
217
+
218
+ server.addTool({
219
+ name: 'memory_store',
220
+ description: 'Store a value in persistent memory',
221
+ parameters: z.object({
222
+ key: z.string().describe('Memory key'),
223
+ value: z.string().describe('Value to store'),
224
+ namespace: z.string().optional().default('default'),
225
+ ttl: z.number().optional()
226
+ }),
227
+ execute: async ({ key, value, namespace, ttl }) => {
228
+ // Implementation
229
+ return `Stored ${key} in ${namespace}`;
230
+ }
231
+ });
232
+
233
+ server.start({ transportType: 'stdio' });
234
+ ```
235
+
236
+ #### Phase 2: Subprocess Servers (claude-flow, agentic-payments)
237
+ **Current**: Spawned as subprocesses with stdio communication
238
+ **Target**: FastMCP with stdio transport, optional authentication
239
+
240
+ ```typescript
241
+ // claude-flow server with optional auth
242
+ import { FastMCP } from 'fastmcp';
243
+ import { z } from 'zod';
244
+
245
+ const server = new FastMCP({
246
+ name: 'claude-flow',
247
+ version: '2.0.0',
248
+ // Optional: Enable authentication for secure environments
249
+ authenticate: process.env.SECURE_MODE === 'true'
250
+ ? async (req) => {
251
+ const token = req.headers.get('authorization')?.replace('Bearer ', '');
252
+ if (!token || token !== process.env.CLAUDE_FLOW_TOKEN) {
253
+ throw new Response('Unauthorized', { status: 401 });
254
+ }
255
+ return { authenticated: true };
256
+ }
257
+ : undefined
258
+ });
259
+
260
+ // Tool definitions with progress reporting
261
+ server.addTool({
262
+ name: 'swarm_init',
263
+ description: 'Initialize multi-agent swarm',
264
+ parameters: z.object({
265
+ topology: z.enum(['mesh', 'hierarchical', 'ring', 'star']),
266
+ maxAgents: z.number().default(8),
267
+ strategy: z.enum(['balanced', 'specialized', 'adaptive']).default('balanced')
268
+ }),
269
+ execute: async ({ topology, maxAgents, strategy }, { onProgress }) => {
270
+ onProgress?.({ progress: 0.2, message: 'Initializing topology...' });
271
+ // Initialize swarm
272
+ onProgress?.({ progress: 0.5, message: 'Spawning agents...' });
273
+ // Spawn agents
274
+ onProgress?.({ progress: 1.0, message: 'Swarm ready' });
275
+ return { swarmId: 'swarm-123', agents: maxAgents, topology };
276
+ }
277
+ });
278
+
279
+ server.start({ transportType: 'stdio' });
280
+ ```
281
+
282
+ #### Phase 3: Cloud/Network Server (flow-nexus)
283
+ **Current**: HTTP-based custom implementation
284
+ **Target**: FastMCP with HTTP streaming transport, full authentication
285
+
286
+ ```typescript
287
+ // flow-nexus cloud server with full security
288
+ import { FastMCP } from 'fastmcp';
289
+ import { z } from 'zod';
290
+ import { verifyJWT, checkRateLimit } from './security';
291
+
292
+ const server = new FastMCP({
293
+ name: 'flow-nexus',
294
+ version: '1.0.0',
295
+ authenticate: async (req) => {
296
+ // JWT-based authentication
297
+ const token = req.headers.get('authorization')?.replace('Bearer ', '');
298
+ if (!token) {
299
+ throw new Response('Missing token', { status: 401 });
300
+ }
301
+
302
+ const payload = await verifyJWT(token);
303
+ if (!payload) {
304
+ throw new Response('Invalid token', { status: 401 });
305
+ }
306
+
307
+ // Rate limiting check
308
+ const allowed = await checkRateLimit(payload.userId);
309
+ if (!allowed) {
310
+ throw new Response('Rate limit exceeded', { status: 429 });
311
+ }
312
+
313
+ return {
314
+ userId: payload.userId,
315
+ tier: payload.tier,
316
+ role: payload.role
317
+ };
318
+ }
319
+ });
320
+
321
+ // Tool with role-based access control
322
+ server.addTool({
323
+ name: 'sandbox_create',
324
+ description: 'Create isolated code execution sandbox',
325
+ canAccess: (auth) => ['pro', 'enterprise'].includes(auth.tier),
326
+ parameters: z.object({
327
+ template: z.enum(['node', 'python', 'react', 'nextjs']),
328
+ name: z.string().optional(),
329
+ env_vars: z.record(z.string()).optional()
330
+ }),
331
+ execute: async ({ template, name, env_vars }, { onProgress, auth }) => {
332
+ onProgress?.({ progress: 0.1, message: 'Allocating sandbox...' });
333
+ // Create sandbox
334
+ onProgress?.({ progress: 0.5, message: 'Installing dependencies...' });
335
+ // Setup environment
336
+ onProgress?.({ progress: 1.0, message: 'Sandbox ready' });
337
+
338
+ return {
339
+ sandboxId: 'sandbox-456',
340
+ template,
341
+ userId: auth.userId,
342
+ url: `https://sandbox-456.flow-nexus.io`
343
+ };
344
+ }
345
+ });
346
+
347
+ // Start with HTTP streaming transport
348
+ server.start({
349
+ transportType: 'http',
350
+ port: process.env.PORT || 8080,
351
+ host: '0.0.0.0'
352
+ });
353
+ ```
354
+
355
+ ### 2.3 Security Architecture
356
+
357
+ #### Authentication Layer
358
+
359
+ ```typescript
360
+ // security/auth.ts
361
+ import jwt from 'jsonwebtoken';
362
+
363
+ export interface AuthContext {
364
+ userId: string;
365
+ tier: 'free' | 'pro' | 'enterprise';
366
+ role: 'user' | 'admin';
367
+ permissions: string[];
368
+ }
369
+
370
+ export async function verifyJWT(token: string): Promise<AuthContext | null> {
371
+ try {
372
+ const payload = jwt.verify(token, process.env.JWT_SECRET!) as any;
373
+ return {
374
+ userId: payload.sub,
375
+ tier: payload.tier || 'free',
376
+ role: payload.role || 'user',
377
+ permissions: payload.permissions || []
378
+ };
379
+ } catch {
380
+ return null;
381
+ }
382
+ }
383
+
384
+ export async function verifyAPIKey(apiKey: string): Promise<AuthContext | null> {
385
+ // Check against database or cache
386
+ const user = await db.users.findByAPIKey(apiKey);
387
+ if (!user) return null;
388
+
389
+ return {
390
+ userId: user.id,
391
+ tier: user.tier,
392
+ role: user.role,
393
+ permissions: user.permissions
394
+ };
395
+ }
396
+ ```
397
+
398
+ #### Rate Limiting
399
+
400
+ ```typescript
401
+ // security/rate-limit.ts
402
+ import { RedisClient } from 'redis';
403
+
404
+ interface RateLimitConfig {
405
+ windowMs: number;
406
+ maxRequests: number;
407
+ keyPrefix: string;
408
+ }
409
+
410
+ export class RateLimiter {
411
+ private redis: RedisClient;
412
+
413
+ constructor(private config: RateLimitConfig) {
414
+ this.redis = new RedisClient(process.env.REDIS_URL);
415
+ }
416
+
417
+ async checkLimit(userId: string): Promise<boolean> {
418
+ const key = `${this.config.keyPrefix}:${userId}`;
419
+ const now = Date.now();
420
+ const windowStart = now - this.config.windowMs;
421
+
422
+ // Remove old entries
423
+ await this.redis.zremrangebyscore(key, 0, windowStart);
424
+
425
+ // Count requests in current window
426
+ const count = await this.redis.zcard(key);
427
+
428
+ if (count >= this.config.maxRequests) {
429
+ return false;
430
+ }
431
+
432
+ // Add current request
433
+ await this.redis.zadd(key, now, `${now}`);
434
+ await this.redis.expire(key, Math.ceil(this.config.windowMs / 1000));
435
+
436
+ return true;
437
+ }
438
+ }
439
+
440
+ // Usage
441
+ const limiter = new RateLimiter({
442
+ windowMs: 60000, // 1 minute
443
+ maxRequests: 100,
444
+ keyPrefix: 'rate-limit'
445
+ });
446
+
447
+ export async function checkRateLimit(userId: string): Promise<boolean> {
448
+ return await limiter.checkLimit(userId);
449
+ }
450
+ ```
451
+
452
+ #### Tool Authorization
453
+
454
+ ```typescript
455
+ // security/authorization.ts
456
+ export interface Permission {
457
+ resource: string;
458
+ action: 'read' | 'write' | 'execute';
459
+ }
460
+
461
+ export function hasPermission(
462
+ auth: AuthContext,
463
+ required: Permission
464
+ ): boolean {
465
+ // Admin has all permissions
466
+ if (auth.role === 'admin') return true;
467
+
468
+ // Check tier-based permissions
469
+ const tierPermissions = {
470
+ free: ['swarm:read', 'memory:read', 'agent:read'],
471
+ pro: ['swarm:*', 'memory:*', 'agent:*', 'sandbox:*'],
472
+ enterprise: ['*']
473
+ };
474
+
475
+ const permissions = tierPermissions[auth.tier];
476
+ const pattern = `${required.resource}:${required.action}`;
477
+
478
+ return permissions.includes(pattern) ||
479
+ permissions.includes(`${required.resource}:*`) ||
480
+ permissions.includes('*');
481
+ }
482
+
483
+ // Tool-level authorization helper
484
+ export function requirePermission(resource: string, action: string) {
485
+ return (auth: AuthContext) => hasPermission(auth, { resource, action });
486
+ }
487
+ ```
488
+
489
+ ### 2.4 Transport Selection Strategy
490
+
491
+ ```typescript
492
+ // config/transport.ts
493
+ export interface TransportConfig {
494
+ type: 'stdio' | 'http';
495
+ port?: number;
496
+ host?: string;
497
+ enableAuth?: boolean;
498
+ enableCORS?: boolean;
499
+ }
500
+
501
+ export function selectTransport(): TransportConfig {
502
+ // Environment-based transport selection
503
+ const env = process.env.NODE_ENV || 'development';
504
+ const deploymentMode = process.env.DEPLOYMENT_MODE || 'local';
505
+
506
+ // Local subprocess: stdio
507
+ if (deploymentMode === 'local' || deploymentMode === 'subprocess') {
508
+ return {
509
+ type: 'stdio',
510
+ enableAuth: false
511
+ };
512
+ }
513
+
514
+ // Docker container: stdio or HTTP based on port
515
+ if (deploymentMode === 'docker') {
516
+ return {
517
+ type: process.env.MCP_PORT ? 'http' : 'stdio',
518
+ port: parseInt(process.env.MCP_PORT || '8080'),
519
+ host: '0.0.0.0',
520
+ enableAuth: env === 'production',
521
+ enableCORS: true
522
+ };
523
+ }
524
+
525
+ // Cloud deployment: HTTP with auth
526
+ if (deploymentMode === 'cloud') {
527
+ return {
528
+ type: 'http',
529
+ port: parseInt(process.env.PORT || '8080'),
530
+ host: '0.0.0.0',
531
+ enableAuth: true,
532
+ enableCORS: true
533
+ };
534
+ }
535
+
536
+ // Default to stdio
537
+ return {
538
+ type: 'stdio',
539
+ enableAuth: false
540
+ };
541
+ }
542
+ ```
543
+
544
+ ---
545
+
546
+ ## 3. Migration Strategy
547
+
548
+ ### 3.1 Migration Phases
549
+
550
+ #### Phase 0: Preparation (Week 1)
551
+ **Goals:**
552
+ - Install and evaluate fastmcp in development environment
553
+ - Create proof-of-concept with single tool
554
+ - Benchmark performance vs current implementation
555
+ - Document API differences
556
+
557
+ **Tasks:**
558
+ 1. Install fastmcp: `npm install fastmcp`
559
+ 2. Create test server with 1-2 tools
560
+ 3. Compare stdio performance
561
+ 4. Test HTTP streaming transport
562
+ 5. Evaluate authentication options
563
+ 6. Document findings
564
+
565
+ **Deliverables:**
566
+ - POC server implementation
567
+ - Performance comparison report
568
+ - API migration guide draft
569
+
570
+ #### Phase 1: In-Process Server Migration (Week 2-3)
571
+ **Target:** claude-flow-sdk server (in-process, stdio)
572
+
573
+ **Migration Steps:**
574
+ 1. Create new `src/mcp/fastmcp/` directory structure
575
+ 2. Implement base FastMCP server class
576
+ 3. Migrate tools one category at a time:
577
+ - Memory tools (store, retrieve, search)
578
+ - Swarm tools (init, spawn, status)
579
+ - Coordination tools (orchestrate, metrics)
580
+ 4. Add comprehensive error handling
581
+ 5. Implement logging integration
582
+ 6. Create migration tests
583
+ 7. Run parallel with old implementation
584
+ 8. Gradual rollout with feature flags
585
+
586
+ **Code Structure:**
587
+ ```
588
+ src/mcp/fastmcp/
589
+ ├── servers/
590
+ │ ├── base.ts # Base FastMCP server class
591
+ │ ├── claude-flow-sdk.ts # In-process server
592
+ │ └── index.ts
593
+ ├── tools/
594
+ │ ├── memory/ # Memory tools
595
+ │ │ ├── store.ts
596
+ │ │ ├── retrieve.ts
597
+ │ │ └── search.ts
598
+ │ ├── swarm/ # Swarm tools
599
+ │ │ ├── init.ts
600
+ │ │ ├── spawn.ts
601
+ │ │ └── status.ts
602
+ │ └── index.ts
603
+ ├── security/
604
+ │ ├── auth.ts # Authentication
605
+ │ ├── rate-limit.ts # Rate limiting
606
+ │ └── authorization.ts # Tool-level auth
607
+ ├── config/
608
+ │ ├── transport.ts # Transport selection
609
+ │ └── server-config.ts # Server configuration
610
+ └── index.ts
611
+ ```
612
+
613
+ **Success Criteria:**
614
+ - All existing tools work with FastMCP
615
+ - No performance degradation
616
+ - Improved error messages
617
+ - Better TypeScript types
618
+ - Tests passing
619
+
620
+ #### Phase 2: Subprocess Servers Migration (Week 4-5)
621
+ **Target:** claude-flow and agentic-payments servers (subprocess, stdio)
622
+
623
+ **Migration Steps:**
624
+ 1. Migrate claude-flow server
625
+ - Convert all swarm coordination tools
626
+ - Add progress reporting
627
+ - Implement streaming for long operations
628
+ - Add optional authentication
629
+ 2. Migrate agentic-payments server
630
+ - Convert payment tools
631
+ - Add transaction streaming
632
+ - Implement webhook notifications
633
+ - Add authentication
634
+ 3. Update subprocess spawning logic
635
+ 4. Test inter-server communication
636
+ 5. Validate memory coordination
637
+
638
+ **Authentication:**
639
+ - **Development**: No authentication
640
+ - **Production**: Optional token-based authentication via environment variable
641
+
642
+ **Success Criteria:**
643
+ - Subprocess servers work seamlessly
644
+ - Progress reporting functional
645
+ - Streaming operations work
646
+ - Optional auth doesn't break existing workflows
647
+
648
+ #### Phase 3: HTTP/Cloud Server (Week 6-7)
649
+ **Target:** flow-nexus server (HTTP streaming, full auth)
650
+
651
+ **Migration Steps:**
652
+ 1. Implement HTTP streaming transport
653
+ 2. Add JWT-based authentication
654
+ 3. Implement rate limiting with Redis
655
+ 4. Add role-based tool access control
656
+ 5. Setup CORS configuration
657
+ 6. Add health-check endpoints
658
+ 7. Implement session management
659
+ 8. Deploy to staging environment
660
+ 9. Load testing
661
+ 10. Production deployment
662
+
663
+ **Security Features:**
664
+ - JWT authentication
665
+ - API key support
666
+ - OAuth 2.0 integration
667
+ - Per-user rate limiting
668
+ - Tool-level authorization
669
+ - Request logging
670
+ - Audit trail
671
+
672
+ **Success Criteria:**
673
+ - HTTP transport working in cloud
674
+ - Authentication prevents unauthorized access
675
+ - Rate limiting prevents abuse
676
+ - Multi-client support verified
677
+ - Health checks operational
678
+ - Performance acceptable under load
679
+
680
+ #### Phase 4: Testing & Validation (Week 8)
681
+ **Goals:**
682
+ - Comprehensive integration testing
683
+ - Performance benchmarking
684
+ - Security audit
685
+ - Documentation update
686
+
687
+ **Testing Matrix:**
688
+ | Server | Transport | Auth | Tests |
689
+ |--------|-----------|------|-------|
690
+ | claude-flow-sdk | stdio | None | Unit, Integration |
691
+ | claude-flow | stdio | Optional | Unit, Integration, E2E |
692
+ | agentic-payments | stdio | Optional | Unit, Integration |
693
+ | flow-nexus | HTTP | Required | Unit, Integration, E2E, Load |
694
+
695
+ **Performance Benchmarks:**
696
+ - Tool invocation latency
697
+ - Throughput (tools/second)
698
+ - Memory usage
699
+ - CPU utilization
700
+ - Startup time
701
+ - Subprocess spawn time
702
+ - HTTP request latency
703
+
704
+ **Security Tests:**
705
+ - Authentication bypass attempts
706
+ - Rate limit effectiveness
707
+ - Authorization checks
708
+ - Token expiration
709
+ - CORS validation
710
+ - Input sanitization
711
+
712
+ #### Phase 5: Documentation & Rollout (Week 9-10)
713
+ **Goals:**
714
+ - Complete documentation
715
+ - Migration guide for users
716
+ - Training materials
717
+ - Staged rollout
718
+
719
+ **Documentation:**
720
+ 1. Architecture overview
721
+ 2. API reference for each server
722
+ 3. Authentication guide
723
+ 4. Transport selection guide
724
+ 5. Security best practices
725
+ 6. Migration guide from v1.x
726
+ 7. Troubleshooting guide
727
+ 8. Performance tuning guide
728
+
729
+ **Rollout Strategy:**
730
+ 1. Beta release (10% users)
731
+ 2. Feedback collection
732
+ 3. Bug fixes
733
+ 4. Expanded rollout (50% users)
734
+ 5. Final validation
735
+ 6. Full rollout (100% users)
736
+ 7. Deprecate old implementation
737
+
738
+ ### 3.2 Backward Compatibility
739
+
740
+ **Strategy:**
741
+ - Maintain old implementation alongside FastMCP
742
+ - Feature flag: `USE_FASTMCP=true/false`
743
+ - Gradual migration path
744
+ - Support both implementations for 2 releases
745
+
746
+ **Feature Flag Implementation:**
747
+ ```typescript
748
+ // src/mcp/index.ts
749
+ import { getServerConfig } from './config';
750
+ import { createLegacyServer } from './legacy';
751
+ import { createFastMCPServer } from './fastmcp';
752
+
753
+ export function createMCPServer(name: string) {
754
+ const config = getServerConfig();
755
+
756
+ if (config.useFastMCP) {
757
+ return createFastMCPServer(name);
758
+ } else {
759
+ return createLegacyServer(name);
760
+ }
761
+ }
762
+ ```
763
+
764
+ **Migration Timeline:**
765
+ - **v2.0.0**: FastMCP available, old implementation default
766
+ - **v2.1.0**: FastMCP default, old implementation available via flag
767
+ - **v2.2.0**: FastMCP only, old implementation removed
768
+
769
+ ### 3.3 Rollback Plan
770
+
771
+ **Triggers:**
772
+ - Critical bugs in production
773
+ - Performance degradation > 20%
774
+ - Authentication vulnerabilities
775
+ - Data loss or corruption
776
+
777
+ **Rollback Procedure:**
778
+ 1. Set `USE_FASTMCP=false` environment variable
779
+ 2. Restart affected servers
780
+ 3. Validate old implementation working
781
+ 4. Investigate issue
782
+ 5. Fix and retest
783
+ 6. Re-enable FastMCP
784
+
785
+ **Rollback Testing:**
786
+ - Practice rollback in staging
787
+ - Document time to rollback (target: < 5 minutes)
788
+ - Validate no data loss during rollback
789
+
790
+ ---
791
+
792
+ ## 4. Implementation Details
793
+
794
+ ### 4.1 Code Structure
795
+
796
+ ```
797
+ src/mcp/
798
+ ├── fastmcp/ # New FastMCP implementation
799
+ │ ├── servers/
800
+ │ │ ├── base.ts # Base server class with common setup
801
+ │ │ ├── claude-flow-sdk.ts # In-process server
802
+ │ │ ├── claude-flow.ts # Subprocess server
803
+ │ │ ├── agentic-payments.ts # Payments subprocess server
804
+ │ │ ├── flow-nexus.ts # Cloud HTTP server
805
+ │ │ └── index.ts
806
+ │ ├── tools/
807
+ │ │ ├── memory/
808
+ │ │ │ ├── store.ts
809
+ │ │ │ ├── retrieve.ts
810
+ │ │ │ ├── search.ts
811
+ │ │ │ ├── list.ts
812
+ │ │ │ └── delete.ts
813
+ │ │ ├── swarm/
814
+ │ │ │ ├── init.ts
815
+ │ │ │ ├── spawn.ts
816
+ │ │ │ ├── status.ts
817
+ │ │ │ ├── scale.ts
818
+ │ │ │ └── destroy.ts
819
+ │ │ ├── agent/
820
+ │ │ │ ├── list.ts
821
+ │ │ │ ├── metrics.ts
822
+ │ │ │ └── monitor.ts
823
+ │ │ ├── task/
824
+ │ │ │ ├── orchestrate.ts
825
+ │ │ │ ├── status.ts
826
+ │ │ │ └── results.ts
827
+ │ │ ├── neural/
828
+ │ │ │ ├── train.ts
829
+ │ │ │ ├── predict.ts
830
+ │ │ │ ├── status.ts
831
+ │ │ │ └── patterns.ts
832
+ │ │ ├── github/
833
+ │ │ │ ├── analyze.ts
834
+ │ │ │ ├── pr-manage.ts
835
+ │ │ │ └── issue-track.ts
836
+ │ │ ├── sandbox/
837
+ │ │ │ ├── create.ts
838
+ │ │ │ ├── execute.ts
839
+ │ │ │ ├── upload.ts
840
+ │ │ │ └── logs.ts
841
+ │ │ └── index.ts
842
+ │ ├── security/
843
+ │ │ ├── auth.ts # Authentication handlers
844
+ │ │ ├── rate-limit.ts # Rate limiting
845
+ │ │ ├── authorization.ts # Tool authorization
846
+ │ │ └── index.ts
847
+ │ ├── middleware/
848
+ │ │ ├── logging.ts # Request/response logging
849
+ │ │ ├── metrics.ts # Performance metrics
850
+ │ │ ├── error-handler.ts # Error handling
851
+ │ │ └── index.ts
852
+ │ ├── config/
853
+ │ │ ├── transport.ts # Transport configuration
854
+ │ │ ├── server-config.ts # Server settings
855
+ │ │ ├── security-config.ts # Security settings
856
+ │ │ └── index.ts
857
+ │ ├── utils/
858
+ │ │ ├── progress.ts # Progress reporting helpers
859
+ │ │ ├── streaming.ts # Streaming helpers
860
+ │ │ ├── validation.ts # Schema validation
861
+ │ │ └── index.ts
862
+ │ ├── types/
863
+ │ │ ├── auth.ts # Auth types
864
+ │ │ ├── tools.ts # Tool types
865
+ │ │ ├── config.ts # Config types
866
+ │ │ └── index.ts
867
+ │ └── index.ts
868
+ ├── legacy/ # Old implementation (deprecated)
869
+ │ └── ...
870
+ └── index.ts # Main entry point with feature flag
871
+ ```
872
+
873
+ ### 4.2 Base Server Implementation
874
+
875
+ ```typescript
876
+ // src/mcp/fastmcp/servers/base.ts
877
+ import { FastMCP } from 'fastmcp';
878
+ import { z } from 'zod';
879
+ import type { AuthContext, TransportConfig } from '../types';
880
+ import { setupLogging } from '../middleware/logging';
881
+ import { setupMetrics } from '../middleware/metrics';
882
+ import { setupErrorHandler } from '../middleware/error-handler';
883
+
884
+ export interface BaseServerConfig {
885
+ name: string;
886
+ version: string;
887
+ transport: TransportConfig;
888
+ enableAuth?: boolean;
889
+ enableMetrics?: boolean;
890
+ enableLogging?: boolean;
891
+ }
892
+
893
+ export abstract class BaseMCPServer {
894
+ protected server: FastMCP;
895
+ protected config: BaseServerConfig;
896
+
897
+ constructor(config: BaseServerConfig) {
898
+ this.config = config;
899
+
900
+ this.server = new FastMCP({
901
+ name: config.name,
902
+ version: config.version,
903
+ authenticate: config.enableAuth
904
+ ? this.authenticate.bind(this)
905
+ : undefined
906
+ });
907
+
908
+ // Setup middleware
909
+ if (config.enableLogging) {
910
+ setupLogging(this.server);
911
+ }
912
+ if (config.enableMetrics) {
913
+ setupMetrics(this.server);
914
+ }
915
+ setupErrorHandler(this.server);
916
+
917
+ // Register tools
918
+ this.registerTools();
919
+ }
920
+
921
+ protected abstract registerTools(): void;
922
+
923
+ protected async authenticate(req: Request): Promise<AuthContext> {
924
+ // Override in subclasses for custom auth
925
+ throw new Response('Authentication not implemented', { status: 501 });
926
+ }
927
+
928
+ public async start() {
929
+ const { transport } = this.config;
930
+
931
+ if (transport.type === 'stdio') {
932
+ await this.server.start({ transportType: 'stdio' });
933
+ } else {
934
+ await this.server.start({
935
+ transportType: 'http',
936
+ port: transport.port,
937
+ host: transport.host
938
+ });
939
+ }
940
+
941
+ console.log(`${this.config.name} server started on ${transport.type}`);
942
+ }
943
+
944
+ public async stop() {
945
+ // Cleanup logic
946
+ }
947
+ }
948
+ ```
949
+
950
+ ### 4.3 Tool Implementation Example
951
+
952
+ ```typescript
953
+ // src/mcp/fastmcp/tools/memory/store.ts
954
+ import { z } from 'zod';
955
+ import type { ToolDefinition } from '../../types';
956
+ import { execSync } from 'child_process';
957
+
958
+ export const memoryStoreTool: ToolDefinition = {
959
+ name: 'memory_store',
960
+ description: 'Store a value in persistent memory with optional namespace and TTL',
961
+ parameters: z.object({
962
+ key: z.string()
963
+ .min(1)
964
+ .describe('Memory key'),
965
+ value: z.string()
966
+ .describe('Value to store'),
967
+ namespace: z.string()
968
+ .optional()
969
+ .default('default')
970
+ .describe('Memory namespace'),
971
+ ttl: z.number()
972
+ .positive()
973
+ .optional()
974
+ .describe('Time-to-live in seconds')
975
+ }),
976
+ execute: async ({ key, value, namespace, ttl }, { onProgress, auth }) => {
977
+ try {
978
+ // Progress reporting
979
+ onProgress?.({ progress: 0.2, message: 'Validating input...' });
980
+
981
+ // Build command
982
+ const cmd = [
983
+ 'npx claude-flow@alpha memory store',
984
+ `"${key}"`,
985
+ `"${value}"`,
986
+ `--namespace "${namespace}"`,
987
+ ttl ? `--ttl ${ttl}` : ''
988
+ ].filter(Boolean).join(' ');
989
+
990
+ onProgress?.({ progress: 0.5, message: 'Storing value...' });
991
+
992
+ // Execute
993
+ const result = execSync(cmd, {
994
+ encoding: 'utf-8',
995
+ maxBuffer: 10 * 1024 * 1024
996
+ });
997
+
998
+ onProgress?.({ progress: 1.0, message: 'Stored successfully' });
999
+
1000
+ // Return formatted result
1001
+ return {
1002
+ success: true,
1003
+ key,
1004
+ namespace,
1005
+ size: value.length,
1006
+ ttl,
1007
+ userId: auth?.userId
1008
+ };
1009
+ } catch (error: any) {
1010
+ throw new Error(`Failed to store memory: ${error.message}`);
1011
+ }
1012
+ }
1013
+ };
1014
+ ```
1015
+
1016
+ ### 4.4 Authentication Implementation
1017
+
1018
+ ```typescript
1019
+ // src/mcp/fastmcp/security/auth.ts
1020
+ import jwt from 'jsonwebtoken';
1021
+ import type { AuthContext } from '../types';
1022
+
1023
+ export async function authenticateJWT(req: Request): Promise<AuthContext> {
1024
+ const authHeader = req.headers.get('authorization');
1025
+ if (!authHeader) {
1026
+ throw new Response('Missing Authorization header', { status: 401 });
1027
+ }
1028
+
1029
+ const token = authHeader.replace('Bearer ', '');
1030
+ if (!token) {
1031
+ throw new Response('Invalid Authorization format', { status: 401 });
1032
+ }
1033
+
1034
+ try {
1035
+ const payload = jwt.verify(token, process.env.JWT_SECRET!) as any;
1036
+
1037
+ return {
1038
+ userId: payload.sub,
1039
+ tier: payload.tier || 'free',
1040
+ role: payload.role || 'user',
1041
+ permissions: payload.permissions || []
1042
+ };
1043
+ } catch (error) {
1044
+ throw new Response('Invalid or expired token', { status: 401 });
1045
+ }
1046
+ }
1047
+
1048
+ export async function authenticateAPIKey(req: Request): Promise<AuthContext> {
1049
+ const apiKey = req.headers.get('x-api-key');
1050
+ if (!apiKey) {
1051
+ throw new Response('Missing API key', { status: 401 });
1052
+ }
1053
+
1054
+ // In production, check against database
1055
+ if (apiKey !== process.env.API_KEY) {
1056
+ throw new Response('Invalid API key', { status: 401 });
1057
+ }
1058
+
1059
+ // Return static context for demo
1060
+ return {
1061
+ userId: 'api-key-user',
1062
+ tier: 'pro',
1063
+ role: 'user',
1064
+ permissions: ['*']
1065
+ };
1066
+ }
1067
+ ```
1068
+
1069
+ ### 4.5 Server-Specific Implementations
1070
+
1071
+ #### Claude Flow SDK Server (In-Process)
1072
+ ```typescript
1073
+ // src/mcp/fastmcp/servers/claude-flow-sdk.ts
1074
+ import { BaseMCPServer } from './base';
1075
+ import { selectTransport } from '../config/transport';
1076
+ import * as memoryTools from '../tools/memory';
1077
+ import * as swarmTools from '../tools/swarm';
1078
+ import * as agentTools from '../tools/agent';
1079
+ import * as taskTools from '../tools/task';
1080
+
1081
+ export class ClaudeFlowSdkServer extends BaseMCPServer {
1082
+ constructor() {
1083
+ super({
1084
+ name: 'claude-flow-sdk',
1085
+ version: '1.0.0',
1086
+ transport: selectTransport(),
1087
+ enableAuth: false, // In-process, no auth needed
1088
+ enableMetrics: true,
1089
+ enableLogging: true
1090
+ });
1091
+ }
1092
+
1093
+ protected registerTools() {
1094
+ // Memory tools
1095
+ this.server.addTool(memoryTools.memoryStoreTool);
1096
+ this.server.addTool(memoryTools.memoryRetrieveTool);
1097
+ this.server.addTool(memoryTools.memorySearchTool);
1098
+ this.server.addTool(memoryTools.memoryListTool);
1099
+ this.server.addTool(memoryTools.memoryDeleteTool);
1100
+
1101
+ // Swarm tools
1102
+ this.server.addTool(swarmTools.swarmInitTool);
1103
+ this.server.addTool(swarmTools.swarmStatusTool);
1104
+ this.server.addTool(swarmTools.swarmDestroyTool);
1105
+
1106
+ // Agent tools
1107
+ this.server.addTool(agentTools.agentSpawnTool);
1108
+ this.server.addTool(agentTools.agentListTool);
1109
+ this.server.addTool(agentTools.agentMetricsTool);
1110
+
1111
+ // Task tools
1112
+ this.server.addTool(taskTools.taskOrchestrateTool);
1113
+ this.server.addTool(taskTools.taskStatusTool);
1114
+ this.server.addTool(taskTools.taskResultsTool);
1115
+ }
1116
+ }
1117
+ ```
1118
+
1119
+ #### Flow Nexus Server (HTTP with Auth)
1120
+ ```typescript
1121
+ // src/mcp/fastmcp/servers/flow-nexus.ts
1122
+ import { BaseMCPServer } from './base';
1123
+ import { authenticateJWT } from '../security/auth';
1124
+ import { checkRateLimit } from '../security/rate-limit';
1125
+ import * as sandboxTools from '../tools/sandbox';
1126
+ import * as neuralTools from '../tools/neural';
1127
+ import * as githubTools from '../tools/github';
1128
+
1129
+ export class FlowNexusServer extends BaseMCPServer {
1130
+ constructor() {
1131
+ super({
1132
+ name: 'flow-nexus',
1133
+ version: '1.0.0',
1134
+ transport: {
1135
+ type: 'http',
1136
+ port: parseInt(process.env.PORT || '8080'),
1137
+ host: '0.0.0.0',
1138
+ enableAuth: true,
1139
+ enableCORS: true
1140
+ },
1141
+ enableAuth: true,
1142
+ enableMetrics: true,
1143
+ enableLogging: true
1144
+ });
1145
+ }
1146
+
1147
+ protected async authenticate(req: Request) {
1148
+ const auth = await authenticateJWT(req);
1149
+
1150
+ // Check rate limit
1151
+ const allowed = await checkRateLimit(auth.userId);
1152
+ if (!allowed) {
1153
+ throw new Response('Rate limit exceeded', { status: 429 });
1154
+ }
1155
+
1156
+ return auth;
1157
+ }
1158
+
1159
+ protected registerTools() {
1160
+ // Sandbox tools (Pro+ only)
1161
+ this.server.addTool({
1162
+ ...sandboxTools.sandboxCreateTool,
1163
+ canAccess: (auth) => ['pro', 'enterprise'].includes(auth.tier)
1164
+ });
1165
+ this.server.addTool({
1166
+ ...sandboxTools.sandboxExecuteTool,
1167
+ canAccess: (auth) => ['pro', 'enterprise'].includes(auth.tier)
1168
+ });
1169
+
1170
+ // Neural tools (All authenticated users)
1171
+ this.server.addTool(neuralTools.neuralTrainTool);
1172
+ this.server.addTool(neuralTools.neuralPredictTool);
1173
+ this.server.addTool(neuralTools.neuralStatusTool);
1174
+
1175
+ // GitHub tools (All authenticated users)
1176
+ this.server.addTool(githubTools.githubAnalyzeTool);
1177
+ this.server.addTool(githubTools.githubPRManageTool);
1178
+
1179
+ // Admin tools (Admin only)
1180
+ this.server.addTool({
1181
+ name: 'admin_metrics',
1182
+ description: 'View system-wide metrics',
1183
+ canAccess: (auth) => auth.role === 'admin',
1184
+ parameters: z.object({}),
1185
+ execute: async () => {
1186
+ // Return metrics
1187
+ }
1188
+ });
1189
+ }
1190
+ }
1191
+ ```
1192
+
1193
+ ---
1194
+
1195
+ ## 5. Testing Strategy
1196
+
1197
+ ### 5.1 Unit Tests
1198
+
1199
+ ```typescript
1200
+ // tests/unit/tools/memory/store.test.ts
1201
+ import { describe, it, expect, vi } from 'vitest';
1202
+ import { memoryStoreTool } from '../../../../src/mcp/fastmcp/tools/memory/store';
1203
+
1204
+ describe('Memory Store Tool', () => {
1205
+ it('should store value successfully', async () => {
1206
+ const result = await memoryStoreTool.execute(
1207
+ { key: 'test', value: 'data', namespace: 'default' },
1208
+ { onProgress: vi.fn(), auth: undefined }
1209
+ );
1210
+
1211
+ expect(result.success).toBe(true);
1212
+ expect(result.key).toBe('test');
1213
+ });
1214
+
1215
+ it('should validate input schema', () => {
1216
+ expect(() => {
1217
+ memoryStoreTool.parameters.parse({ key: '', value: 'data' });
1218
+ }).toThrow();
1219
+ });
1220
+
1221
+ it('should report progress', async () => {
1222
+ const onProgress = vi.fn();
1223
+ await memoryStoreTool.execute(
1224
+ { key: 'test', value: 'data', namespace: 'default' },
1225
+ { onProgress, auth: undefined }
1226
+ );
1227
+
1228
+ expect(onProgress).toHaveBeenCalledWith(
1229
+ expect.objectContaining({ progress: 0.2 })
1230
+ );
1231
+ });
1232
+ });
1233
+ ```
1234
+
1235
+ ### 5.2 Integration Tests
1236
+
1237
+ ```typescript
1238
+ // tests/integration/servers/claude-flow-sdk.test.ts
1239
+ import { describe, it, expect, beforeAll, afterAll } from 'vitest';
1240
+ import { ClaudeFlowSdkServer } from '../../../src/mcp/fastmcp/servers/claude-flow-sdk';
1241
+ import { StdioClientTransport } from '@modelcontextprotocol/sdk/client/stdio.js';
1242
+
1243
+ describe('Claude Flow SDK Server', () => {
1244
+ let server: ClaudeFlowSdkServer;
1245
+ let client: any;
1246
+
1247
+ beforeAll(async () => {
1248
+ server = new ClaudeFlowSdkServer();
1249
+ await server.start();
1250
+
1251
+ // Create client
1252
+ const transport = new StdioClientTransport({
1253
+ command: 'node',
1254
+ args: ['dist/mcp/fastmcp/servers/claude-flow-sdk.js']
1255
+ });
1256
+ client = await transport.connect();
1257
+ });
1258
+
1259
+ afterAll(async () => {
1260
+ await server.stop();
1261
+ });
1262
+
1263
+ it('should list available tools', async () => {
1264
+ const tools = await client.listTools();
1265
+ expect(tools).toContain('memory_store');
1266
+ expect(tools).toContain('swarm_init');
1267
+ });
1268
+
1269
+ it('should execute memory_store tool', async () => {
1270
+ const result = await client.callTool('memory_store', {
1271
+ key: 'integration-test',
1272
+ value: 'test-data',
1273
+ namespace: 'test'
1274
+ });
1275
+
1276
+ expect(result.success).toBe(true);
1277
+ });
1278
+ });
1279
+ ```
1280
+
1281
+ ### 5.3 E2E Tests
1282
+
1283
+ ```typescript
1284
+ // tests/e2e/multi-server.test.ts
1285
+ import { describe, it, expect, beforeAll, afterAll } from 'vitest';
1286
+ import { ClaudeFlowSdkServer } from '../../src/mcp/fastmcp/servers/claude-flow-sdk';
1287
+ import { FlowNexusServer } from '../../src/mcp/fastmcp/servers/flow-nexus';
1288
+
1289
+ describe('Multi-Server Coordination', () => {
1290
+ let sdkServer: ClaudeFlowSdkServer;
1291
+ let nexusServer: FlowNexusServer;
1292
+
1293
+ beforeAll(async () => {
1294
+ sdkServer = new ClaudeFlowSdkServer();
1295
+ nexusServer = new FlowNexusServer();
1296
+ await Promise.all([sdkServer.start(), nexusServer.start()]);
1297
+ });
1298
+
1299
+ afterAll(async () => {
1300
+ await Promise.all([sdkServer.stop(), nexusServer.stop()]);
1301
+ });
1302
+
1303
+ it('should coordinate swarm initialization', async () => {
1304
+ // Initialize swarm via SDK
1305
+ const swarmResult = await sdkClient.callTool('swarm_init', {
1306
+ topology: 'mesh',
1307
+ maxAgents: 5
1308
+ });
1309
+
1310
+ // Create sandbox via Nexus
1311
+ const sandboxResult = await nexusClient.callTool('sandbox_create', {
1312
+ template: 'node',
1313
+ name: 'test-sandbox'
1314
+ });
1315
+
1316
+ // Verify coordination
1317
+ const status = await sdkClient.callTool('swarm_status');
1318
+ expect(status.agents).toHaveLength(5);
1319
+ });
1320
+ });
1321
+ ```
1322
+
1323
+ ### 5.4 Performance Tests
1324
+
1325
+ ```typescript
1326
+ // tests/performance/throughput.test.ts
1327
+ import { describe, it, expect } from 'vitest';
1328
+ import { performance } from 'perf_hooks';
1329
+
1330
+ describe('Performance Benchmarks', () => {
1331
+ it('should handle 1000 tool calls within 5 seconds', async () => {
1332
+ const start = performance.now();
1333
+
1334
+ const promises = Array.from({ length: 1000 }, () =>
1335
+ client.callTool('memory_store', {
1336
+ key: `perf-${Math.random()}`,
1337
+ value: 'test-data',
1338
+ namespace: 'perf'
1339
+ })
1340
+ );
1341
+
1342
+ await Promise.all(promises);
1343
+ const duration = performance.now() - start;
1344
+
1345
+ expect(duration).toBeLessThan(5000);
1346
+ console.log(`Throughput: ${(1000 / duration * 1000).toFixed(2)} tools/sec`);
1347
+ });
1348
+
1349
+ it('should maintain low latency under load', async () => {
1350
+ const latencies: number[] = [];
1351
+
1352
+ for (let i = 0; i < 100; i++) {
1353
+ const start = performance.now();
1354
+ await client.callTool('swarm_status');
1355
+ latencies.push(performance.now() - start);
1356
+ }
1357
+
1358
+ const avg = latencies.reduce((a, b) => a + b) / latencies.length;
1359
+ const p95 = latencies.sort()[Math.floor(latencies.length * 0.95)];
1360
+
1361
+ expect(avg).toBeLessThan(50); // 50ms average
1362
+ expect(p95).toBeLessThan(100); // 100ms p95
1363
+
1364
+ console.log(`Avg latency: ${avg.toFixed(2)}ms, P95: ${p95.toFixed(2)}ms`);
1365
+ });
1366
+ });
1367
+ ```
1368
+
1369
+ ### 5.5 Security Tests
1370
+
1371
+ ```typescript
1372
+ // tests/security/auth.test.ts
1373
+ import { describe, it, expect } from 'vitest';
1374
+ import { FlowNexusServer } from '../../src/mcp/fastmcp/servers/flow-nexus';
1375
+
1376
+ describe('Authentication Security', () => {
1377
+ it('should reject requests without token', async () => {
1378
+ const response = await fetch('http://localhost:8080/tools/list');
1379
+ expect(response.status).toBe(401);
1380
+ });
1381
+
1382
+ it('should reject invalid tokens', async () => {
1383
+ const response = await fetch('http://localhost:8080/tools/list', {
1384
+ headers: { 'Authorization': 'Bearer invalid-token' }
1385
+ });
1386
+ expect(response.status).toBe(401);
1387
+ });
1388
+
1389
+ it('should accept valid tokens', async () => {
1390
+ const token = generateValidToken();
1391
+ const response = await fetch('http://localhost:8080/tools/list', {
1392
+ headers: { 'Authorization': `Bearer ${token}` }
1393
+ });
1394
+ expect(response.status).toBe(200);
1395
+ });
1396
+
1397
+ it('should enforce rate limits', async () => {
1398
+ const token = generateValidToken();
1399
+
1400
+ // Make 100 requests (rate limit)
1401
+ for (let i = 0; i < 100; i++) {
1402
+ await fetch('http://localhost:8080/tools/list', {
1403
+ headers: { 'Authorization': `Bearer ${token}` }
1404
+ });
1405
+ }
1406
+
1407
+ // 101st request should be rate limited
1408
+ const response = await fetch('http://localhost:8080/tools/list', {
1409
+ headers: { 'Authorization': `Bearer ${token}` }
1410
+ });
1411
+ expect(response.status).toBe(429);
1412
+ });
1413
+ });
1414
+ ```
1415
+
1416
+ ---
1417
+
1418
+ ## 6. Development & Deployment
1419
+
1420
+ ### 6.1 Development Setup
1421
+
1422
+ ```bash
1423
+ # Install dependencies
1424
+ npm install fastmcp zod jsonwebtoken redis
1425
+
1426
+ # Install dev dependencies
1427
+ npm install -D @types/jsonwebtoken vitest
1428
+
1429
+ # Run in development
1430
+ npm run dev
1431
+
1432
+ # Test FastMCP server
1433
+ npx fastmcp dev src/mcp/fastmcp/servers/claude-flow-sdk.ts
1434
+
1435
+ # Inspect server
1436
+ npx fastmcp inspect src/mcp/fastmcp/servers/claude-flow-sdk.ts
1437
+ ```
1438
+
1439
+ ### 6.2 Environment Configuration
1440
+
1441
+ ```bash
1442
+ # .env.development
1443
+ NODE_ENV=development
1444
+ DEPLOYMENT_MODE=local
1445
+ USE_FASTMCP=true
1446
+ ENABLE_AUTH=false
1447
+ ENABLE_METRICS=true
1448
+ LOG_LEVEL=debug
1449
+
1450
+ # .env.production
1451
+ NODE_ENV=production
1452
+ DEPLOYMENT_MODE=cloud
1453
+ USE_FASTMCP=true
1454
+ ENABLE_AUTH=true
1455
+ ENABLE_METRICS=true
1456
+ LOG_LEVEL=info
1457
+ JWT_SECRET=your-secret-key
1458
+ API_KEY=your-api-key
1459
+ REDIS_URL=redis://localhost:6379
1460
+ PORT=8080
1461
+ ```
1462
+
1463
+ ### 6.3 Docker Configuration
1464
+
1465
+ ```dockerfile
1466
+ # Dockerfile
1467
+ FROM node:18-alpine
1468
+
1469
+ WORKDIR /app
1470
+
1471
+ # Install dependencies
1472
+ COPY package*.json ./
1473
+ RUN npm ci --only=production
1474
+
1475
+ # Copy source
1476
+ COPY dist ./dist
1477
+ COPY .env.production ./.env
1478
+
1479
+ # Expose ports
1480
+ EXPOSE 8080
1481
+
1482
+ # Health check
1483
+ HEALTHCHECK --interval=30s --timeout=3s --start-period=5s --retries=3 \
1484
+ CMD node -e "require('http').get('http://localhost:8080/health', (r) => r.statusCode === 200 ? process.exit(0) : process.exit(1))"
1485
+
1486
+ # Start server
1487
+ CMD ["node", "dist/mcp/fastmcp/servers/flow-nexus.js"]
1488
+ ```
1489
+
1490
+ ```yaml
1491
+ # docker-compose.yml
1492
+ version: '3.8'
1493
+
1494
+ services:
1495
+ # In-process server (not containerized, runs with main app)
1496
+
1497
+ # Claude Flow subprocess server
1498
+ claude-flow:
1499
+ build: .
1500
+ command: node dist/mcp/fastmcp/servers/claude-flow.js
1501
+ environment:
1502
+ - NODE_ENV=production
1503
+ - DEPLOYMENT_MODE=docker
1504
+ - ENABLE_AUTH=false
1505
+ volumes:
1506
+ - ./data:/app/data
1507
+
1508
+ # Flow Nexus HTTP server
1509
+ flow-nexus:
1510
+ build: .
1511
+ command: node dist/mcp/fastmcp/servers/flow-nexus.js
1512
+ ports:
1513
+ - "8080:8080"
1514
+ environment:
1515
+ - NODE_ENV=production
1516
+ - DEPLOYMENT_MODE=cloud
1517
+ - ENABLE_AUTH=true
1518
+ - JWT_SECRET=${JWT_SECRET}
1519
+ - REDIS_URL=redis://redis:6379
1520
+ - PORT=8080
1521
+ depends_on:
1522
+ - redis
1523
+ healthcheck:
1524
+ test: ["CMD", "curl", "-f", "http://localhost:8080/health"]
1525
+ interval: 30s
1526
+ timeout: 3s
1527
+ retries: 3
1528
+
1529
+ # Redis for rate limiting
1530
+ redis:
1531
+ image: redis:7-alpine
1532
+ ports:
1533
+ - "6379:6379"
1534
+ volumes:
1535
+ - redis-data:/data
1536
+
1537
+ volumes:
1538
+ redis-data:
1539
+ ```
1540
+
1541
+ ### 6.4 Kubernetes Deployment
1542
+
1543
+ ```yaml
1544
+ # k8s/deployment.yaml
1545
+ apiVersion: apps/v1
1546
+ kind: Deployment
1547
+ metadata:
1548
+ name: flow-nexus
1549
+ spec:
1550
+ replicas: 3
1551
+ selector:
1552
+ matchLabels:
1553
+ app: flow-nexus
1554
+ template:
1555
+ metadata:
1556
+ labels:
1557
+ app: flow-nexus
1558
+ spec:
1559
+ containers:
1560
+ - name: flow-nexus
1561
+ image: flow-nexus:latest
1562
+ ports:
1563
+ - containerPort: 8080
1564
+ env:
1565
+ - name: NODE_ENV
1566
+ value: "production"
1567
+ - name: DEPLOYMENT_MODE
1568
+ value: "cloud"
1569
+ - name: ENABLE_AUTH
1570
+ value: "true"
1571
+ - name: JWT_SECRET
1572
+ valueFrom:
1573
+ secretKeyRef:
1574
+ name: flow-nexus-secrets
1575
+ key: jwt-secret
1576
+ - name: REDIS_URL
1577
+ value: "redis://redis-service:6379"
1578
+ livenessProbe:
1579
+ httpGet:
1580
+ path: /health
1581
+ port: 8080
1582
+ initialDelaySeconds: 10
1583
+ periodSeconds: 30
1584
+ readinessProbe:
1585
+ httpGet:
1586
+ path: /health
1587
+ port: 8080
1588
+ initialDelaySeconds: 5
1589
+ periodSeconds: 10
1590
+ resources:
1591
+ requests:
1592
+ memory: "256Mi"
1593
+ cpu: "250m"
1594
+ limits:
1595
+ memory: "512Mi"
1596
+ cpu: "500m"
1597
+ ---
1598
+ apiVersion: v1
1599
+ kind: Service
1600
+ metadata:
1601
+ name: flow-nexus-service
1602
+ spec:
1603
+ type: LoadBalancer
1604
+ selector:
1605
+ app: flow-nexus
1606
+ ports:
1607
+ - protocol: TCP
1608
+ port: 80
1609
+ targetPort: 8080
1610
+ ```
1611
+
1612
+ ### 6.5 CI/CD Pipeline
1613
+
1614
+ ```yaml
1615
+ # .github/workflows/deploy.yml
1616
+ name: Deploy FastMCP Servers
1617
+
1618
+ on:
1619
+ push:
1620
+ branches: [main]
1621
+ pull_request:
1622
+ branches: [main]
1623
+
1624
+ jobs:
1625
+ test:
1626
+ runs-on: ubuntu-latest
1627
+ steps:
1628
+ - uses: actions/checkout@v3
1629
+ - uses: actions/setup-node@v3
1630
+ with:
1631
+ node-version: '18'
1632
+ - run: npm ci
1633
+ - run: npm run build
1634
+ - run: npm test
1635
+ - run: npm run test:integration
1636
+ - run: npm run test:security
1637
+
1638
+ benchmark:
1639
+ runs-on: ubuntu-latest
1640
+ needs: test
1641
+ steps:
1642
+ - uses: actions/checkout@v3
1643
+ - uses: actions/setup-node@v3
1644
+ with:
1645
+ node-version: '18'
1646
+ - run: npm ci
1647
+ - run: npm run build
1648
+ - run: npm run benchmark
1649
+ - name: Compare performance
1650
+ run: |
1651
+ node scripts/compare-benchmarks.js
1652
+
1653
+ deploy-staging:
1654
+ runs-on: ubuntu-latest
1655
+ needs: [test, benchmark]
1656
+ if: github.ref == 'refs/heads/main'
1657
+ steps:
1658
+ - uses: actions/checkout@v3
1659
+ - name: Deploy to staging
1660
+ run: |
1661
+ kubectl apply -f k8s/staging/
1662
+ - name: Run smoke tests
1663
+ run: npm run test:e2e:staging
1664
+
1665
+ deploy-production:
1666
+ runs-on: ubuntu-latest
1667
+ needs: deploy-staging
1668
+ if: github.ref == 'refs/heads/main'
1669
+ environment: production
1670
+ steps:
1671
+ - uses: actions/checkout@v3
1672
+ - name: Deploy to production
1673
+ run: |
1674
+ kubectl apply -f k8s/production/
1675
+ - name: Run smoke tests
1676
+ run: npm run test:e2e:production
1677
+ - name: Monitor rollout
1678
+ run: kubectl rollout status deployment/flow-nexus
1679
+ ```
1680
+
1681
+ ---
1682
+
1683
+ ## 7. Code Examples
1684
+
1685
+ ### 7.1 Basic Stdio Server
1686
+
1687
+ ```typescript
1688
+ // examples/stdio-server.ts
1689
+ import { FastMCP } from 'fastmcp';
1690
+ import { z } from 'zod';
1691
+
1692
+ // Create server
1693
+ const server = new FastMCP({
1694
+ name: 'example-stdio-server',
1695
+ version: '1.0.0'
1696
+ });
1697
+
1698
+ // Add tool with Zod schema
1699
+ server.addTool({
1700
+ name: 'calculate',
1701
+ description: 'Perform basic arithmetic operations',
1702
+ parameters: z.object({
1703
+ operation: z.enum(['add', 'subtract', 'multiply', 'divide']),
1704
+ a: z.number(),
1705
+ b: z.number()
1706
+ }),
1707
+ execute: async ({ operation, a, b }) => {
1708
+ switch (operation) {
1709
+ case 'add':
1710
+ return a + b;
1711
+ case 'subtract':
1712
+ return a - b;
1713
+ case 'multiply':
1714
+ return a * b;
1715
+ case 'divide':
1716
+ if (b === 0) throw new Error('Division by zero');
1717
+ return a / b;
1718
+ }
1719
+ }
1720
+ });
1721
+
1722
+ // Start with stdio transport
1723
+ server.start({ transportType: 'stdio' });
1724
+ ```
1725
+
1726
+ ### 7.2 HTTP Server with Authentication
1727
+
1728
+ ```typescript
1729
+ // examples/http-server-auth.ts
1730
+ import { FastMCP } from 'fastmcp';
1731
+ import { z } from 'zod';
1732
+ import jwt from 'jsonwebtoken';
1733
+
1734
+ // Create server with authentication
1735
+ const server = new FastMCP({
1736
+ name: 'secure-http-server',
1737
+ version: '1.0.0',
1738
+ authenticate: async (req) => {
1739
+ const token = req.headers.get('authorization')?.replace('Bearer ', '');
1740
+ if (!token) {
1741
+ throw new Response('Missing token', { status: 401 });
1742
+ }
1743
+
1744
+ try {
1745
+ const payload = jwt.verify(token, process.env.JWT_SECRET!) as any;
1746
+ return {
1747
+ userId: payload.sub,
1748
+ role: payload.role
1749
+ };
1750
+ } catch {
1751
+ throw new Response('Invalid token', { status: 401 });
1752
+ }
1753
+ }
1754
+ });
1755
+
1756
+ // Add public tool (no auth required)
1757
+ server.addTool({
1758
+ name: 'health',
1759
+ description: 'Health check endpoint',
1760
+ parameters: z.object({}),
1761
+ execute: async () => ({
1762
+ status: 'healthy',
1763
+ timestamp: new Date().toISOString()
1764
+ })
1765
+ });
1766
+
1767
+ // Add authenticated tool with role check
1768
+ server.addTool({
1769
+ name: 'admin_action',
1770
+ description: 'Admin-only action',
1771
+ canAccess: (auth) => auth.role === 'admin',
1772
+ parameters: z.object({
1773
+ action: z.string()
1774
+ }),
1775
+ execute: async ({ action }, { auth }) => {
1776
+ console.log(`Admin ${auth.userId} performed: ${action}`);
1777
+ return { success: true };
1778
+ }
1779
+ });
1780
+
1781
+ // Start with HTTP transport
1782
+ server.start({
1783
+ transportType: 'http',
1784
+ port: 8080,
1785
+ host: '0.0.0.0'
1786
+ });
1787
+ ```
1788
+
1789
+ ### 7.3 Server with Progress Reporting
1790
+
1791
+ ```typescript
1792
+ // examples/progress-server.ts
1793
+ import { FastMCP } from 'fastmcp';
1794
+ import { z } from 'zod';
1795
+
1796
+ const server = new FastMCP({
1797
+ name: 'progress-server',
1798
+ version: '1.0.0'
1799
+ });
1800
+
1801
+ server.addTool({
1802
+ name: 'process_data',
1803
+ description: 'Process large dataset with progress updates',
1804
+ parameters: z.object({
1805
+ dataSize: z.number().min(1).max(1000000)
1806
+ }),
1807
+ execute: async ({ dataSize }, { onProgress }) => {
1808
+ const chunks = Math.ceil(dataSize / 1000);
1809
+
1810
+ for (let i = 0; i < chunks; i++) {
1811
+ // Simulate processing
1812
+ await new Promise(resolve => setTimeout(resolve, 100));
1813
+
1814
+ // Report progress
1815
+ const progress = (i + 1) / chunks;
1816
+ onProgress?.({
1817
+ progress,
1818
+ message: `Processing chunk ${i + 1}/${chunks}`
1819
+ });
1820
+ }
1821
+
1822
+ return {
1823
+ processed: dataSize,
1824
+ chunks,
1825
+ duration: chunks * 100
1826
+ };
1827
+ }
1828
+ });
1829
+
1830
+ server.start({ transportType: 'stdio' });
1831
+ ```
1832
+
1833
+ ### 7.4 Server with Streaming Output
1834
+
1835
+ ```typescript
1836
+ // examples/streaming-server.ts
1837
+ import { FastMCP } from 'fastmcp';
1838
+ import { z } from 'zod';
1839
+
1840
+ const server = new FastMCP({
1841
+ name: 'streaming-server',
1842
+ version: '1.0.0'
1843
+ });
1844
+
1845
+ server.addTool({
1846
+ name: 'generate_report',
1847
+ description: 'Generate report with streaming output',
1848
+ parameters: z.object({
1849
+ sections: z.array(z.string())
1850
+ }),
1851
+ execute: async function* ({ sections }) {
1852
+ yield '# Report\n\n';
1853
+
1854
+ for (const section of sections) {
1855
+ yield `## ${section}\n\n`;
1856
+
1857
+ // Simulate section generation
1858
+ await new Promise(resolve => setTimeout(resolve, 500));
1859
+
1860
+ yield `Content for ${section}...\n\n`;
1861
+ }
1862
+
1863
+ yield '---\nReport complete\n';
1864
+ }
1865
+ });
1866
+
1867
+ server.start({ transportType: 'http', port: 8080 });
1868
+ ```
1869
+
1870
+ ### 7.5 Multi-Transport Server
1871
+
1872
+ ```typescript
1873
+ // examples/multi-transport.ts
1874
+ import { FastMCP } from 'fastmcp';
1875
+ import { z } from 'zod';
1876
+
1877
+ function createServer() {
1878
+ const server = new FastMCP({
1879
+ name: 'multi-transport-server',
1880
+ version: '1.0.0'
1881
+ });
1882
+
1883
+ // Add tools...
1884
+ server.addTool({
1885
+ name: 'echo',
1886
+ description: 'Echo a message',
1887
+ parameters: z.object({ message: z.string() }),
1888
+ execute: async ({ message }) => message
1889
+ });
1890
+
1891
+ return server;
1892
+ }
1893
+
1894
+ // Determine transport from environment
1895
+ const transportType = process.env.TRANSPORT_TYPE || 'stdio';
1896
+
1897
+ if (transportType === 'stdio') {
1898
+ const server = createServer();
1899
+ server.start({ transportType: 'stdio' });
1900
+ console.error('Started with stdio transport');
1901
+ } else {
1902
+ const server = createServer();
1903
+ server.start({
1904
+ transportType: 'http',
1905
+ port: parseInt(process.env.PORT || '8080'),
1906
+ host: process.env.HOST || '0.0.0.0'
1907
+ });
1908
+ console.error(`Started with HTTP transport on ${process.env.PORT || 8080}`);
1909
+ }
1910
+ ```
1911
+
1912
+ ---
1913
+
1914
+ ## 8. Performance Optimization
1915
+
1916
+ ### 8.1 Connection Pooling
1917
+
1918
+ ```typescript
1919
+ // src/mcp/fastmcp/utils/connection-pool.ts
1920
+ export class ConnectionPool {
1921
+ private connections: Map<string, any> = new Map();
1922
+ private maxSize: number;
1923
+
1924
+ constructor(maxSize = 10) {
1925
+ this.maxSize = maxSize;
1926
+ }
1927
+
1928
+ async getConnection(key: string, factory: () => Promise<any>) {
1929
+ if (this.connections.has(key)) {
1930
+ return this.connections.get(key);
1931
+ }
1932
+
1933
+ if (this.connections.size >= this.maxSize) {
1934
+ // Evict oldest connection
1935
+ const firstKey = this.connections.keys().next().value;
1936
+ const conn = this.connections.get(firstKey);
1937
+ await conn?.close?.();
1938
+ this.connections.delete(firstKey);
1939
+ }
1940
+
1941
+ const conn = await factory();
1942
+ this.connections.set(key, conn);
1943
+ return conn;
1944
+ }
1945
+
1946
+ async closeAll() {
1947
+ for (const [key, conn] of this.connections) {
1948
+ await conn?.close?.();
1949
+ }
1950
+ this.connections.clear();
1951
+ }
1952
+ }
1953
+ ```
1954
+
1955
+ ### 8.2 Caching Layer
1956
+
1957
+ ```typescript
1958
+ // src/mcp/fastmcp/middleware/cache.ts
1959
+ import { createHash } from 'crypto';
1960
+
1961
+ interface CacheEntry {
1962
+ value: any;
1963
+ timestamp: number;
1964
+ ttl: number;
1965
+ }
1966
+
1967
+ export class ToolCache {
1968
+ private cache = new Map<string, CacheEntry>();
1969
+
1970
+ private getCacheKey(toolName: string, args: any): string {
1971
+ const hash = createHash('sha256');
1972
+ hash.update(JSON.stringify({ toolName, args }));
1973
+ return hash.digest('hex');
1974
+ }
1975
+
1976
+ get(toolName: string, args: any): any | null {
1977
+ const key = this.getCacheKey(toolName, args);
1978
+ const entry = this.cache.get(key);
1979
+
1980
+ if (!entry) return null;
1981
+
1982
+ const now = Date.now();
1983
+ if (now - entry.timestamp > entry.ttl) {
1984
+ this.cache.delete(key);
1985
+ return null;
1986
+ }
1987
+
1988
+ return entry.value;
1989
+ }
1990
+
1991
+ set(toolName: string, args: any, value: any, ttl = 60000) {
1992
+ const key = this.getCacheKey(toolName, args);
1993
+ this.cache.set(key, {
1994
+ value,
1995
+ timestamp: Date.now(),
1996
+ ttl
1997
+ });
1998
+ }
1999
+
2000
+ clear() {
2001
+ this.cache.clear();
2002
+ }
2003
+ }
2004
+
2005
+ // Wrap tool execution with caching
2006
+ export function withCache(cache: ToolCache, ttl?: number) {
2007
+ return (tool: any) => ({
2008
+ ...tool,
2009
+ execute: async (args: any, context: any) => {
2010
+ // Check cache
2011
+ const cached = cache.get(tool.name, args);
2012
+ if (cached) {
2013
+ return cached;
2014
+ }
2015
+
2016
+ // Execute tool
2017
+ const result = await tool.execute(args, context);
2018
+
2019
+ // Store in cache
2020
+ cache.set(tool.name, args, result, ttl);
2021
+
2022
+ return result;
2023
+ }
2024
+ });
2025
+ }
2026
+ ```
2027
+
2028
+ ### 8.3 Request Batching
2029
+
2030
+ ```typescript
2031
+ // src/mcp/fastmcp/utils/batch.ts
2032
+ export class RequestBatcher {
2033
+ private pending: Map<string, Promise<any>> = new Map();
2034
+ private batchDelay: number;
2035
+
2036
+ constructor(batchDelay = 10) {
2037
+ this.batchDelay = batchDelay;
2038
+ }
2039
+
2040
+ async batch<T>(key: string, executor: () => Promise<T>): Promise<T> {
2041
+ // Check if request with same key is pending
2042
+ if (this.pending.has(key)) {
2043
+ return this.pending.get(key);
2044
+ }
2045
+
2046
+ // Create new batch
2047
+ const promise = new Promise<T>((resolve, reject) => {
2048
+ setTimeout(async () => {
2049
+ try {
2050
+ const result = await executor();
2051
+ this.pending.delete(key);
2052
+ resolve(result);
2053
+ } catch (error) {
2054
+ this.pending.delete(key);
2055
+ reject(error);
2056
+ }
2057
+ }, this.batchDelay);
2058
+ });
2059
+
2060
+ this.pending.set(key, promise);
2061
+ return promise;
2062
+ }
2063
+ }
2064
+ ```
2065
+
2066
+ ---
2067
+
2068
+ ## 9. Monitoring & Observability
2069
+
2070
+ ### 9.1 Metrics Collection
2071
+
2072
+ ```typescript
2073
+ // src/mcp/fastmcp/middleware/metrics.ts
2074
+ import { Counter, Histogram, Registry } from 'prom-client';
2075
+
2076
+ export class MetricsCollector {
2077
+ private registry: Registry;
2078
+ private toolCallCounter: Counter;
2079
+ private toolDurationHistogram: Histogram;
2080
+ private errorCounter: Counter;
2081
+
2082
+ constructor() {
2083
+ this.registry = new Registry();
2084
+
2085
+ this.toolCallCounter = new Counter({
2086
+ name: 'mcp_tool_calls_total',
2087
+ help: 'Total number of tool calls',
2088
+ labelNames: ['tool', 'status'],
2089
+ registers: [this.registry]
2090
+ });
2091
+
2092
+ this.toolDurationHistogram = new Histogram({
2093
+ name: 'mcp_tool_duration_seconds',
2094
+ help: 'Tool execution duration',
2095
+ labelNames: ['tool'],
2096
+ buckets: [0.001, 0.01, 0.1, 0.5, 1, 5, 10],
2097
+ registers: [this.registry]
2098
+ });
2099
+
2100
+ this.errorCounter = new Counter({
2101
+ name: 'mcp_errors_total',
2102
+ help: 'Total errors',
2103
+ labelNames: ['tool', 'error_type'],
2104
+ registers: [this.registry]
2105
+ });
2106
+ }
2107
+
2108
+ recordToolCall(tool: string, duration: number, success: boolean) {
2109
+ this.toolCallCounter.inc({ tool, status: success ? 'success' : 'error' });
2110
+ this.toolDurationHistogram.observe({ tool }, duration);
2111
+ }
2112
+
2113
+ recordError(tool: string, errorType: string) {
2114
+ this.errorCounter.inc({ tool, error_type: errorType });
2115
+ }
2116
+
2117
+ async getMetrics(): Promise<string> {
2118
+ return this.registry.metrics();
2119
+ }
2120
+ }
2121
+
2122
+ // Add metrics endpoint
2123
+ export function setupMetrics(server: FastMCP) {
2124
+ const collector = new MetricsCollector();
2125
+
2126
+ server.addTool({
2127
+ name: 'metrics',
2128
+ description: 'Get Prometheus metrics',
2129
+ parameters: z.object({}),
2130
+ execute: async () => {
2131
+ return await collector.getMetrics();
2132
+ }
2133
+ });
2134
+
2135
+ return collector;
2136
+ }
2137
+ ```
2138
+
2139
+ ### 9.2 Distributed Tracing
2140
+
2141
+ ```typescript
2142
+ // src/mcp/fastmcp/middleware/tracing.ts
2143
+ import { trace, context, SpanStatusCode } from '@opentelemetry/api';
2144
+ import { NodeTracerProvider } from '@opentelemetry/sdk-trace-node';
2145
+ import { JaegerExporter } from '@opentelemetry/exporter-jaeger';
2146
+
2147
+ const tracer = trace.getTracer('fastmcp-server');
2148
+
2149
+ export function withTracing(tool: any) {
2150
+ return {
2151
+ ...tool,
2152
+ execute: async (args: any, ctx: any) => {
2153
+ const span = tracer.startSpan(`tool.${tool.name}`);
2154
+
2155
+ try {
2156
+ span.setAttributes({
2157
+ 'tool.name': tool.name,
2158
+ 'tool.args': JSON.stringify(args),
2159
+ 'user.id': ctx.auth?.userId
2160
+ });
2161
+
2162
+ const result = await tool.execute(args, ctx);
2163
+
2164
+ span.setStatus({ code: SpanStatusCode.OK });
2165
+ return result;
2166
+ } catch (error: any) {
2167
+ span.setStatus({
2168
+ code: SpanStatusCode.ERROR,
2169
+ message: error.message
2170
+ });
2171
+ span.recordException(error);
2172
+ throw error;
2173
+ } finally {
2174
+ span.end();
2175
+ }
2176
+ }
2177
+ };
2178
+ }
2179
+ ```
2180
+
2181
+ ---
2182
+
2183
+ ## 10. Migration Checklist
2184
+
2185
+ ### 10.1 Pre-Migration
2186
+
2187
+ - [ ] Install fastmcp package
2188
+ - [ ] Review current MCP tool inventory (203+ tools)
2189
+ - [ ] Identify authentication requirements per server
2190
+ - [ ] Plan transport strategy (stdio vs HTTP)
2191
+ - [ ] Setup development environment
2192
+ - [ ] Create feature flag system
2193
+ - [ ] Backup current implementation
2194
+ - [ ] Document current API contracts
2195
+
2196
+ ### 10.2 Phase 1: In-Process Server
2197
+
2198
+ - [ ] Create fastmcp directory structure
2199
+ - [ ] Implement base server class
2200
+ - [ ] Migrate memory tools (5 tools)
2201
+ - [ ] Migrate swarm tools (3 tools)
2202
+ - [ ] Migrate agent tools (3 tools)
2203
+ - [ ] Migrate task tools (3 tools)
2204
+ - [ ] Add error handling
2205
+ - [ ] Add logging integration
2206
+ - [ ] Write unit tests
2207
+ - [ ] Write integration tests
2208
+ - [ ] Performance benchmark
2209
+ - [ ] Code review
2210
+ - [ ] Deploy to development
2211
+ - [ ] Gradual rollout with feature flag
2212
+ - [ ] Monitor for issues
2213
+ - [ ] Full rollout
2214
+
2215
+ ### 10.3 Phase 2: Subprocess Servers
2216
+
2217
+ - [ ] Migrate claude-flow server
2218
+ - [ ] Convert all tools to FastMCP
2219
+ - [ ] Add progress reporting
2220
+ - [ ] Add streaming support
2221
+ - [ ] Optional authentication
2222
+ - [ ] Tests
2223
+ - [ ] Migrate agentic-payments server
2224
+ - [ ] Convert payment tools
2225
+ - [ ] Add transaction streaming
2226
+ - [ ] Authentication
2227
+ - [ ] Tests
2228
+ - [ ] Update subprocess spawning
2229
+ - [ ] Integration tests
2230
+ - [ ] Deploy to development
2231
+ - [ ] Testing period (1 week)
2232
+ - [ ] Production deployment
2233
+
2234
+ ### 10.4 Phase 3: HTTP Server
2235
+
2236
+ - [ ] Implement HTTP streaming transport
2237
+ - [ ] JWT authentication
2238
+ - [ ] API key authentication
2239
+ - [ ] OAuth integration
2240
+ - [ ] Rate limiting with Redis
2241
+ - [ ] Tool authorization
2242
+ - [ ] CORS configuration
2243
+ - [ ] Health-check endpoints
2244
+ - [ ] Session management
2245
+ - [ ] Load testing
2246
+ - [ ] Security audit
2247
+ - [ ] Staging deployment
2248
+ - [ ] Production deployment
2249
+
2250
+ ### 10.5 Phase 4: Testing & Validation
2251
+
2252
+ - [ ] Unit tests (100+ tests)
2253
+ - [ ] Integration tests (30+ tests)
2254
+ - [ ] E2E tests (10+ tests)
2255
+ - [ ] Performance benchmarks
2256
+ - [ ] Security tests
2257
+ - [ ] Load tests
2258
+ - [ ] Chaos testing
2259
+ - [ ] Documentation review
2260
+ - [ ] Migration guide
2261
+ - [ ] Troubleshooting guide
2262
+
2263
+ ### 10.6 Phase 5: Documentation & Rollout
2264
+
2265
+ - [ ] Architecture documentation
2266
+ - [ ] API reference
2267
+ - [ ] Authentication guide
2268
+ - [ ] Security best practices
2269
+ - [ ] Migration guide
2270
+ - [ ] Troubleshooting guide
2271
+ - [ ] Performance tuning guide
2272
+ - [ ] Beta release (10%)
2273
+ - [ ] Expanded rollout (50%)
2274
+ - [ ] Full rollout (100%)
2275
+ - [ ] Deprecate old implementation
2276
+
2277
+ ---
2278
+
2279
+ ## 11. Risk Assessment & Mitigation
2280
+
2281
+ ### 11.1 Technical Risks
2282
+
2283
+ | Risk | Probability | Impact | Mitigation |
2284
+ |------|------------|--------|------------|
2285
+ | Performance degradation | Low | High | Benchmark before migration, feature flag rollback |
2286
+ | Authentication vulnerabilities | Medium | Critical | Security audit, penetration testing |
2287
+ | Tool compatibility issues | Medium | High | Parallel testing, gradual rollout |
2288
+ | Transport reliability | Low | High | Connection pooling, retry logic, fallback |
2289
+ | Memory leaks | Low | Medium | Load testing, monitoring, profiling |
2290
+ | Breaking API changes | Medium | High | Backward compatibility layer, versioning |
2291
+
2292
+ ### 11.2 Operational Risks
2293
+
2294
+ | Risk | Probability | Impact | Mitigation |
2295
+ |------|------------|--------|------------|
2296
+ | Deployment failure | Low | High | Rollback plan, staging testing |
2297
+ | Downtime during migration | Medium | High | Blue-green deployment, feature flags |
2298
+ | Training needs | High | Low | Documentation, examples, workshops |
2299
+ | Support burden | Medium | Medium | Comprehensive docs, troubleshooting guide |
2300
+ | Third-party dependency | Low | Medium | Pin versions, vendor evaluation |
2301
+
2302
+ ### 11.3 Mitigation Strategies
2303
+
2304
+ **Performance Degradation:**
2305
+ - Benchmark current implementation
2306
+ - Set performance SLAs (latency, throughput)
2307
+ - Implement automatic rollback if SLAs breached
2308
+ - Load testing before production
2309
+ - Gradual rollout with monitoring
2310
+
2311
+ **Authentication Security:**
2312
+ - Security audit by external firm
2313
+ - Penetration testing
2314
+ - Rate limiting to prevent brute force
2315
+ - JWT expiration and rotation
2316
+ - Audit logging for security events
2317
+ - Regular security reviews
2318
+
2319
+ **Tool Compatibility:**
2320
+ - Parallel testing (old vs new)
2321
+ - Schema validation
2322
+ - Comprehensive test suite
2323
+ - Gradual migration (tool by tool)
2324
+ - Fallback to old implementation
2325
+
2326
+ **Deployment Risks:**
2327
+ - Blue-green deployment
2328
+ - Feature flags for instant rollback
2329
+ - Automated rollback triggers
2330
+ - Staging environment testing
2331
+ - Canary deployments
2332
+
2333
+ ---
2334
+
2335
+ ## 12. Success Metrics
2336
+
2337
+ ### 12.1 Performance Metrics
2338
+
2339
+ **Target Improvements:**
2340
+ - Tool invocation latency: < 50ms (p95)
2341
+ - Throughput: > 1000 tools/sec
2342
+ - Startup time: < 2 seconds
2343
+ - Memory usage: < 500MB baseline
2344
+ - CPU usage: < 50% under load
2345
+
2346
+ **Current Baseline:**
2347
+ - Measure current performance
2348
+ - Establish benchmarks
2349
+ - Set improvement targets
2350
+ - Monitor regression
2351
+
2352
+ ### 12.2 Developer Experience Metrics
2353
+
2354
+ - Lines of code reduction: Target 30-40%
2355
+ - Tool definition time: Target 50% reduction
2356
+ - Bug density: Target 50% reduction
2357
+ - Time to add new tool: Target 60% reduction
2358
+ - Developer satisfaction score: Target 8+/10
2359
+
2360
+ ### 12.3 Reliability Metrics
2361
+
2362
+ - Uptime: > 99.9%
2363
+ - Error rate: < 0.1%
2364
+ - Mean time to recovery: < 5 minutes
2365
+ - Authentication success rate: > 99%
2366
+ - Rate limit false positives: < 1%
2367
+
2368
+ ### 12.4 Security Metrics
2369
+
2370
+ - Authentication failures: < 1% legitimate requests
2371
+ - Rate limit effectiveness: 100% abuse prevention
2372
+ - Security incidents: 0
2373
+ - Audit log completeness: 100%
2374
+ - Vulnerability response time: < 24 hours
2375
+
2376
+ ---
2377
+
2378
+ ## 13. Timeline & Resources
2379
+
2380
+ ### 13.1 Timeline
2381
+
2382
+ **Total Duration: 10 weeks**
2383
+
2384
+ | Phase | Duration | Start | End |
2385
+ |-------|----------|-------|-----|
2386
+ | Phase 0: Preparation | 1 week | Week 1 | Week 1 |
2387
+ | Phase 1: In-Process Server | 2 weeks | Week 2 | Week 3 |
2388
+ | Phase 2: Subprocess Servers | 2 weeks | Week 4 | Week 5 |
2389
+ | Phase 3: HTTP Server | 2 weeks | Week 6 | Week 7 |
2390
+ | Phase 4: Testing | 1 week | Week 8 | Week 8 |
2391
+ | Phase 5: Documentation & Rollout | 2 weeks | Week 9 | Week 10 |
2392
+
2393
+ ### 13.2 Resource Requirements
2394
+
2395
+ **Team:**
2396
+ - 1 Senior Backend Engineer (full-time)
2397
+ - 1 DevOps Engineer (50%)
2398
+ - 1 Security Engineer (25%)
2399
+ - 1 QA Engineer (50%)
2400
+ - 1 Technical Writer (25%)
2401
+
2402
+ **Infrastructure:**
2403
+ - Development environment
2404
+ - Staging environment (identical to production)
2405
+ - Load testing infrastructure
2406
+ - Redis for rate limiting
2407
+ - Monitoring stack (Prometheus, Grafana)
2408
+ - Tracing infrastructure (Jaeger)
2409
+
2410
+ **Tools & Services:**
2411
+ - fastmcp npm package
2412
+ - JWT library (jsonwebtoken)
2413
+ - Redis client
2414
+ - Testing framework (vitest)
2415
+ - Load testing (k6)
2416
+ - Security scanning tools
2417
+
2418
+ ### 13.3 Budget Estimate
2419
+
2420
+ - Personnel: $40,000 (10 weeks * combined effort)
2421
+ - Infrastructure: $2,000 (staging, testing)
2422
+ - Tools & Services: $500
2423
+ - Security audit: $5,000
2424
+ - Contingency (20%): $9,500
2425
+ - **Total: ~$57,000**
2426
+
2427
+ ---
2428
+
2429
+ ## 14. Conclusion
2430
+
2431
+ ### 14.1 Summary
2432
+
2433
+ This implementation plan provides a comprehensive roadmap for migrating agentic-flow's MCP infrastructure to the fastmcp TypeScript framework. The migration will be executed in five phases over 10 weeks, with each phase building on the previous one.
2434
+
2435
+ **Key Benefits:**
2436
+ 1. **Simplified Development**: Reduced boilerplate, intuitive APIs
2437
+ 2. **Enhanced Security**: Built-in authentication, authorization, rate limiting
2438
+ 3. **Better Performance**: Optimized transport, connection pooling, caching
2439
+ 4. **Improved Observability**: Metrics, tracing, health checks
2440
+ 5. **Cloud-Ready**: HTTP streaming transport for scalable deployments
2441
+ 6. **Future-Proof**: Standardized framework, active community
2442
+
2443
+ ### 14.2 Next Steps
2444
+
2445
+ 1. **Week 1**: Get approval and allocate resources
2446
+ 2. **Week 1**: Setup development environment and POC
2447
+ 3. **Week 2-3**: Begin Phase 1 (in-process server migration)
2448
+ 4. **Ongoing**: Weekly status reviews and risk assessment
2449
+ 5. **Week 8**: Comprehensive testing and validation
2450
+ 6. **Week 9-10**: Documentation and staged rollout
2451
+
2452
+ ### 14.3 Long-Term Vision
2453
+
2454
+ Post-migration, agentic-flow will have:
2455
+ - Modern, maintainable MCP server infrastructure
2456
+ - Flexible transport options (stdio, HTTP)
2457
+ - Production-ready security features
2458
+ - Scalable architecture for cloud deployment
2459
+ - Improved developer experience
2460
+ - Foundation for future enhancements
2461
+
2462
+ ### 14.4 Recommendations
2463
+
2464
+ 1. **Start with POC**: Validate assumptions before full commitment
2465
+ 2. **Gradual Rollout**: Use feature flags for safe deployment
2466
+ 3. **Monitor Closely**: Set up comprehensive monitoring from day 1
2467
+ 4. **Document Everything**: Maintain migration journal and lessons learned
2468
+ 5. **Engage Community**: Contribute improvements back to fastmcp
2469
+ 6. **Plan for Scale**: Design for 10x growth from the start
2470
+
2471
+ ---
2472
+
2473
+ ## 15. Appendix
2474
+
2475
+ ### 15.1 References
2476
+
2477
+ - **FastMCP TypeScript**: https://github.com/punkpeye/fastmcp
2478
+ - **FastMCP Documentation**: https://gofastmcp.com/
2479
+ - **MCP Specification**: https://modelcontextprotocol.io/
2480
+ - **MCP TypeScript SDK**: https://github.com/modelcontextprotocol/typescript-sdk
2481
+ - **Zod Documentation**: https://zod.dev/
2482
+
2483
+ ### 15.2 Glossary
2484
+
2485
+ - **MCP**: Model Context Protocol - standardized protocol for AI tool integration
2486
+ - **FastMCP**: TypeScript framework for building MCP servers
2487
+ - **Stdio**: Standard input/output transport for local communication
2488
+ - **SSE**: Server-Sent Events (deprecated in favor of HTTP streaming)
2489
+ - **HTTP Streaming**: Bidirectional HTTP transport with optional SSE
2490
+ - **Tool**: Executable function exposed via MCP
2491
+ - **Resource**: Data source exposed via MCP
2492
+ - **Prompt**: Reusable template for LLM interactions
2493
+ - **Transport**: Communication mechanism between client and server
2494
+ - **Authentication**: Verifying user identity
2495
+ - **Authorization**: Controlling access to tools
2496
+ - **Rate Limiting**: Preventing abuse through request throttling
2497
+
2498
+ ### 15.3 Contact Information
2499
+
2500
+ - **Project Lead**: [Name] <email>
2501
+ - **Tech Lead**: [Name] <email>
2502
+ - **Security Lead**: [Name] <email>
2503
+ - **DevOps Lead**: [Name] <email>
2504
+
2505
+ ### 15.4 Change Log
2506
+
2507
+ | Version | Date | Changes | Author |
2508
+ |---------|------|---------|--------|
2509
+ | 1.0 | 2025-10-03 | Initial plan | Claude |
2510
+ | | | | |
2511
+
2512
+ ---
2513
+
2514
+ **Document Status**: Draft for Review
2515
+ **Last Updated**: 2025-10-03
2516
+ **Next Review**: After Phase 0 completion