polyrob 0.5.0__py3-none-any.whl

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 (745) hide show
  1. agents/README.md +453 -0
  2. agents/__init__.py +164 -0
  3. agents/base_agent.py +743 -0
  4. agents/personality/character.py +119 -0
  5. agents/personality/character_manager.py +309 -0
  6. agents/personality/characters/rob.character.json +56 -0
  7. agents/personality/characters/trump.character.json +63 -0
  8. agents/personality/persona_render.py +78 -0
  9. agents/personality/persona_resolver.py +115 -0
  10. agents/prompt/__init__.py +58 -0
  11. agents/prompt/base_prompt.py +92 -0
  12. agents/prompt/system.py +417 -0
  13. agents/task/README_PATH_MANAGEMENT.md +141 -0
  14. agents/task/__init__.py +162 -0
  15. agents/task/agent/__init__.py +70 -0
  16. agents/task/agent/agent_state.py +408 -0
  17. agents/task/agent/async_delegation.py +274 -0
  18. agents/task/agent/autonomy_state.py +275 -0
  19. agents/task/agent/conversation.py +75 -0
  20. agents/task/agent/core/__init__.py +6 -0
  21. agents/task/agent/core/aux_metering.py +61 -0
  22. agents/task/agent/core/background_review.py +157 -0
  23. agents/task/agent/core/construction.py +1179 -0
  24. agents/task/agent/core/conversational_exit.py +49 -0
  25. agents/task/agent/core/correspondent_gate.py +227 -0
  26. agents/task/agent/core/curator.py +246 -0
  27. agents/task/agent/core/episodic_digest.py +103 -0
  28. agents/task/agent/core/error_recovery.py +480 -0
  29. agents/task/agent/core/history_io.py +257 -0
  30. agents/task/agent/core/llm_provisioning.py +287 -0
  31. agents/task/agent/core/llm_runner.py +547 -0
  32. agents/task/agent/core/logging_io.py +276 -0
  33. agents/task/agent/core/loop_detection.py +262 -0
  34. agents/task/agent/core/memory_prefetch.py +325 -0
  35. agents/task/agent/core/memory_writer.py +667 -0
  36. agents/task/agent/core/model_introspection.py +82 -0
  37. agents/task/agent/core/model_swap.py +177 -0
  38. agents/task/agent/core/next_action_internal.py +1331 -0
  39. agents/task/agent/core/output_validation.py +303 -0
  40. agents/task/agent/core/project_context.py +272 -0
  41. agents/task/agent/core/resources.py +93 -0
  42. agents/task/agent/core/result_processing.py +389 -0
  43. agents/task/agent/core/run_loop.py +661 -0
  44. agents/task/agent/core/safety_lifecycle.py +228 -0
  45. agents/task/agent/core/secret_guard.py +293 -0
  46. agents/task/agent/core/self_wake.py +280 -0
  47. agents/task/agent/core/session_metadata.py +104 -0
  48. agents/task/agent/core/step.py +781 -0
  49. agents/task/agent/core/step_execution.py +398 -0
  50. agents/task/agent/core/step_telemetry.py +222 -0
  51. agents/task/agent/core/test_aux_metering.py +50 -0
  52. agents/task/agent/core/test_billing_failover.py +68 -0
  53. agents/task/agent/core/test_fatal_error_classifier.py +38 -0
  54. agents/task/agent/core/test_judge_validation.py +275 -0
  55. agents/task/agent/core/test_model_swap.py +190 -0
  56. agents/task/agent/core/test_reflection_offload.py +54 -0
  57. agents/task/agent/core/turn_input.py +8 -0
  58. agents/task/agent/core/untrusted_wrap.py +103 -0
  59. agents/task/agent/core/user_ingress.py +228 -0
  60. agents/task/agent/hitl_manager.py +396 -0
  61. agents/task/agent/log_sanitize.py +36 -0
  62. agents/task/agent/message_manager/config.py +97 -0
  63. agents/task/agent/message_manager/service.py +758 -0
  64. agents/task/agent/message_manager/tests.py +305 -0
  65. agents/task/agent/message_manager/tool_call_builder.py +539 -0
  66. agents/task/agent/message_manager/tool_message_repair.py +364 -0
  67. agents/task/agent/message_manager/views.py +143 -0
  68. agents/task/agent/messages/__init__.py +8 -0
  69. agents/task/agent/messages/builders.py +309 -0
  70. agents/task/agent/messages/compactor.py +611 -0
  71. agents/task/agent/messages/context_references.py +271 -0
  72. agents/task/agent/messages/filters.py +333 -0
  73. agents/task/agent/messages/guidance.py +328 -0
  74. agents/task/agent/messages/persistence.py +448 -0
  75. agents/task/agent/messages/retrieval.py +506 -0
  76. agents/task/agent/messages/sqlite_persistence.py +85 -0
  77. agents/task/agent/messages/test_compaction_upgrade.py +349 -0
  78. agents/task/agent/messages/test_persistence_subdir_fix.py +28 -0
  79. agents/task/agent/messages/test_sqlite_persistence.py +54 -0
  80. agents/task/agent/messages/token_counter.py +532 -0
  81. agents/task/agent/orchestrator.py +776 -0
  82. agents/task/agent/profile_manager.py +105 -0
  83. agents/task/agent/profile_registry.py +173 -0
  84. agents/task/agent/prompts.py +1090 -0
  85. agents/task/agent/scenario_registry.py +226 -0
  86. agents/task/agent/service.py +509 -0
  87. agents/task/agent/session.py +984 -0
  88. agents/task/agent/skill_discovery.py +110 -0
  89. agents/task/agent/skill_frontmatter.py +94 -0
  90. agents/task/agent/skill_manager.py +1201 -0
  91. agents/task/agent/skill_store.py +627 -0
  92. agents/task/agent/skill_validation.py +56 -0
  93. agents/task/agent/skill_writer.py +492 -0
  94. agents/task/agent/sub_agent_manager.py +1137 -0
  95. agents/task/agent/test_session_disk_recovery.py +34 -0
  96. agents/task/agent/tests.py +513 -0
  97. agents/task/agent/tool_call_tracker.py +511 -0
  98. agents/task/agent/views.py +469 -0
  99. agents/task/config.py +432 -0
  100. agents/task/constants.py +1384 -0
  101. agents/task/flag_defaults.py +63 -0
  102. agents/task/goals/__init__.py +1 -0
  103. agents/task/goals/autonomy_marker.py +28 -0
  104. agents/task/goals/board.py +690 -0
  105. agents/task/goals/completion_judge.py +247 -0
  106. agents/task/goals/context.py +62 -0
  107. agents/task/goals/dispatcher.py +848 -0
  108. agents/task/goals/escalation.py +102 -0
  109. agents/task/goals/planner.py +114 -0
  110. agents/task/logging_config.py +155 -0
  111. agents/task/path.py +991 -0
  112. agents/task/robust_parse_config.py +400 -0
  113. agents/task/runtime/__init__.py +0 -0
  114. agents/task/runtime/run_as_session.py +130 -0
  115. agents/task/runtime_safety.py +308 -0
  116. agents/task/session/__init__.py +5 -0
  117. agents/task/session/browser_pool.py +130 -0
  118. agents/task/session/cleanup.py +612 -0
  119. agents/task/session/execution.py +397 -0
  120. agents/task/session/feed.py +200 -0
  121. agents/task/session/hitl_ingress.py +201 -0
  122. agents/task/session/hooks.py +83 -0
  123. agents/task/session/multi_agent.py +243 -0
  124. agents/task/session/workspace.py +91 -0
  125. agents/task/session_registry.py +91 -0
  126. agents/task/session_route.py +35 -0
  127. agents/task/sqlite_session_registry.py +261 -0
  128. agents/task/surface_config.py +185 -0
  129. agents/task/telemetry/__init__.py +58 -0
  130. agents/task/telemetry/event_log.py +180 -0
  131. agents/task/telemetry/formatters.py +642 -0
  132. agents/task/telemetry/manager.py +571 -0
  133. agents/task/telemetry/memory_events.py +66 -0
  134. agents/task/telemetry/self_events.py +53 -0
  135. agents/task/telemetry/sequence.py +160 -0
  136. agents/task/telemetry/service.py +1265 -0
  137. agents/task/telemetry/views.py +882 -0
  138. agents/task/templates.py +98 -0
  139. agents/task/test_aux_chain.py +151 -0
  140. agents/task/test_aux_router.py +41 -0
  141. agents/task/tests/test_parse_robustness.py +170 -0
  142. agents/task/tool_defaults.py +110 -0
  143. agents/task/utils.py +762 -0
  144. agents/task/utils_json.py +768 -0
  145. agents/task/utils_webview.py +86 -0
  146. agents/task/workspace_context.py +229 -0
  147. agents/task_agent_lite.py +2398 -0
  148. api/README.md +683 -0
  149. api/TASK_API_DOCS.md +151 -0
  150. api/__init__.py +0 -0
  151. api/a2a/__init__.py +37 -0
  152. api/a2a/agent_card.py +337 -0
  153. api/a2a/client.py +657 -0
  154. api/a2a/endpoints.py +375 -0
  155. api/a2a/models.py +268 -0
  156. api/a2a/streaming.py +419 -0
  157. api/a2a/task_handler.py +929 -0
  158. api/admin_endpoints.py +1584 -0
  159. api/app.py +923 -0
  160. api/auth_constants.py +28 -0
  161. api/auth_endpoints.py +402 -0
  162. api/auth_state.py +36 -0
  163. api/chat_via_task.py +42 -0
  164. api/conversation_manager.py +231 -0
  165. api/dependencies.py +186 -0
  166. api/eip8004_endpoints.py +452 -0
  167. api/hyperliquid_models.py +174 -0
  168. api/hyperliquid_routes.py +450 -0
  169. api/interfaces.py +207 -0
  170. api/jwt_middleware.py +83 -0
  171. api/kb/__init__.py +1 -0
  172. api/kb/endpoints.py +314 -0
  173. api/mcp_models.py +279 -0
  174. api/mcp_routes.py +438 -0
  175. api/middleware.py +526 -0
  176. api/models.py +176 -0
  177. api/openai_compat/__init__.py +0 -0
  178. api/openai_compat/model_map.py +25 -0
  179. api/openai_compat/models.py +59 -0
  180. api/openai_compat/router.py +140 -0
  181. api/payment_endpoints.py +444 -0
  182. api/payment_verification.py +138 -0
  183. api/polymarket_models.py +155 -0
  184. api/polymarket_routes.py +501 -0
  185. api/pricing_endpoints.py +89 -0
  186. api/session_routing.py +54 -0
  187. api/skill_endpoints.py +453 -0
  188. api/task_http_api.py +1856 -0
  189. api/webhooks.py +52 -0
  190. api/x402_endpoints.py +280 -0
  191. avatar/README.md +44 -0
  192. avatar/__init__.py +1 -0
  193. avatar/config/rob.json +7 -0
  194. avatar/mindprint.js +395 -0
  195. avatar/renders/rob.meta.json +20 -0
  196. avatar/renders/rob.png +0 -0
  197. avatar/studio.html +373 -0
  198. avatar/webview/avatar-live.js +44 -0
  199. cli/README.md +89 -0
  200. cli/__init__.py +0 -0
  201. cli/cli_surface.py +67 -0
  202. cli/commands/__init__.py +0 -0
  203. cli/commands/_bootstrap.py +49 -0
  204. cli/commands/_errors.py +53 -0
  205. cli/commands/chat.py +973 -0
  206. cli/commands/config.py +100 -0
  207. cli/commands/dashboard.py +103 -0
  208. cli/commands/doctor.py +222 -0
  209. cli/commands/email.py +174 -0
  210. cli/commands/gateway.py +346 -0
  211. cli/commands/goals.py +509 -0
  212. cli/commands/init.py +276 -0
  213. cli/commands/journey.py +30 -0
  214. cli/commands/kb.py +280 -0
  215. cli/commands/model.py +107 -0
  216. cli/commands/owner.py +431 -0
  217. cli/commands/pfp.py +232 -0
  218. cli/commands/run.py +414 -0
  219. cli/commands/serve.py +41 -0
  220. cli/commands/session.py +684 -0
  221. cli/commands/skill_install.py +786 -0
  222. cli/commands/skills.py +128 -0
  223. cli/commands/subagents.py +100 -0
  224. cli/commands/surface.py +81 -0
  225. cli/commands/telegram.py +185 -0
  226. cli/commands/todos.py +209 -0
  227. cli/commands/tools.py +102 -0
  228. cli/commands/update.py +316 -0
  229. cli/commands/whatsapp.py +175 -0
  230. cli/config_store.py +276 -0
  231. cli/gitignore.py +43 -0
  232. cli/inventory.py +46 -0
  233. cli/keys.py +101 -0
  234. cli/persona.py +17 -0
  235. cli/polyrob.py +137 -0
  236. cli/ui/__init__.py +64 -0
  237. cli/ui/activity.py +141 -0
  238. cli/ui/app.py +538 -0
  239. cli/ui/banner.py +233 -0
  240. cli/ui/blocks.py +534 -0
  241. cli/ui/bootstrap_notice.py +47 -0
  242. cli/ui/commands/__init__.py +41 -0
  243. cli/ui/commands/h_cron.py +64 -0
  244. cli/ui/commands/h_journey.py +164 -0
  245. cli/ui/commands/h_kb.py +121 -0
  246. cli/ui/commands/h_learn.py +100 -0
  247. cli/ui/commands/h_mcp.py +215 -0
  248. cli/ui/commands/h_self.py +113 -0
  249. cli/ui/commands/h_skills.py +314 -0
  250. cli/ui/commands/handlers.py +1672 -0
  251. cli/ui/commands/registry.py +426 -0
  252. cli/ui/dialog.py +425 -0
  253. cli/ui/event_registry.py +110 -0
  254. cli/ui/event_specs.py +45 -0
  255. cli/ui/events.py +433 -0
  256. cli/ui/identity.py +15 -0
  257. cli/ui/lifecycle.py +159 -0
  258. cli/ui/live_hooks.py +43 -0
  259. cli/ui/model_selector.py +532 -0
  260. cli/ui/persistent_loop.py +181 -0
  261. cli/ui/pick.py +113 -0
  262. cli/ui/plain_renderer.py +351 -0
  263. cli/ui/renderer.py +384 -0
  264. cli/ui/rich_renderer.py +533 -0
  265. cli/ui/secrets.py +115 -0
  266. cli/ui/state.py +376 -0
  267. cli/ui/statusbar.py +231 -0
  268. cli/ui/streaming.py +254 -0
  269. cli/ui/terminal_render.py +105 -0
  270. cli/ui/theme.py +132 -0
  271. cli/update/__init__.py +6 -0
  272. cli/update/context.py +121 -0
  273. cli/update/detect.py +176 -0
  274. cli/update/engine.py +95 -0
  275. cli/update/migrate_guarded.py +55 -0
  276. cli/update/process_guard.py +215 -0
  277. cli/update/runners.py +78 -0
  278. cli/update/snapshot.py +270 -0
  279. cli/update/versions.py +205 -0
  280. core/README.md +377 -0
  281. core/__init__.py +174 -0
  282. core/assets.py +87 -0
  283. core/async_bridge.py +76 -0
  284. core/autonomy_runtime.py +259 -0
  285. core/base_component.py +302 -0
  286. core/bootstrap.py +681 -0
  287. core/bot.py +310 -0
  288. core/config.py +833 -0
  289. core/constants.py +126 -0
  290. core/container.py +462 -0
  291. core/db_manifest.py +101 -0
  292. core/embedding.py +57 -0
  293. core/env.py +39 -0
  294. core/exceptions.py +287 -0
  295. core/flags.py +144 -0
  296. core/flags_catalog.py +345 -0
  297. core/home_migration.py +62 -0
  298. core/identity.py +118 -0
  299. core/initialization.py +1004 -0
  300. core/instance.py +537 -0
  301. core/interactive_gate.py +96 -0
  302. core/logging.py +436 -0
  303. core/owner_doc_writer.py +176 -0
  304. core/pairing.py +193 -0
  305. core/path_safety.py +20 -0
  306. core/paths.py +27 -0
  307. core/payment_config.py +21 -0
  308. core/permissions.py +322 -0
  309. core/runtime_config.py +96 -0
  310. core/runtime_paths.py +135 -0
  311. core/seams.py +35 -0
  312. core/secret_scan.py +25 -0
  313. core/secret_scrub.py +71 -0
  314. core/secrets.py +35 -0
  315. core/security_logging_filter.py +148 -0
  316. core/self_context_writer.py +333 -0
  317. core/self_evolution.py +294 -0
  318. core/session_context.py +47 -0
  319. core/sqlite_util.py +59 -0
  320. core/surfaces/__init__.py +16 -0
  321. core/surfaces/access.py +118 -0
  322. core/surfaces/binding.py +88 -0
  323. core/surfaces/bootstrap.py +78 -0
  324. core/surfaces/circuit.py +168 -0
  325. core/surfaces/continuity.py +77 -0
  326. core/surfaces/correspondents.py +228 -0
  327. core/surfaces/dispatcher.py +216 -0
  328. core/surfaces/envelopes.py +75 -0
  329. core/surfaces/gc.py +30 -0
  330. core/surfaces/idempotency.py +57 -0
  331. core/surfaces/inbound_webhook.py +124 -0
  332. core/surfaces/media.py +32 -0
  333. core/surfaces/message_router.py +91 -0
  334. core/surfaces/outbound_allowlist.py +80 -0
  335. core/surfaces/outbound_dispatcher.py +110 -0
  336. core/surfaces/outbound_mirror.py +37 -0
  337. core/surfaces/outbound_queue.py +107 -0
  338. core/surfaces/outbound_target.py +12 -0
  339. core/surfaces/owner_admin.py +29 -0
  340. core/surfaces/proactive.py +78 -0
  341. core/surfaces/progress.py +108 -0
  342. core/surfaces/rate_bucket.py +21 -0
  343. core/surfaces/registry.py +51 -0
  344. core/surfaces/rendering.py +53 -0
  345. core/surfaces/send_policy.py +14 -0
  346. core/surfaces/serialize.py +24 -0
  347. core/surfaces/session_chat_registry.py +112 -0
  348. core/surfaces/session_policy.py +60 -0
  349. core/surfaces/surface.py +288 -0
  350. core/surfaces/transcription.py +88 -0
  351. core/surfaces/voice_echo.py +26 -0
  352. core/surfaces/voice_guard.py +23 -0
  353. core/tickers.py +174 -0
  354. core/tool_catalog.py +192 -0
  355. core/version.py +75 -0
  356. core/wallet/__init__.py +5 -0
  357. core/wallet/agent_wallet.py +59 -0
  358. core/wallet/audit_sink.py +61 -0
  359. core/wallet/config.py +70 -0
  360. core/wallet/factory.py +87 -0
  361. core/wallet/policy.py +104 -0
  362. core/wallet/signer.py +51 -0
  363. cron/README.md +65 -0
  364. cron/__init__.py +0 -0
  365. cron/delivery.py +277 -0
  366. cron/digest.py +124 -0
  367. cron/jobs.py +207 -0
  368. cron/runner.py +297 -0
  369. cron/schedule.py +194 -0
  370. cron/scheduler.py +201 -0
  371. cron/service.py +57 -0
  372. cron/wake_gate.py +223 -0
  373. data/__init__.py +1 -0
  374. data/prompts/autov2_prompts.json +87 -0
  375. data/prompts/skills/browser-automation/SKILL.md +43 -0
  376. data/prompts/skills/coding-workflow/SKILL.md +36 -0
  377. data/prompts/skills/crypto-trading-safety/SKILL.md +53 -0
  378. data/prompts/skills/document-writing/SKILL.md +33 -0
  379. data/prompts/skills/email-comms/SKILL.md +33 -0
  380. data/prompts/skills/file-data-ops/SKILL.md +35 -0
  381. data/prompts/skills/hyperliquid-account-review/SKILL.md +48 -0
  382. data/prompts/skills/hyperliquid-market-data/SKILL.md +52 -0
  383. data/prompts/skills/hyperliquid-trading/SKILL.md +59 -0
  384. data/prompts/skills/lead-research/SKILL.md +86 -0
  385. data/prompts/skills/market-research-brief/SKILL.md +104 -0
  386. data/prompts/skills/person-analyzer/SKILL.md +124 -0
  387. data/prompts/skills/polymarket-market-research/SKILL.md +54 -0
  388. data/prompts/skills/polymarket-portfolio-review/SKILL.md +50 -0
  389. data/prompts/skills/polymarket-trading/SKILL.md +55 -0
  390. data/prompts/skills/presentation-creator/SKILL.md +36 -0
  391. data/prompts/skills/project-analyzer/SKILL.md +169 -0
  392. data/prompts/skills/rules.json +268 -0
  393. data/prompts/skills/secret-handling/SKILL.md +20 -0
  394. data/prompts/skills/skill-authoring/SKILL.md +31 -0
  395. data/prompts/skills/skill-security-review/SKILL.md +27 -0
  396. data/prompts/skills/social-discovery/SKILL.md +57 -0
  397. data/prompts/skills/task-planning/SKILL.md +33 -0
  398. data/prompts/skills/web-research/SKILL.md +39 -0
  399. data/prompts/skills/web-scraping/SKILL.md +73 -0
  400. data/prompts/skills/x-engagement/SKILL.md +69 -0
  401. data/prompts/system_prompts.json +4 -0
  402. data/subscription_channels.json +5 -0
  403. modules/README.md +503 -0
  404. modules/__init__.py +124 -0
  405. modules/auth/__init__.py +13 -0
  406. modules/auth/api_key_manager.py +157 -0
  407. modules/auth/identity_mapper.py +380 -0
  408. modules/auth/siwe_auth.py +273 -0
  409. modules/auth/tier_manager.py +173 -0
  410. modules/base_module.py +190 -0
  411. modules/credits/__init__.py +29 -0
  412. modules/credits/balance_manager.py +237 -0
  413. modules/credits/cost_utils.py +129 -0
  414. modules/credits/pricing.py +139 -0
  415. modules/credits/unified_ledger.py +148 -0
  416. modules/credits/usage_meter.py +310 -0
  417. modules/credits/usage_tracker.py +674 -0
  418. modules/database/__init__.py +33 -0
  419. modules/database/audit_log.py +322 -0
  420. modules/database/auth_tables.py +276 -0
  421. modules/database/connection.py +644 -0
  422. modules/database/connection_pool.py +305 -0
  423. modules/database/conversation_contexts.py +446 -0
  424. modules/database/database_manager.py +237 -0
  425. modules/database/hyperliquid.py +375 -0
  426. modules/database/polymarket.py +574 -0
  427. modules/database/user_mcp_servers.py +728 -0
  428. modules/database/user_profiles.py +562 -0
  429. modules/database/utils.py +107 -0
  430. modules/database/x402_tables.py +92 -0
  431. modules/eip8004/README.md +1069 -0
  432. modules/eip8004/__init__.py +65 -0
  433. modules/eip8004/contracts.py +498 -0
  434. modules/eip8004/models.py +271 -0
  435. modules/eip8004/registration.py +148 -0
  436. modules/eip8004/reputation.py +367 -0
  437. modules/eip8004/validation.py +277 -0
  438. modules/llm/__init__.py +97 -0
  439. modules/llm/adapters.py +963 -0
  440. modules/llm/anthropic_client.py +831 -0
  441. modules/llm/available_models.py +106 -0
  442. modules/llm/brain_scrubber.py +137 -0
  443. modules/llm/cache_hints.py +162 -0
  444. modules/llm/deepseek_client.py +562 -0
  445. modules/llm/gemini_client.py +1367 -0
  446. modules/llm/llm_client.py +1139 -0
  447. modules/llm/llm_client_registry.py +188 -0
  448. modules/llm/llm_factory.py +237 -0
  449. modules/llm/llm_manager.py +1036 -0
  450. modules/llm/messages.py +374 -0
  451. modules/llm/model_registry.py +1935 -0
  452. modules/llm/nvidia_client.py +125 -0
  453. modules/llm/openai_client.py +800 -0
  454. modules/llm/openrouter_client.py +969 -0
  455. modules/llm/profiles.py +178 -0
  456. modules/llm/test_anthropic_cache_capture.py +35 -0
  457. modules/llm/test_cached_pricing_derivation.py +24 -0
  458. modules/llm/think_scrubber.py +444 -0
  459. modules/llm/token_counter.py +268 -0
  460. modules/memory/__init__.py +35 -0
  461. modules/memory/backend_factory.py +83 -0
  462. modules/memory/cache_manager.py +186 -0
  463. modules/memory/episodic.py +108 -0
  464. modules/memory/local_vector_memory_provider.py +552 -0
  465. modules/memory/memory_manager.py +225 -0
  466. modules/memory/models.py +312 -0
  467. modules/memory/provider.py +210 -0
  468. modules/memory/registry.py +205 -0
  469. modules/memory/sqlite_memory_provider.py +767 -0
  470. modules/memory/task/__init__.py +52 -0
  471. modules/memory/task/compaction_manager.py +157 -0
  472. modules/memory/task/context_retriever.py +809 -0
  473. modules/memory/task/hierarchical_memory.py +1002 -0
  474. modules/memory/task/lexical_retriever.py +71 -0
  475. modules/memory/task/null_context_manager.py +213 -0
  476. modules/memory/task/phase_manager.py +625 -0
  477. modules/memory/task/reflection_service.py +157 -0
  478. modules/memory/task/semantic_retriever.py +218 -0
  479. modules/memory/task/task_context_manager.py +1165 -0
  480. modules/memory/task/test_forgetting_engages.py +24 -0
  481. modules/memory/task/test_reflection_llm.py +39 -0
  482. modules/memory/task/test_threat_scan.py +53 -0
  483. modules/memory/task/threat_scan.py +90 -0
  484. modules/memory/test_sqlite_memory_provider.py +106 -0
  485. modules/memory/user_profile_manager.py +527 -0
  486. modules/payments/__init__.py +11 -0
  487. modules/payments/deposit_monitor.py +478 -0
  488. modules/payments/price_oracle.py +70 -0
  489. modules/payments/treasury_sweeper.py +401 -0
  490. modules/payments/wallet_generator.py +145 -0
  491. modules/pfp/__init__.py +1 -0
  492. modules/pfp/config.py +92 -0
  493. modules/pfp/mesh.py +565 -0
  494. modules/pfp/push.py +69 -0
  495. modules/pfp/renderer.py +85 -0
  496. modules/pfp/store.py +82 -0
  497. modules/skills/__init__.py +1 -0
  498. modules/skills/skill_usage.py +248 -0
  499. modules/transcription/__init__.py +24 -0
  500. modules/transcription/base.py +20 -0
  501. modules/transcription/faster_whisper_transcriber.py +55 -0
  502. modules/x402/README.md +249 -0
  503. modules/x402/__init__.py +22 -0
  504. modules/x402/invoicing.py +416 -0
  505. modules/x402/middleware.py +364 -0
  506. modules/x402/settlement_watcher.py +145 -0
  507. modules/x402/x402_integration.py +344 -0
  508. polyrob-0.5.0.dist-info/METADATA +482 -0
  509. polyrob-0.5.0.dist-info/RECORD +745 -0
  510. polyrob-0.5.0.dist-info/WHEEL +5 -0
  511. polyrob-0.5.0.dist-info/entry_points.txt +2 -0
  512. polyrob-0.5.0.dist-info/licenses/LICENSE +21 -0
  513. polyrob-0.5.0.dist-info/top_level.txt +12 -0
  514. surfaces/README.md +70 -0
  515. surfaces/__init__.py +0 -0
  516. surfaces/email/__init__.py +0 -0
  517. surfaces/email/dedup.py +44 -0
  518. surfaces/email/harness.py +187 -0
  519. surfaces/email/inbound.py +159 -0
  520. surfaces/email/seed.py +60 -0
  521. surfaces/email/surface.py +105 -0
  522. surfaces/telegram/__init__.py +0 -0
  523. surfaces/telegram/dedup.py +83 -0
  524. surfaces/telegram/harness.py +886 -0
  525. surfaces/telegram/inbound.py +145 -0
  526. surfaces/telegram/interactive_tools.py +49 -0
  527. surfaces/telegram/markdown.py +347 -0
  528. surfaces/telegram/rate_limit.py +167 -0
  529. surfaces/telegram/surface.py +187 -0
  530. surfaces/telegram/voice.py +52 -0
  531. surfaces/whatsapp/__init__.py +0 -0
  532. surfaces/whatsapp/client.py +51 -0
  533. surfaces/whatsapp/harness.py +62 -0
  534. surfaces/whatsapp/inbound.py +132 -0
  535. surfaces/whatsapp/surface.py +64 -0
  536. surfaces/whatsapp/window.py +34 -0
  537. tools/README.md +578 -0
  538. tools/__init__.py +424 -0
  539. tools/alchemy/__init__.py +5 -0
  540. tools/alchemy/alchemy_tool.py +389 -0
  541. tools/anysite/__init__.py +17 -0
  542. tools/anysite/client.py +88 -0
  543. tools/anysite/tool.py +89 -0
  544. tools/base_tool.py +468 -0
  545. tools/browser/__init__.py +22 -0
  546. tools/browser/actions.py +118 -0
  547. tools/browser/browser.py +1457 -0
  548. tools/browser/browser_manager.py +690 -0
  549. tools/browser/context.py +1748 -0
  550. tools/browser/playwright_utils.py +137 -0
  551. tools/browser/views.py +56 -0
  552. tools/code_exec/SANDBOX_SECURITY.md +144 -0
  553. tools/code_exec/__init__.py +178 -0
  554. tools/code_exec/backend.py +73 -0
  555. tools/code_exec/backends/__init__.py +1 -0
  556. tools/code_exec/backends/docker.py +779 -0
  557. tools/code_exec/backends/local_subprocess.py +154 -0
  558. tools/code_exec/env_policy.py +45 -0
  559. tools/code_exec/result.py +42 -0
  560. tools/code_exec/sandbox_guard.py +59 -0
  561. tools/code_exec/tool.py +227 -0
  562. tools/coding/__init__.py +50 -0
  563. tools/coding/edit.py +107 -0
  564. tools/coding/search.py +113 -0
  565. tools/coding/tool.py +353 -0
  566. tools/collabland/__init__.py +5 -0
  567. tools/collabland/collabland_tool.py +471 -0
  568. tools/controller/__init__.py +0 -0
  569. tools/controller/_helpers.py +165 -0
  570. tools/controller/action_registration.py +1765 -0
  571. tools/controller/approval.py +244 -0
  572. tools/controller/approval_interactive.py +90 -0
  573. tools/controller/delegation.py +195 -0
  574. tools/controller/execution.py +797 -0
  575. tools/controller/execution_context.py +141 -0
  576. tools/controller/hooks.py +135 -0
  577. tools/controller/introspection.py +344 -0
  578. tools/controller/mcp_registrar.py +190 -0
  579. tools/controller/message_send.py +31 -0
  580. tools/controller/registry/__init__.py +4 -0
  581. tools/controller/registry/schema_generators.py +395 -0
  582. tools/controller/registry/schema_sanitizer.py +406 -0
  583. tools/controller/registry/service.py +1266 -0
  584. tools/controller/registry/views.py +151 -0
  585. tools/controller/service.py +409 -0
  586. tools/controller/tool_management.py +334 -0
  587. tools/controller/types.py +28 -0
  588. tools/controller/views.py +450 -0
  589. tools/cronjob_tools.py +166 -0
  590. tools/crypto_trade_gate.py +59 -0
  591. tools/descriptors.py +452 -0
  592. tools/dom/__init__.py +0 -0
  593. tools/dom/history_tree_processor/service.py +244 -0
  594. tools/dom/history_tree_processor/view.py +99 -0
  595. tools/dom/service.py +471 -0
  596. tools/dom/views.py +346 -0
  597. tools/email_tool.py +403 -0
  598. tools/exceptions.py +169 -0
  599. tools/filesystem.py +1038 -0
  600. tools/filesystem_docproc.py +331 -0
  601. tools/filesystem_pdf.py +755 -0
  602. tools/git/__init__.py +42 -0
  603. tools/git/tool.py +258 -0
  604. tools/github/__init__.py +33 -0
  605. tools/github/client.py +94 -0
  606. tools/github/tool.py +237 -0
  607. tools/goal_tools.py +309 -0
  608. tools/hyperliquid/__init__.py +56 -0
  609. tools/hyperliquid/models.py +233 -0
  610. tools/hyperliquid/service.py +1680 -0
  611. tools/knowledge_ingest.py +950 -0
  612. tools/mcp/README.md +535 -0
  613. tools/mcp/__init__.py +52 -0
  614. tools/mcp/catalog.py +115 -0
  615. tools/mcp/config.py +337 -0
  616. tools/mcp/mcp_tool.py +1415 -0
  617. tools/mcp/param_coercion.py +289 -0
  618. tools/mcp/protocol.py +1520 -0
  619. tools/mcp/rate_limit.py +50 -0
  620. tools/mcp/security.py +424 -0
  621. tools/mcp/self_install.py +111 -0
  622. tools/mcp/server_manager.py +829 -0
  623. tools/mcp/subscriptions.py +72 -0
  624. tools/mcp/user_mcp_service.py +899 -0
  625. tools/mcp/validation_tracker.py +89 -0
  626. tools/mcp/views.py +346 -0
  627. tools/oauth/__init__.py +17 -0
  628. tools/oauth/manager.py +75 -0
  629. tools/oauth/provider.py +69 -0
  630. tools/oauth/providers/__init__.py +1 -0
  631. tools/oauth/providers/generic_oauth2.py +96 -0
  632. tools/perplexity_tool.py +280 -0
  633. tools/polymarket/__init__.py +41 -0
  634. tools/polymarket/clob_adapter.py +76 -0
  635. tools/polymarket/models.py +182 -0
  636. tools/polymarket/service.py +2082 -0
  637. tools/self_env/__init__.py +61 -0
  638. tools/self_env/tool.py +274 -0
  639. tools/shell/__init__.py +80 -0
  640. tools/shell/backend_pool.py +118 -0
  641. tools/shell/discipline.py +62 -0
  642. tools/shell/executor.py +157 -0
  643. tools/shell/loopback_allow.py +87 -0
  644. tools/shell/process_registry.py +113 -0
  645. tools/shell/process_tool.py +131 -0
  646. tools/shell/state.py +129 -0
  647. tools/shell/tool.py +151 -0
  648. tools/task_tool.py +637 -0
  649. tools/twitter_tool.py +2086 -0
  650. tools/user_directory.py +179 -0
  651. tools/web_fetch/__init__.py +3 -0
  652. tools/web_fetch/fetcher.py +144 -0
  653. tools/web_fetch/render.py +44 -0
  654. tools/web_fetch/tool.py +60 -0
  655. tools/x402/__init__.py +60 -0
  656. tools/x402/client.py +47 -0
  657. tools/x402/invoice_tool.py +143 -0
  658. tools/x402/real_client.py +250 -0
  659. tools/x402/service.py +131 -0
  660. utils/README.md +498 -0
  661. utils/__init__.py +46 -0
  662. utils/auth_utils.py +114 -0
  663. utils/bounded_collections.py +162 -0
  664. utils/circuit_breaker.py +389 -0
  665. utils/gif_utils.py +435 -0
  666. utils/markdown_utils.py +291 -0
  667. utils/message_utils.py +147 -0
  668. utils/metrics.py +36 -0
  669. utils/path_validator.py +227 -0
  670. utils/rate_limit_manager.py +399 -0
  671. utils/result_size.py +296 -0
  672. utils/time_utils.py +206 -0
  673. utils/user_utils.py +188 -0
  674. webview/README.md +111 -0
  675. webview/RENAME_AND_ALIGN_HANDOFF.md +200 -0
  676. webview/__init__.py +8 -0
  677. webview/activity.py +636 -0
  678. webview/owner_auth.py +108 -0
  679. webview/pages.py +448 -0
  680. webview/repair_sessions.py +399 -0
  681. webview/server.py +4323 -0
  682. webview/server_launcher.py +112 -0
  683. webview/static/css/activity.css +89 -0
  684. webview/static/css/chat.css +1772 -0
  685. webview/static/css/components.css +1190 -0
  686. webview/static/css/config-panel.css +651 -0
  687. webview/static/css/pages/admin.css +766 -0
  688. webview/static/css/pages/profile.css +231 -0
  689. webview/static/css/pages/settings.css +297 -0
  690. webview/static/css/pages/signin.css +316 -0
  691. webview/static/css/style.css +4250 -0
  692. webview/static/css/variables.css +147 -0
  693. webview/static/css/workspace-fullwidth-fix.css +109 -0
  694. webview/static/img/favicon.ico +0 -0
  695. webview/static/js/activity.js +394 -0
  696. webview/static/js/admin/activity.js +186 -0
  697. webview/static/js/admin/dashboard.js +163 -0
  698. webview/static/js/admin/user_detail.js +400 -0
  699. webview/static/js/admin/users.js +174 -0
  700. webview/static/js/admin/utils.js +214 -0
  701. webview/static/js/chat.js +3178 -0
  702. webview/static/js/config-panel.js +522 -0
  703. webview/static/js/constants.js +20 -0
  704. webview/static/js/error-handler.js +226 -0
  705. webview/static/js/ethers.min.js +1 -0
  706. webview/static/js/event-filter.js +137 -0
  707. webview/static/js/event-store.js +351 -0
  708. webview/static/js/file-attachments.js +374 -0
  709. webview/static/js/file-loader.js +163 -0
  710. webview/static/js/index.js +103 -0
  711. webview/static/js/performance-utils.js +196 -0
  712. webview/static/js/profile.js +396 -0
  713. webview/static/js/screenshot.js +386 -0
  714. webview/static/js/session.js +1527 -0
  715. webview/static/js/settings.js +1288 -0
  716. webview/static/js/sidebar-data.js +766 -0
  717. webview/static/js/sidebar-toggle.js +296 -0
  718. webview/static/js/socket.io.min.js +7 -0
  719. webview/static/js/stats.js +355 -0
  720. webview/static/js/ui-utils.js +420 -0
  721. webview/static/js/workspace.js +966 -0
  722. webview/stats_service.py +613 -0
  723. webview/templates/__init__.py +1 -0
  724. webview/templates/__pycache__/__init__.cpython-311.pyc +0 -0
  725. webview/templates/activity.html +36 -0
  726. webview/templates/admin/activity.html +122 -0
  727. webview/templates/admin/dashboard.html +112 -0
  728. webview/templates/admin/user_detail.html +228 -0
  729. webview/templates/admin/users.html +105 -0
  730. webview/templates/autonomy.html +60 -0
  731. webview/templates/error.html +133 -0
  732. webview/templates/finance.html +90 -0
  733. webview/templates/identity.html +73 -0
  734. webview/templates/index.html +42 -0
  735. webview/templates/layout.html +125 -0
  736. webview/templates/memory.html +59 -0
  737. webview/templates/owner_login.html +15 -0
  738. webview/templates/profile.html +121 -0
  739. webview/templates/session.html +312 -0
  740. webview/templates/settings.html +534 -0
  741. webview/templates/sidebar.html +112 -0
  742. webview/templates/signin.html +213 -0
  743. webview/templates/status.html +14 -0
  744. webview/templates/system.html +45 -0
  745. webview/webgate.py +196 -0
tools/mcp/protocol.py ADDED
@@ -0,0 +1,1520 @@
1
+ """MCP (Model Context Protocol) implementation."""
2
+
3
+ import asyncio
4
+ import json
5
+ import socket
6
+ import uuid
7
+ import time
8
+ from typing import Dict, Any, Optional, List, Union, AsyncIterator, Callable
9
+ from dataclasses import dataclass, field
10
+ from enum import Enum
11
+ import aiohttp
12
+ import subprocess
13
+
14
+ from core.exceptions import MCPError, MCPConnectionError, MCPProtocolError, MCPToolExecutionError
15
+ from core.logging import get_component_logger
16
+
17
+ _protocol_logger = get_component_logger("MCPTransportSecurity")
18
+
19
+
20
+ def _client_version() -> str:
21
+ """POLYROB version advertised as MCP ``clientInfo.version``. Fail-open to a
22
+ neutral literal so a version-resolution hiccup never breaks the MCP handshake."""
23
+ try:
24
+ from core.version import get_version
25
+ return get_version()
26
+ except Exception:
27
+ return "0"
28
+
29
+
30
+ class _PinnedResolver:
31
+ """aiohttp resolver that pins a hostname to a single pre-validated IP.
32
+
33
+ SECURITY (SSRF / DNS rebinding): the connect-time SSRF check resolves the
34
+ host once and validates the resulting IP. This resolver makes aiohttp
35
+ connect to *that exact IP* instead of re-resolving DNS, so a rebind to an
36
+ internal/metadata address between validation and connection cannot redirect
37
+ the socket. The original hostname is preserved for the TLS SNI / Host header
38
+ (aiohttp keeps the request host; only the address is overridden), so HTTPS
39
+ certificate validation still matches the real hostname.
40
+
41
+ Any host other than the pinned one resolves to nothing (defensive — a
42
+ redirect-induced lookup to a different host is refused rather than resolved).
43
+ """
44
+
45
+ def __init__(self, host: str, ip: str, family: int):
46
+ self._host = host
47
+ self._ip = ip
48
+ self._family = family
49
+
50
+ async def resolve(self, host, port=0, family=socket.AF_INET):
51
+ if host != self._host:
52
+ # Unknown host (e.g. via a redirect) — refuse to resolve it.
53
+ raise OSError(f"Refusing to resolve non-pinned host: {host}")
54
+ return [
55
+ {
56
+ "hostname": host,
57
+ "host": self._ip,
58
+ "port": port,
59
+ "family": self._family,
60
+ "proto": 0,
61
+ "flags": socket.AI_NUMERICHOST,
62
+ }
63
+ ]
64
+
65
+ async def close(self) -> None:
66
+ return None
67
+
68
+
69
+ def _validate_and_pin_connector(
70
+ url: str,
71
+ *,
72
+ allow_http: bool = False,
73
+ ssl: bool = True,
74
+ limit: int = 10,
75
+ validate_ssrf: bool = True,
76
+ ttl_dns_cache: Optional[int] = None,
77
+ ) -> "aiohttp.TCPConnector":
78
+ """Validate ``url`` against SSRF policy at CONNECT time and build a pinned connector.
79
+
80
+ Resolves+validates the host once (via ``MCPURLValidator.validate_and_resolve``)
81
+ and returns a ``TCPConnector`` whose resolver pins the validated IP. This is
82
+ the live-path defense against DNS rebinding: even though the server was
83
+ validated at add/update time, DNS is re-checked here, immediately before the
84
+ socket opens, and the connection is bound to the address that was checked.
85
+
86
+ When ``validate_ssrf`` is False (trusted operator-configured global servers —
87
+ e.g. a dev localhost server), no validation/pinning is applied
88
+ and a plain connector is returned, preserving legacy behavior. The SSRF
89
+ defense is enabled only for user-registered servers, which is where the
90
+ rebinding threat lives.
91
+
92
+ Raises:
93
+ MCPConnectionError: if ``validate_ssrf`` and the URL fails SSRF validation
94
+ (blocked host, blocked/rebound IP, bad scheme, unresolvable).
95
+ """
96
+ from urllib.parse import urlparse
97
+ from tools.mcp.security import MCPURLValidator
98
+
99
+ if not validate_ssrf:
100
+ # Trusted server — legacy plain connector (still no redirect-following at
101
+ # the request layer, which is a safe tightening applied unconditionally).
102
+ kwargs: Dict[str, Any] = {"ssl": ssl, "limit": limit}
103
+ if ttl_dns_cache is not None:
104
+ kwargs["ttl_dns_cache"] = ttl_dns_cache
105
+ return aiohttp.TCPConnector(**kwargs)
106
+
107
+ validator = MCPURLValidator(allow_http=allow_http)
108
+ is_valid, error, pinned_ip = validator.validate_and_resolve(url)
109
+ if not is_valid or not pinned_ip:
110
+ _protocol_logger.error(
111
+ f"SECURITY: MCP connect-time URL validation failed for {urlparse(url).hostname}: {error}"
112
+ )
113
+ raise MCPConnectionError(f"MCP connect blocked (SSRF protection): {error}")
114
+
115
+ host = urlparse(url).hostname or ""
116
+ try:
117
+ family = socket.AF_INET6 if ":" in pinned_ip else socket.AF_INET
118
+ except Exception:
119
+ family = socket.AF_INET
120
+
121
+ resolver = _PinnedResolver(host=host, ip=pinned_ip, family=family)
122
+ return aiohttp.TCPConnector(
123
+ ssl=ssl,
124
+ limit=limit,
125
+ resolver=resolver,
126
+ # The host is already an IP behind the resolver; keep DNS cache off so
127
+ # nothing else can re-resolve it.
128
+ use_dns_cache=False,
129
+ )
130
+
131
+
132
+ class MCPMessageType(str, Enum):
133
+ """MCP message types."""
134
+ REQUEST = "request"
135
+ RESPONSE = "response"
136
+ NOTIFICATION = "notification"
137
+
138
+
139
+ @dataclass
140
+ class MCPMessage:
141
+ """Base MCP message."""
142
+ jsonrpc: str = "2.0"
143
+ id: Optional[Union[str, int]] = None
144
+
145
+
146
+ @dataclass
147
+ class MCPRequest(MCPMessage):
148
+ """MCP request message."""
149
+ method: str = ""
150
+ params: Optional[Dict[str, Any]] = None
151
+
152
+ def __post_init__(self):
153
+ if self.id is None:
154
+ self.id = str(uuid.uuid4())
155
+
156
+
157
+ @dataclass
158
+ class MCPResponse(MCPMessage):
159
+ """MCP response message."""
160
+ result: Optional[Any] = None
161
+ error: Optional[Dict[str, Any]] = None
162
+
163
+
164
+ @dataclass
165
+ class MCPNotification(MCPMessage):
166
+ """MCP notification message."""
167
+ method: str = ""
168
+ params: Optional[Dict[str, Any]] = None
169
+ id: Optional[Union[str, int]] = None # Notifications don't have IDs
170
+
171
+
172
+ class MCPTransport:
173
+ """Base transport for MCP communication."""
174
+
175
+ def __init__(self, timeout: int = 180):
176
+ self.timeout = timeout
177
+ self.logger = get_component_logger(self.__class__.__name__)
178
+ self._closed = False
179
+ # Log timeout for debugging
180
+ self.logger.info(f"🔧 {self.__class__.__name__} initialized with {timeout}s timeout")
181
+
182
+ async def send_message(self, message: MCPMessage) -> None:
183
+ """Send a message through the transport."""
184
+ raise NotImplementedError
185
+
186
+ async def receive_message(self) -> Optional[MCPMessage]:
187
+ """Receive a message from the transport."""
188
+ raise NotImplementedError
189
+
190
+ async def close(self) -> None:
191
+ """Close the transport."""
192
+ self._closed = True
193
+
194
+ @property
195
+ def is_closed(self) -> bool:
196
+ """Check if transport is closed."""
197
+ return self._closed
198
+
199
+
200
+ class MCPStdioTransport(MCPTransport):
201
+ """STDIO transport for MCP communication."""
202
+
203
+ # SECURITY: Allowlist of permitted MCP server commands
204
+ # Only these commands can be executed as MCP servers
205
+ ALLOWED_COMMANDS = {
206
+ "npx": True, # Node.js package runner (for MCP servers)
207
+ "node": True, # Node.js runtime
208
+ "python": True, # Python runtime
209
+ "python3": True, # Python 3 runtime
210
+ "uvx": True, # Python uv package runner
211
+ }
212
+
213
+ # SECURITY: Blocklist of dangerous patterns - use regex for robust matching
214
+ # These patterns are checked against each individual argument
215
+ BLOCKED_ARG_PATTERNS = [
216
+ r'^-e$', # node -e 'code' or python -e 'code' (inline execution)
217
+ r'^-c$', # python -c 'code' (inline execution)
218
+ r'^--eval$', # node --eval (inline execution)
219
+ r'^--print$', # node --print (inline execution with output)
220
+ r'^-p$', # node -p (inline execution with output)
221
+ ]
222
+
223
+ # SECURITY: Blocklist of dangerous shell metacharacters in arguments
224
+ BLOCKED_CHARS = frozenset([
225
+ ';', # Command chaining
226
+ '|', # Piping
227
+ '&', # Background/chaining
228
+ '`', # Command substitution
229
+ '$', # Variable expansion/command substitution
230
+ '>', # Output redirection
231
+ '<', # Input redirection
232
+ '\n', # Newline (command injection)
233
+ '\r', # Carriage return
234
+ '\0', # Null byte
235
+ ])
236
+
237
+ @classmethod
238
+ def validate_command(cls, command: List[str]) -> tuple[bool, str]:
239
+ """Validate command against security rules.
240
+
241
+ SECURITY: Uses a multi-layer approach:
242
+ 1. Whitelist base commands
243
+ 2. Block dangerous argument flags (like -e, -c for inline code execution)
244
+ 3. Block shell metacharacters that could enable command injection
245
+
246
+ Returns:
247
+ Tuple of (is_valid, error_message)
248
+ """
249
+ import re
250
+
251
+ if not command:
252
+ return False, "Empty command"
253
+
254
+ # Get base command (first element)
255
+ base_cmd = command[0].split("/")[-1] # Handle full paths
256
+
257
+ # Check if base command is in allowlist
258
+ if base_cmd not in cls.ALLOWED_COMMANDS:
259
+ return False, f"Command '{base_cmd}' not in MCP server allowlist. Allowed: {list(cls.ALLOWED_COMMANDS.keys())}"
260
+
261
+ # SECURITY FIX: Check each argument individually (not as a joined string)
262
+ for i, arg in enumerate(command):
263
+ # Check for blocked argument patterns (e.g., -e, -c for inline execution)
264
+ for pattern in cls.BLOCKED_ARG_PATTERNS:
265
+ if re.match(pattern, arg, re.IGNORECASE):
266
+ return False, f"Blocked argument pattern '{arg}' at position {i} - inline code execution not allowed"
267
+
268
+ # Check for shell metacharacters that could enable injection
269
+ dangerous_chars = cls.BLOCKED_CHARS.intersection(set(arg))
270
+ if dangerous_chars:
271
+ return False, f"Blocked shell metacharacters {dangerous_chars} in argument at position {i}"
272
+
273
+ return True, ""
274
+
275
+ def __init__(self, command: List[str], env: Optional[Dict[str, str]] = None, timeout: int = 180):
276
+ """Initialize STDIO transport.
277
+
278
+ Args:
279
+ command: Command to execute for MCP server
280
+ env: Environment variables for the process
281
+ timeout: Default timeout in seconds for operations (default: 180s for long-running operations)
282
+
283
+ Raises:
284
+ MCPConnectionError: If command fails validation
285
+ """
286
+ super().__init__(timeout)
287
+
288
+ # SECURITY: Validate command before storing
289
+ is_valid, error_msg = self.validate_command(command)
290
+ if not is_valid:
291
+ self.logger.error(f"SECURITY: MCP command validation failed: {error_msg}")
292
+ raise MCPConnectionError(f"MCP command validation failed: {error_msg}")
293
+
294
+ self.command = command
295
+ self.env = env
296
+ self.process: Optional[subprocess.Popen] = None
297
+ self._read_lock = asyncio.Lock()
298
+ self._write_lock = asyncio.Lock()
299
+ self._health_task: Optional[asyncio.Task] = None
300
+
301
+ async def _monitor_process_health(self) -> None:
302
+ """Monitor subprocess health."""
303
+ while not self._closed:
304
+ try:
305
+ if self.process:
306
+ # Check if process is still running
307
+ returncode = self.process.poll()
308
+ if returncode is not None:
309
+ self.logger.error(
310
+ f"❌ MCP subprocess exited with code {returncode}!"
311
+ )
312
+ # Try to read stderr for error info
313
+ if self.process.stderr:
314
+ try:
315
+ stderr = self.process.stderr.read()
316
+ if stderr:
317
+ self.logger.error(f"Subprocess stderr: {stderr}")
318
+ except Exception:
319
+ pass
320
+ break
321
+
322
+ await asyncio.sleep(5) # Check every 5s
323
+
324
+ except Exception as e:
325
+ self.logger.error(f"Error in health monitor: {e}")
326
+ await asyncio.sleep(5)
327
+
328
+ async def _read_stderr(self) -> None:
329
+ """Read stderr for debugging."""
330
+ try:
331
+ if self.process and self.process.stderr:
332
+ while self.process.poll() is None:
333
+ line = await asyncio.to_thread(self.process.stderr.readline)
334
+ if line:
335
+ self.logger.debug(f"MCP stderr: {line.strip()}")
336
+ else:
337
+ await asyncio.sleep(0.1)
338
+ except Exception as e:
339
+ self.logger.debug(f"Stderr reader ended: {e}")
340
+
341
+ async def connect(self) -> None:
342
+ """Start the subprocess and establish connection."""
343
+ try:
344
+ import os
345
+ full_env = {**os.environ, **(self.env or {})}
346
+
347
+ # Debug logging
348
+ self.logger.debug(f"Starting MCP process with command: {self.command}")
349
+ if self.env:
350
+ self.logger.debug(f"Additional env vars: {list(self.env.keys())}")
351
+
352
+ self.process = subprocess.Popen(
353
+ self.command,
354
+ stdin=subprocess.PIPE,
355
+ stdout=subprocess.PIPE,
356
+ stderr=subprocess.PIPE,
357
+ text=True,
358
+ env=full_env,
359
+ bufsize=0 # Unbuffered for better real-time communication
360
+ )
361
+
362
+ # Wait a bit for process to start
363
+ await asyncio.sleep(0.1)
364
+
365
+ # Check if process started successfully
366
+ if self.process.poll() is not None:
367
+ stderr_output = ""
368
+ if self.process.stderr:
369
+ stderr_output = self.process.stderr.read()
370
+ raise MCPConnectionError(f"Process failed to start: {stderr_output}")
371
+
372
+ self.logger.info(f"Started MCP STDIO process with PID {self.process.pid}")
373
+
374
+ # Start health monitor
375
+ self._health_task = asyncio.create_task(self._monitor_process_health())
376
+
377
+ # Start stderr reader task for debugging
378
+ if self.process.stderr:
379
+ asyncio.create_task(self._read_stderr())
380
+
381
+ except Exception as e:
382
+ raise MCPConnectionError(f"Failed to start STDIO transport: {e}")
383
+
384
+ async def send_message(self, message: MCPMessage) -> None:
385
+ """Send message to STDIO process."""
386
+ if not self.process or self.process.stdin is None:
387
+ raise MCPConnectionError("STDIO transport not connected")
388
+
389
+ async with self._write_lock:
390
+ try:
391
+ # Convert message to JSON
392
+ message_dict = {
393
+ "jsonrpc": message.jsonrpc,
394
+ "id": message.id
395
+ }
396
+
397
+ if isinstance(message, MCPRequest):
398
+ message_dict["method"] = message.method
399
+ if message.params:
400
+ message_dict["params"] = message.params
401
+ elif isinstance(message, MCPResponse):
402
+ if message.result is not None:
403
+ message_dict["result"] = message.result
404
+ if message.error is not None:
405
+ message_dict["error"] = message.error
406
+ elif isinstance(message, MCPNotification):
407
+ message_dict["method"] = message.method
408
+ if message.params:
409
+ message_dict["params"] = message.params
410
+ # Remove id for notifications
411
+ message_dict.pop("id", None)
412
+
413
+ json_str = json.dumps(message_dict) + "\n"
414
+
415
+ # Write to process stdin
416
+ await asyncio.to_thread(self.process.stdin.write, json_str)
417
+ await asyncio.to_thread(self.process.stdin.flush)
418
+
419
+ self.logger.debug(f"Sent MCP message: {json_str.strip()}")
420
+
421
+ except Exception as e:
422
+ raise MCPProtocolError(f"Failed to send message: {e}")
423
+
424
+ async def receive_message(self, timeout: Optional[float] = None) -> Optional[MCPMessage]:
425
+ """Receive message from STDIO process.
426
+
427
+ Args:
428
+ timeout: Optional timeout override (uses self.timeout if None)
429
+
430
+ Returns:
431
+ MCPMessage if received, None if timeout or no message available
432
+ """
433
+ if not self.process or self.process.stdout is None:
434
+ raise MCPConnectionError("STDIO transport not connected")
435
+
436
+ receive_timeout = timeout if timeout is not None else self.timeout
437
+
438
+ async with self._read_lock:
439
+ try:
440
+ # Read line from stdout with timeout
441
+ line = await asyncio.wait_for(
442
+ asyncio.to_thread(self.process.stdout.readline),
443
+ timeout=receive_timeout
444
+ )
445
+
446
+ if not line:
447
+ return None
448
+
449
+ # Parse JSON
450
+ message_dict = json.loads(line.strip())
451
+
452
+ # Validate basic structure
453
+ if message_dict.get("jsonrpc") != "2.0":
454
+ raise MCPProtocolError(f"Invalid JSON-RPC version: {message_dict.get('jsonrpc')}")
455
+
456
+ # Create appropriate message object
457
+ if "method" in message_dict:
458
+ if "id" in message_dict:
459
+ # Request
460
+ return MCPRequest(
461
+ id=message_dict["id"],
462
+ method=message_dict["method"],
463
+ params=message_dict.get("params")
464
+ )
465
+ else:
466
+ # Notification
467
+ return MCPNotification(
468
+ method=message_dict["method"],
469
+ params=message_dict.get("params")
470
+ )
471
+ else:
472
+ # Response
473
+ return MCPResponse(
474
+ id=message_dict.get("id"),
475
+ result=message_dict.get("result"),
476
+ error=message_dict.get("error")
477
+ )
478
+
479
+ except asyncio.TimeoutError:
480
+ self.logger.debug(f"receive_message timed out after {receive_timeout}s")
481
+ return None
482
+ except json.JSONDecodeError as e:
483
+ raise MCPProtocolError(f"Invalid JSON received: {e}")
484
+ except Exception as e:
485
+ raise MCPProtocolError(f"Failed to receive message: {e}")
486
+
487
+ async def close(self) -> None:
488
+ """Close the STDIO transport."""
489
+ await super().close()
490
+
491
+ if self.process:
492
+ try:
493
+ # Terminate process gracefully
494
+ self.process.terminate()
495
+
496
+ # Wait for process to end
497
+ try:
498
+ await asyncio.wait_for(
499
+ asyncio.to_thread(self.process.wait),
500
+ timeout=5.0
501
+ )
502
+ except asyncio.TimeoutError:
503
+ # Force kill if it doesn't terminate
504
+ self.process.kill()
505
+ await asyncio.to_thread(self.process.wait)
506
+
507
+ self.logger.info(f"Closed MCP STDIO process PID {self.process.pid}")
508
+
509
+ except Exception as e:
510
+ self.logger.error(f"Error closing STDIO transport: {e}")
511
+ finally:
512
+ self.process = None
513
+
514
+
515
+ class MCPSSETransport(MCPTransport):
516
+ """Server-Sent Events transport for MCP communication."""
517
+
518
+ def __init__(
519
+ self,
520
+ url: str,
521
+ headers: Optional[Dict[str, str]] = None,
522
+ timeout: int = 180,
523
+ message_endpoint: Optional[str] = None, # FIX #7: Explicit POST endpoint
524
+ allow_http: bool = False, # SSRF: only relax HTTPS for local dev
525
+ validate_ssrf: bool = False # SSRF: pin+validate at connect (user servers)
526
+ ):
527
+ super().__init__(timeout)
528
+ self.url = url
529
+ self.headers = headers or {}
530
+ self.message_endpoint = message_endpoint # User-provided or auto-derived
531
+ self.allow_http = allow_http
532
+ self.validate_ssrf = validate_ssrf
533
+ self.session: Optional[aiohttp.ClientSession] = None
534
+ self._response: Optional[aiohttp.ClientResponse] = None
535
+ self._message_queue: asyncio.Queue = asyncio.Queue()
536
+ self._reader_task: Optional[asyncio.Task] = None
537
+ self._session_id: Optional[str] = None # For servers requiring sessionId
538
+
539
+ async def connect(self) -> None:
540
+ """Connect to SSE endpoint."""
541
+ try:
542
+ # Generate sessionId for servers that require it (like Anysite)
543
+ import uuid
544
+ self._session_id = str(uuid.uuid4())
545
+
546
+ # FIX: Increase timeout for SSE connections (they can be slow to establish)
547
+ timeout = aiohttp.ClientTimeout(
548
+ total=self.timeout,
549
+ connect=30, # 30s for connection
550
+ sock_read=self.timeout # Full timeout for reading
551
+ )
552
+
553
+ # SECURITY (SSRF/DNS rebinding): validate the URL at connect time and
554
+ # pin the resolved+validated IP so DNS cannot rebind to an internal
555
+ # address between add-time validation and now.
556
+ connector = _validate_and_pin_connector(
557
+ self.url, allow_http=self.allow_http, ssl=True, limit=10,
558
+ validate_ssrf=self.validate_ssrf, ttl_dns_cache=300
559
+ )
560
+
561
+ self.session = aiohttp.ClientSession(
562
+ headers=self.headers,
563
+ timeout=timeout,
564
+ connector=connector
565
+ )
566
+
567
+ # FIX: Connect to SSE endpoint with proper headers and sessionId query parameter
568
+ sse_headers = {
569
+ **self.headers,
570
+ 'Accept': 'text/event-stream',
571
+ 'Cache-Control': 'no-cache',
572
+ 'Connection': 'keep-alive'
573
+ }
574
+
575
+ # Add sessionId query parameter for servers that require it
576
+ sse_url = f"{self.url}?sessionId={self._session_id}"
577
+
578
+ self.logger.info(f"Connecting to SSE endpoint: {sse_url}")
579
+ self.logger.debug(f"SSE headers: {list(sse_headers.keys())}")
580
+
581
+ # SECURITY: do not follow redirects — a 3xx Location could point at an
582
+ # internal/metadata host that bypasses the pinned connector.
583
+ self._response = await self.session.get(
584
+ sse_url,
585
+ headers=sse_headers,
586
+ allow_redirects=False
587
+ )
588
+
589
+ if self._response.status != 200:
590
+ body = await self._response.text()
591
+ self.logger.error(
592
+ f"SSE connection failed - Status: {self._response.status}, "
593
+ f"Body: {body[:500]}"
594
+ )
595
+ raise MCPConnectionError(
596
+ f"SSE connection failed with status {self._response.status}: {body[:200]}"
597
+ )
598
+
599
+ # Verify content type
600
+ content_type = self._response.headers.get('Content-Type', '')
601
+ if 'text/event-stream' not in content_type:
602
+ self.logger.warning(
603
+ f"Unexpected Content-Type: {content_type} (expected text/event-stream)"
604
+ )
605
+
606
+ # Start reading SSE messages
607
+ self._reader_task = asyncio.create_task(self._read_sse_messages())
608
+
609
+ self.logger.info(f"✅ Connected to MCP SSE endpoint: {self.url}")
610
+
611
+ except aiohttp.ClientError as e:
612
+ self.logger.error(f"Network error connecting to SSE endpoint: {e}")
613
+ await self.close()
614
+ raise MCPConnectionError(f"Network error connecting to SSE endpoint: {e}")
615
+ except Exception as e:
616
+ self.logger.error(f"Failed to connect to SSE endpoint: {e}", exc_info=True)
617
+ await self.close()
618
+ raise MCPConnectionError(f"Failed to connect to SSE endpoint: {e}")
619
+
620
+ async def _read_sse_messages(self) -> None:
621
+ """Read SSE messages and queue them."""
622
+ try:
623
+ if not self._response:
624
+ return
625
+
626
+ async for line in self._response.content:
627
+ line_str = line.decode('utf-8').strip()
628
+
629
+ if line_str.startswith('data: '):
630
+ data = line_str[6:] # Remove 'data: ' prefix
631
+
632
+ try:
633
+ message_dict = json.loads(data)
634
+
635
+ # Create message object
636
+ if "method" in message_dict:
637
+ if "id" in message_dict:
638
+ message = MCPRequest(
639
+ id=message_dict["id"],
640
+ method=message_dict["method"],
641
+ params=message_dict.get("params")
642
+ )
643
+ else:
644
+ message = MCPNotification(
645
+ method=message_dict["method"],
646
+ params=message_dict.get("params")
647
+ )
648
+ else:
649
+ message = MCPResponse(
650
+ id=message_dict.get("id"),
651
+ result=message_dict.get("result"),
652
+ error=message_dict.get("error")
653
+ )
654
+
655
+ await self._message_queue.put(message)
656
+
657
+ except json.JSONDecodeError as e:
658
+ self.logger.warning(f"Invalid JSON in SSE message: {e}")
659
+
660
+ except Exception as e:
661
+ self.logger.error(f"Error reading SSE messages: {e}")
662
+
663
+ async def send_message(self, message: MCPMessage) -> None:
664
+ """Send message via HTTP POST to the message endpoint.
665
+
666
+ For MCP over SSE, messages are sent to a separate POST endpoint
667
+ (typically the same URL without /sse suffix or a /messages endpoint).
668
+ """
669
+ if not self.session:
670
+ raise MCPConnectionError("SSE transport not connected")
671
+
672
+ try:
673
+ # Convert message to dict
674
+ message_dict = {
675
+ "jsonrpc": message.jsonrpc,
676
+ "id": message.id
677
+ }
678
+
679
+ if isinstance(message, MCPRequest):
680
+ message_dict["method"] = message.method
681
+ if message.params:
682
+ message_dict["params"] = message.params
683
+ elif isinstance(message, MCPResponse):
684
+ if message.result is not None:
685
+ message_dict["result"] = message.result
686
+ if message.error is not None:
687
+ message_dict["error"] = message.error
688
+
689
+ # FIX #7: Use explicit message_endpoint if provided, otherwise derive
690
+ if self.message_endpoint:
691
+ # User provided explicit POST endpoint
692
+ post_url = self.message_endpoint
693
+ else:
694
+ # Derive POST endpoint from SSE URL
695
+ post_url = self.url
696
+
697
+ # If URL ends with /sse, try replacing with /message
698
+ if post_url.endswith('/sse'):
699
+ post_url = post_url[:-4] + '/message'
700
+ elif post_url.endswith('/events'):
701
+ post_url = post_url[:-7] + '/message'
702
+
703
+ # Add sessionId query parameter if we have one
704
+ if self._session_id:
705
+ separator = '&' if '?' in post_url else '?'
706
+ post_url = f"{post_url}{separator}sessionId={self._session_id}"
707
+
708
+ self.logger.debug(f"Sending message to POST endpoint: {post_url}")
709
+
710
+ # Send via POST with proper headers
711
+ # SECURITY: don't follow redirects (would bypass the pinned connector).
712
+ async with self.session.post(
713
+ post_url,
714
+ json=message_dict,
715
+ headers={**self.headers, 'Content-Type': 'application/json'},
716
+ allow_redirects=False
717
+ ) as response:
718
+ if response.status not in (200, 202, 204):
719
+ response_text = await response.text()
720
+ self.logger.error(
721
+ f"Failed to send message - Status: {response.status}, "
722
+ f"Body: {response_text[:200]}"
723
+ )
724
+ raise MCPProtocolError(
725
+ f"Failed to send message, status: {response.status}, body: {response_text[:100]}"
726
+ )
727
+
728
+ self.logger.debug(f"✅ Sent MCP message to {post_url}: {message_dict.get('method', 'response')}")
729
+
730
+ except aiohttp.ClientError as e:
731
+ self.logger.error(f"Network error sending SSE message: {e}")
732
+ raise MCPProtocolError(f"Network error sending SSE message: {e}")
733
+ except Exception as e:
734
+ self.logger.error(f"Failed to send SSE message: {e}", exc_info=True)
735
+ raise MCPProtocolError(f"Failed to send SSE message: {e}")
736
+
737
+ async def receive_message(self, timeout: Optional[float] = None) -> Optional[MCPMessage]:
738
+ """Receive message from queue.
739
+
740
+ Args:
741
+ timeout: Optional timeout override (uses self.timeout if None)
742
+
743
+ Returns:
744
+ MCPMessage if received, None if timeout
745
+ """
746
+ receive_timeout = timeout if timeout is not None else self.timeout
747
+ try:
748
+ return await asyncio.wait_for(
749
+ self._message_queue.get(),
750
+ timeout=receive_timeout
751
+ )
752
+ except asyncio.TimeoutError:
753
+ return None
754
+
755
+ async def close(self) -> None:
756
+ """Close SSE transport."""
757
+ await super().close()
758
+
759
+ if self._reader_task:
760
+ self._reader_task.cancel()
761
+ try:
762
+ await self._reader_task
763
+ except asyncio.CancelledError:
764
+ pass
765
+
766
+ if self._response:
767
+ self._response.close()
768
+ self._response = None
769
+
770
+ if self.session:
771
+ await self.session.close()
772
+ self.session = None
773
+
774
+ self.logger.info("Closed MCP SSE transport")
775
+
776
+
777
+ class MCPHTTPTransport(MCPTransport):
778
+ """HTTP JSON-RPC transport for MCP (request-response, no streaming)."""
779
+
780
+ def __init__(self, url: str, headers: Optional[Dict[str, str]] = None, timeout: int = 180, allow_http: bool = False, validate_ssrf: bool = False):
781
+ super().__init__(timeout)
782
+ self.url = url
783
+ self.headers = headers or {}
784
+ self.allow_http = allow_http # SSRF: only relax HTTPS for local dev
785
+ self.validate_ssrf = validate_ssrf # SSRF: pin+validate at connect (user servers)
786
+ self.session: Optional[aiohttp.ClientSession] = None
787
+ self._message_queue: asyncio.Queue = asyncio.Queue()
788
+ self._response_futures: Dict[str, asyncio.Future] = {}
789
+
790
+ async def connect(self) -> None:
791
+ """Connect HTTP session."""
792
+ try:
793
+ timeout = aiohttp.ClientTimeout(total=self.timeout)
794
+ # SECURITY (SSRF/DNS rebinding): validate + pin resolved IP at connect time.
795
+ connector = _validate_and_pin_connector(self.url, allow_http=self.allow_http, ssl=True, validate_ssrf=self.validate_ssrf)
796
+
797
+ self.session = aiohttp.ClientSession(
798
+ headers=self.headers,
799
+ timeout=timeout,
800
+ connector=connector
801
+ )
802
+
803
+ self.logger.info(f"✅ HTTP JSON-RPC transport ready: {self.url}")
804
+
805
+ except Exception as e:
806
+ await self.close()
807
+ raise MCPConnectionError(f"Failed to initialize HTTP transport: {e}")
808
+
809
+ async def send_message(self, message: MCPMessage) -> None:
810
+ """Send message via HTTP POST and queue response."""
811
+ if not self.session:
812
+ raise MCPConnectionError("HTTP transport not connected")
813
+
814
+ try:
815
+ # Convert message to dict
816
+ message_dict = {
817
+ "jsonrpc": message.jsonrpc,
818
+ "id": message.id
819
+ }
820
+
821
+ if isinstance(message, MCPRequest):
822
+ message_dict["method"] = message.method
823
+ if message.params:
824
+ message_dict["params"] = message.params
825
+
826
+ self.logger.debug(f"📤 HTTP POST {message_dict.get('method', 'response')}")
827
+
828
+ # Send via POST and get immediate response
829
+ # SECURITY: don't follow redirects (would bypass the pinned connector).
830
+ async with self.session.post(
831
+ self.url,
832
+ json=message_dict,
833
+ headers={**self.headers, 'Content-Type': 'application/json'},
834
+ allow_redirects=False
835
+ ) as response:
836
+ if response.status not in (200, 202):
837
+ response_text = await response.text()
838
+ self.logger.error(
839
+ f"HTTP failed - Status: {response.status}, Body: {response_text[:200]}"
840
+ )
841
+ raise MCPProtocolError(
842
+ f"HTTP failed, status: {response.status}, body: {response_text[:100]}"
843
+ )
844
+
845
+ # Parse and queue response
846
+ response_data = await response.json()
847
+ response_msg = MCPResponse(
848
+ id=response_data.get("id"),
849
+ result=response_data.get("result"),
850
+ error=response_data.get("error")
851
+ )
852
+
853
+ # Queue the response for receive_message to pick up
854
+ await self._message_queue.put(response_msg)
855
+ self.logger.debug(f"📥 HTTP response queued")
856
+
857
+ except aiohttp.ClientError as e:
858
+ self.logger.error(f"Network error in HTTP transport: {e}")
859
+ raise MCPProtocolError(f"Network error: {e}")
860
+ except Exception as e:
861
+ self.logger.error(f"Failed HTTP request: {e}", exc_info=True)
862
+ raise MCPProtocolError(f"Failed HTTP request: {e}")
863
+
864
+ async def receive_message(self, timeout: Optional[float] = None) -> Optional[MCPMessage]:
865
+ """Receive message from queue."""
866
+ receive_timeout = timeout if timeout is not None else self.timeout
867
+ try:
868
+ return await asyncio.wait_for(
869
+ self._message_queue.get(),
870
+ timeout=receive_timeout
871
+ )
872
+ except asyncio.TimeoutError:
873
+ return None
874
+
875
+ async def close(self) -> None:
876
+ """Close HTTP transport."""
877
+ await super().close()
878
+
879
+ if self.session:
880
+ await self.session.close()
881
+ self.session = None
882
+
883
+ self.logger.info("Closed MCP HTTP transport")
884
+
885
+
886
+ class MCPStreamableHTTPTransport(MCPTransport):
887
+ """
888
+ Streamable HTTP transport for MCP (POST with SSE responses).
889
+
890
+ This transport type is used by servers like mcp.anysite.io/mcp that:
891
+ - Accept POST requests with JSON-RPC body
892
+ - Return responses as SSE-formatted streams (event: message, data: {...})
893
+ - Require session ID management via mcp-session-id header
894
+ - Require Accept: application/json, text/event-stream header
895
+ """
896
+
897
+ def __init__(
898
+ self,
899
+ url: str,
900
+ headers: Optional[Dict[str, str]] = None,
901
+ timeout: int = 180,
902
+ allow_http: bool = False, # SSRF: only relax HTTPS for local dev
903
+ validate_ssrf: bool = False # SSRF: pin+validate at connect (user servers)
904
+ ):
905
+ super().__init__(timeout)
906
+ self.url = url
907
+ self.headers = headers or {}
908
+ self.allow_http = allow_http
909
+ self.validate_ssrf = validate_ssrf
910
+ self.session: Optional[aiohttp.ClientSession] = None
911
+ self._message_queue: asyncio.Queue = asyncio.Queue()
912
+ self._session_id: Optional[str] = None # MCP session ID for stateful connections
913
+
914
+ async def connect(self) -> None:
915
+ """Initialize HTTP session for streamable transport."""
916
+ try:
917
+ timeout = aiohttp.ClientTimeout(
918
+ total=self.timeout,
919
+ connect=30
920
+ )
921
+ # SECURITY (SSRF/DNS rebinding): validate + pin resolved IP at connect time.
922
+ connector = _validate_and_pin_connector(self.url, allow_http=self.allow_http, ssl=True, limit=10, validate_ssrf=self.validate_ssrf)
923
+
924
+ # Base headers (session ID will be added per-request after initialization)
925
+ base_headers = {
926
+ **self.headers,
927
+ 'Accept': 'application/json, text/event-stream',
928
+ 'Content-Type': 'application/json'
929
+ }
930
+
931
+ self.session = aiohttp.ClientSession(
932
+ headers=base_headers,
933
+ timeout=timeout,
934
+ connector=connector
935
+ )
936
+
937
+ self.logger.info(f"✅ Streamable HTTP transport ready: {self.url}")
938
+
939
+ except Exception as e:
940
+ await self.close()
941
+ raise MCPConnectionError(f"Failed to initialize Streamable HTTP transport: {e}")
942
+
943
+ async def send_message(self, message: MCPMessage) -> None:
944
+ """Send message via POST and read SSE-formatted response."""
945
+ if not self.session:
946
+ raise MCPConnectionError("Streamable HTTP transport not connected")
947
+
948
+ try:
949
+ # Convert message to dict based on type
950
+ message_dict = {"jsonrpc": message.jsonrpc}
951
+
952
+ # Build request headers - include session ID if we have one
953
+ request_headers = {}
954
+ if self._session_id:
955
+ request_headers['mcp-session-id'] = self._session_id
956
+
957
+ if isinstance(message, MCPRequest):
958
+ message_dict["id"] = message.id
959
+ message_dict["method"] = message.method
960
+ if message.params:
961
+ message_dict["params"] = message.params
962
+ elif isinstance(message, MCPNotification):
963
+ # Notifications don't have id field
964
+ message_dict["method"] = message.method
965
+ if message.params:
966
+ message_dict["params"] = message.params
967
+ # Skip sending response wait for notifications
968
+ self.logger.debug(f"📤 Streamable notification: {message.method}")
969
+ async with self.session.post(self.url, json=message_dict, headers=request_headers, allow_redirects=False) as response:
970
+ # Capture session ID from response if present
971
+ if 'mcp-session-id' in response.headers:
972
+ self._session_id = response.headers['mcp-session-id']
973
+ self.logger.debug(f"📋 Session ID updated: {self._session_id[:20]}...")
974
+ if response.status not in (200, 202, 204):
975
+ response_text = await response.text()
976
+ self.logger.warning(f"Notification response: {response.status}, {response_text[:100]}")
977
+ return # No response expected for notifications
978
+ elif isinstance(message, MCPResponse):
979
+ message_dict["id"] = message.id
980
+ if message.result is not None:
981
+ message_dict["result"] = message.result
982
+ if message.error is not None:
983
+ message_dict["error"] = message.error
984
+
985
+ self.logger.debug(f"📤 Streamable POST {message_dict.get('method', 'response')}")
986
+
987
+ # Send POST and read SSE response
988
+ # SECURITY: don't follow redirects (would bypass the pinned connector).
989
+ async with self.session.post(self.url, json=message_dict, headers=request_headers, allow_redirects=False) as response:
990
+ # Capture session ID from response headers (servers send it on initialize)
991
+ if 'mcp-session-id' in response.headers:
992
+ self._session_id = response.headers['mcp-session-id']
993
+ self.logger.info(f"📋 MCP Session ID captured: {self._session_id[:20]}...")
994
+
995
+ if response.status not in (200, 202):
996
+ response_text = await response.text()
997
+ self.logger.error(
998
+ f"Streamable HTTP failed - Status: {response.status}, Body: {response_text[:200]}"
999
+ )
1000
+ raise MCPProtocolError(
1001
+ f"Streamable HTTP failed, status: {response.status}"
1002
+ )
1003
+
1004
+ # Read response as SSE stream
1005
+ content_type = response.headers.get('Content-Type', '')
1006
+
1007
+ if 'text/event-stream' in content_type:
1008
+ # Parse SSE response - may have multiple events
1009
+ async for line in response.content:
1010
+ line_str = line.decode('utf-8').strip()
1011
+
1012
+ if line_str.startswith('data: '):
1013
+ data = line_str[6:] # Remove 'data: ' prefix
1014
+ try:
1015
+ response_data = json.loads(data)
1016
+ response_msg = MCPResponse(
1017
+ id=response_data.get("id"),
1018
+ result=response_data.get("result"),
1019
+ error=response_data.get("error")
1020
+ )
1021
+ await self._message_queue.put(response_msg)
1022
+ self.logger.debug(f"📥 Streamable response queued")
1023
+ break # Got our response
1024
+ except json.JSONDecodeError as e:
1025
+ self.logger.warning(f"Invalid JSON in SSE data: {e}")
1026
+ else:
1027
+ # Plain JSON response
1028
+ response_data = await response.json()
1029
+ response_msg = MCPResponse(
1030
+ id=response_data.get("id"),
1031
+ result=response_data.get("result"),
1032
+ error=response_data.get("error")
1033
+ )
1034
+ await self._message_queue.put(response_msg)
1035
+ self.logger.debug(f"📥 HTTP response queued")
1036
+
1037
+ except aiohttp.ClientError as e:
1038
+ self.logger.error(f"Network error in Streamable HTTP transport: {e}")
1039
+ raise MCPProtocolError(f"Network error: {e}")
1040
+ except Exception as e:
1041
+ self.logger.error(f"Failed Streamable HTTP request: {e}", exc_info=True)
1042
+ raise MCPProtocolError(f"Failed Streamable HTTP request: {e}")
1043
+
1044
+ async def receive_message(self, timeout: Optional[float] = None) -> Optional[MCPMessage]:
1045
+ """Receive message from queue."""
1046
+ receive_timeout = timeout if timeout is not None else self.timeout
1047
+ try:
1048
+ return await asyncio.wait_for(
1049
+ self._message_queue.get(),
1050
+ timeout=receive_timeout
1051
+ )
1052
+ except asyncio.TimeoutError:
1053
+ return None
1054
+
1055
+ async def close(self) -> None:
1056
+ """Close Streamable HTTP transport."""
1057
+ await super().close()
1058
+
1059
+ if self.session:
1060
+ await self.session.close()
1061
+ self.session = None
1062
+
1063
+ self.logger.info("Closed MCP Streamable HTTP transport")
1064
+
1065
+
1066
+ class MCPClient:
1067
+ """MCP client for handling protocol communication."""
1068
+
1069
+ def __init__(self, transport: MCPTransport):
1070
+ self.transport = transport
1071
+ self.logger = get_component_logger(self.__class__.__name__)
1072
+ self._pending_requests: Dict[str, asyncio.Future] = {}
1073
+ self._capabilities: Dict[str, Any] = {}
1074
+ self._tools: List[Dict[str, Any]] = []
1075
+ self._resources: List[Dict[str, Any]] = []
1076
+ self._connected = False
1077
+ self._message_handler_task: Optional[asyncio.Task] = None
1078
+
1079
+ # Health monitoring attributes
1080
+ self._message_loop_alive = asyncio.Event()
1081
+ self._last_message_time = 0.0
1082
+ self._message_loop_restart_count = 0
1083
+ self._cleanup_task: Optional[asyncio.Task] = None
1084
+
1085
+ # Item 7F: invoked with the updated resource uri when the server sends
1086
+ # notifications/resources/updated. Set by the server manager. Default no-op.
1087
+ self._resource_update_handler: Optional[Callable[[str], Any]] = None
1088
+
1089
+ async def connect(self) -> None:
1090
+ """Connect and initialize MCP session."""
1091
+ try:
1092
+ await self.transport.connect()
1093
+
1094
+ # Start message handler task
1095
+ self._message_handler_task = asyncio.create_task(self.process_messages())
1096
+
1097
+ # Send initialize request
1098
+ init_request = MCPRequest(
1099
+ method="initialize",
1100
+ params={
1101
+ "protocolVersion": "2024-11-05",
1102
+ "capabilities": {
1103
+ "tools": True,
1104
+ "resources": True
1105
+ },
1106
+ "clientInfo": {
1107
+ "name": "POLYROB MCP Client",
1108
+ "version": _client_version()
1109
+ }
1110
+ }
1111
+ )
1112
+
1113
+ response = await self._send_request(init_request)
1114
+
1115
+ if response.error:
1116
+ raise MCPProtocolError(f"Initialization failed: {response.error}")
1117
+
1118
+ # Store server capabilities
1119
+ if response.result:
1120
+ self._capabilities = response.result.get("capabilities", {})
1121
+ self.logger.info(f"Server capabilities: {self._capabilities}")
1122
+
1123
+ # Send initialized notification
1124
+ initialized_notification = MCPNotification(
1125
+ method="initialized"
1126
+ )
1127
+ await self.transport.send_message(initialized_notification)
1128
+
1129
+ # Discover tools and resources
1130
+ await self._discover_capabilities()
1131
+
1132
+ # Start cleanup task
1133
+ self._cleanup_task = asyncio.create_task(self._cleanup_pending_requests())
1134
+
1135
+ self._connected = True
1136
+ self.logger.info("MCP client connected and initialized")
1137
+
1138
+ except Exception as e:
1139
+ await self.close()
1140
+ raise MCPConnectionError(f"Failed to connect MCP client: {e}")
1141
+
1142
+ async def _send_request(self, request: MCPRequest, timeout: Optional[float] = None) -> MCPResponse:
1143
+ """Send request and wait for response.
1144
+
1145
+ Args:
1146
+ request: The MCP request to send
1147
+ timeout: Timeout in seconds (defaults to transport timeout)
1148
+
1149
+ Returns:
1150
+ MCPResponse from the server
1151
+
1152
+ Raises:
1153
+ MCPProtocolError: If request times out or fails
1154
+ """
1155
+ import time
1156
+
1157
+ if not request.id:
1158
+ request.id = str(uuid.uuid4())
1159
+
1160
+ # Use provided timeout or default to transport timeout
1161
+ request_timeout = timeout if timeout is not None else self.transport.timeout
1162
+
1163
+ # Create future with timeout tracking
1164
+ future = asyncio.Future()
1165
+ future._timeout_at = time.time() + request_timeout
1166
+ future._request_method = request.method
1167
+ self._pending_requests[request.id] = future
1168
+
1169
+ try:
1170
+ # Detailed logging showing timeout source for debugging
1171
+ timeout_source = "explicit" if timeout is not None else "transport"
1172
+ self.logger.info(
1173
+ f"📤 Sending request {request.method} (id={request.id[:8]}) "
1174
+ f"with {request_timeout}s timeout "
1175
+ f"(source: {timeout_source}, transport: {self.transport.timeout}s, "
1176
+ f"transport_class: {self.transport.__class__.__name__})"
1177
+ )
1178
+
1179
+ await self.transport.send_message(request)
1180
+
1181
+ # Wait with timeout
1182
+ start_time = time.time()
1183
+ try:
1184
+ response = await asyncio.wait_for(future, timeout=request_timeout)
1185
+ elapsed = time.time() - start_time
1186
+ self.logger.info(f"📥 Received response for {request.method} in {elapsed:.2f}s")
1187
+ return response
1188
+ except asyncio.TimeoutError:
1189
+ elapsed = time.time() - start_time
1190
+
1191
+ # Provide context-aware error hints
1192
+ if request_timeout < 60:
1193
+ hint = (
1194
+ f"\n\n💡 Timeout is very short (<60s). For MCP operations, 90-180s is recommended. "
1195
+ f"This may be a configuration issue. "
1196
+ f"Check timeout settings in mcp_config.json for this server."
1197
+ )
1198
+ else:
1199
+ hint = (
1200
+ f"\n\n💡 This may be a server issue or the operation is too complex. "
1201
+ f"Consider: (1) Check if MCP server process is running, "
1202
+ f"(2) Try a simpler/smaller operation, (3) Check server logs for errors."
1203
+ )
1204
+
1205
+ error_msg = (
1206
+ f"⏱️ Request {request.method} (id={request.id[:8]}) timed out after {elapsed:.2f}s.\n"
1207
+ f"Timeout configured: {request_timeout}s (source: {timeout_source})\n"
1208
+ f"Transport: {self.transport.__class__.__name__} @ {self.transport.timeout}s\n"
1209
+ f"Pending requests: {len(self._pending_requests)}\n"
1210
+ f"Message loop: {'healthy' if self.is_message_loop_healthy else 'UNHEALTHY'}"
1211
+ f"{hint}"
1212
+ )
1213
+
1214
+ self.logger.error(error_msg)
1215
+ raise MCPProtocolError(error_msg)
1216
+
1217
+ finally:
1218
+ # Always cleanup
1219
+ self._pending_requests.pop(request.id, None)
1220
+
1221
+ async def _discover_capabilities(self) -> None:
1222
+ """Discover available tools and resources with retry logic."""
1223
+ max_retries = 3
1224
+ retry_delay = 1.0
1225
+
1226
+ self.logger.debug(f"Starting capability discovery. Server capabilities: {self._capabilities}")
1227
+
1228
+ for attempt in range(max_retries):
1229
+ try:
1230
+ # List tools
1231
+ # Check if server supports tools (can be True, {}, or any truthy value)
1232
+ if "tools" in self._capabilities:
1233
+ self.logger.debug(f"Requesting tools list (attempt {attempt + 1})")
1234
+ tools_request = MCPRequest(method="tools/list")
1235
+ tools_response = await self._send_request(tools_request)
1236
+
1237
+ self.logger.debug(f"Tools response: {tools_response.result}")
1238
+
1239
+ if tools_response.result:
1240
+ self._tools = tools_response.result.get("tools", [])
1241
+ self.logger.info(f"Discovered {len(self._tools)} tools")
1242
+ if self._tools:
1243
+ for tool in self._tools[:3]: # Log first 3 tools
1244
+ self.logger.debug(f" Tool: {tool.get('name', 'unknown')}")
1245
+
1246
+ # List resources
1247
+ if "resources" in self._capabilities:
1248
+ self.logger.debug(f"Requesting resources list (attempt {attempt + 1})")
1249
+ resources_request = MCPRequest(method="resources/list")
1250
+ resources_response = await self._send_request(resources_request)
1251
+
1252
+ if resources_response.result:
1253
+ self._resources = resources_response.result.get("resources", [])
1254
+ self.logger.info(f"Discovered {len(self._resources)} resources")
1255
+
1256
+ # If we got tools or don't support tools, we're done
1257
+ if self._tools or "tools" not in self._capabilities:
1258
+ break
1259
+
1260
+ # If no tools found but server supports them, wait and retry
1261
+ if attempt < max_retries - 1:
1262
+ self.logger.info(f"No tools discovered yet, retrying in {retry_delay}s (attempt {attempt + 1}/{max_retries})")
1263
+ await asyncio.sleep(retry_delay)
1264
+ retry_delay *= 1.5 # Exponential backoff
1265
+
1266
+ except Exception as e:
1267
+ if attempt < max_retries - 1:
1268
+ self.logger.warning(f"Failed to discover capabilities (attempt {attempt + 1}/{max_retries}): {e}")
1269
+ await asyncio.sleep(retry_delay)
1270
+ retry_delay *= 1.5
1271
+ else:
1272
+ self.logger.warning(f"Failed to discover capabilities after {max_retries} attempts: {e}")
1273
+
1274
+ async def _cleanup_pending_requests(self) -> None:
1275
+ """Cleanup stale pending requests."""
1276
+ import time
1277
+
1278
+ while self._connected:
1279
+ try:
1280
+ await asyncio.sleep(10) # Check every 10s
1281
+
1282
+ current_time = time.time()
1283
+ stale_requests = []
1284
+
1285
+ for req_id, future in list(self._pending_requests.items()):
1286
+ # Check if request has timed out
1287
+ if hasattr(future, '_timeout_at'):
1288
+ if current_time > future._timeout_at:
1289
+ stale_requests.append(req_id)
1290
+
1291
+ # Cancel stale requests
1292
+ for req_id in stale_requests:
1293
+ future = self._pending_requests.pop(req_id, None)
1294
+ if future and not future.done():
1295
+ method = getattr(future, '_request_method', 'unknown')
1296
+ self.logger.warning(f"Cancelling stale request {req_id[:8]} ({method})")
1297
+ future.cancel()
1298
+
1299
+ except Exception as e:
1300
+ self.logger.error(f"Error in cleanup task: {e}")
1301
+
1302
+ async def execute_tool(self, name: str, arguments: Dict[str, Any], timeout: Optional[float] = None) -> Any:
1303
+ """Execute a tool.
1304
+
1305
+ Args:
1306
+ name: Name of the tool to execute
1307
+ arguments: Tool arguments
1308
+ timeout: Optional timeout in seconds (defaults to transport timeout)
1309
+
1310
+ Returns:
1311
+ Tool execution result
1312
+
1313
+ Raises:
1314
+ MCPConnectionError: If client not connected
1315
+ MCPToolExecutionError: If tool not found or execution fails
1316
+ MCPProtocolError: If request times out
1317
+ """
1318
+ if not self._connected:
1319
+ raise MCPConnectionError("Client not connected")
1320
+
1321
+ # Find tool
1322
+ tool = None
1323
+ for t in self._tools:
1324
+ if t.get("name") == name:
1325
+ tool = t
1326
+ break
1327
+
1328
+ if not tool:
1329
+ raise MCPToolExecutionError(f"Tool '{name}' not found")
1330
+
1331
+ # Execute tool with timeout
1332
+ request = MCPRequest(
1333
+ method="tools/call",
1334
+ params={
1335
+ "name": name,
1336
+ "arguments": arguments
1337
+ }
1338
+ )
1339
+
1340
+ # Pass timeout to _send_request
1341
+ response = await self._send_request(request, timeout=timeout)
1342
+
1343
+ if response.error:
1344
+ raise MCPToolExecutionError(f"Tool execution failed: {response.error}")
1345
+
1346
+ return response.result
1347
+
1348
+ async def read_resource(self, uri: str) -> Any:
1349
+ """Read a resource."""
1350
+ if not self._connected:
1351
+ raise MCPConnectionError("Client not connected")
1352
+
1353
+ request = MCPRequest(
1354
+ method="resources/read",
1355
+ params={"uri": uri}
1356
+ )
1357
+
1358
+ response = await self._send_request(request)
1359
+
1360
+ if response.error:
1361
+ raise MCPProtocolError(f"Resource read failed: {response.error}")
1362
+
1363
+ return response.result
1364
+
1365
+ async def subscribe_resource(self, uri: str) -> Any:
1366
+ """Subscribe to updates for a resource (Item 7F — ``resources/subscribe``)."""
1367
+ if not self._connected:
1368
+ raise MCPConnectionError("Client not connected")
1369
+ response = await self._send_request(
1370
+ MCPRequest(method="resources/subscribe", params={"uri": uri})
1371
+ )
1372
+ if response.error:
1373
+ raise MCPProtocolError(f"Resource subscribe failed: {response.error}")
1374
+ return response.result
1375
+
1376
+ async def unsubscribe_resource(self, uri: str) -> Any:
1377
+ """Unsubscribe from a resource (Item 7F — ``resources/unsubscribe``)."""
1378
+ if not self._connected:
1379
+ raise MCPConnectionError("Client not connected")
1380
+ response = await self._send_request(
1381
+ MCPRequest(method="resources/unsubscribe", params={"uri": uri})
1382
+ )
1383
+ if response.error:
1384
+ raise MCPProtocolError(f"Resource unsubscribe failed: {response.error}")
1385
+ return response.result
1386
+
1387
+ async def process_messages(self) -> None:
1388
+ """Process incoming messages (should be run as task).
1389
+
1390
+ This runs continuously in the background to receive messages from the MCP server
1391
+ and complete pending request futures.
1392
+ """
1393
+ import time
1394
+
1395
+ # Set health flag at start
1396
+ self._message_loop_alive.set()
1397
+ self.logger.info("Message processing loop started")
1398
+
1399
+ while not self.transport.is_closed:
1400
+ try:
1401
+ # Update last message time before receiving
1402
+ self._last_message_time = time.time()
1403
+
1404
+ # Use a reasonable timeout for polling to allow periodic checks
1405
+ # Individual requests will have their own timeouts via _send_request
1406
+ message = await self.transport.receive_message(timeout=30.0)
1407
+
1408
+ if message is None:
1409
+ # Timeout or no message - this is normal, just continue
1410
+ continue
1411
+
1412
+ if isinstance(message, MCPResponse):
1413
+ # Handle response - complete the pending future
1414
+ future = self._pending_requests.get(message.id)
1415
+ if future and not future.done():
1416
+ future.set_result(message)
1417
+ self.logger.debug(f"Completed pending request {message.id}")
1418
+ else:
1419
+ self.logger.warning(f"Received response for unknown or completed request: {message.id}")
1420
+
1421
+ elif isinstance(message, MCPRequest):
1422
+ # Handle incoming request (not common for client)
1423
+ self.logger.warning(f"Received unexpected request: {message.method}")
1424
+
1425
+ elif isinstance(message, MCPNotification):
1426
+ # Handle notification
1427
+ self.logger.debug(f"Received notification: {message.method}")
1428
+ await self._handle_notification(message)
1429
+
1430
+ except MCPProtocolError as e:
1431
+ self.logger.error(f"Protocol error in message processing: {e}")
1432
+ # Continue processing despite protocol errors
1433
+ except Exception as e:
1434
+ self.logger.error(f"Error processing message: {e}", exc_info=True)
1435
+ await asyncio.sleep(1) # Brief pause before retrying
1436
+
1437
+ # Loop exited - clear health flag
1438
+ self._message_loop_alive.clear()
1439
+ self.logger.warning("Message processing loop exited!")
1440
+
1441
+ async def _handle_notification(self, message: "MCPNotification") -> None:
1442
+ """Process a server notification (Item 7F). Fail-open.
1443
+
1444
+ ``notifications/resources/updated`` (params ``{"uri": ...}``) is routed to
1445
+ ``self._resource_update_handler`` (set by the server manager). Other
1446
+ notifications are debug-logged only, as before.
1447
+ """
1448
+ try:
1449
+ method = getattr(message, "method", "") or ""
1450
+ if method == "notifications/resources/updated":
1451
+ params = getattr(message, "params", None) or {}
1452
+ uri = params.get("uri")
1453
+ handler = self._resource_update_handler
1454
+ if uri and handler is not None:
1455
+ result = handler(uri)
1456
+ if asyncio.iscoroutine(result) or asyncio.isfuture(result):
1457
+ await result
1458
+ except Exception as e:
1459
+ self.logger.error(f"Error handling notification {getattr(message, 'method', '?')}: {e}")
1460
+
1461
+ @property
1462
+ def is_message_loop_healthy(self) -> bool:
1463
+ """Check if message loop is running and recent.
1464
+
1465
+ Returns:
1466
+ True if the message loop is alive and has processed messages recently
1467
+ """
1468
+ import time
1469
+
1470
+ if not self._message_loop_alive.is_set():
1471
+ return False
1472
+
1473
+ # Check if we received message recently (within 60s)
1474
+ time_since_last = time.time() - self._last_message_time
1475
+ if time_since_last > 60:
1476
+ self.logger.warning(f"No messages for {time_since_last:.1f}s")
1477
+ return False
1478
+
1479
+ return True
1480
+
1481
+ async def close(self) -> None:
1482
+ """Close the client."""
1483
+ self._connected = False
1484
+
1485
+ # Cancel message handler task
1486
+ if self._message_handler_task and not self._message_handler_task.done():
1487
+ self._message_handler_task.cancel()
1488
+ try:
1489
+ await self._message_handler_task
1490
+ except asyncio.CancelledError:
1491
+ pass
1492
+
1493
+ # Cancel pending requests
1494
+ for future in self._pending_requests.values():
1495
+ if not future.done():
1496
+ future.cancel()
1497
+ self._pending_requests.clear()
1498
+
1499
+ await self.transport.close()
1500
+ self.logger.info("MCP client closed")
1501
+
1502
+ @property
1503
+ def capabilities(self) -> Dict[str, Any]:
1504
+ """Get server capabilities."""
1505
+ return self._capabilities
1506
+
1507
+ @property
1508
+ def tools(self) -> List[Dict[str, Any]]:
1509
+ """Get available tools."""
1510
+ return self._tools
1511
+
1512
+ @property
1513
+ def resources(self) -> List[Dict[str, Any]]:
1514
+ """Get available resources."""
1515
+ return self._resources
1516
+
1517
+ @property
1518
+ def is_connected(self) -> bool:
1519
+ """Check if client is connected."""
1520
+ return self._connected and not self.transport.is_closed