indusagi 0.13.7 → 0.13.8

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 (446) hide show
  1. package/dist/agent.js +28713 -0
  2. package/dist/ai.js +19964 -0
  3. package/dist/capabilities.js +2730 -0
  4. package/dist/cli.js +9 -0
  5. package/dist/connectors-saas.js +3355 -0
  6. package/dist/index.js +18211 -0
  7. package/dist/interop.js +3247 -0
  8. package/dist/llmgateway.js +3343 -0
  9. package/dist/mcp.js +2448 -0
  10. package/dist/memory.js +0 -0
  11. package/dist/react-host/index.js +101 -0
  12. package/dist/react-host/ink.js +97 -0
  13. package/dist/react-host/jsx-runtime.js +95 -0
  14. package/dist/react-ink.js +3834 -0
  15. package/dist/runtime.js +4521 -0
  16. package/dist/sarvam-mcp.js +960 -0
  17. package/dist/shell-app.js +12435 -0
  18. package/dist/smithy.js +8133 -0
  19. package/dist/swarm.js +8918 -0
  20. package/dist/tracing.js +761 -0
  21. package/dist/tui.js +2213 -0
  22. package/dist/types/capabilities/backends/index.d.ts +10 -0
  23. package/dist/types/capabilities/backends/node-backends.d.ts +30 -0
  24. package/dist/types/capabilities/capabilities.test.d.ts +14 -0
  25. package/dist/types/capabilities/files/diff.d.ts +49 -0
  26. package/dist/types/capabilities/files/edit.d.ts +21 -0
  27. package/dist/types/capabilities/files/ls.d.ts +16 -0
  28. package/dist/types/capabilities/files/read-state-gate.d.ts +69 -0
  29. package/dist/types/capabilities/files/read-state-gate.test.d.ts +14 -0
  30. package/dist/types/capabilities/files/read.d.ts +15 -0
  31. package/dist/types/capabilities/files/write.d.ts +16 -0
  32. package/dist/types/capabilities/index.d.ts +29 -0
  33. package/dist/types/capabilities/kernel/backends.d.ts +119 -0
  34. package/dist/types/capabilities/kernel/context.d.ts +52 -0
  35. package/dist/types/capabilities/kernel/index.d.ts +24 -0
  36. package/dist/types/capabilities/kernel/output.d.ts +40 -0
  37. package/dist/types/capabilities/kernel/registry.d.ts +61 -0
  38. package/dist/types/capabilities/kernel/spec.d.ts +168 -0
  39. package/dist/types/capabilities/planning/todo.d.ts +62 -0
  40. package/dist/types/capabilities/registry.d.ts +44 -0
  41. package/dist/types/capabilities/search/find.d.ts +33 -0
  42. package/dist/types/capabilities/search/grep.d.ts +30 -0
  43. package/dist/types/capabilities/shell/bash.d.ts +18 -0
  44. package/dist/types/capabilities/shell/process.d.ts +33 -0
  45. package/dist/types/capabilities/web/webfetch.d.ts +25 -0
  46. package/dist/types/capabilities/web/websearch.d.ts +23 -0
  47. package/dist/types/connectors-saas/connectors-saas.test.d.ts +12 -0
  48. package/dist/types/connectors-saas/index.d.ts +16 -0
  49. package/dist/types/connectors-saas/saas/adapter/composio-backend.d.ts +60 -0
  50. package/dist/types/connectors-saas/saas/control/connect.d.ts +114 -0
  51. package/dist/types/connectors-saas/saas/control/tools.d.ts +67 -0
  52. package/dist/types/connectors-saas/saas/core/builder.d.ts +86 -0
  53. package/dist/types/connectors-saas/saas/core/cache.d.ts +53 -0
  54. package/dist/types/connectors-saas/saas/core/index.d.ts +14 -0
  55. package/dist/types/connectors-saas/saas/core/port.d.ts +157 -0
  56. package/dist/types/connectors-saas/saas/core/scope-planner.d.ts +74 -0
  57. package/dist/types/connectors-saas/saas/gateway.d.ts +133 -0
  58. package/dist/types/connectors-saas/saas/render/format.d.ts +54 -0
  59. package/dist/types/connectors-saas/saas/render/index.d.ts +19 -0
  60. package/dist/types/connectors-saas/saas/render/summarizers.d.ts +58 -0
  61. package/dist/types/connectors-sarvam/connect.d.ts +14 -0
  62. package/dist/types/connectors-sarvam/connectors-sarvam.test.d.ts +14 -0
  63. package/dist/types/connectors-sarvam/index.d.ts +14 -0
  64. package/dist/types/connectors-sarvam/toolbox.d.ts +19 -0
  65. package/dist/types/connectors-sarvam/types.d.ts +49 -0
  66. package/dist/types/connectors-zoho/connect.d.ts +22 -0
  67. package/dist/types/connectors-zoho/connectors-zoho.test.d.ts +10 -0
  68. package/dist/types/connectors-zoho/index.d.ts +13 -0
  69. package/dist/types/connectors-zoho/toolbox.d.ts +19 -0
  70. package/dist/types/connectors-zoho/types.d.ts +56 -0
  71. package/dist/types/facade/agent.d.ts +1 -0
  72. package/dist/types/facade/ai.d.ts +1 -0
  73. package/dist/types/facade/bot/actions/bash.d.ts +71 -0
  74. package/dist/types/facade/bot/actions/bash.test.d.ts +1 -0
  75. package/dist/types/facade/bot/actions/checkpoint.d.ts +49 -0
  76. package/dist/types/facade/bot/actions/checkpoint.test.d.ts +1 -0
  77. package/dist/types/facade/bot/actions/composio/accounts.d.ts +22 -0
  78. package/dist/types/facade/bot/actions/composio/client.d.ts +39 -0
  79. package/dist/types/facade/bot/actions/composio/connect.d.ts +19 -0
  80. package/dist/types/facade/bot/actions/composio/enable.d.ts +25 -0
  81. package/dist/types/facade/bot/actions/composio/execute.d.ts +26 -0
  82. package/dist/types/facade/bot/actions/composio/helpers.d.ts +16 -0
  83. package/dist/types/facade/bot/actions/composio/index.d.ts +9 -0
  84. package/dist/types/facade/bot/actions/composio/provider.d.ts +8 -0
  85. package/dist/types/facade/bot/actions/composio/toolkits.d.ts +22 -0
  86. package/dist/types/facade/bot/actions/composio/tools.d.ts +28 -0
  87. package/dist/types/facade/bot/actions/composio/types.d.ts +137 -0
  88. package/dist/types/facade/bot/actions/crew/activity-tracker.d.ts +65 -0
  89. package/dist/types/facade/bot/actions/crew/cleanup.d.ts +50 -0
  90. package/dist/types/facade/bot/actions/crew/fs-lock.d.ts +11 -0
  91. package/dist/types/facade/bot/actions/crew/index.d.ts +11 -0
  92. package/dist/types/facade/bot/actions/crew/mailbox.d.ts +20 -0
  93. package/dist/types/facade/bot/actions/crew/model-policy.d.ts +22 -0
  94. package/dist/types/facade/bot/actions/crew/names.d.ts +27 -0
  95. package/dist/types/facade/bot/actions/crew/protocol.d.ts +74 -0
  96. package/dist/types/facade/bot/actions/crew/task-store.d.ts +88 -0
  97. package/dist/types/facade/bot/actions/crew/team-attach-claim.d.ts +35 -0
  98. package/dist/types/facade/bot/actions/crew/team-config.d.ts +54 -0
  99. package/dist/types/facade/bot/actions/crew/worktree.d.ts +39 -0
  100. package/dist/types/facade/bot/actions/edit-diff.d.ts +66 -0
  101. package/dist/types/facade/bot/actions/edit-utils.d.ts +86 -0
  102. package/dist/types/facade/bot/actions/edit.d.ts +59 -0
  103. package/dist/types/facade/bot/actions/edit.test.d.ts +1 -0
  104. package/dist/types/facade/bot/actions/find.d.ts +27 -0
  105. package/dist/types/facade/bot/actions/find.test.d.ts +1 -0
  106. package/dist/types/facade/bot/actions/grep.d.ts +53 -0
  107. package/dist/types/facade/bot/actions/grep.test.d.ts +1 -0
  108. package/dist/types/facade/bot/actions/index.d.ts +316 -0
  109. package/dist/types/facade/bot/actions/kit/hook-runner.d.ts +12 -0
  110. package/dist/types/facade/bot/actions/kit/image-resize.d.ts +19 -0
  111. package/dist/types/facade/bot/actions/kit/mime.d.ts +1 -0
  112. package/dist/types/facade/bot/actions/kit/shell.d.ts +12 -0
  113. package/dist/types/facade/bot/actions/ls.d.ts +41 -0
  114. package/dist/types/facade/bot/actions/path-utils.d.ts +8 -0
  115. package/dist/types/facade/bot/actions/process-controller.d.ts +14 -0
  116. package/dist/types/facade/bot/actions/process-manager.d.ts +59 -0
  117. package/dist/types/facade/bot/actions/process-types.d.ts +73 -0
  118. package/dist/types/facade/bot/actions/process.d.ts +37 -0
  119. package/dist/types/facade/bot/actions/read-state.d.ts +83 -0
  120. package/dist/types/facade/bot/actions/read-state.test.d.ts +1 -0
  121. package/dist/types/facade/bot/actions/read.d.ts +43 -0
  122. package/dist/types/facade/bot/actions/read.test.d.ts +1 -0
  123. package/dist/types/facade/bot/actions/registry.d.ts +20 -0
  124. package/dist/types/facade/bot/actions/sandbox-backend.d.ts +99 -0
  125. package/dist/types/facade/bot/actions/sandbox-backend.test.d.ts +1 -0
  126. package/dist/types/facade/bot/actions/todo-store.d.ts +76 -0
  127. package/dist/types/facade/bot/actions/todo-types.d.ts +72 -0
  128. package/dist/types/facade/bot/actions/todo.d.ts +76 -0
  129. package/dist/types/facade/bot/actions/truncate.d.ts +78 -0
  130. package/dist/types/facade/bot/actions/webfetch.d.ts +35 -0
  131. package/dist/types/facade/bot/actions/websearch.d.ts +37 -0
  132. package/dist/types/facade/bot/actions/websearch.test.d.ts +1 -0
  133. package/dist/types/facade/bot/actions/write.d.ts +45 -0
  134. package/dist/types/facade/bot/agent-loop.d.ts +30 -0
  135. package/dist/types/facade/bot/agent-loop.test.d.ts +1 -0
  136. package/dist/types/facade/bot/agent.d.ts +140 -0
  137. package/dist/types/facade/bot/error-handler.d.ts +7 -0
  138. package/dist/types/facade/bot/event-bus.d.ts +8 -0
  139. package/dist/types/facade/bot/index.d.ts +7 -0
  140. package/dist/types/facade/bot/messages.d.ts +83 -0
  141. package/dist/types/facade/bot/permission-gate.test.d.ts +1 -0
  142. package/dist/types/facade/bot/proxy.d.ts +70 -0
  143. package/dist/types/facade/bot/session-manager.d.ts +409 -0
  144. package/dist/types/facade/bot/state-manager.d.ts +21 -0
  145. package/dist/types/facade/bot/telemetry.d.ts +6 -0
  146. package/dist/types/facade/bot/types.d.ts +267 -0
  147. package/dist/types/facade/mcp-core/client-pool.d.ts +105 -0
  148. package/dist/types/facade/mcp-core/client.d.ts +245 -0
  149. package/dist/types/facade/mcp-core/client.test.d.ts +18 -0
  150. package/dist/types/facade/mcp-core/config.d.ts +60 -0
  151. package/dist/types/facade/mcp-core/errors.d.ts +103 -0
  152. package/dist/types/facade/mcp-core/index.d.ts +59 -0
  153. package/dist/types/facade/mcp-core/oauth/flow.d.ts +72 -0
  154. package/dist/types/facade/mcp-core/oauth/index.d.ts +18 -0
  155. package/dist/types/facade/mcp-core/oauth/oauth.test.d.ts +8 -0
  156. package/dist/types/facade/mcp-core/oauth/provider.d.ts +51 -0
  157. package/dist/types/facade/mcp-core/oauth/token-store.d.ts +31 -0
  158. package/dist/types/facade/mcp-core/oauth/types.d.ts +96 -0
  159. package/dist/types/facade/mcp-core/schema-converter.d.ts +67 -0
  160. package/dist/types/facade/mcp-core/server.d.ts +110 -0
  161. package/dist/types/facade/mcp-core/tool-factory.d.ts +62 -0
  162. package/dist/types/facade/mcp-core/toolbox-bridge.d.ts +46 -0
  163. package/dist/types/facade/mcp-core/toolbox-bridge.test.d.ts +8 -0
  164. package/dist/types/facade/mcp-core/types.d.ts +298 -0
  165. package/dist/types/facade/mcp.d.ts +1 -0
  166. package/dist/types/facade/memory.d.ts +1 -0
  167. package/dist/types/facade/ml/adapters/amazon-bedrock.d.ts +32 -0
  168. package/dist/types/facade/ml/adapters/anthropic-retry.test.d.ts +1 -0
  169. package/dist/types/facade/ml/adapters/anthropic.d.ts +78 -0
  170. package/dist/types/facade/ml/adapters/azure-openai-responses.d.ts +14 -0
  171. package/dist/types/facade/ml/adapters/google-shared.d.ts +99 -0
  172. package/dist/types/facade/ml/adapters/google-vertex.d.ts +14 -0
  173. package/dist/types/facade/ml/adapters/google.d.ts +15 -0
  174. package/dist/types/facade/ml/adapters/kimi.d.ts +21 -0
  175. package/dist/types/facade/ml/adapters/mock.d.ts +9 -0
  176. package/dist/types/facade/ml/adapters/nvidia.d.ts +12 -0
  177. package/dist/types/facade/ml/adapters/openai-codex-responses.d.ts +8 -0
  178. package/dist/types/facade/ml/adapters/openai-completions.d.ts +24 -0
  179. package/dist/types/facade/ml/adapters/openai-responses-shared.d.ts +25 -0
  180. package/dist/types/facade/ml/adapters/openai-responses.d.ts +12 -0
  181. package/dist/types/facade/ml/adapters/openai-scaffold.d.ts +3 -0
  182. package/dist/types/facade/ml/adapters/register-builtins.d.ts +2 -0
  183. package/dist/types/facade/ml/adapters/simple-options.d.ts +39 -0
  184. package/dist/types/facade/ml/adapters/simple-options.test.d.ts +1 -0
  185. package/dist/types/facade/ml/adapters/transform-messages.d.ts +23 -0
  186. package/dist/types/facade/ml/api-registry.d.ts +49 -0
  187. package/dist/types/facade/ml/cli.d.ts +2 -0
  188. package/dist/types/facade/ml/env-api-keys.d.ts +19 -0
  189. package/dist/types/facade/ml/index.d.ts +27 -0
  190. package/dist/types/facade/ml/kit/auth/anthropic.d.ts +17 -0
  191. package/dist/types/facade/ml/kit/auth/github-copilot.d.ts +22 -0
  192. package/dist/types/facade/ml/kit/auth/index.d.ts +50 -0
  193. package/dist/types/facade/ml/kit/auth/kimi.d.ts +23 -0
  194. package/dist/types/facade/ml/kit/auth/oauth-page.d.ts +2 -0
  195. package/dist/types/facade/ml/kit/auth/openai-codex.d.ts +36 -0
  196. package/dist/types/facade/ml/kit/auth/pkce.d.ts +12 -0
  197. package/dist/types/facade/ml/kit/auth/types.d.ts +67 -0
  198. package/dist/types/facade/ml/kit/base-stream-handler.d.ts +30 -0
  199. package/dist/types/facade/ml/kit/event-stream.d.ts +63 -0
  200. package/dist/types/facade/ml/kit/index.d.ts +14 -0
  201. package/dist/types/facade/ml/kit/json-parse.d.ts +23 -0
  202. package/dist/types/facade/ml/kit/message-transform.d.ts +32 -0
  203. package/dist/types/facade/ml/kit/output-factory.d.ts +8 -0
  204. package/dist/types/facade/ml/kit/overflow.d.ts +9 -0
  205. package/dist/types/facade/ml/kit/provider-adapter.d.ts +56 -0
  206. package/dist/types/facade/ml/kit/provider-client-builder.d.ts +36 -0
  207. package/dist/types/facade/ml/kit/provider-consolidation.d.ts +3 -0
  208. package/dist/types/facade/ml/kit/provider-constants.d.ts +34 -0
  209. package/dist/types/facade/ml/kit/provider-errors.d.ts +52 -0
  210. package/dist/types/facade/ml/kit/sanitize-unicode.d.ts +2 -0
  211. package/dist/types/facade/ml/kit/stream-event-helper.d.ts +38 -0
  212. package/dist/types/facade/ml/kit/stream-handler-types.d.ts +46 -0
  213. package/dist/types/facade/ml/kit/streaming-state-manager.d.ts +42 -0
  214. package/dist/types/facade/ml/kit/tool-converter.d.ts +49 -0
  215. package/dist/types/facade/ml/kit/typebox-helpers.d.ts +24 -0
  216. package/dist/types/facade/ml/kit/validation.d.ts +26 -0
  217. package/dist/types/facade/ml/models.d.ts +41 -0
  218. package/dist/types/facade/ml/models.generated.d.ts +12405 -0
  219. package/dist/types/facade/ml/stream.d.ts +27 -0
  220. package/dist/types/facade/ml/types.d.ts +269 -0
  221. package/dist/types/index.d.ts +18 -0
  222. package/dist/types/interop/index.d.ts +12 -0
  223. package/dist/types/interop/interop.test.d.ts +19 -0
  224. package/dist/types/interop/protocol-bridge/bridge.d.ts +52 -0
  225. package/dist/types/interop/protocol-bridge/contract.d.ts +249 -0
  226. package/dist/types/interop/protocol-bridge/endpoint.d.ts +124 -0
  227. package/dist/types/interop/protocol-bridge/fleet.d.ts +92 -0
  228. package/dist/types/interop/protocol-bridge/host.d.ts +61 -0
  229. package/dist/types/interop/protocol-bridge/index.d.ts +16 -0
  230. package/dist/types/interop/protocol-bridge/schema.d.ts +29 -0
  231. package/dist/types/llmgateway/catalog/cards.d.ts +18 -0
  232. package/dist/types/llmgateway/catalog/cost.d.ts +15 -0
  233. package/dist/types/llmgateway/catalog/index.d.ts +7 -0
  234. package/dist/types/llmgateway/catalog/query.d.ts +40 -0
  235. package/dist/types/llmgateway/connectors/anthropic.d.ts +35 -0
  236. package/dist/types/llmgateway/connectors/azure-openai.d.ts +33 -0
  237. package/dist/types/llmgateway/connectors/bedrock.d.ts +113 -0
  238. package/dist/types/llmgateway/connectors/google-vertex.d.ts +38 -0
  239. package/dist/types/llmgateway/connectors/google.d.ts +40 -0
  240. package/dist/types/llmgateway/connectors/index.d.ts +26 -0
  241. package/dist/types/llmgateway/connectors/kimi.d.ts +28 -0
  242. package/dist/types/llmgateway/connectors/mock.d.ts +37 -0
  243. package/dist/types/llmgateway/connectors/nvidia.d.ts +27 -0
  244. package/dist/types/llmgateway/connectors/ollama.d.ts +45 -0
  245. package/dist/types/llmgateway/connectors/openai-chat.d.ts +25 -0
  246. package/dist/types/llmgateway/connectors/openai-responses.d.ts +49 -0
  247. package/dist/types/llmgateway/contract/connector.d.ts +32 -0
  248. package/dist/types/llmgateway/contract/conversation.d.ts +86 -0
  249. package/dist/types/llmgateway/contract/emission.d.ts +55 -0
  250. package/dist/types/llmgateway/contract/errors.d.ts +27 -0
  251. package/dist/types/llmgateway/contract/index.d.ts +13 -0
  252. package/dist/types/llmgateway/contract/model-card.d.ts +42 -0
  253. package/dist/types/llmgateway/contract/options.d.ts +31 -0
  254. package/dist/types/llmgateway/contract/reply.d.ts +33 -0
  255. package/dist/types/llmgateway/conversion/index.d.ts +10 -0
  256. package/dist/types/llmgateway/conversion/mappers.d.ts +65 -0
  257. package/dist/types/llmgateway/conversion/openai-compatible.d.ts +46 -0
  258. package/dist/types/llmgateway/conversion/reduce.d.ts +20 -0
  259. package/dist/types/llmgateway/credentials/oauth.d.ts +73 -0
  260. package/dist/types/llmgateway/credentials/pkce.d.ts +52 -0
  261. package/dist/types/llmgateway/credentials/secrets.d.ts +76 -0
  262. package/dist/types/llmgateway/gateway.d.ts +34 -0
  263. package/dist/types/llmgateway/gateway.test.d.ts +14 -0
  264. package/dist/types/llmgateway/index.d.ts +11 -0
  265. package/dist/types/llmgateway/streaming/channel.d.ts +24 -0
  266. package/dist/types/llmgateway/streaming/index.d.ts +10 -0
  267. package/dist/types/llmgateway/streaming/ndjson.d.ts +17 -0
  268. package/dist/types/llmgateway/streaming/sse.d.ts +31 -0
  269. package/dist/types/react-host/index.d.ts +9 -0
  270. package/dist/types/react-host/ink.d.ts +5 -0
  271. package/dist/types/react-host/jsx-runtime.d.ts +4 -0
  272. package/dist/types/react-host/loader.d.ts +3 -0
  273. package/dist/types/react-ink/components/ChangelogBlock.d.ts +8 -0
  274. package/dist/types/react-ink/components/DisplayBlockView.d.ts +8 -0
  275. package/dist/types/react-ink/components/Footer.d.ts +11 -0
  276. package/dist/types/react-ink/components/MessageList.d.ts +14 -0
  277. package/dist/types/react-ink/components/MessageRow.d.ts +13 -0
  278. package/dist/types/react-ink/components/StatusLine.d.ts +18 -0
  279. package/dist/types/react-ink/components/TaskPanel.d.ts +11 -0
  280. package/dist/types/react-ink/components/ToolEventBlock.d.ts +48 -0
  281. package/dist/types/react-ink/components/ToolEventBlock.test.d.ts +1 -0
  282. package/dist/types/react-ink/components/dialogs/DialogFrame.d.ts +8 -0
  283. package/dist/types/react-ink/components/dialogs/LoginDialog.d.ts +14 -0
  284. package/dist/types/react-ink/components/dialogs/ModelDialog.d.ts +9 -0
  285. package/dist/types/react-ink/components/dialogs/OAuthDialog.d.ts +9 -0
  286. package/dist/types/react-ink/components/dialogs/ScopedModelsDialog.d.ts +9 -0
  287. package/dist/types/react-ink/components/dialogs/SelectableDialog.d.ts +22 -0
  288. package/dist/types/react-ink/components/dialogs/SessionDialog.d.ts +13 -0
  289. package/dist/types/react-ink/components/dialogs/SettingsDialog.d.ts +14 -0
  290. package/dist/types/react-ink/components/dialogs/StartupSessionPicker.d.ts +9 -0
  291. package/dist/types/react-ink/components/dialogs/ThemeDialog.d.ts +26 -0
  292. package/dist/types/react-ink/components/dialogs/TreeDialog.d.ts +8 -0
  293. package/dist/types/react-ink/components/dialogs/UserMessageDialog.d.ts +8 -0
  294. package/dist/types/react-ink/components/messages/AssistantMessage.d.ts +12 -0
  295. package/dist/types/react-ink/components/messages/BashMessage.d.ts +8 -0
  296. package/dist/types/react-ink/components/messages/BranchSummaryMessage.d.ts +8 -0
  297. package/dist/types/react-ink/components/messages/CompactionMessage.d.ts +8 -0
  298. package/dist/types/react-ink/components/messages/CustomMessage.d.ts +9 -0
  299. package/dist/types/react-ink/components/messages/SkillInvocationMessage.d.ts +7 -0
  300. package/dist/types/react-ink/components/messages/ToolCallMessage.d.ts +8 -0
  301. package/dist/types/react-ink/components/messages/ToolResultBlock.d.ts +12 -0
  302. package/dist/types/react-ink/components/messages/UserMessage.d.ts +9 -0
  303. package/dist/types/react-ink/diff/Diff.d.ts +22 -0
  304. package/dist/types/react-ink/diff/diff.test.d.ts +1 -0
  305. package/dist/types/react-ink/diff/structured.d.ts +41 -0
  306. package/dist/types/react-ink/diff/word-diff.d.ts +27 -0
  307. package/dist/types/react-ink/index.d.ts +42 -0
  308. package/dist/types/react-ink/markdown/Markdown.d.ts +23 -0
  309. package/dist/types/react-ink/markdown/MarkdownTable.d.ts +19 -0
  310. package/dist/types/react-ink/markdown/StreamingMarkdown.d.ts +34 -0
  311. package/dist/types/react-ink/markdown/format-token.d.ts +39 -0
  312. package/dist/types/react-ink/markdown/highlight.d.ts +31 -0
  313. package/dist/types/react-ink/theme-adapter.d.ts +66 -0
  314. package/dist/types/react-ink/types.d.ts +133 -0
  315. package/dist/types/react-ink/utils/message-groups.d.ts +25 -0
  316. package/dist/types/react-ink/utils/selection-dialog.d.ts +2 -0
  317. package/dist/types/react-ink/utils/session-browser.d.ts +27 -0
  318. package/dist/types/react-ink/utils/tool-display.d.ts +37 -0
  319. package/dist/types/runtime/cadence/cadence.test.d.ts +6 -0
  320. package/dist/types/runtime/cadence/fold.d.ts +48 -0
  321. package/dist/types/runtime/cadence/index.d.ts +12 -0
  322. package/dist/types/runtime/cadence/reducer.d.ts +44 -0
  323. package/dist/types/runtime/conductor/agent.d.ts +71 -0
  324. package/dist/types/runtime/conductor/index.d.ts +11 -0
  325. package/dist/types/runtime/contract/config.d.ts +44 -0
  326. package/dist/types/runtime/contract/effect.d.ts +41 -0
  327. package/dist/types/runtime/contract/errors.d.ts +22 -0
  328. package/dist/types/runtime/contract/events.d.ts +63 -0
  329. package/dist/types/runtime/contract/index.d.ts +18 -0
  330. package/dist/types/runtime/contract/run-state.d.ts +57 -0
  331. package/dist/types/runtime/contract/session.d.ts +42 -0
  332. package/dist/types/runtime/contract/signal.d.ts +49 -0
  333. package/dist/types/runtime/contract/tools.d.ts +45 -0
  334. package/dist/types/runtime/dispatch/index.d.ts +9 -0
  335. package/dist/types/runtime/dispatch/scheduler.d.ts +53 -0
  336. package/dist/types/runtime/index.d.ts +22 -0
  337. package/dist/types/runtime/ledger/accumulator.d.ts +44 -0
  338. package/dist/types/runtime/ledger/bus.d.ts +50 -0
  339. package/dist/types/runtime/ledger/index.d.ts +11 -0
  340. package/dist/types/runtime/memory/compactor.d.ts +56 -0
  341. package/dist/types/runtime/memory/estimate.d.ts +21 -0
  342. package/dist/types/runtime/memory/index.d.ts +8 -0
  343. package/dist/types/runtime/runtime.test.d.ts +15 -0
  344. package/dist/types/runtime/store/dag.d.ts +72 -0
  345. package/dist/types/runtime/store/hash.d.ts +18 -0
  346. package/dist/types/runtime/store/index.d.ts +12 -0
  347. package/dist/types/runtime/store/persist.d.ts +49 -0
  348. package/dist/types/runtime/turn/driver.d.ts +32 -0
  349. package/dist/types/runtime/turn/index.d.ts +8 -0
  350. package/dist/types/runtime/wire/index.d.ts +10 -0
  351. package/dist/types/runtime/wire/projectors.d.ts +53 -0
  352. package/dist/types/shell-app/auth-cli/index.d.ts +9 -0
  353. package/dist/types/shell-app/auth-cli/oauth-cli.d.ts +73 -0
  354. package/dist/types/shell-app/boot/context.d.ts +108 -0
  355. package/dist/types/shell-app/boot/index.d.ts +13 -0
  356. package/dist/types/shell-app/boot/pipeline.d.ts +66 -0
  357. package/dist/types/shell-app/boot/stages.d.ts +77 -0
  358. package/dist/types/shell-app/cli.d.ts +75 -0
  359. package/dist/types/shell-app/config/index.d.ts +11 -0
  360. package/dist/types/shell-app/config/locator.d.ts +85 -0
  361. package/dist/types/shell-app/config/settings.d.ts +91 -0
  362. package/dist/types/shell-app/index.d.ts +26 -0
  363. package/dist/types/shell-app/invocation/flags.d.ts +89 -0
  364. package/dist/types/shell-app/invocation/parse.d.ts +89 -0
  365. package/dist/types/shell-app/locate/brand.d.ts +71 -0
  366. package/dist/types/shell-app/locate/index.d.ts +12 -0
  367. package/dist/types/shell-app/locate/locator.d.ts +122 -0
  368. package/dist/types/shell-app/runners/contract.d.ts +116 -0
  369. package/dist/types/shell-app/runners/index.d.ts +15 -0
  370. package/dist/types/shell-app/runners/one-shot.d.ts +21 -0
  371. package/dist/types/shell-app/runners/registry.d.ts +34 -0
  372. package/dist/types/shell-app/runners/repl.d.ts +51 -0
  373. package/dist/types/shell-app/runners/wire.d.ts +34 -0
  374. package/dist/types/shell-app/shell-app.test.d.ts +14 -0
  375. package/dist/types/shell-app/upgrade/index.d.ts +9 -0
  376. package/dist/types/shell-app/upgrade/upgrades.d.ts +62 -0
  377. package/dist/types/smithy/config/flag-reader.d.ts +128 -0
  378. package/dist/types/smithy/config/index.d.ts +9 -0
  379. package/dist/types/smithy/forge.d.ts +135 -0
  380. package/dist/types/smithy/index.d.ts +36 -0
  381. package/dist/types/smithy/knowledge/index.d.ts +10 -0
  382. package/dist/types/smithy/knowledge/loader.d.ts +64 -0
  383. package/dist/types/smithy/persona/blueprint.d.ts +75 -0
  384. package/dist/types/smithy/persona/define-agent.d.ts +51 -0
  385. package/dist/types/smithy/persona/index.d.ts +14 -0
  386. package/dist/types/smithy/persona/profiles.d.ts +44 -0
  387. package/dist/types/smithy/runtime/index.d.ts +9 -0
  388. package/dist/types/smithy/runtime/tool-ledger.d.ts +130 -0
  389. package/dist/types/smithy/smithy.test.d.ts +20 -0
  390. package/dist/types/smithy/ui/index.d.ts +11 -0
  391. package/dist/types/smithy/ui/transcript.d.ts +183 -0
  392. package/dist/types/swarm/coordinator.d.ts +192 -0
  393. package/dist/types/swarm/index.d.ts +33 -0
  394. package/dist/types/swarm/isolation/index.d.ts +14 -0
  395. package/dist/types/swarm/isolation/runner.d.ts +61 -0
  396. package/dist/types/swarm/isolation/worktree.d.ts +142 -0
  397. package/dist/types/swarm/kernel/faults.d.ts +52 -0
  398. package/dist/types/swarm/kernel/ids.d.ts +25 -0
  399. package/dist/types/swarm/kernel/index.d.ts +26 -0
  400. package/dist/types/swarm/kernel/json-cell.d.ts +113 -0
  401. package/dist/types/swarm/kernel/jsonl-log.d.ts +81 -0
  402. package/dist/types/swarm/postbox/channel.d.ts +88 -0
  403. package/dist/types/swarm/postbox/codecs.d.ts +253 -0
  404. package/dist/types/swarm/postbox/index.d.ts +16 -0
  405. package/dist/types/swarm/roster/index.d.ts +16 -0
  406. package/dist/types/swarm/roster/manifest.d.ts +185 -0
  407. package/dist/types/swarm/swarm.test.d.ts +24 -0
  408. package/dist/types/swarm/telemetry/activity.d.ts +143 -0
  409. package/dist/types/swarm/workboard/board.d.ts +174 -0
  410. package/dist/types/swarm/workboard/dep-graph.d.ts +77 -0
  411. package/dist/types/swarm/workboard/index.d.ts +12 -0
  412. package/dist/types/tracing/adapter/index.d.ts +12 -0
  413. package/dist/types/tracing/adapter/runtime-trace.d.ts +54 -0
  414. package/dist/types/tracing/channel/index.d.ts +9 -0
  415. package/dist/types/tracing/channel/signal.d.ts +93 -0
  416. package/dist/types/tracing/index.d.ts +25 -0
  417. package/dist/types/tracing/recorder/index.d.ts +12 -0
  418. package/dist/types/tracing/recorder/recorder.d.ts +75 -0
  419. package/dist/types/tracing/recorder/sampling.d.ts +55 -0
  420. package/dist/types/tracing/redaction/index.d.ts +8 -0
  421. package/dist/types/tracing/redaction/secret-scrubber.d.ts +95 -0
  422. package/dist/types/tracing/registry/hub.d.ts +57 -0
  423. package/dist/types/tracing/registry/index.d.ts +7 -0
  424. package/dist/types/tracing/signal/handle.d.ts +73 -0
  425. package/dist/types/tracing/signal/index.d.ts +12 -0
  426. package/dist/types/tracing/signal/segment.d.ts +124 -0
  427. package/dist/types/tracing/sinks/base.d.ts +51 -0
  428. package/dist/types/tracing/sinks/console.d.ts +44 -0
  429. package/dist/types/tracing/sinks/file.d.ts +47 -0
  430. package/dist/types/tracing/sinks/index.d.ts +16 -0
  431. package/dist/types/tracing/sinks/stream.d.ts +46 -0
  432. package/dist/types/tracing/tracing.test.d.ts +7 -0
  433. package/dist/types/ui/autocomplete.d.ts +59 -0
  434. package/dist/types/ui/contracts.d.ts +38 -0
  435. package/dist/types/ui/editor-component.d.ts +100 -0
  436. package/dist/types/ui/fuzzy.d.ts +29 -0
  437. package/dist/types/ui/index.d.ts +8 -0
  438. package/dist/types/ui/keybindings.d.ts +62 -0
  439. package/dist/types/ui/keys.d.ts +171 -0
  440. package/dist/types/ui/theme-types.d.ts +36 -0
  441. package/dist/types/ui/utils.d.ts +101 -0
  442. package/dist/types/ui-bridge/InteractiveApp.d.ts +38 -0
  443. package/dist/types/ui-bridge/adapter.d.ts +90 -0
  444. package/dist/types/ui-bridge/index.d.ts +37 -0
  445. package/dist/zoho.js +1451 -0
  446. package/package.json +48 -48
package/dist/mcp.js ADDED
@@ -0,0 +1,2448 @@
1
+ var __defProp = Object.defineProperty;
2
+ var __require = /* @__PURE__ */ ((x) => typeof require !== "undefined" ? require : typeof Proxy !== "undefined" ? new Proxy(x, {
3
+ get: (a, b) => (typeof require !== "undefined" ? require : a)[b]
4
+ }) : x)(function(x) {
5
+ if (typeof require !== "undefined") return require.apply(this, arguments);
6
+ throw Error('Dynamic require of "' + x + '" is not supported');
7
+ });
8
+ var __export = (target, all) => {
9
+ for (var name in all)
10
+ __defProp(target, name, { get: all[name], enumerable: true });
11
+ };
12
+
13
+ // src/facade/mcp-core/client.ts
14
+ import { Client } from "@modelcontextprotocol/sdk/client/index.js";
15
+ import { StdioClientTransport } from "@modelcontextprotocol/sdk/client/stdio.js";
16
+ import { StreamableHTTPClientTransport } from "@modelcontextprotocol/sdk/client/streamableHttp.js";
17
+ import { SSEClientTransport } from "@modelcontextprotocol/sdk/client/sse.js";
18
+ import {
19
+ UnauthorizedError
20
+ } from "@modelcontextprotocol/sdk/client/auth.js";
21
+ import {
22
+ ListRootsRequestSchema,
23
+ ElicitRequestSchema,
24
+ CreateMessageRequestSchema,
25
+ PingRequestSchema,
26
+ ToolListChangedNotificationSchema,
27
+ ResourceListChangedNotificationSchema,
28
+ ResourceUpdatedNotificationSchema,
29
+ PromptListChangedNotificationSchema,
30
+ ProgressNotificationSchema,
31
+ LoggingMessageNotificationSchema,
32
+ CancelledNotificationSchema
33
+ } from "@modelcontextprotocol/sdk/types.js";
34
+
35
+ // src/facade/mcp-core/errors.ts
36
+ var MCPErrorCode = /* @__PURE__ */ ((MCPErrorCode2) => {
37
+ MCPErrorCode2["CONNECTION_FAILED"] = "CONNECTION_FAILED";
38
+ MCPErrorCode2["TIMEOUT"] = "TIMEOUT";
39
+ MCPErrorCode2["TOOL_NOT_FOUND"] = "TOOL_NOT_FOUND";
40
+ MCPErrorCode2["INVALID_PARAMETERS"] = "INVALID_PARAMETERS";
41
+ MCPErrorCode2["SERVER_ERROR"] = "SERVER_ERROR";
42
+ MCPErrorCode2["TRANSPORT_ERROR"] = "TRANSPORT_ERROR";
43
+ MCPErrorCode2["NOT_CONNECTED"] = "NOT_CONNECTED";
44
+ MCPErrorCode2["PROTOCOL_ERROR"] = "PROTOCOL_ERROR";
45
+ MCPErrorCode2["CONFIG_ERROR"] = "CONFIG_ERROR";
46
+ MCPErrorCode2["SCHEMA_CONVERSION_ERROR"] = "SCHEMA_CONVERSION_ERROR";
47
+ MCPErrorCode2["RESOURCE_NOT_FOUND"] = "RESOURCE_NOT_FOUND";
48
+ MCPErrorCode2["PROMPT_NOT_FOUND"] = "PROMPT_NOT_FOUND";
49
+ MCPErrorCode2["SESSION_ERROR"] = "SESSION_ERROR";
50
+ return MCPErrorCode2;
51
+ })(MCPErrorCode || {});
52
+ var MCPError = class extends Error {
53
+ /** Error code */
54
+ code;
55
+ /** Additional error details */
56
+ details;
57
+ /** Server name where error occurred */
58
+ serverName;
59
+ /** Tool name if error occurred during tool execution */
60
+ toolName;
61
+ constructor(message, code, details, options) {
62
+ super(message, options?.cause ? { cause: options.cause } : void 0);
63
+ this.name = "MCPError";
64
+ this.code = code;
65
+ this.details = details;
66
+ this.serverName = options?.serverName;
67
+ this.toolName = options?.toolName;
68
+ }
69
+ /**
70
+ * Convert error to JSON for logging/serialization.
71
+ */
72
+ toJSON() {
73
+ return {
74
+ name: this.name,
75
+ message: this.message,
76
+ code: this.code,
77
+ details: this.details,
78
+ serverName: this.serverName,
79
+ toolName: this.toolName
80
+ };
81
+ }
82
+ /**
83
+ * Create a string representation of the error.
84
+ */
85
+ toString() {
86
+ let str = `${this.name} [${this.code}]: ${this.message}`;
87
+ if (this.serverName) str += ` (server: ${this.serverName})`;
88
+ if (this.toolName) str += ` (tool: ${this.toolName})`;
89
+ return str;
90
+ }
91
+ };
92
+ function isMCPError(error) {
93
+ return error instanceof MCPError;
94
+ }
95
+ function isSessionError(error) {
96
+ if (!isMCPError(error)) return false;
97
+ return error.code === "SESSION_ERROR" /* SESSION_ERROR */ || error.code === "NOT_CONNECTED" /* NOT_CONNECTED */;
98
+ }
99
+ function createConnectionError(serverName, cause) {
100
+ return new MCPError(
101
+ `Failed to connect to MCP server: ${serverName}`,
102
+ "CONNECTION_FAILED" /* CONNECTION_FAILED */,
103
+ { cause: cause?.message },
104
+ { serverName, cause }
105
+ );
106
+ }
107
+ function createTimeoutError(operation, serverName) {
108
+ return new MCPError(`Operation timed out: ${operation}`, "TIMEOUT" /* TIMEOUT */, { operation }, { serverName });
109
+ }
110
+ function createToolNotFoundError(toolName, serverName) {
111
+ return new MCPError(`Tool not found: ${toolName}`, "TOOL_NOT_FOUND" /* TOOL_NOT_FOUND */, { toolName }, { serverName, toolName });
112
+ }
113
+ function createInvalidParametersError(toolName, details, serverName) {
114
+ return new MCPError(
115
+ `Invalid parameters for tool: ${toolName}`,
116
+ "INVALID_PARAMETERS" /* INVALID_PARAMETERS */,
117
+ details,
118
+ { serverName, toolName }
119
+ );
120
+ }
121
+ function createServerError(message, serverName, details) {
122
+ return new MCPError(message, "SERVER_ERROR" /* SERVER_ERROR */, details, { serverName });
123
+ }
124
+ function createNotConnectedError(serverName) {
125
+ return new MCPError("Not connected to MCP server", "NOT_CONNECTED" /* NOT_CONNECTED */, void 0, { serverName });
126
+ }
127
+ function createConfigError(message, details) {
128
+ return new MCPError(message, "CONFIG_ERROR" /* CONFIG_ERROR */, details);
129
+ }
130
+ function createSchemaConversionError(toolName, details, serverName) {
131
+ return new MCPError(
132
+ `Failed to convert schema for tool: ${toolName}`,
133
+ "SCHEMA_CONVERSION_ERROR" /* SCHEMA_CONVERSION_ERROR */,
134
+ details,
135
+ { serverName, toolName }
136
+ );
137
+ }
138
+
139
+ // src/facade/mcp-core/client.ts
140
+ var DEFAULT_REQUEST_TIMEOUT = 6e4;
141
+ var DEFAULT_CONNECT_TIMEOUT = 3e4;
142
+ var MCPClient = class {
143
+ constructor(options) {
144
+ this.options = options;
145
+ this.serverName = options.name;
146
+ this.config = options.config;
147
+ this.timeout = options.timeout ?? DEFAULT_REQUEST_TIMEOUT;
148
+ this.logHandler = options.logger;
149
+ this.enableServerLogs = options.enableServerLogs ?? true;
150
+ this.enableProgressTracking = options.enableProgressTracking ?? false;
151
+ this._roots = options.roots ?? [];
152
+ }
153
+ options;
154
+ client;
155
+ transport;
156
+ isConnected = false;
157
+ connectionPromise = null;
158
+ serverCapabilities;
159
+ logHandler;
160
+ enableServerLogs;
161
+ enableProgressTracking;
162
+ _roots;
163
+ // --- Host-overridable handlers (Core of #13) --------------------------------
164
+ // Server-initiated REQUESTS are answered by request handlers registered on the
165
+ // SDK client; the handlers delegate to these host-supplied callbacks when set,
166
+ // and fall back to sensible defaults otherwise.
167
+ elicitationHandler;
168
+ samplingHandler;
169
+ // Server-initiated NOTIFICATIONS are dispatched to these (so the host can, for
170
+ // example, re-list tools when a `tools/list_changed` arrives).
171
+ resourceUpdatedHandler;
172
+ resourceListChangedHandler;
173
+ toolListChangedHandler;
174
+ promptListChangedHandler;
175
+ progressHandler;
176
+ /** Server name */
177
+ serverName;
178
+ /** Server config */
179
+ config;
180
+ /** Request timeout */
181
+ timeout;
182
+ // ========================================================================
183
+ // Connection Lifecycle
184
+ // ========================================================================
185
+ /**
186
+ * Connect to the MCP server.
187
+ * Safe to call multiple times - returns existing connection if already connected.
188
+ */
189
+ async connect() {
190
+ if (this.isConnected) return;
191
+ if (this.connectionPromise) {
192
+ return this.connectionPromise;
193
+ }
194
+ this.connectionPromise = this.doConnect();
195
+ try {
196
+ await this.connectionPromise;
197
+ } finally {
198
+ this.connectionPromise = null;
199
+ }
200
+ }
201
+ async doConnect() {
202
+ const transport = this.createTransport(this.config);
203
+ this.transport = transport;
204
+ const client = new Client(
205
+ { name: "indusagi-coding-agent", version: "0.13.0" },
206
+ {
207
+ capabilities: {
208
+ roots: { listChanged: true },
209
+ elicitation: {},
210
+ sampling: {}
211
+ }
212
+ }
213
+ );
214
+ this.client = client;
215
+ this.registerServerHandlers(client);
216
+ const prevOnClose = transport.onclose;
217
+ transport.onclose = () => {
218
+ this.isConnected = false;
219
+ this.log("debug", "Transport closed");
220
+ prevOnClose?.();
221
+ };
222
+ try {
223
+ await client.connect(transport, { timeout: DEFAULT_CONNECT_TIMEOUT });
224
+ } catch (err) {
225
+ const recovered = await this.tryFinishOAuthAndReconnect(client, transport, err);
226
+ if (!recovered) {
227
+ throw this.wrapConnectError(err);
228
+ }
229
+ }
230
+ this.serverCapabilities = client.getServerCapabilities();
231
+ this.isConnected = true;
232
+ this.log("info", `Connected to MCP server`);
233
+ }
234
+ /**
235
+ * If `err` is an OAuth challenge and we have a provider + finishAuth-capable
236
+ * transport, wait for the browser code, exchange tokens, then reconnect on a
237
+ * **fresh** transport (the first transport is already `start()`ed and cannot
238
+ * be reused — see StreamableHTTPClientTransport.start).
239
+ *
240
+ * Matches the official SDK CLI example (`simpleOAuthClient`):
241
+ * finishAuth(code) → new StreamableHTTPClientTransport → client.connect again
242
+ *
243
+ * Client.connect already called `close()` on init failure, so the Client is
244
+ * free to attach a new transport.
245
+ */
246
+ async tryFinishOAuthAndReconnect(client, transport, err) {
247
+ if (!isAuthRequiredError(err)) return false;
248
+ const provider = this.options.authProvider;
249
+ if (!provider) return false;
250
+ const finishAuth = transport.finishAuth;
251
+ const waitForCode = provider.waitForAuthorizationCode;
252
+ if (typeof finishAuth !== "function" || typeof waitForCode !== "function") {
253
+ this.log(
254
+ "error",
255
+ "MCP server requires authentication but OAuth finish path is incomplete (need authProvider.waitForAuthorizationCode + transport.finishAuth)."
256
+ );
257
+ return false;
258
+ }
259
+ this.log("info", "MCP server requires OAuth \u2014 complete login in the browser\u2026");
260
+ try {
261
+ const code = await waitForCode.call(provider);
262
+ this.log("info", "OAuth authorization code received \u2014 exchanging tokens\u2026");
263
+ await finishAuth.call(transport, code);
264
+ try {
265
+ await transport.close?.();
266
+ } catch {
267
+ }
268
+ const fresh = this.createTransport(this.config);
269
+ this.transport = fresh;
270
+ const prevOnClose = fresh.onclose;
271
+ fresh.onclose = () => {
272
+ this.isConnected = false;
273
+ this.log("debug", "Transport closed");
274
+ prevOnClose?.();
275
+ };
276
+ this.log("info", "Reconnecting MCP session with OAuth tokens\u2026");
277
+ await client.connect(fresh, { timeout: DEFAULT_CONNECT_TIMEOUT });
278
+ return true;
279
+ } catch (oauthErr) {
280
+ this.log(
281
+ "error",
282
+ `OAuth finish failed: ${oauthErr instanceof Error ? oauthErr.message : String(oauthErr)}`
283
+ );
284
+ throw this.wrapConnectError(oauthErr);
285
+ }
286
+ }
287
+ /** Turn raw SDK / network errors into a clearer MCPError for callers. */
288
+ wrapConnectError(err) {
289
+ if (err instanceof MCPError) return err;
290
+ const message = err instanceof Error ? err.message : String(err);
291
+ if (isAuthRequiredError(err)) {
292
+ return new MCPError(
293
+ `Authentication required for MCP server "${this.serverName}". Pass auth: "auto" (default) to run the OAuth browser flow, or set a Bearer token via headers. Original: ${message}`,
294
+ "CONNECTION_FAILED" /* CONNECTION_FAILED */,
295
+ err,
296
+ { serverName: this.serverName, cause: err instanceof Error ? err : void 0 }
297
+ );
298
+ }
299
+ return new MCPError(
300
+ `Failed to connect to MCP server "${this.serverName}": ${message}`,
301
+ "CONNECTION_FAILED" /* CONNECTION_FAILED */,
302
+ err,
303
+ { serverName: this.serverName, cause: err instanceof Error ? err : void 0 }
304
+ );
305
+ }
306
+ /**
307
+ * Build the SDK transport for the configured server.
308
+ *
309
+ * - stdio: `StdioClientTransport` (inherits the parent env, merges config.env).
310
+ * - http: `StreamableHTTPClientTransport` (POST + server-push SSE channel,
311
+ * reconnect + session-expiry handled by the SDK), unless the config
312
+ * asks for the legacy `SSEClientTransport`.
313
+ */
314
+ createTransport(config) {
315
+ if ("command" in config) {
316
+ return new StdioClientTransport({
317
+ command: config.command,
318
+ args: config.args ?? [],
319
+ env: { ...sanitizeEnv(process.env), ...config.env ?? {} },
320
+ cwd: config.cwd,
321
+ stderr: "pipe"
322
+ });
323
+ }
324
+ if ("url" in config) {
325
+ const requestInit = config.headers ? { headers: config.headers } : void 0;
326
+ if (config.transport === "sse") {
327
+ return new SSEClientTransport(config.url, {
328
+ requestInit,
329
+ ...this.options.authProvider ? { authProvider: this.options.authProvider } : {}
330
+ });
331
+ }
332
+ return new StreamableHTTPClientTransport(config.url, {
333
+ requestInit,
334
+ ...this.options.authProvider ? { authProvider: this.options.authProvider } : {}
335
+ });
336
+ }
337
+ throw new MCPError(
338
+ "Server configuration must include either a command or a url",
339
+ "CONFIG_ERROR" /* CONFIG_ERROR */,
340
+ void 0,
341
+ { serverName: this.serverName }
342
+ );
343
+ }
344
+ /**
345
+ * Register handlers for server-initiated REQUESTS and NOTIFICATIONS.
346
+ *
347
+ * REQUESTS (have both `.method` AND `.id`) must be ANSWERED with a JSON-RPC
348
+ * RESPONSE carrying the matching id — the SDK does this automatically for the
349
+ * value a request handler returns (or rejects). The previous hand-rolled
350
+ * transport routed these into the notification path, so they were never
351
+ * answered (bug #13).
352
+ *
353
+ * Defaults:
354
+ * - ping → {}
355
+ * - roots/list → the configured roots
356
+ * - elicitation/create→ decline ({action:"cancel"}) unless a host handler is set
357
+ * - sampling → reject "Method not found" unless a host handler is set
358
+ */
359
+ registerServerHandlers(client) {
360
+ client.setRequestHandler(PingRequestSchema, async () => ({}));
361
+ client.setRequestHandler(ListRootsRequestSchema, async () => ({
362
+ roots: this._roots.map((r) => ({ uri: r.uri, name: r.name }))
363
+ }));
364
+ client.setRequestHandler(ElicitRequestSchema, async (request) => {
365
+ if (!this.elicitationHandler) {
366
+ return { action: "cancel" };
367
+ }
368
+ const params = request.params;
369
+ const elicitRequest = {
370
+ message: params.message,
371
+ requestedSchema: params.requestedSchema ?? {}
372
+ };
373
+ const result = await this.elicitationHandler(elicitRequest);
374
+ return mapToSdkElicitResult(result);
375
+ });
376
+ client.setRequestHandler(CreateMessageRequestSchema, async (request) => {
377
+ if (!this.samplingHandler) {
378
+ throw new MCPError(
379
+ "Method not found: sampling/createMessage",
380
+ "SERVER_ERROR" /* SERVER_ERROR */,
381
+ { method: "sampling/createMessage" },
382
+ { serverName: this.serverName }
383
+ );
384
+ }
385
+ return await this.samplingHandler(request.params);
386
+ });
387
+ client.setNotificationHandler(ToolListChangedNotificationSchema, () => {
388
+ this.log("debug", "Tool list changed");
389
+ this.toolListChangedHandler?.();
390
+ });
391
+ client.setNotificationHandler(ResourceListChangedNotificationSchema, () => {
392
+ this.log("debug", "Resource list changed");
393
+ this.resourceListChangedHandler?.();
394
+ });
395
+ client.setNotificationHandler(ResourceUpdatedNotificationSchema, (n) => {
396
+ const uri = n.params?.uri;
397
+ this.log("debug", `Resource updated: ${uri}`);
398
+ if (uri) this.resourceUpdatedHandler?.({ uri });
399
+ });
400
+ client.setNotificationHandler(PromptListChangedNotificationSchema, () => {
401
+ this.log("debug", "Prompt list changed");
402
+ this.promptListChangedHandler?.();
403
+ });
404
+ client.setNotificationHandler(ProgressNotificationSchema, (n) => {
405
+ const params = n.params;
406
+ this.log("debug", `Progress: ${JSON.stringify(params)}`);
407
+ if (this.progressHandler && params) {
408
+ const notification = {
409
+ progressToken: params.progressToken,
410
+ progress: params.progress,
411
+ total: params.total,
412
+ message: params.message
413
+ };
414
+ this.progressHandler(notification);
415
+ }
416
+ });
417
+ client.setNotificationHandler(LoggingMessageNotificationSchema, (n) => {
418
+ if (this.enableServerLogs && n.params) {
419
+ const { level, ...rest } = n.params;
420
+ this.log(level || "info", "[SERVER]", rest);
421
+ }
422
+ });
423
+ client.setNotificationHandler(CancelledNotificationSchema, (n) => {
424
+ this.log("debug", `Request cancelled: ${JSON.stringify(n.params)}`);
425
+ });
426
+ }
427
+ /**
428
+ * Disconnect from the MCP server.
429
+ *
430
+ * The SDK's `client.close()` closes the transport and rejects any pending
431
+ * requests — a clean teardown for both stdio (graceful subprocess shutdown)
432
+ * and HTTP (close the push channel / end the session).
433
+ */
434
+ async disconnect() {
435
+ if (!this.client) {
436
+ this.log("debug", "Disconnect called but not connected");
437
+ this.isConnected = false;
438
+ return;
439
+ }
440
+ this.log("debug", "Disconnecting from MCP server");
441
+ try {
442
+ await this.client.close();
443
+ } catch (error) {
444
+ this.log("error", `Error during disconnect: ${error}`);
445
+ } finally {
446
+ this.client = void 0;
447
+ this.transport = void 0;
448
+ this.isConnected = false;
449
+ this.log("debug", "Successfully disconnected");
450
+ }
451
+ }
452
+ /**
453
+ * Whether the client is connected.
454
+ */
455
+ get connected() {
456
+ return this.isConnected;
457
+ }
458
+ // ========================================================================
459
+ // Tool Operations
460
+ // ========================================================================
461
+ /**
462
+ * List all tools available from the server.
463
+ */
464
+ async listTools() {
465
+ this.ensureConnected();
466
+ const result = await this.client.listTools(void 0, {
467
+ timeout: this.timeout
468
+ });
469
+ return result.tools;
470
+ }
471
+ /**
472
+ * Call a tool on the server.
473
+ */
474
+ async callTool(name, args) {
475
+ this.ensureConnected();
476
+ this.log("debug", `Calling tool: ${name}`);
477
+ try {
478
+ const result = await this.client.callTool(
479
+ { name, arguments: args },
480
+ void 0,
481
+ { timeout: this.timeout }
482
+ );
483
+ this.log("debug", `Tool ${name} executed successfully`);
484
+ return result;
485
+ } catch (error) {
486
+ this.log("error", `Tool ${name} failed: ${error}`);
487
+ throw this.wrapError(error);
488
+ }
489
+ }
490
+ // ========================================================================
491
+ // Resource Operations
492
+ // ========================================================================
493
+ /**
494
+ * List all resources available from the server.
495
+ */
496
+ async listResources() {
497
+ this.ensureConnected();
498
+ if (!this.serverCapabilities?.resources) {
499
+ return [];
500
+ }
501
+ const result = await this.client.listResources(void 0, {
502
+ timeout: this.timeout
503
+ });
504
+ return result.resources;
505
+ }
506
+ /**
507
+ * Read a resource from the server.
508
+ */
509
+ async readResource(uri) {
510
+ this.ensureConnected();
511
+ return await this.client.readResource({ uri }, { timeout: this.timeout });
512
+ }
513
+ /**
514
+ * Subscribe to resource updates.
515
+ */
516
+ async subscribeResource(uri) {
517
+ this.ensureConnected();
518
+ await this.client.subscribeResource({ uri }, { timeout: this.timeout });
519
+ }
520
+ /**
521
+ * Unsubscribe from resource updates.
522
+ */
523
+ async unsubscribeResource(uri) {
524
+ this.ensureConnected();
525
+ await this.client.unsubscribeResource({ uri }, { timeout: this.timeout });
526
+ }
527
+ // ========================================================================
528
+ // Prompt Operations
529
+ // ========================================================================
530
+ /**
531
+ * List all prompts available from the server.
532
+ */
533
+ async listPrompts() {
534
+ this.ensureConnected();
535
+ if (!this.serverCapabilities?.prompts) {
536
+ return [];
537
+ }
538
+ const result = await this.client.listPrompts(void 0, {
539
+ timeout: this.timeout
540
+ });
541
+ return result.prompts;
542
+ }
543
+ /**
544
+ * Get a prompt from the server.
545
+ */
546
+ async getPrompt(name, args) {
547
+ this.ensureConnected();
548
+ return await this.client.getPrompt(
549
+ { name, arguments: args },
550
+ { timeout: this.timeout }
551
+ );
552
+ }
553
+ // ========================================================================
554
+ // Roots Operations
555
+ // ========================================================================
556
+ /**
557
+ * Get the configured roots.
558
+ */
559
+ get roots() {
560
+ return [...this._roots];
561
+ }
562
+ /**
563
+ * Update the roots and notify the server.
564
+ */
565
+ async setRoots(roots) {
566
+ this.log("debug", `Updating roots to ${roots.length} entries`);
567
+ this._roots = [...roots];
568
+ if (this.isConnected && this.client) {
569
+ try {
570
+ await this.client.sendRootsListChanged();
571
+ } catch (error) {
572
+ this.log("debug", `Failed to send roots/list_changed: ${error}`);
573
+ }
574
+ }
575
+ }
576
+ // ========================================================================
577
+ // Handler Registration
578
+ //
579
+ // Setters STORE the host handler (and, for notifications, the SDK handler
580
+ // registered in `registerServerHandlers` delegates to the stored callback).
581
+ // This is the host-overridable layer at the core of bug #13.
582
+ // ========================================================================
583
+ /**
584
+ * Set a handler for resource updated notifications.
585
+ */
586
+ setResourceUpdatedHandler(handler) {
587
+ this.resourceUpdatedHandler = handler;
588
+ this.log("debug", "Resource updated handler registered");
589
+ }
590
+ /**
591
+ * Set a handler for resource list changed notifications.
592
+ */
593
+ setResourceListChangedHandler(handler) {
594
+ this.resourceListChangedHandler = handler;
595
+ this.log("debug", "Resource list changed handler registered");
596
+ }
597
+ /**
598
+ * Set a handler for tool list changed notifications.
599
+ */
600
+ setToolListChangedHandler(handler) {
601
+ this.toolListChangedHandler = handler;
602
+ this.log("debug", "Tool list changed handler registered");
603
+ }
604
+ /**
605
+ * Set a handler for prompt list changed notifications.
606
+ */
607
+ setPromptListChangedHandler(handler) {
608
+ this.promptListChangedHandler = handler;
609
+ this.log("debug", "Prompt list changed handler registered");
610
+ }
611
+ /**
612
+ * Set a handler for elicitation requests. When set, the server's
613
+ * `elicitation/create` REQUEST is answered with the host's decision; when
614
+ * unset the request is declined ({action:"cancel"}).
615
+ */
616
+ setElicitationHandler(handler) {
617
+ this.elicitationHandler = handler;
618
+ this.log("debug", "Elicitation handler registered");
619
+ }
620
+ /**
621
+ * Set a handler for sampling (`sampling/createMessage`) requests. When set,
622
+ * the server request is answered with the host's result; when unset the
623
+ * request is rejected with "Method not found".
624
+ */
625
+ setSamplingHandler(handler) {
626
+ this.samplingHandler = handler;
627
+ this.log("debug", "Sampling handler registered");
628
+ }
629
+ /**
630
+ * Set a handler for progress notifications.
631
+ */
632
+ setProgressHandler(handler) {
633
+ this.progressHandler = handler;
634
+ this.log("debug", "Progress handler registered");
635
+ }
636
+ // ========================================================================
637
+ // Private Methods
638
+ // ========================================================================
639
+ ensureConnected() {
640
+ if (!this.isConnected || !this.client) {
641
+ throw new MCPError(
642
+ "Not connected to MCP server",
643
+ "NOT_CONNECTED" /* NOT_CONNECTED */,
644
+ void 0,
645
+ { serverName: this.serverName }
646
+ );
647
+ }
648
+ }
649
+ /**
650
+ * Normalize an SDK/transport error into an MCPError. Session-expiry style
651
+ * failures (404 session / -32001) are surfaced as SESSION_ERROR so callers
652
+ * (the pool) can decide to reconnect; the SDK's StreamableHTTP transport
653
+ * already attempts a bounded reconnect re-using the session id before this.
654
+ */
655
+ wrapError(error) {
656
+ if (error instanceof MCPError) return error;
657
+ const message = error instanceof Error ? error.message : String(error);
658
+ const code = error.code;
659
+ if (code === -32001 || /\b404\b|session/i.test(message)) {
660
+ return new MCPError(message, "SESSION_ERROR" /* SESSION_ERROR */, { code }, {
661
+ serverName: this.serverName
662
+ });
663
+ }
664
+ return new MCPError(message, "SERVER_ERROR" /* SERVER_ERROR */, { code }, {
665
+ serverName: this.serverName
666
+ });
667
+ }
668
+ log(level, message, details) {
669
+ const msg = `[${this.serverName}] ${message}`;
670
+ if (this.logHandler) {
671
+ this.logHandler({
672
+ level,
673
+ message: msg,
674
+ timestamp: /* @__PURE__ */ new Date(),
675
+ serverName: this.serverName,
676
+ details
677
+ });
678
+ } else {
679
+ if (process.env.INDUSAGI_DEBUG || level === "error") {
680
+ const prefix = `[MCP:${level.toUpperCase()}]`;
681
+ if (details) {
682
+ if (level === "error") {
683
+ console.error(prefix, msg, details);
684
+ } else {
685
+ console.log(prefix, msg, details);
686
+ }
687
+ } else {
688
+ if (level === "error") {
689
+ console.error(prefix, msg);
690
+ } else {
691
+ console.log(prefix, msg);
692
+ }
693
+ }
694
+ }
695
+ }
696
+ }
697
+ };
698
+ function mapToSdkElicitResult(result) {
699
+ if (result.action === "accept") {
700
+ return {
701
+ action: "accept",
702
+ content: result.content ?? {}
703
+ };
704
+ }
705
+ return { action: result.action };
706
+ }
707
+ function isAuthRequiredError(err) {
708
+ if (err == null) return false;
709
+ if (err instanceof UnauthorizedError) return true;
710
+ if (typeof err === "object") {
711
+ const code = err.code;
712
+ if (code === 401 || code === "401") return true;
713
+ }
714
+ if (err instanceof Error) {
715
+ const msg = err.message;
716
+ if (/unauthorized/i.test(msg)) return true;
717
+ if (/authentication required/i.test(msg)) return true;
718
+ if (/auth required/i.test(msg)) return true;
719
+ if (err.name === "UnauthorizedError") return true;
720
+ }
721
+ return false;
722
+ }
723
+ function sanitizeEnv(env) {
724
+ const out = {};
725
+ for (const [k, v] of Object.entries(env)) {
726
+ if (typeof v === "string") out[k] = v;
727
+ }
728
+ return out;
729
+ }
730
+
731
+ // src/facade/mcp-core/client-pool.ts
732
+ var MCPClientPool = class {
733
+ constructor(options) {
734
+ this.options = options;
735
+ }
736
+ options;
737
+ clients = /* @__PURE__ */ new Map();
738
+ isConnecting = false;
739
+ /**
740
+ * Connect to all configured servers.
741
+ *
742
+ * Errors for individual servers are logged but don't fail the entire operation.
743
+ */
744
+ async connectAll() {
745
+ if (this.isConnecting) {
746
+ throw new MCPError(
747
+ "Already connecting to servers",
748
+ "CONNECTION_FAILED" /* CONNECTION_FAILED */
749
+ );
750
+ }
751
+ this.isConnecting = true;
752
+ try {
753
+ for (const serverConfig of this.options.servers) {
754
+ try {
755
+ const client = new MCPClient(serverConfig);
756
+ await client.connect();
757
+ this.clients.set(serverConfig.name, client);
758
+ console.log(`[MCP] Connected to ${serverConfig.name}`);
759
+ } catch (error) {
760
+ console.error(
761
+ `[MCP] Failed to connect to ${serverConfig.name}:`,
762
+ error instanceof Error ? error.message : String(error)
763
+ );
764
+ }
765
+ }
766
+ } finally {
767
+ this.isConnecting = false;
768
+ }
769
+ }
770
+ /**
771
+ * Disconnect from all servers.
772
+ */
773
+ async disconnectAll() {
774
+ for (const [name, client] of this.clients) {
775
+ try {
776
+ await client.disconnect();
777
+ console.log(`[MCP] Disconnected from ${name}`);
778
+ } catch (error) {
779
+ console.error(`[MCP] Error disconnecting from ${name}:`, error);
780
+ }
781
+ }
782
+ this.clients.clear();
783
+ }
784
+ /**
785
+ * Get a specific client by name.
786
+ */
787
+ getClient(name) {
788
+ return this.clients.get(name);
789
+ }
790
+ /**
791
+ * Get all connected clients.
792
+ */
793
+ getAllClients() {
794
+ return Array.from(this.clients.values());
795
+ }
796
+ /**
797
+ * Check if a client is connected.
798
+ */
799
+ isConnected(name) {
800
+ return this.clients.get(name)?.connected ?? false;
801
+ }
802
+ /**
803
+ * Get status of all servers.
804
+ */
805
+ async getStatus() {
806
+ const statuses = [];
807
+ for (const [name, client] of this.clients) {
808
+ const status = {
809
+ name,
810
+ connected: client.connected
811
+ };
812
+ if (client.connected) {
813
+ try {
814
+ const tools = await client.listTools();
815
+ status.toolCount = tools.length;
816
+ } catch {
817
+ }
818
+ try {
819
+ const resources = await client.listResources();
820
+ status.resourceCount = resources.length;
821
+ } catch {
822
+ }
823
+ try {
824
+ const prompts = await client.listPrompts();
825
+ status.promptCount = prompts.length;
826
+ } catch {
827
+ }
828
+ }
829
+ statuses.push(status);
830
+ }
831
+ return statuses;
832
+ }
833
+ /**
834
+ * Get all tools from all connected servers.
835
+ */
836
+ async listAllTools() {
837
+ const allTools = {};
838
+ for (const [name, client] of this.clients) {
839
+ if (client.connected) {
840
+ try {
841
+ allTools[name] = await client.listTools();
842
+ } catch (error) {
843
+ console.error(`[MCP] Failed to list tools from ${name}:`, error);
844
+ allTools[name] = [];
845
+ }
846
+ }
847
+ }
848
+ return allTools;
849
+ }
850
+ /**
851
+ * Get all resources from all connected servers.
852
+ */
853
+ async listAllResources() {
854
+ const allResources = {};
855
+ for (const [name, client] of this.clients) {
856
+ if (client.connected) {
857
+ try {
858
+ allResources[name] = await client.listResources();
859
+ } catch (error) {
860
+ console.error(`[MCP] Failed to list resources from ${name}:`, error);
861
+ allResources[name] = [];
862
+ }
863
+ }
864
+ }
865
+ return allResources;
866
+ }
867
+ /**
868
+ * Get all prompts from all connected servers.
869
+ */
870
+ async listAllPrompts() {
871
+ const allPrompts = {};
872
+ for (const [name, client] of this.clients) {
873
+ if (client.connected) {
874
+ try {
875
+ allPrompts[name] = await client.listPrompts();
876
+ } catch (error) {
877
+ console.error(`[MCP] Failed to list prompts from ${name}:`, error);
878
+ allPrompts[name] = [];
879
+ }
880
+ }
881
+ }
882
+ return allPrompts;
883
+ }
884
+ /**
885
+ * Reload all connections.
886
+ */
887
+ async reload() {
888
+ await this.disconnectAll();
889
+ await this.connectAll();
890
+ }
891
+ /**
892
+ * Add a new server connection.
893
+ */
894
+ async addServer(config) {
895
+ if (this.clients.has(config.name)) {
896
+ console.warn(`[MCP] Server ${config.name} already exists`);
897
+ return false;
898
+ }
899
+ try {
900
+ const client = new MCPClient(config);
901
+ await client.connect();
902
+ this.clients.set(config.name, client);
903
+ console.log(`[MCP] Connected to ${config.name}`);
904
+ return true;
905
+ } catch (error) {
906
+ console.error(`[MCP] Failed to connect to ${config.name}:`, error);
907
+ return false;
908
+ }
909
+ }
910
+ /**
911
+ * Remove a server connection.
912
+ */
913
+ async removeServer(name) {
914
+ const client = this.clients.get(name);
915
+ if (!client) {
916
+ return false;
917
+ }
918
+ try {
919
+ await client.disconnect();
920
+ this.clients.delete(name);
921
+ console.log(`[MCP] Disconnected from ${name}`);
922
+ return true;
923
+ } catch (error) {
924
+ console.error(`[MCP] Error disconnecting from ${name}:`, error);
925
+ return false;
926
+ }
927
+ }
928
+ };
929
+
930
+ // src/facade/mcp-core/config.ts
931
+ import { existsSync, readFileSync, mkdirSync, statSync, writeFileSync } from "fs";
932
+ import { join, dirname } from "path";
933
+ import { homedir } from "os";
934
+ function loadMCPConfig(configPathOrCwd = process.cwd()) {
935
+ const configs = [];
936
+ if (existsSync(configPathOrCwd)) {
937
+ try {
938
+ const stats = statSync(configPathOrCwd);
939
+ if (stats.isFile()) {
940
+ const fileConfigs = parseConfigFile(configPathOrCwd);
941
+ configs.push(...fileConfigs);
942
+ return configs;
943
+ }
944
+ } catch {
945
+ }
946
+ }
947
+ const cwd = configPathOrCwd;
948
+ const projectConfig = join(cwd, ".indusvx", "mcp.json");
949
+ if (existsSync(projectConfig)) {
950
+ try {
951
+ const projectConfigs = parseConfigFile(projectConfig);
952
+ configs.push(...projectConfigs);
953
+ console.log(`[MCP] Loaded ${projectConfigs.length} servers from project config`);
954
+ } catch (error) {
955
+ console.error(`[MCP] Error loading project config:`, error);
956
+ }
957
+ }
958
+ const xdgConfigHome = process.env.XDG_CONFIG_HOME || join(homedir(), ".config");
959
+ const userConfig = join(xdgConfigHome, "indusvx", "mcp.json");
960
+ if (existsSync(userConfig)) {
961
+ try {
962
+ const userConfigs = parseConfigFile(userConfig);
963
+ configs.push(...userConfigs);
964
+ console.log(`[MCP] Loaded ${userConfigs.length} servers from user config`);
965
+ } catch (error) {
966
+ console.error(`[MCP] Error loading user config:`, error);
967
+ }
968
+ }
969
+ const legacyConfig = join(homedir(), ".indusvx", "agent", "mcp.json");
970
+ if (existsSync(legacyConfig)) {
971
+ try {
972
+ const legacyConfigs = parseConfigFile(legacyConfig);
973
+ configs.push(...legacyConfigs);
974
+ console.log(`[MCP] Loaded ${legacyConfigs.length} servers from legacy config`);
975
+ } catch (error) {
976
+ console.error(`[MCP] Error loading legacy config:`, error);
977
+ }
978
+ }
979
+ const legacyServersConfig = join(homedir(), ".indusvx", "agent", "mcp-servers.json");
980
+ if (existsSync(legacyServersConfig)) {
981
+ try {
982
+ const legacyConfigs = parseConfigFile(legacyServersConfig);
983
+ configs.push(...legacyConfigs);
984
+ console.log(`[MCP] Loaded ${legacyConfigs.length} servers from mcp-servers.json`);
985
+ } catch (error) {
986
+ console.error(`[MCP] Error loading mcp-servers.json:`, error);
987
+ }
988
+ }
989
+ return configs;
990
+ }
991
+ function parseConfigFile(path) {
992
+ const content = readFileSync(path, "utf-8");
993
+ const config = JSON.parse(content);
994
+ if (!config.servers) {
995
+ console.warn(`[MCP] Invalid config file ${path}: missing "servers" field`);
996
+ return [];
997
+ }
998
+ let serversArray;
999
+ if (Array.isArray(config.servers)) {
1000
+ serversArray = config.servers;
1001
+ } else if (typeof config.servers === "object") {
1002
+ serversArray = Object.entries(config.servers).map(([name, serverConfig]) => ({
1003
+ name,
1004
+ ...serverConfig
1005
+ }));
1006
+ } else {
1007
+ console.warn(`[MCP] Invalid config file ${path}: "servers" must be array or object`);
1008
+ return [];
1009
+ }
1010
+ return serversArray.filter((server) => server.enabled !== false).map((server) => {
1011
+ if (server.url) {
1012
+ return {
1013
+ name: server.name,
1014
+ config: {
1015
+ url: new URL(server.url),
1016
+ headers: server.headers,
1017
+ ...server.transport ? { transport: server.transport } : {}
1018
+ },
1019
+ timeout: server.timeout
1020
+ };
1021
+ } else if (server.command) {
1022
+ return {
1023
+ name: server.name,
1024
+ config: {
1025
+ command: server.command,
1026
+ args: server.args,
1027
+ env: server.env
1028
+ },
1029
+ timeout: server.timeout
1030
+ };
1031
+ }
1032
+ throw new MCPError(
1033
+ `Invalid server config: ${server.name}`,
1034
+ "CONFIG_ERROR" /* CONFIG_ERROR */,
1035
+ { server }
1036
+ );
1037
+ });
1038
+ }
1039
+ function getUserConfigPath() {
1040
+ const xdgConfigHome = process.env.XDG_CONFIG_HOME || join(homedir(), ".config");
1041
+ return join(xdgConfigHome, "indusvx", "mcp.json");
1042
+ }
1043
+ function getProjectConfigPath(cwd = process.cwd()) {
1044
+ return join(cwd, ".indusvx", "mcp.json");
1045
+ }
1046
+ function ensureUserConfigDir() {
1047
+ const xdgConfigHome = process.env.XDG_CONFIG_HOME || join(homedir(), ".config");
1048
+ const configDir = join(xdgConfigHome, "indusvx");
1049
+ if (!existsSync(configDir)) {
1050
+ mkdirSync(configDir, { recursive: true });
1051
+ }
1052
+ return configDir;
1053
+ }
1054
+ function ensureProjectConfigDir(cwd = process.cwd()) {
1055
+ const configDir = join(cwd, ".indusvx");
1056
+ if (!existsSync(configDir)) {
1057
+ mkdirSync(configDir, { recursive: true });
1058
+ }
1059
+ return configDir;
1060
+ }
1061
+ function saveConfig(path, config) {
1062
+ const dir = dirname(path);
1063
+ if (!existsSync(dir)) {
1064
+ mkdirSync(dir, { recursive: true });
1065
+ }
1066
+ const content = JSON.stringify(config, null, 2);
1067
+ writeFileSync(path, content, "utf-8");
1068
+ }
1069
+ function saveUserConfig(config) {
1070
+ saveConfig(getUserConfigPath(), config);
1071
+ }
1072
+ function saveProjectConfig(config, cwd = process.cwd()) {
1073
+ saveConfig(getProjectConfigPath(cwd), config);
1074
+ }
1075
+ function createDefaultConfig() {
1076
+ return {
1077
+ servers: []
1078
+ };
1079
+ }
1080
+ var EXAMPLE_CONFIG = {
1081
+ servers: [
1082
+ {
1083
+ name: "filesystem",
1084
+ command: "npx",
1085
+ args: ["-y", "@modelcontextprotocol/server-filesystem", "/path/to/allowed/dir"],
1086
+ enabled: true
1087
+ },
1088
+ {
1089
+ name: "github",
1090
+ command: "npx",
1091
+ args: ["-y", "@modelcontextprotocol/server-github"],
1092
+ env: {
1093
+ GITHUB_TOKEN: "your-github-token"
1094
+ },
1095
+ enabled: true
1096
+ },
1097
+ {
1098
+ name: "remote-server",
1099
+ url: "http://localhost:8080/mcp",
1100
+ headers: {
1101
+ Authorization: "Bearer your-token"
1102
+ },
1103
+ enabled: false
1104
+ }
1105
+ ]
1106
+ };
1107
+
1108
+ // src/facade/mcp-core/schema-converter.ts
1109
+ import { Type } from "@sinclair/typebox";
1110
+ function jsonSchemaToTypeBox(schema) {
1111
+ if (schema.type === "null") {
1112
+ return Type.Null({ description: schema.description });
1113
+ }
1114
+ if (schema.enum) {
1115
+ if (schema.enum.length === 1) {
1116
+ return Type.Literal(schema.enum[0], {
1117
+ description: schema.description
1118
+ });
1119
+ }
1120
+ const literals = schema.enum.map((e) => {
1121
+ if (e === null) return Type.Null();
1122
+ return Type.Literal(e);
1123
+ });
1124
+ return Type.Union(literals, { description: schema.description });
1125
+ }
1126
+ if (schema.const !== void 0) {
1127
+ if (schema.const === null) {
1128
+ return Type.Null({ description: schema.description });
1129
+ }
1130
+ return Type.Literal(schema.const, {
1131
+ description: schema.description
1132
+ });
1133
+ }
1134
+ if (schema.oneOf || schema.anyOf) {
1135
+ const schemas = (schema.oneOf || schema.anyOf).map((s) => jsonSchemaToTypeBox(s));
1136
+ return Type.Union(schemas, { description: schema.description });
1137
+ }
1138
+ if (schema.allOf) {
1139
+ const schemas = schema.allOf.map((s) => jsonSchemaToTypeBox(s));
1140
+ return Type.Intersect(schemas, { description: schema.description });
1141
+ }
1142
+ if (schema.type === "array" || Array.isArray(schema.type) && schema.type.includes("array")) {
1143
+ return convertArraySchema(schema);
1144
+ }
1145
+ if (schema.type === "object" || Array.isArray(schema.type) && schema.type.includes("object")) {
1146
+ return convertObjectSchema(schema);
1147
+ }
1148
+ switch (schema.type) {
1149
+ case "string":
1150
+ return convertStringSchema(schema);
1151
+ case "number":
1152
+ case "integer":
1153
+ return convertNumberSchema(schema);
1154
+ case "boolean":
1155
+ return Type.Boolean({ description: schema.description });
1156
+ default:
1157
+ if (schema.properties) {
1158
+ return convertObjectSchema(schema);
1159
+ }
1160
+ if (schema.items) {
1161
+ return convertArraySchema(schema);
1162
+ }
1163
+ return Type.Any({ description: schema.description });
1164
+ }
1165
+ }
1166
+ function convertStringSchema(schema) {
1167
+ return Type.String({
1168
+ description: schema.description,
1169
+ minLength: schema.minLength,
1170
+ maxLength: schema.maxLength,
1171
+ pattern: schema.pattern,
1172
+ format: schema.format
1173
+ });
1174
+ }
1175
+ function convertNumberSchema(schema) {
1176
+ const options = {
1177
+ description: schema.description
1178
+ };
1179
+ if (schema.minimum !== void 0) options.minimum = schema.minimum;
1180
+ if (schema.maximum !== void 0) options.maximum = schema.maximum;
1181
+ if (typeof schema.exclusiveMinimum === "number") options.exclusiveMinimum = schema.exclusiveMinimum;
1182
+ if (typeof schema.exclusiveMaximum === "number") options.exclusiveMaximum = schema.exclusiveMaximum;
1183
+ if (schema.multipleOf !== void 0) options.multipleOf = schema.multipleOf;
1184
+ return Type.Number(options);
1185
+ }
1186
+ function convertArraySchema(schema) {
1187
+ let itemsSchema;
1188
+ if (schema.items) {
1189
+ if (Array.isArray(schema.items)) {
1190
+ const items = schema.items.map((item) => jsonSchemaToTypeBox(item));
1191
+ itemsSchema = Type.Tuple(items);
1192
+ } else {
1193
+ itemsSchema = jsonSchemaToTypeBox(schema.items);
1194
+ }
1195
+ } else {
1196
+ itemsSchema = Type.Any();
1197
+ }
1198
+ return Type.Array(itemsSchema, {
1199
+ description: schema.description,
1200
+ minItems: schema.minItems,
1201
+ maxItems: schema.maxItems
1202
+ });
1203
+ }
1204
+ function convertObjectSchema(schema) {
1205
+ const properties = {};
1206
+ const required = new Set(schema.required ?? []);
1207
+ for (const [key, value] of Object.entries(schema.properties ?? {})) {
1208
+ let propSchema = jsonSchemaToTypeBox(value);
1209
+ if (!required.has(key)) {
1210
+ propSchema = Type.Optional(propSchema);
1211
+ }
1212
+ properties[key] = propSchema;
1213
+ }
1214
+ let additionalProperties = void 0;
1215
+ if (schema.additionalProperties === true) {
1216
+ additionalProperties = true;
1217
+ } else if (schema.additionalProperties && typeof schema.additionalProperties === "object") {
1218
+ additionalProperties = jsonSchemaToTypeBox(schema.additionalProperties);
1219
+ } else if (schema.additionalProperties === false) {
1220
+ additionalProperties = false;
1221
+ }
1222
+ return Type.Object(properties, {
1223
+ description: schema.description,
1224
+ additionalProperties
1225
+ });
1226
+ }
1227
+ function applyPassthrough(schema) {
1228
+ const kind = schema[/* @__PURE__ */ Symbol.for("TypeBox.Kind")];
1229
+ if (kind === "Object") {
1230
+ const shape = { ...schema.properties };
1231
+ for (const key of Object.keys(shape)) {
1232
+ shape[key] = applyPassthrough(shape[key]);
1233
+ }
1234
+ return Type.Object(shape, {
1235
+ description: schema.description,
1236
+ additionalProperties: true
1237
+ });
1238
+ }
1239
+ if (kind === "Array") {
1240
+ return Type.Array(applyPassthrough(schema.items), {
1241
+ description: schema.description,
1242
+ minItems: schema.minItems,
1243
+ maxItems: schema.maxItems
1244
+ });
1245
+ }
1246
+ if (kind === "Union") {
1247
+ return Type.Union(
1248
+ schema.anyOf.map((s) => applyPassthrough(s)),
1249
+ { description: schema.description }
1250
+ );
1251
+ }
1252
+ if (kind === "Intersect") {
1253
+ return Type.Intersect(
1254
+ schema.allOf.map((s) => applyPassthrough(s)),
1255
+ { description: schema.description }
1256
+ );
1257
+ }
1258
+ if (kind === "Optional") {
1259
+ return Type.Optional(applyPassthrough(schema.schema ?? schema.type));
1260
+ }
1261
+ return schema;
1262
+ }
1263
+ function convertMCPInputSchema(inputSchema) {
1264
+ const typeboxSchema = jsonSchemaToTypeBox(inputSchema);
1265
+ return applyPassthrough(typeboxSchema);
1266
+ }
1267
+ function convertMCPOutputSchema(outputSchema) {
1268
+ if (!outputSchema) return void 0;
1269
+ const typeboxSchema = jsonSchemaToTypeBox(outputSchema);
1270
+ return applyPassthrough(typeboxSchema);
1271
+ }
1272
+
1273
+ // src/facade/mcp-core/tool-factory.ts
1274
+ function createMCPAgentToolFactory(mcpTool, client) {
1275
+ return () => {
1276
+ const namespacedName = `${client.serverName}_${mcpTool.name}`;
1277
+ const parameters = convertMCPInputSchema(mcpTool.inputSchema);
1278
+ return {
1279
+ name: namespacedName,
1280
+ label: mcpTool.name,
1281
+ description: `[${client.serverName}] ${mcpTool.description || ""}`,
1282
+ category: "mcp",
1283
+ parameters,
1284
+ execute: async (toolCallId, params, signal, onUpdate) => {
1285
+ const typedParams = params;
1286
+ try {
1287
+ if (!client.connected) {
1288
+ throw new MCPError(
1289
+ `MCP server ${client.serverName} not connected`,
1290
+ "NOT_CONNECTED" /* NOT_CONNECTED */,
1291
+ void 0,
1292
+ { serverName: client.serverName, toolName: mcpTool.name }
1293
+ );
1294
+ }
1295
+ if (signal?.aborted) {
1296
+ throw new MCPError(
1297
+ "Tool execution aborted",
1298
+ "TIMEOUT" /* TIMEOUT */,
1299
+ void 0,
1300
+ { serverName: client.serverName, toolName: mcpTool.name }
1301
+ );
1302
+ }
1303
+ const result = await client.callTool(mcpTool.name, typedParams);
1304
+ return convertMCPResultToAgentResult(result, client.serverName, mcpTool.name);
1305
+ } catch (error) {
1306
+ if (error instanceof MCPError) {
1307
+ return {
1308
+ content: [
1309
+ {
1310
+ type: "text",
1311
+ text: `MCP Error: ${error.message}`
1312
+ }
1313
+ ],
1314
+ details: {
1315
+ error: error.message,
1316
+ code: error.code,
1317
+ serverName: error.serverName,
1318
+ toolName: error.toolName
1319
+ },
1320
+ isError: true
1321
+ };
1322
+ }
1323
+ if (error instanceof Error && error.name === "AbortError") {
1324
+ return {
1325
+ content: [
1326
+ {
1327
+ type: "text",
1328
+ text: `Tool execution aborted`
1329
+ }
1330
+ ],
1331
+ details: {
1332
+ error: "Aborted"
1333
+ },
1334
+ isError: true
1335
+ };
1336
+ }
1337
+ return {
1338
+ content: [
1339
+ {
1340
+ type: "text",
1341
+ text: `Error: ${error instanceof Error ? error.message : String(error)}`
1342
+ }
1343
+ ],
1344
+ details: {
1345
+ error: String(error)
1346
+ },
1347
+ isError: true
1348
+ };
1349
+ }
1350
+ }
1351
+ };
1352
+ };
1353
+ }
1354
+ function truncateTextForDisplay(text, maxLines = 4, maxChars = 500) {
1355
+ const lines = text.split("\n");
1356
+ if (lines.length <= maxLines && text.length <= maxChars) {
1357
+ return text;
1358
+ }
1359
+ let truncated = lines.slice(0, maxLines).join("\n");
1360
+ if (truncated.length > maxChars) {
1361
+ truncated = truncated.slice(0, maxChars);
1362
+ }
1363
+ const remaining = lines.length - maxLines;
1364
+ if (remaining > 0) {
1365
+ truncated += `
1366
+ ... (${remaining} more lines)`;
1367
+ } else if (text.length > maxChars) {
1368
+ truncated += "...";
1369
+ }
1370
+ return truncated;
1371
+ }
1372
+ function convertMCPResultToAgentResult(result, serverName, toolName) {
1373
+ const content = [];
1374
+ if (result.content && Array.isArray(result.content)) {
1375
+ for (const item of result.content) {
1376
+ if (item.type === "text") {
1377
+ const truncatedText = truncateTextForDisplay(item.text);
1378
+ content.push({ type: "text", text: truncatedText });
1379
+ } else if (item.type === "image") {
1380
+ content.push({
1381
+ type: "image",
1382
+ data: item.data,
1383
+ mimeType: item.mimeType
1384
+ });
1385
+ }
1386
+ }
1387
+ } else if (typeof result === "string") {
1388
+ const truncatedText = truncateTextForDisplay(result);
1389
+ content.push({ type: "text", text: truncatedText });
1390
+ } else {
1391
+ const jsonStr = JSON.stringify(result, null, 2);
1392
+ const truncatedText = truncateTextForDisplay(jsonStr);
1393
+ content.push({ type: "text", text: truncatedText });
1394
+ }
1395
+ return {
1396
+ content,
1397
+ details: result,
1398
+ isError: result.isError || false
1399
+ };
1400
+ }
1401
+ async function registerMCPToolsInRegistry(registry, client, tools) {
1402
+ let registeredCount = 0;
1403
+ for (const tool of tools) {
1404
+ try {
1405
+ const factory = createMCPAgentToolFactory(tool, client);
1406
+ registry.register(
1407
+ {
1408
+ name: `${client.serverName}_${tool.name}`,
1409
+ label: tool.name,
1410
+ category: "mcp",
1411
+ description: `[${client.serverName}] ${tool.description || ""}`
1412
+ },
1413
+ factory
1414
+ );
1415
+ registeredCount++;
1416
+ } catch (error) {
1417
+ console.error(`Failed to register MCP tool ${tool.name}:`, error);
1418
+ }
1419
+ }
1420
+ return registeredCount;
1421
+ }
1422
+ function createMCPToolsMap(tools, client) {
1423
+ const toolMap = /* @__PURE__ */ new Map();
1424
+ for (const tool of tools) {
1425
+ const factory = createMCPAgentToolFactory(tool, client);
1426
+ const namespacedName = `${client.serverName}_${tool.name}`;
1427
+ toolMap.set(namespacedName, factory());
1428
+ }
1429
+ return toolMap;
1430
+ }
1431
+ function createMCPToolsRecord(tools, client) {
1432
+ const toolRecord = {};
1433
+ for (const tool of tools) {
1434
+ const factory = createMCPAgentToolFactory(tool, client);
1435
+ const namespacedName = `${client.serverName}_${tool.name}`;
1436
+ toolRecord[namespacedName] = factory();
1437
+ }
1438
+ return toolRecord;
1439
+ }
1440
+
1441
+ // src/capabilities/kernel/spec.ts
1442
+ function coerceInput(raw) {
1443
+ if (typeof raw === "string") {
1444
+ const trimmed = raw.trim();
1445
+ if (trimmed.startsWith("{") || trimmed.startsWith("[")) {
1446
+ try {
1447
+ return JSON.parse(trimmed);
1448
+ } catch {
1449
+ }
1450
+ }
1451
+ return raw;
1452
+ }
1453
+ if (raw === null || raw === void 0) {
1454
+ return {};
1455
+ }
1456
+ return raw;
1457
+ }
1458
+ function describeThrow(err) {
1459
+ if (err instanceof Error) return err.message;
1460
+ if (typeof err === "string") return err;
1461
+ try {
1462
+ return JSON.stringify(err);
1463
+ } catch {
1464
+ return String(err);
1465
+ }
1466
+ }
1467
+ function projectOutcome(id, result) {
1468
+ const blocks = result.content;
1469
+ let output;
1470
+ if (blocks.length === 1) {
1471
+ const only = blocks[0];
1472
+ output = only.kind === "text" ? only.text : only.value;
1473
+ } else {
1474
+ output = blocks;
1475
+ }
1476
+ return { id, output, isError: result.isError === true };
1477
+ }
1478
+ function defineTool(spec) {
1479
+ return {
1480
+ name: spec.name,
1481
+ // Facade `AgentTool` surface: top-level schema fields + an `execute` adapter
1482
+ // so the tool is usable by the high-level `Agent` as well as the kernel.
1483
+ label: spec.name,
1484
+ description: spec.description,
1485
+ parameters: spec.parameters,
1486
+ async execute(_toolCallId, params, signal) {
1487
+ const ctx = {
1488
+ cwd: process.cwd(),
1489
+ signal: signal ?? new AbortController().signal
1490
+ };
1491
+ try {
1492
+ const result = await spec.run(coerceInput(params), ctx);
1493
+ return {
1494
+ content: result.content.map(
1495
+ (block) => block.kind === "text" ? { type: "text", text: block.text } : { type: "text", text: JSON.stringify(block.value) }
1496
+ ),
1497
+ details: {},
1498
+ isError: result.isError ?? false
1499
+ };
1500
+ } catch (err) {
1501
+ return {
1502
+ content: [{ type: "text", text: `${spec.name} did not finish: ${describeThrow(err)}` }],
1503
+ details: {},
1504
+ isError: true
1505
+ };
1506
+ }
1507
+ },
1508
+ descriptor() {
1509
+ return {
1510
+ name: spec.name,
1511
+ description: spec.description,
1512
+ parameters: spec.parameters
1513
+ };
1514
+ },
1515
+ async invoke(call, ctx) {
1516
+ if (ctx.signal.aborted) {
1517
+ return {
1518
+ id: call.id,
1519
+ output: `Cancelled before ${spec.name} could begin.`,
1520
+ isError: true
1521
+ };
1522
+ }
1523
+ try {
1524
+ const input = coerceInput(call.input);
1525
+ const result = await spec.run(input, ctx);
1526
+ return projectOutcome(call.id, result);
1527
+ } catch (err) {
1528
+ return {
1529
+ id: call.id,
1530
+ output: `${spec.name} did not finish: ${describeThrow(err)}`,
1531
+ isError: true
1532
+ };
1533
+ }
1534
+ }
1535
+ };
1536
+ }
1537
+
1538
+ // src/facade/mcp-core/toolbox-bridge.ts
1539
+ var NOOP_FS_NOT_SUPPORTED = "not supported in MCP-wrapped tools";
1540
+ var noopFs = {
1541
+ readFile: () => {
1542
+ throw new MCPError(NOOP_FS_NOT_SUPPORTED, "CONFIG_ERROR");
1543
+ },
1544
+ writeFile: () => {
1545
+ throw new MCPError(NOOP_FS_NOT_SUPPORTED, "CONFIG_ERROR");
1546
+ },
1547
+ stat: () => {
1548
+ throw new MCPError(NOOP_FS_NOT_SUPPORTED, "CONFIG_ERROR");
1549
+ },
1550
+ readdir: () => {
1551
+ throw new MCPError(NOOP_FS_NOT_SUPPORTED, "CONFIG_ERROR");
1552
+ },
1553
+ mkdir: () => {
1554
+ throw new MCPError(NOOP_FS_NOT_SUPPORTED, "CONFIG_ERROR");
1555
+ },
1556
+ rm: () => {
1557
+ throw new MCPError(NOOP_FS_NOT_SUPPORTED, "CONFIG_ERROR");
1558
+ },
1559
+ exists: () => {
1560
+ throw new MCPError(NOOP_FS_NOT_SUPPORTED, "CONFIG_ERROR");
1561
+ }
1562
+ };
1563
+ var noopShell = {
1564
+ exec: () => {
1565
+ throw new MCPError(NOOP_FS_NOT_SUPPORTED, "CONFIG_ERROR");
1566
+ },
1567
+ spawn: () => {
1568
+ throw new MCPError(NOOP_FS_NOT_SUPPORTED, "CONFIG_ERROR");
1569
+ }
1570
+ };
1571
+ function makeToolContext(signal) {
1572
+ return {
1573
+ cwd: process.cwd(),
1574
+ fs: noopFs,
1575
+ shell: noopShell,
1576
+ signal,
1577
+ budget: { kind: "tail", maxBytes: 5e4 }
1578
+ };
1579
+ }
1580
+ function describeThrow2(err) {
1581
+ if (err instanceof Error) return err.message;
1582
+ if (typeof err === "string") return err;
1583
+ try {
1584
+ return JSON.stringify(err);
1585
+ } catch {
1586
+ return String(err);
1587
+ }
1588
+ }
1589
+ function projectMcpResult(result, logger) {
1590
+ const blocks = [];
1591
+ if (result.content && result.content.length > 0) {
1592
+ for (const block of result.content) {
1593
+ if (block.type === "text") {
1594
+ blocks.push({ kind: "text", text: block.text });
1595
+ } else if (block.type === "image") {
1596
+ const len = typeof block.data === "string" ? block.data.length : 0;
1597
+ blocks.push({ kind: "text", text: `[image ${block.mimeType}, ${len} chars base64]` });
1598
+ logger?.debug(`mcp bridge: image block collapsed to text mention (${block.mimeType})`);
1599
+ } else if (block.type === "resource") {
1600
+ blocks.push({ kind: "text", text: `[resource ${block.resource.uri}]` });
1601
+ } else {
1602
+ blocks.push({ kind: "text", text: "[unknown content block]" });
1603
+ }
1604
+ }
1605
+ }
1606
+ if (result.structuredContent !== void 0) {
1607
+ blocks.push({ kind: "json", value: result.structuredContent });
1608
+ }
1609
+ const content = blocks.length > 0 ? blocks : [{ kind: "text", text: "(no content)" }];
1610
+ return {
1611
+ content,
1612
+ ...result.isError === true ? { isError: true } : {}
1613
+ };
1614
+ }
1615
+ function makeRunner(client, remoteName, logger) {
1616
+ return async (input, ctx) => {
1617
+ if (ctx.signal.aborted) {
1618
+ return {
1619
+ content: [{ kind: "text", text: "Cancelled before tool could start." }],
1620
+ isError: true
1621
+ };
1622
+ }
1623
+ try {
1624
+ const args = input ?? {};
1625
+ const result = await client.callTool(remoteName, args);
1626
+ return projectMcpResult(result, logger);
1627
+ } catch (err) {
1628
+ const wrapped = err instanceof MCPError ? err : createServerError(describeThrow2(err), client.serverName);
1629
+ logger?.error(`mcp bridge: tool "${remoteName}" failed: ${wrapped.message}`, wrapped);
1630
+ return {
1631
+ content: [{ kind: "text", text: `MCP tool failed: ${wrapped.message}` }],
1632
+ isError: true
1633
+ };
1634
+ }
1635
+ };
1636
+ }
1637
+ async function mcpClientToToolBox(client, options = {}) {
1638
+ const prefix = options.namePrefix ?? "mcp";
1639
+ const logger = options.logger;
1640
+ const tools = await client.listTools();
1641
+ const filtered = typeof options.filter === "function" ? tools.filter((t) => options.filter(t)) : tools;
1642
+ const byName = /* @__PURE__ */ new Map();
1643
+ for (const tool of filtered) {
1644
+ const remoteName = tool.name;
1645
+ const prefixed = `${prefix}__${remoteName}`;
1646
+ const description = tool.description && tool.description.length > 0 ? tool.description : `<tool "${remoteName}" from MCP server "${client.serverName}">`;
1647
+ const parameters = tool.inputSchema;
1648
+ const def = defineTool({
1649
+ name: prefixed,
1650
+ description,
1651
+ parameters,
1652
+ run: makeRunner(client, remoteName, logger)
1653
+ });
1654
+ byName.set(prefixed, def);
1655
+ }
1656
+ const runner = {
1657
+ async run(call, signal) {
1658
+ const def = byName.get(call.name);
1659
+ if (!def) {
1660
+ return {
1661
+ id: call.id,
1662
+ output: `No tool "${call.name}" on MCP server "${client.serverName}".`,
1663
+ isError: true
1664
+ };
1665
+ }
1666
+ return def.invoke(call, makeToolContext(signal));
1667
+ }
1668
+ };
1669
+ return {
1670
+ descriptors() {
1671
+ return Array.from(byName.values()).map((d) => d.descriptor());
1672
+ },
1673
+ runner
1674
+ };
1675
+ }
1676
+
1677
+ // src/facade/mcp-core/oauth/index.ts
1678
+ var oauth_exports = {};
1679
+ __export(oauth_exports, {
1680
+ auth: () => auth,
1681
+ clearMcpOAuthState: () => clearMcpOAuthState,
1682
+ createMcpOAuthProvider: () => createMcpOAuthProvider,
1683
+ credentialsPath: () => credentialsPath,
1684
+ discoverOAuthServerInfo: () => discoverOAuthServerInfo,
1685
+ exchangeAuthorization: () => exchangeAuthorization,
1686
+ extractWWWAuthenticateParams: () => extractWWWAuthenticateParams,
1687
+ openBrowser: () => openBrowser,
1688
+ readMcpOAuthState: () => readMcpOAuthState,
1689
+ refreshAuthorization: () => refreshAuthorization,
1690
+ registerClient: () => registerClient,
1691
+ resolveCredentialsDir: () => resolveCredentialsDir,
1692
+ startAuthorization: () => startAuthorization,
1693
+ startOAuthCallbackServer: () => startOAuthCallbackServer,
1694
+ waitForAuthorizationCode: () => waitForAuthorizationCode,
1695
+ writeMcpOAuthState: () => writeMcpOAuthState
1696
+ });
1697
+
1698
+ // src/facade/mcp-core/oauth/flow.ts
1699
+ import { createServer } from "node:http";
1700
+ var CALLBACK_TIMEOUT_MS = 5 * 60 * 1e3;
1701
+ var SUCCESS_HTML = '<!doctype html><html><body style="font-family:system-ui;padding:2rem"><h1>Authorization complete</h1><p>You can close this tab and return to your terminal.</p></body></html>';
1702
+ var ERROR_HTML = (msg) => `<!doctype html><html><body style="font-family:system-ui;padding:2rem"><h1>Authorization failed</h1><pre>${escapeHtml(msg)}</pre></body></html>`;
1703
+ function escapeHtml(s) {
1704
+ return s.replace(/&/g, "&amp;").replace(/</g, "&lt;").replace(/>/g, "&gt;").replace(/"/g, "&quot;");
1705
+ }
1706
+ async function startOAuthCallbackServer(options) {
1707
+ const timeoutMs = options?.timeoutMs ?? CALLBACK_TIMEOUT_MS;
1708
+ const logger = options?.logger;
1709
+ let settled = false;
1710
+ let timer;
1711
+ let resolveCode;
1712
+ let rejectCode;
1713
+ const codePromise = new Promise((res, rej) => {
1714
+ resolveCode = res;
1715
+ rejectCode = rej;
1716
+ });
1717
+ codePromise.catch(() => {
1718
+ });
1719
+ let expectedState;
1720
+ const clearTimer = () => {
1721
+ if (timer !== void 0) {
1722
+ clearTimeout(timer);
1723
+ timer = void 0;
1724
+ }
1725
+ };
1726
+ const settleReject = (err) => {
1727
+ if (settled) return;
1728
+ settled = true;
1729
+ clearTimer();
1730
+ try {
1731
+ server.close();
1732
+ } catch {
1733
+ }
1734
+ rejectCode(err);
1735
+ };
1736
+ const settleResolve = (code) => {
1737
+ if (settled) return;
1738
+ settled = true;
1739
+ clearTimer();
1740
+ resolveCode(code);
1741
+ setTimeout(() => {
1742
+ try {
1743
+ server.close();
1744
+ } catch {
1745
+ }
1746
+ }, 50);
1747
+ };
1748
+ const server = createServer((req, res) => {
1749
+ if (settled) {
1750
+ res.statusCode = 410;
1751
+ res.end("already used");
1752
+ return;
1753
+ }
1754
+ handleRequest(
1755
+ req,
1756
+ res,
1757
+ expectedState,
1758
+ (code) => settleResolve(code),
1759
+ (err) => settleReject(err),
1760
+ logger
1761
+ );
1762
+ });
1763
+ await new Promise((resolveListen, rejectListen) => {
1764
+ server.once("error", rejectListen);
1765
+ server.listen(0, "127.0.0.1", () => resolveListen());
1766
+ });
1767
+ const address = server.address();
1768
+ if (!address) {
1769
+ server.close();
1770
+ throw new Error("oauth-callback: server bound to no address");
1771
+ }
1772
+ const port = address.port;
1773
+ const redirectUri = `http://127.0.0.1:${port}/callback`;
1774
+ const close = () => {
1775
+ if (!settled) {
1776
+ settleReject(new Error("oauth-callback: closed before browser login completed"));
1777
+ } else {
1778
+ clearTimer();
1779
+ try {
1780
+ server.close();
1781
+ } catch {
1782
+ }
1783
+ }
1784
+ };
1785
+ return {
1786
+ redirectUri,
1787
+ port,
1788
+ waitForCode(state) {
1789
+ expectedState = state;
1790
+ logger?.debug(`oauth-callback: waiting for browser at ${redirectUri}`);
1791
+ if (!settled && timer === void 0) {
1792
+ timer = setTimeout(() => {
1793
+ settleReject(
1794
+ new Error(
1795
+ `oauth-callback: timed out after ${timeoutMs}ms waiting for browser login at ${redirectUri}`
1796
+ )
1797
+ );
1798
+ }, timeoutMs);
1799
+ timer.unref();
1800
+ }
1801
+ return codePromise;
1802
+ },
1803
+ close
1804
+ };
1805
+ }
1806
+ async function waitForAuthorizationCode(expectedState, options) {
1807
+ const server = await startOAuthCallbackServer(options);
1808
+ const code = await server.waitForCode(expectedState);
1809
+ return {
1810
+ code,
1811
+ redirectUri: server.redirectUri,
1812
+ port: server.port,
1813
+ close: () => server.close()
1814
+ };
1815
+ }
1816
+ function handleRequest(req, res, expectedState, onCode, onError, logger) {
1817
+ const url = new URL(req.url ?? "/", "http://127.0.0.1");
1818
+ if (url.pathname !== "/callback") {
1819
+ if (url.pathname === "/favicon.ico") {
1820
+ res.statusCode = 404;
1821
+ res.end();
1822
+ return;
1823
+ }
1824
+ res.statusCode = 404;
1825
+ res.end("not found");
1826
+ return;
1827
+ }
1828
+ const errorParam = url.searchParams.get("error");
1829
+ if (errorParam) {
1830
+ const desc = url.searchParams.get("error_description") ?? "";
1831
+ logger?.warn(`oauth-callback: server returned error ${errorParam} ${desc}`);
1832
+ res.statusCode = 400;
1833
+ res.setHeader("content-type", "text/html; charset=utf-8");
1834
+ res.end(ERROR_HTML(`${errorParam}${desc ? ": " + desc : ""}`));
1835
+ onError(new Error(`OAuth provider returned error: ${errorParam}${desc ? " \u2014 " + desc : ""}`));
1836
+ return;
1837
+ }
1838
+ const code = url.searchParams.get("code");
1839
+ const state = url.searchParams.get("state");
1840
+ if (!code) {
1841
+ res.statusCode = 400;
1842
+ res.setHeader("content-type", "text/html; charset=utf-8");
1843
+ res.end(ERROR_HTML("missing code"));
1844
+ return;
1845
+ }
1846
+ if (expectedState && state && state !== expectedState) {
1847
+ res.statusCode = 400;
1848
+ res.setHeader("content-type", "text/html; charset=utf-8");
1849
+ res.end(ERROR_HTML("state mismatch \u2014 possible CSRF"));
1850
+ onError(new Error("OAuth callback state did not match \u2014 refusing to exchange code"));
1851
+ return;
1852
+ }
1853
+ res.statusCode = 200;
1854
+ res.setHeader("content-type", "text/html; charset=utf-8");
1855
+ res.end(SUCCESS_HTML);
1856
+ logger?.debug(`oauth-callback: received authorization code (${code.length} chars)`);
1857
+ onCode(code);
1858
+ }
1859
+ async function openBrowser(url) {
1860
+ try {
1861
+ const mod = await import("node:child_process").catch(() => null);
1862
+ if (!mod) return false;
1863
+ const cmd = platformOpenCommand(url);
1864
+ if (!cmd) return false;
1865
+ const child = mod.spawn(cmd.cmd, cmd.args, { detached: true, stdio: "ignore" });
1866
+ child.unref();
1867
+ return true;
1868
+ } catch {
1869
+ return false;
1870
+ }
1871
+ }
1872
+ function platformOpenCommand(url) {
1873
+ switch (process.platform) {
1874
+ case "darwin":
1875
+ return { cmd: "open", args: [url] };
1876
+ case "win32":
1877
+ return { cmd: "rundll32", args: ["url.dll,FileProtocolHandler", url] };
1878
+ default:
1879
+ return { cmd: "xdg-open", args: [url] };
1880
+ }
1881
+ }
1882
+
1883
+ // src/facade/mcp-core/oauth/token-store.ts
1884
+ import { chmodSync, existsSync as existsSync2, mkdirSync as mkdirSync2, readFileSync as readFileSync2, renameSync, writeFileSync as writeFileSync2 } from "node:fs";
1885
+ import { dirname as dirname2, join as join2 } from "node:path";
1886
+ function defaultCredentialsDir() {
1887
+ const xdg = process.env.XDG_CONFIG_HOME;
1888
+ const home = process.env.HOME ?? process.env.USERPROFILE ?? "";
1889
+ if (xdg && xdg.length > 0) return join2(xdg, "indusagi", "credentials", "mcp");
1890
+ if (home.length > 0) return join2(home, ".config", "indusagi", "credentials", "mcp");
1891
+ return join2(process.cwd(), ".indusagi", "credentials", "mcp");
1892
+ }
1893
+ function resolveCredentialsDir(override) {
1894
+ return override && override.length > 0 ? override : defaultCredentialsDir();
1895
+ }
1896
+ function credentialsPath(credentialsDir, id) {
1897
+ const safe = id.replace(/[^a-zA-Z0-9._-]/g, "-");
1898
+ return join2(credentialsDir, `${safe}.json`);
1899
+ }
1900
+ function readMcpOAuthState(credentialsDir, id) {
1901
+ const path = credentialsPath(credentialsDir, id);
1902
+ if (!existsSync2(path)) return void 0;
1903
+ let raw;
1904
+ try {
1905
+ raw = readFileSync2(path, "utf8");
1906
+ } catch (e) {
1907
+ return void 0;
1908
+ }
1909
+ let parsed;
1910
+ try {
1911
+ parsed = JSON.parse(raw);
1912
+ } catch (e) {
1913
+ return void 0;
1914
+ }
1915
+ if (typeof parsed !== "object" || parsed === null) return void 0;
1916
+ return { id, updatedAt: Date.now(), ...parsed };
1917
+ }
1918
+ function writeMcpOAuthState(credentialsDir, state) {
1919
+ const path = credentialsPath(credentialsDir, state.id);
1920
+ mkdirSync2(dirname2(path), { recursive: true });
1921
+ const tmp = `${path}.tmp-${process.pid}-${Date.now()}`;
1922
+ const json = JSON.stringify({ ...state, updatedAt: Date.now() }, null, 2);
1923
+ writeFileSync2(tmp, json, { mode: 384 });
1924
+ renameSync(tmp, path);
1925
+ try {
1926
+ chmodSync(path, 384);
1927
+ } catch {
1928
+ }
1929
+ }
1930
+ function clearMcpOAuthState(credentialsDir, id) {
1931
+ const path = credentialsPath(credentialsDir, id);
1932
+ try {
1933
+ const fs = __require("node:fs");
1934
+ fs.rmSync(path, { force: true });
1935
+ } catch {
1936
+ }
1937
+ }
1938
+
1939
+ // src/facade/mcp-core/oauth/provider.ts
1940
+ function randomState() {
1941
+ const bytes = new Uint8Array(16);
1942
+ crypto.getRandomValues(bytes);
1943
+ return Array.from(bytes, (b) => b.toString(16).padStart(2, "0")).join("");
1944
+ }
1945
+ function toSdkTokens(t) {
1946
+ return {
1947
+ access_token: t.access_token,
1948
+ refresh_token: t.refresh_token,
1949
+ scope: t.scope,
1950
+ token_type: t.token_type ?? "Bearer",
1951
+ expires_in: t.expires_at !== void 0 ? Math.max(0, Math.floor((t.expires_at - Date.now()) / 1e3)) : void 0
1952
+ };
1953
+ }
1954
+ function toSdkClientInfo(c) {
1955
+ return {
1956
+ client_id: c.client_id,
1957
+ client_secret: c.client_secret,
1958
+ client_id_issued_at: c.client_id_issued_at,
1959
+ client_secret_expires_at: c.client_secret_expires_at
1960
+ };
1961
+ }
1962
+ async function createMcpOAuthProvider(config) {
1963
+ const credentialsDir = resolveCredentialsDir(config.credentialsDir);
1964
+ const openBrowserEnabled = config.openBrowser ?? Boolean(process.env.CI !== "true" && process.stdout.isTTY);
1965
+ let callback;
1966
+ let redirectUrl;
1967
+ if (config.redirectUrl) {
1968
+ redirectUrl = config.redirectUrl;
1969
+ } else {
1970
+ callback = await startOAuthCallbackServer({
1971
+ logger: config.logger ? { debug: config.logger.debug, warn: config.logger.warn } : void 0
1972
+ });
1973
+ redirectUrl = callback.redirectUri;
1974
+ }
1975
+ const clientMetadata = {
1976
+ client_name: config.clientMetadata?.client_name ?? "indusagi-mcp-client",
1977
+ client_uri: config.clientMetadata?.client_uri,
1978
+ logo_uri: config.clientMetadata?.logo_uri,
1979
+ contacts: config.clientMetadata?.contacts ? [...config.clientMetadata.contacts] : void 0,
1980
+ tos_uri: config.clientMetadata?.tos_uri,
1981
+ policy_uri: config.clientMetadata?.policy_uri,
1982
+ redirect_uris: config.clientMetadata?.redirect_uris ? [...config.clientMetadata.redirect_uris] : [redirectUrl],
1983
+ token_endpoint_auth_method: config.clientMetadata?.token_endpoint_auth_method ?? "none",
1984
+ grant_types: config.clientMetadata?.grant_types ? [...config.clientMetadata.grant_types] : ["authorization_code", "refresh_token"],
1985
+ response_types: config.clientMetadata?.response_types ? [...config.clientMetadata.response_types] : ["code"],
1986
+ scope: config.clientMetadata?.scope
1987
+ };
1988
+ let lastAuthUrl;
1989
+ let lastState;
1990
+ let pendingCode;
1991
+ const provider = {
1992
+ id: config.id,
1993
+ credentialsDir,
1994
+ redirectUrl,
1995
+ get clientMetadata() {
1996
+ return clientMetadata;
1997
+ },
1998
+ state() {
1999
+ const s = randomState();
2000
+ lastState = s;
2001
+ return s;
2002
+ },
2003
+ clientInformation() {
2004
+ const state = readMcpOAuthState(credentialsDir, config.id);
2005
+ return state?.client ? toSdkClientInfo(state.client) : void 0;
2006
+ },
2007
+ saveClientInformation(client) {
2008
+ const state = readMcpOAuthState(credentialsDir, config.id) ?? {
2009
+ id: config.id,
2010
+ updatedAt: Date.now()
2011
+ };
2012
+ writeMcpOAuthState(credentialsDir, {
2013
+ ...state,
2014
+ client: {
2015
+ client_id: client.client_id,
2016
+ client_secret: client.client_secret,
2017
+ client_id_issued_at: client.client_id_issued_at,
2018
+ client_secret_expires_at: client.client_secret_expires_at
2019
+ }
2020
+ });
2021
+ },
2022
+ tokens() {
2023
+ const state = readMcpOAuthState(credentialsDir, config.id);
2024
+ return state?.tokens ? toSdkTokens(state.tokens) : void 0;
2025
+ },
2026
+ saveTokens(tokens) {
2027
+ const state = readMcpOAuthState(credentialsDir, config.id) ?? {
2028
+ id: config.id,
2029
+ updatedAt: Date.now()
2030
+ };
2031
+ writeMcpOAuthState(credentialsDir, {
2032
+ ...state,
2033
+ tokens: {
2034
+ access_token: tokens.access_token,
2035
+ refresh_token: tokens.refresh_token,
2036
+ scope: tokens.scope,
2037
+ token_type: tokens.token_type,
2038
+ expires_at: tokens.expires_in !== void 0 ? Date.now() + Math.trunc(tokens.expires_in) * 1e3 : void 0
2039
+ }
2040
+ });
2041
+ },
2042
+ async redirectToAuthorization(authorizationUrl) {
2043
+ const url = authorizationUrl.toString();
2044
+ lastAuthUrl = url;
2045
+ try {
2046
+ lastState = new URL(url).searchParams.get("state") ?? lastState;
2047
+ } catch {
2048
+ }
2049
+ const prompt = `oauth: open this URL in your browser to authorize Zoho MCP:
2050
+ ${url}`;
2051
+ config.logger?.info?.(prompt);
2052
+ config.logger?.debug?.(prompt);
2053
+ console.error(`
2054
+ [zoho oauth] Authorize in browser:
2055
+ ${url}
2056
+ `);
2057
+ let opened = false;
2058
+ if (openBrowserEnabled) opened = await openBrowser(url);
2059
+ if (!opened) {
2060
+ const tip = "oauth: could not auto-open browser. Visit the URL above manually.";
2061
+ config.logger?.info?.(tip);
2062
+ config.logger?.debug?.(tip);
2063
+ console.error(`[zoho oauth] ${tip}`);
2064
+ } else {
2065
+ config.logger?.debug?.("oauth: browser open launched");
2066
+ }
2067
+ },
2068
+ saveCodeVerifier(verifier) {
2069
+ const state = readMcpOAuthState(credentialsDir, config.id) ?? {
2070
+ id: config.id,
2071
+ updatedAt: Date.now()
2072
+ };
2073
+ writeMcpOAuthState(credentialsDir, { ...state, codeVerifier: verifier });
2074
+ },
2075
+ codeVerifier() {
2076
+ const state = readMcpOAuthState(credentialsDir, config.id);
2077
+ const verifier = state?.codeVerifier;
2078
+ if (!verifier) throw new Error("No PKCE code verifier saved");
2079
+ return verifier;
2080
+ },
2081
+ invalidateCredentials(scope) {
2082
+ if (scope === "all") {
2083
+ clearMcpOAuthState(credentialsDir, config.id);
2084
+ return;
2085
+ }
2086
+ const state = readMcpOAuthState(credentialsDir, config.id);
2087
+ if (!state) return;
2088
+ const next = { ...state };
2089
+ if (scope === "tokens" || scope === "verifier") next.tokens = void 0;
2090
+ if (scope === "verifier") next.codeVerifier = void 0;
2091
+ if (scope === "discovery") {
2092
+ next.resourceMetadata = void 0;
2093
+ next.authServerMetadata = void 0;
2094
+ }
2095
+ writeMcpOAuthState(credentialsDir, next);
2096
+ },
2097
+ async waitForAuthorizationCode() {
2098
+ if (pendingCode) return pendingCode;
2099
+ if (!callback) {
2100
+ throw new Error(
2101
+ "oauth: no local callback server (custom redirectUrl set). Pass the authorization code via finishAuth yourself."
2102
+ );
2103
+ }
2104
+ config.logger?.info("oauth: waiting for browser authorization\u2026");
2105
+ console.error("[zoho oauth] Waiting for browser authorization\u2026");
2106
+ const code = await callback.waitForCode(lastState);
2107
+ pendingCode = code;
2108
+ return code;
2109
+ },
2110
+ dispose() {
2111
+ callback?.close();
2112
+ callback = void 0;
2113
+ },
2114
+ lastAuthorizationUrl() {
2115
+ return lastAuthUrl;
2116
+ }
2117
+ };
2118
+ return provider;
2119
+ }
2120
+
2121
+ // src/facade/mcp-core/oauth/index.ts
2122
+ import {
2123
+ auth,
2124
+ discoverOAuthServerInfo,
2125
+ startAuthorization,
2126
+ exchangeAuthorization,
2127
+ refreshAuthorization,
2128
+ registerClient,
2129
+ extractWWWAuthenticateParams
2130
+ } from "@modelcontextprotocol/sdk/client/auth.js";
2131
+
2132
+ // src/facade/mcp-core/server.ts
2133
+ var MCPServer = class {
2134
+ constructor(options) {
2135
+ this.options = options;
2136
+ this.name = options.name;
2137
+ this.version = options.version || "1.0.0";
2138
+ for (const tool of options.tools) {
2139
+ const converted = this.convertTool(tool);
2140
+ this.tools.set(converted.name, converted);
2141
+ }
2142
+ console.error(`[MCP Server] Initialized "${this.name}" v${this.version} with ${this.tools.size} tools`);
2143
+ }
2144
+ options;
2145
+ tools = /* @__PURE__ */ new Map();
2146
+ buffer = "";
2147
+ isConnected = false;
2148
+ /** Server name */
2149
+ name;
2150
+ /** Server version */
2151
+ version;
2152
+ // ========================================================================
2153
+ // Lifecycle
2154
+ // ========================================================================
2155
+ /**
2156
+ * Start the server using stdio transport.
2157
+ *
2158
+ * This is typically used when running the server as a subprocess
2159
+ * that MCP clients (like Claude Desktop) spawn.
2160
+ */
2161
+ async startStdio() {
2162
+ this.isConnected = true;
2163
+ console.error(`[MCP Server] Starting stdio transport`);
2164
+ process.stdin.setEncoding("utf8");
2165
+ process.stdin.on("data", (chunk) => {
2166
+ this.buffer += chunk;
2167
+ this.processBuffer();
2168
+ });
2169
+ process.stdin.on("end", () => {
2170
+ console.error(`[MCP Server] Stdin closed, shutting down`);
2171
+ this.isConnected = false;
2172
+ process.exit(0);
2173
+ });
2174
+ return new Promise(() => {
2175
+ });
2176
+ }
2177
+ /**
2178
+ * Stop the server.
2179
+ */
2180
+ async stop() {
2181
+ this.isConnected = false;
2182
+ console.error(`[MCP Server] Stopped`);
2183
+ }
2184
+ // ========================================================================
2185
+ // Tool Management
2186
+ // ========================================================================
2187
+ /**
2188
+ * Add a tool to the server.
2189
+ */
2190
+ addTool(tool) {
2191
+ const converted = this.convertTool(tool);
2192
+ this.tools.set(converted.name, converted);
2193
+ console.error(`[MCP Server] Added tool: ${converted.name}`);
2194
+ }
2195
+ /**
2196
+ * Remove a tool from the server.
2197
+ */
2198
+ removeTool(name) {
2199
+ const result = this.tools.delete(name);
2200
+ if (result) {
2201
+ console.error(`[MCP Server] Removed tool: ${name}`);
2202
+ }
2203
+ return result;
2204
+ }
2205
+ /**
2206
+ * List all available tools.
2207
+ */
2208
+ listTools() {
2209
+ return Array.from(this.tools.values());
2210
+ }
2211
+ // ========================================================================
2212
+ // Private Methods
2213
+ // ========================================================================
2214
+ convertTool(tool) {
2215
+ const inputSchema = this.typeBoxToJsonSchema(tool.parameters);
2216
+ return {
2217
+ name: tool.name,
2218
+ description: tool.description || tool.label,
2219
+ inputSchema,
2220
+ execute: async (args) => {
2221
+ const result = await tool.execute(
2222
+ `mcp_${Date.now()}`,
2223
+ args,
2224
+ void 0,
2225
+ void 0
2226
+ );
2227
+ return result;
2228
+ }
2229
+ };
2230
+ }
2231
+ typeBoxToJsonSchema(schema) {
2232
+ if (!schema) {
2233
+ return { type: "object", properties: {} };
2234
+ }
2235
+ if (schema.type || schema.properties || schema.$schema) {
2236
+ return schema;
2237
+ }
2238
+ const jsonSchema = schema.toJSONSchema?.() || schema;
2239
+ return {
2240
+ type: "object",
2241
+ properties: jsonSchema.properties || {},
2242
+ required: jsonSchema.required || []
2243
+ };
2244
+ }
2245
+ processBuffer() {
2246
+ const lines = this.buffer.split("\n");
2247
+ this.buffer = lines.pop() || "";
2248
+ for (const line of lines) {
2249
+ const trimmed = line.trim();
2250
+ if (!trimmed) continue;
2251
+ try {
2252
+ const message = JSON.parse(trimmed);
2253
+ this.handleMessage(message);
2254
+ } catch (error) {
2255
+ console.error(`[MCP Server] Failed to parse message: ${trimmed}`);
2256
+ }
2257
+ }
2258
+ }
2259
+ async handleMessage(message) {
2260
+ console.error(`[MCP Server] Received: ${message.method || `response to ${message.id}`}`);
2261
+ try {
2262
+ if (message.method) {
2263
+ const response = await this.handleRequest(message);
2264
+ this.sendResponse(message.id, response);
2265
+ }
2266
+ } catch (error) {
2267
+ console.error(`[MCP Server] Error handling message:`, error);
2268
+ if (message.id !== void 0) {
2269
+ this.sendError(message.id, error);
2270
+ }
2271
+ }
2272
+ }
2273
+ async handleRequest(message) {
2274
+ switch (message.method) {
2275
+ case "initialize":
2276
+ return this.handleInitialize(message.params);
2277
+ case "tools/list":
2278
+ return this.handleToolsList();
2279
+ case "tools/call":
2280
+ return this.handleToolsCall(message.params);
2281
+ case "resources/list":
2282
+ return { resources: [] };
2283
+ case "prompts/list":
2284
+ return { prompts: [] };
2285
+ default:
2286
+ throw new MCPError(
2287
+ `Unknown method: ${message.method}`,
2288
+ "PROTOCOL_ERROR" /* PROTOCOL_ERROR */
2289
+ );
2290
+ }
2291
+ }
2292
+ handleInitialize(params) {
2293
+ console.error(`[MCP Server] Initialize from client: ${params?.clientInfo?.name || "unknown"}`);
2294
+ return {
2295
+ protocolVersion: "2024-11-05",
2296
+ serverInfo: {
2297
+ name: this.name,
2298
+ version: this.version
2299
+ },
2300
+ capabilities: {
2301
+ tools: {}
2302
+ }
2303
+ };
2304
+ }
2305
+ handleToolsList() {
2306
+ const tools = Array.from(this.tools.values()).map((tool) => ({
2307
+ name: tool.name,
2308
+ description: tool.description,
2309
+ inputSchema: tool.inputSchema
2310
+ }));
2311
+ return { tools };
2312
+ }
2313
+ async handleToolsCall(params) {
2314
+ const { name, arguments: args } = params;
2315
+ const tool = this.tools.get(name);
2316
+ if (!tool) {
2317
+ return {
2318
+ content: [{ type: "text", text: `Unknown tool: ${name}` }],
2319
+ isError: true
2320
+ };
2321
+ }
2322
+ try {
2323
+ console.error(`[MCP Server] Executing tool: ${name}`);
2324
+ const result = await tool.execute(args || {});
2325
+ if (result && typeof result === "object" && "content" in result) {
2326
+ const agentResult = result;
2327
+ const content = [];
2328
+ for (const item of agentResult.content || []) {
2329
+ if (item.type === "text") {
2330
+ content.push({ type: "text", text: item.text });
2331
+ } else if (item.type === "image") {
2332
+ content.push({
2333
+ type: "text",
2334
+ text: `[Image: ${item.mimeType}, ${item.data.length} bytes]`
2335
+ });
2336
+ }
2337
+ }
2338
+ return {
2339
+ content,
2340
+ isError: agentResult.isError || false
2341
+ };
2342
+ }
2343
+ return {
2344
+ content: [
2345
+ {
2346
+ type: "text",
2347
+ text: typeof result === "string" ? result : JSON.stringify(result, null, 2)
2348
+ }
2349
+ ]
2350
+ };
2351
+ } catch (error) {
2352
+ console.error(`[MCP Server] Tool execution failed:`, error);
2353
+ return {
2354
+ content: [
2355
+ {
2356
+ type: "text",
2357
+ text: `Error: ${error instanceof Error ? error.message : String(error)}`
2358
+ }
2359
+ ],
2360
+ isError: true
2361
+ };
2362
+ }
2363
+ }
2364
+ sendResponse(id, result) {
2365
+ const response = {
2366
+ jsonrpc: "2.0",
2367
+ id,
2368
+ result
2369
+ };
2370
+ process.stdout.write(JSON.stringify(response) + "\n");
2371
+ }
2372
+ sendError(id, error) {
2373
+ const response = {
2374
+ jsonrpc: "2.0",
2375
+ id,
2376
+ error: {
2377
+ code: -32e3,
2378
+ message: error instanceof Error ? error.message : String(error)
2379
+ }
2380
+ };
2381
+ process.stdout.write(JSON.stringify(response) + "\n");
2382
+ }
2383
+ };
2384
+ function createMCPServer(options) {
2385
+ return new MCPServer(options);
2386
+ }
2387
+
2388
+ // src/facade/mcp-core/index.ts
2389
+ async function initializeMCP(registry, cwd = process.cwd()) {
2390
+ const configs = loadMCPConfig(cwd);
2391
+ if (configs.length === 0) {
2392
+ console.log("[MCP] No servers configured");
2393
+ return { pool: new MCPClientPool({ servers: [] }), toolCount: 0 };
2394
+ }
2395
+ const pool = new MCPClientPool({ servers: configs });
2396
+ await pool.connectAll();
2397
+ let totalTools = 0;
2398
+ for (const client of pool.getAllClients()) {
2399
+ try {
2400
+ const tools = await client.listTools();
2401
+ const count = await registerMCPToolsInRegistry(registry, client, tools);
2402
+ totalTools += count;
2403
+ console.log(`[MCP] Registered ${count} tools from ${client.serverName}`);
2404
+ } catch (error) {
2405
+ console.error(`[MCP] Failed to register tools from ${client.serverName}:`, error);
2406
+ }
2407
+ }
2408
+ return { pool, toolCount: totalTools };
2409
+ }
2410
+ export {
2411
+ EXAMPLE_CONFIG,
2412
+ MCPClient,
2413
+ MCPClientPool,
2414
+ MCPError,
2415
+ MCPErrorCode,
2416
+ MCPServer,
2417
+ applyPassthrough,
2418
+ convertMCPInputSchema,
2419
+ convertMCPOutputSchema,
2420
+ createConfigError,
2421
+ createConnectionError,
2422
+ createDefaultConfig,
2423
+ createInvalidParametersError,
2424
+ createMCPAgentToolFactory,
2425
+ createMCPServer,
2426
+ createMCPToolsMap,
2427
+ createMCPToolsRecord,
2428
+ createNotConnectedError,
2429
+ createSchemaConversionError,
2430
+ createServerError,
2431
+ createTimeoutError,
2432
+ createToolNotFoundError,
2433
+ ensureProjectConfigDir,
2434
+ ensureUserConfigDir,
2435
+ getProjectConfigPath,
2436
+ getUserConfigPath,
2437
+ initializeMCP,
2438
+ isMCPError,
2439
+ isSessionError,
2440
+ jsonSchemaToTypeBox,
2441
+ loadMCPConfig,
2442
+ mcpClientToToolBox,
2443
+ oauth_exports as oauth,
2444
+ registerMCPToolsInRegistry,
2445
+ saveConfig,
2446
+ saveProjectConfig,
2447
+ saveUserConfig
2448
+ };