aider-ce 0.88.20__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 (279) hide show
  1. aider/__init__.py +20 -0
  2. aider/__main__.py +4 -0
  3. aider/_version.py +34 -0
  4. aider/analytics.py +258 -0
  5. aider/args.py +1056 -0
  6. aider/args_formatter.py +228 -0
  7. aider/change_tracker.py +133 -0
  8. aider/coders/__init__.py +36 -0
  9. aider/coders/agent_coder.py +2166 -0
  10. aider/coders/agent_prompts.py +104 -0
  11. aider/coders/architect_coder.py +48 -0
  12. aider/coders/architect_prompts.py +40 -0
  13. aider/coders/ask_coder.py +9 -0
  14. aider/coders/ask_prompts.py +35 -0
  15. aider/coders/base_coder.py +3613 -0
  16. aider/coders/base_prompts.py +87 -0
  17. aider/coders/chat_chunks.py +64 -0
  18. aider/coders/context_coder.py +53 -0
  19. aider/coders/context_prompts.py +75 -0
  20. aider/coders/editblock_coder.py +657 -0
  21. aider/coders/editblock_fenced_coder.py +10 -0
  22. aider/coders/editblock_fenced_prompts.py +143 -0
  23. aider/coders/editblock_func_coder.py +141 -0
  24. aider/coders/editblock_func_prompts.py +27 -0
  25. aider/coders/editblock_prompts.py +175 -0
  26. aider/coders/editor_diff_fenced_coder.py +9 -0
  27. aider/coders/editor_diff_fenced_prompts.py +11 -0
  28. aider/coders/editor_editblock_coder.py +9 -0
  29. aider/coders/editor_editblock_prompts.py +21 -0
  30. aider/coders/editor_whole_coder.py +9 -0
  31. aider/coders/editor_whole_prompts.py +12 -0
  32. aider/coders/help_coder.py +16 -0
  33. aider/coders/help_prompts.py +46 -0
  34. aider/coders/patch_coder.py +706 -0
  35. aider/coders/patch_prompts.py +159 -0
  36. aider/coders/search_replace.py +757 -0
  37. aider/coders/shell.py +37 -0
  38. aider/coders/single_wholefile_func_coder.py +102 -0
  39. aider/coders/single_wholefile_func_prompts.py +27 -0
  40. aider/coders/udiff_coder.py +429 -0
  41. aider/coders/udiff_prompts.py +115 -0
  42. aider/coders/udiff_simple.py +14 -0
  43. aider/coders/udiff_simple_prompts.py +25 -0
  44. aider/coders/wholefile_coder.py +144 -0
  45. aider/coders/wholefile_func_coder.py +134 -0
  46. aider/coders/wholefile_func_prompts.py +27 -0
  47. aider/coders/wholefile_prompts.py +65 -0
  48. aider/commands.py +2173 -0
  49. aider/copypaste.py +72 -0
  50. aider/deprecated.py +126 -0
  51. aider/diffs.py +128 -0
  52. aider/dump.py +29 -0
  53. aider/editor.py +147 -0
  54. aider/exceptions.py +115 -0
  55. aider/format_settings.py +26 -0
  56. aider/gui.py +545 -0
  57. aider/help.py +163 -0
  58. aider/help_pats.py +19 -0
  59. aider/helpers/__init__.py +9 -0
  60. aider/helpers/similarity.py +98 -0
  61. aider/history.py +180 -0
  62. aider/io.py +1608 -0
  63. aider/linter.py +304 -0
  64. aider/llm.py +55 -0
  65. aider/main.py +1415 -0
  66. aider/mcp/__init__.py +174 -0
  67. aider/mcp/server.py +149 -0
  68. aider/mdstream.py +243 -0
  69. aider/models.py +1313 -0
  70. aider/onboarding.py +429 -0
  71. aider/openrouter.py +129 -0
  72. aider/prompts.py +56 -0
  73. aider/queries/tree-sitter-language-pack/README.md +7 -0
  74. aider/queries/tree-sitter-language-pack/arduino-tags.scm +5 -0
  75. aider/queries/tree-sitter-language-pack/c-tags.scm +9 -0
  76. aider/queries/tree-sitter-language-pack/chatito-tags.scm +16 -0
  77. aider/queries/tree-sitter-language-pack/clojure-tags.scm +7 -0
  78. aider/queries/tree-sitter-language-pack/commonlisp-tags.scm +122 -0
  79. aider/queries/tree-sitter-language-pack/cpp-tags.scm +15 -0
  80. aider/queries/tree-sitter-language-pack/csharp-tags.scm +26 -0
  81. aider/queries/tree-sitter-language-pack/d-tags.scm +26 -0
  82. aider/queries/tree-sitter-language-pack/dart-tags.scm +92 -0
  83. aider/queries/tree-sitter-language-pack/elisp-tags.scm +5 -0
  84. aider/queries/tree-sitter-language-pack/elixir-tags.scm +54 -0
  85. aider/queries/tree-sitter-language-pack/elm-tags.scm +19 -0
  86. aider/queries/tree-sitter-language-pack/gleam-tags.scm +41 -0
  87. aider/queries/tree-sitter-language-pack/go-tags.scm +42 -0
  88. aider/queries/tree-sitter-language-pack/java-tags.scm +20 -0
  89. aider/queries/tree-sitter-language-pack/javascript-tags.scm +88 -0
  90. aider/queries/tree-sitter-language-pack/lua-tags.scm +34 -0
  91. aider/queries/tree-sitter-language-pack/matlab-tags.scm +10 -0
  92. aider/queries/tree-sitter-language-pack/ocaml-tags.scm +115 -0
  93. aider/queries/tree-sitter-language-pack/ocaml_interface-tags.scm +98 -0
  94. aider/queries/tree-sitter-language-pack/pony-tags.scm +39 -0
  95. aider/queries/tree-sitter-language-pack/properties-tags.scm +5 -0
  96. aider/queries/tree-sitter-language-pack/python-tags.scm +14 -0
  97. aider/queries/tree-sitter-language-pack/r-tags.scm +21 -0
  98. aider/queries/tree-sitter-language-pack/racket-tags.scm +12 -0
  99. aider/queries/tree-sitter-language-pack/ruby-tags.scm +64 -0
  100. aider/queries/tree-sitter-language-pack/rust-tags.scm +60 -0
  101. aider/queries/tree-sitter-language-pack/solidity-tags.scm +43 -0
  102. aider/queries/tree-sitter-language-pack/swift-tags.scm +51 -0
  103. aider/queries/tree-sitter-language-pack/udev-tags.scm +20 -0
  104. aider/queries/tree-sitter-languages/README.md +24 -0
  105. aider/queries/tree-sitter-languages/c-tags.scm +9 -0
  106. aider/queries/tree-sitter-languages/c_sharp-tags.scm +46 -0
  107. aider/queries/tree-sitter-languages/cpp-tags.scm +15 -0
  108. aider/queries/tree-sitter-languages/dart-tags.scm +91 -0
  109. aider/queries/tree-sitter-languages/elisp-tags.scm +8 -0
  110. aider/queries/tree-sitter-languages/elixir-tags.scm +54 -0
  111. aider/queries/tree-sitter-languages/elm-tags.scm +19 -0
  112. aider/queries/tree-sitter-languages/fortran-tags.scm +15 -0
  113. aider/queries/tree-sitter-languages/go-tags.scm +30 -0
  114. aider/queries/tree-sitter-languages/haskell-tags.scm +3 -0
  115. aider/queries/tree-sitter-languages/hcl-tags.scm +77 -0
  116. aider/queries/tree-sitter-languages/java-tags.scm +20 -0
  117. aider/queries/tree-sitter-languages/javascript-tags.scm +88 -0
  118. aider/queries/tree-sitter-languages/julia-tags.scm +60 -0
  119. aider/queries/tree-sitter-languages/kotlin-tags.scm +27 -0
  120. aider/queries/tree-sitter-languages/matlab-tags.scm +10 -0
  121. aider/queries/tree-sitter-languages/ocaml-tags.scm +115 -0
  122. aider/queries/tree-sitter-languages/ocaml_interface-tags.scm +98 -0
  123. aider/queries/tree-sitter-languages/php-tags.scm +26 -0
  124. aider/queries/tree-sitter-languages/python-tags.scm +12 -0
  125. aider/queries/tree-sitter-languages/ql-tags.scm +26 -0
  126. aider/queries/tree-sitter-languages/ruby-tags.scm +64 -0
  127. aider/queries/tree-sitter-languages/rust-tags.scm +60 -0
  128. aider/queries/tree-sitter-languages/scala-tags.scm +65 -0
  129. aider/queries/tree-sitter-languages/typescript-tags.scm +41 -0
  130. aider/queries/tree-sitter-languages/zig-tags.scm +3 -0
  131. aider/reasoning_tags.py +82 -0
  132. aider/repo.py +621 -0
  133. aider/repomap.py +1174 -0
  134. aider/report.py +260 -0
  135. aider/resources/__init__.py +3 -0
  136. aider/resources/model-metadata.json +776 -0
  137. aider/resources/model-settings.yml +2068 -0
  138. aider/run_cmd.py +133 -0
  139. aider/scrape.py +293 -0
  140. aider/sendchat.py +242 -0
  141. aider/sessions.py +256 -0
  142. aider/special.py +203 -0
  143. aider/tools/__init__.py +72 -0
  144. aider/tools/command.py +105 -0
  145. aider/tools/command_interactive.py +122 -0
  146. aider/tools/delete_block.py +182 -0
  147. aider/tools/delete_line.py +155 -0
  148. aider/tools/delete_lines.py +184 -0
  149. aider/tools/extract_lines.py +341 -0
  150. aider/tools/finished.py +48 -0
  151. aider/tools/git_branch.py +129 -0
  152. aider/tools/git_diff.py +60 -0
  153. aider/tools/git_log.py +57 -0
  154. aider/tools/git_remote.py +53 -0
  155. aider/tools/git_show.py +51 -0
  156. aider/tools/git_status.py +46 -0
  157. aider/tools/grep.py +256 -0
  158. aider/tools/indent_lines.py +221 -0
  159. aider/tools/insert_block.py +288 -0
  160. aider/tools/list_changes.py +86 -0
  161. aider/tools/ls.py +93 -0
  162. aider/tools/make_editable.py +85 -0
  163. aider/tools/make_readonly.py +69 -0
  164. aider/tools/remove.py +91 -0
  165. aider/tools/replace_all.py +126 -0
  166. aider/tools/replace_line.py +173 -0
  167. aider/tools/replace_lines.py +217 -0
  168. aider/tools/replace_text.py +187 -0
  169. aider/tools/show_numbered_context.py +147 -0
  170. aider/tools/tool_utils.py +313 -0
  171. aider/tools/undo_change.py +95 -0
  172. aider/tools/update_todo_list.py +156 -0
  173. aider/tools/view.py +57 -0
  174. aider/tools/view_files_matching.py +141 -0
  175. aider/tools/view_files_with_symbol.py +129 -0
  176. aider/urls.py +17 -0
  177. aider/utils.py +456 -0
  178. aider/versioncheck.py +113 -0
  179. aider/voice.py +205 -0
  180. aider/waiting.py +38 -0
  181. aider/watch.py +318 -0
  182. aider/watch_prompts.py +12 -0
  183. aider/website/Gemfile +8 -0
  184. aider/website/_includes/blame.md +162 -0
  185. aider/website/_includes/get-started.md +22 -0
  186. aider/website/_includes/help-tip.md +5 -0
  187. aider/website/_includes/help.md +24 -0
  188. aider/website/_includes/install.md +5 -0
  189. aider/website/_includes/keys.md +4 -0
  190. aider/website/_includes/model-warnings.md +67 -0
  191. aider/website/_includes/multi-line.md +22 -0
  192. aider/website/_includes/python-m-aider.md +5 -0
  193. aider/website/_includes/recording.css +228 -0
  194. aider/website/_includes/recording.md +34 -0
  195. aider/website/_includes/replit-pipx.md +9 -0
  196. aider/website/_includes/works-best.md +1 -0
  197. aider/website/_sass/custom/custom.scss +103 -0
  198. aider/website/docs/config/adv-model-settings.md +2261 -0
  199. aider/website/docs/config/agent-mode.md +194 -0
  200. aider/website/docs/config/aider_conf.md +548 -0
  201. aider/website/docs/config/api-keys.md +90 -0
  202. aider/website/docs/config/dotenv.md +493 -0
  203. aider/website/docs/config/editor.md +127 -0
  204. aider/website/docs/config/mcp.md +95 -0
  205. aider/website/docs/config/model-aliases.md +104 -0
  206. aider/website/docs/config/options.md +890 -0
  207. aider/website/docs/config/reasoning.md +210 -0
  208. aider/website/docs/config.md +44 -0
  209. aider/website/docs/faq.md +384 -0
  210. aider/website/docs/git.md +76 -0
  211. aider/website/docs/index.md +47 -0
  212. aider/website/docs/install/codespaces.md +39 -0
  213. aider/website/docs/install/docker.md +57 -0
  214. aider/website/docs/install/optional.md +100 -0
  215. aider/website/docs/install/replit.md +8 -0
  216. aider/website/docs/install.md +115 -0
  217. aider/website/docs/languages.md +264 -0
  218. aider/website/docs/legal/contributor-agreement.md +111 -0
  219. aider/website/docs/legal/privacy.md +104 -0
  220. aider/website/docs/llms/anthropic.md +77 -0
  221. aider/website/docs/llms/azure.md +48 -0
  222. aider/website/docs/llms/bedrock.md +132 -0
  223. aider/website/docs/llms/cohere.md +34 -0
  224. aider/website/docs/llms/deepseek.md +32 -0
  225. aider/website/docs/llms/gemini.md +49 -0
  226. aider/website/docs/llms/github.md +111 -0
  227. aider/website/docs/llms/groq.md +36 -0
  228. aider/website/docs/llms/lm-studio.md +39 -0
  229. aider/website/docs/llms/ollama.md +75 -0
  230. aider/website/docs/llms/openai-compat.md +39 -0
  231. aider/website/docs/llms/openai.md +58 -0
  232. aider/website/docs/llms/openrouter.md +78 -0
  233. aider/website/docs/llms/other.md +117 -0
  234. aider/website/docs/llms/vertex.md +50 -0
  235. aider/website/docs/llms/warnings.md +10 -0
  236. aider/website/docs/llms/xai.md +53 -0
  237. aider/website/docs/llms.md +54 -0
  238. aider/website/docs/more/analytics.md +127 -0
  239. aider/website/docs/more/edit-formats.md +116 -0
  240. aider/website/docs/more/infinite-output.md +165 -0
  241. aider/website/docs/more-info.md +8 -0
  242. aider/website/docs/recordings/auto-accept-architect.md +31 -0
  243. aider/website/docs/recordings/dont-drop-original-read-files.md +35 -0
  244. aider/website/docs/recordings/index.md +21 -0
  245. aider/website/docs/recordings/model-accepts-settings.md +69 -0
  246. aider/website/docs/recordings/tree-sitter-language-pack.md +80 -0
  247. aider/website/docs/repomap.md +112 -0
  248. aider/website/docs/scripting.md +100 -0
  249. aider/website/docs/sessions.md +203 -0
  250. aider/website/docs/troubleshooting/aider-not-found.md +24 -0
  251. aider/website/docs/troubleshooting/edit-errors.md +76 -0
  252. aider/website/docs/troubleshooting/imports.md +62 -0
  253. aider/website/docs/troubleshooting/models-and-keys.md +54 -0
  254. aider/website/docs/troubleshooting/support.md +79 -0
  255. aider/website/docs/troubleshooting/token-limits.md +96 -0
  256. aider/website/docs/troubleshooting/warnings.md +12 -0
  257. aider/website/docs/troubleshooting.md +11 -0
  258. aider/website/docs/usage/browser.md +57 -0
  259. aider/website/docs/usage/caching.md +49 -0
  260. aider/website/docs/usage/commands.md +133 -0
  261. aider/website/docs/usage/conventions.md +119 -0
  262. aider/website/docs/usage/copypaste.md +121 -0
  263. aider/website/docs/usage/images-urls.md +48 -0
  264. aider/website/docs/usage/lint-test.md +118 -0
  265. aider/website/docs/usage/modes.md +211 -0
  266. aider/website/docs/usage/not-code.md +179 -0
  267. aider/website/docs/usage/notifications.md +87 -0
  268. aider/website/docs/usage/tips.md +79 -0
  269. aider/website/docs/usage/tutorials.md +30 -0
  270. aider/website/docs/usage/voice.md +121 -0
  271. aider/website/docs/usage/watch.md +294 -0
  272. aider/website/docs/usage.md +102 -0
  273. aider/website/share/index.md +101 -0
  274. aider_ce-0.88.20.dist-info/METADATA +187 -0
  275. aider_ce-0.88.20.dist-info/RECORD +279 -0
  276. aider_ce-0.88.20.dist-info/WHEEL +5 -0
  277. aider_ce-0.88.20.dist-info/entry_points.txt +2 -0
  278. aider_ce-0.88.20.dist-info/licenses/LICENSE.txt +202 -0
  279. aider_ce-0.88.20.dist-info/top_level.txt +1 -0
aider/mcp/__init__.py ADDED
@@ -0,0 +1,174 @@
1
+ import json
2
+ from pathlib import Path
3
+
4
+ from aider.mcp.server import HttpStreamingServer, McpServer, SseServer
5
+
6
+
7
+ def _parse_mcp_servers_from_json_string(json_string, io, verbose=False, mcp_transport="stdio"):
8
+ """Parse MCP servers from a JSON string."""
9
+ servers = []
10
+
11
+ try:
12
+ config = json.loads(json_string)
13
+ if verbose:
14
+ io.tool_output("Loading MCP servers from provided JSON string")
15
+
16
+ if "mcpServers" in config:
17
+ for name, server_config in config["mcpServers"].items():
18
+ if verbose:
19
+ io.tool_output(f"Loading MCP server: {name}")
20
+
21
+ # Create a server config with name included
22
+ server_config["name"] = name
23
+ transport = server_config.get("transport", mcp_transport)
24
+ if transport == "stdio":
25
+ servers.append(McpServer(server_config))
26
+ elif transport == "http":
27
+ servers.append(HttpStreamingServer(server_config))
28
+ elif transport == "sse":
29
+ servers.append(SseServer(server_config))
30
+
31
+ if verbose:
32
+ io.tool_output(f"Loaded {len(servers)} MCP servers from JSON string")
33
+ return servers
34
+ else:
35
+ io.tool_warning("No 'mcpServers' key found in MCP config JSON string")
36
+ except json.JSONDecodeError:
37
+ io.tool_error("Invalid JSON in MCP config string")
38
+ except Exception as e:
39
+ io.tool_error(f"Error loading MCP config from string: {e}")
40
+
41
+ return servers
42
+
43
+
44
+ def _resolve_mcp_config_path(file_path, io, verbose=False):
45
+ """Resolve MCP config file path relative to closest aider.conf.yml, git directory, or CWD."""
46
+ if not file_path:
47
+ return None
48
+
49
+ # If the path is absolute or already exists, use it as-is
50
+ path = Path(file_path)
51
+ if path.is_absolute() or path.exists():
52
+ return str(path.resolve())
53
+
54
+ # Search for the closest aider.conf.yml in parent directories
55
+ current_dir = Path.cwd()
56
+ aider_conf_path = None
57
+
58
+ for parent in [current_dir] + list(current_dir.parents):
59
+ conf_file = parent / ".aider.conf.yml"
60
+ if conf_file.exists():
61
+ aider_conf_path = parent
62
+ break
63
+
64
+ # If aider.conf.yml found, try relative to that directory
65
+ if aider_conf_path:
66
+ resolved_path = aider_conf_path / file_path
67
+ if resolved_path.exists():
68
+ if verbose:
69
+ io.tool_output(f"Resolved MCP config relative to aider.conf.yml: {resolved_path}")
70
+ return str(resolved_path.resolve())
71
+
72
+ # Try to find git root directory
73
+ git_root = None
74
+ try:
75
+ import git
76
+
77
+ repo = git.Repo(search_parent_directories=True)
78
+ git_root = Path(repo.working_tree_dir)
79
+ except (ImportError, git.InvalidGitRepositoryError, FileNotFoundError):
80
+ pass
81
+
82
+ # If git root found, try relative to that directory
83
+ if git_root:
84
+ resolved_path = git_root / file_path
85
+ if resolved_path.exists():
86
+ if verbose:
87
+ io.tool_output(f"Resolved MCP config relative to git root: {resolved_path}")
88
+ return str(resolved_path.resolve())
89
+
90
+ # Finally, try relative to current working directory
91
+ resolved_path = current_dir / file_path
92
+ if resolved_path.exists():
93
+ if verbose:
94
+ io.tool_output(f"Resolved MCP config relative to CWD: {resolved_path}")
95
+ return str(resolved_path.resolve())
96
+
97
+ # If none found, return the original path (will trigger FileNotFoundError)
98
+ return str(path.resolve())
99
+
100
+
101
+ def _parse_mcp_servers_from_file(file_path, io, verbose=False, mcp_transport="stdio"):
102
+ """Parse MCP servers from a JSON file."""
103
+ servers = []
104
+
105
+ # Resolve the file path relative to closest aider.conf.yml, git directory, or CWD
106
+ resolved_file_path = _resolve_mcp_config_path(file_path, io, verbose)
107
+
108
+ try:
109
+ with open(resolved_file_path, "r") as f:
110
+ config = json.load(f)
111
+
112
+ if verbose:
113
+ io.tool_output(f"Loading MCP servers from file: {file_path}")
114
+
115
+ if "mcpServers" in config:
116
+ for name, server_config in config["mcpServers"].items():
117
+ if verbose:
118
+ io.tool_output(f"Loading MCP server: {name}")
119
+
120
+ # Create a server config with name included
121
+ server_config["name"] = name
122
+ transport = server_config.get("transport", mcp_transport)
123
+ if transport == "stdio":
124
+ servers.append(McpServer(server_config))
125
+ elif transport == "http":
126
+ servers.append(HttpStreamingServer(server_config))
127
+
128
+ if verbose:
129
+ io.tool_output(f"Loaded {len(servers)} MCP servers from {file_path}")
130
+ return servers
131
+ else:
132
+ io.tool_warning(f"No 'mcpServers' key found in MCP config file: {file_path}")
133
+ except FileNotFoundError:
134
+ io.tool_warning(f"MCP config file not found: {file_path}")
135
+ except json.JSONDecodeError:
136
+ io.tool_error(f"Invalid JSON in MCP config file: {file_path}")
137
+ except Exception as e:
138
+ io.tool_error(f"Error loading MCP config from file: {e}")
139
+
140
+ return servers
141
+
142
+
143
+ def load_mcp_servers(mcp_servers, mcp_servers_file, io, verbose=False, mcp_transport="stdio"):
144
+ """Load MCP servers from a JSON string or file."""
145
+ servers = []
146
+
147
+ # First try to load from the JSON string (preferred)
148
+ if mcp_servers:
149
+ servers = _parse_mcp_servers_from_json_string(mcp_servers, io, verbose, mcp_transport)
150
+ if servers:
151
+ return servers
152
+
153
+ # If JSON string failed or wasn't provided, try the file
154
+ if mcp_servers_file:
155
+ servers = _parse_mcp_servers_from_file(mcp_servers_file, io, verbose, mcp_transport)
156
+
157
+ if not servers:
158
+ # A default MCP server is actually now necessary for the overall agentic loop
159
+ # and a dummy server does suffice for the job
160
+ # because I am not smart enough to figure out why
161
+ # on coder switch, the agent actually initializes the prompt area twice
162
+ # once immediately after input for the old coder
163
+ # and immediately again for the new target coder
164
+ # which causes a race condition where we are awaiting a coroutine
165
+ # that can no longer yield control (somehow?)
166
+ # but somehow having to run through the MCP server checks
167
+ # allows control to be yielded again somehow
168
+ # and I cannot figure out just how that is happening
169
+ # and maybe it is actually prompt_toolkit's fault
170
+ # but this hack works swimmingly because ???
171
+ # so sure! why not
172
+ servers = [McpServer(json.loads('{"aider_default": {}}'))]
173
+
174
+ return servers
aider/mcp/server.py ADDED
@@ -0,0 +1,149 @@
1
+ import asyncio
2
+ import logging
3
+ import os
4
+ from contextlib import AsyncExitStack
5
+
6
+ from mcp import ClientSession, StdioServerParameters
7
+ from mcp.client.sse import sse_client
8
+ from mcp.client.stdio import stdio_client
9
+ from mcp.client.streamable_http import streamablehttp_client
10
+
11
+
12
+ class McpServer:
13
+ """
14
+ A client for MCP servers that provides tools to Aider coders. An McpServer class
15
+ is initialized per configured MCP Server
16
+
17
+ Uses the mcp library to create and initialize ClientSession objects.
18
+ """
19
+
20
+ def __init__(self, server_config):
21
+ """Initialize the MCP tool provider.
22
+
23
+ Args:
24
+ server_config: Configuration for the MCP server
25
+ """
26
+ self.config = server_config
27
+ self.name = server_config.get("name", "unnamed-server")
28
+ self.session = None
29
+ self._cleanup_lock: asyncio.Lock = asyncio.Lock()
30
+ self.exit_stack = AsyncExitStack()
31
+
32
+ async def connect(self):
33
+ """Connect to the MCP server and return the session.
34
+
35
+ If a session is already active, returns the existing session.
36
+ Otherwise, establishes a new connection and initializes the session.
37
+
38
+ Returns:
39
+ ClientSession: The active session
40
+ """
41
+ if self.session is not None:
42
+ logging.info(f"Using existing session for MCP server: {self.name}")
43
+ return self.session
44
+
45
+ logging.info(f"Establishing new connection to MCP server: {self.name}")
46
+ command = self.config["command"]
47
+ server_params = StdioServerParameters(
48
+ command=command,
49
+ args=self.config.get("args"),
50
+ env={**os.environ, **self.config["env"]} if self.config.get("env") else None,
51
+ )
52
+
53
+ try:
54
+ os.makedirs(".aider/logs/", exist_ok=True)
55
+ with open(".aider/logs/mcp-errors.log", "w") as err_file:
56
+ stdio_transport = await self.exit_stack.enter_async_context(
57
+ stdio_client(server_params, errlog=err_file)
58
+ )
59
+ read, write = stdio_transport
60
+ session = await self.exit_stack.enter_async_context(ClientSession(read, write))
61
+ await session.initialize()
62
+ self.session = session
63
+ return session
64
+ except Exception as e:
65
+ logging.error(f"Error initializing server {self.name}: {e}")
66
+ await self.disconnect()
67
+ raise
68
+
69
+ async def disconnect(self):
70
+ """Disconnect from the MCP server and clean up resources."""
71
+ async with self._cleanup_lock:
72
+ try:
73
+ await self.exit_stack.aclose()
74
+ self.session = None
75
+ except Exception as e:
76
+ logging.error(f"Error during cleanup of server {self.name}: {e}")
77
+
78
+
79
+ class HttpStreamingServer(McpServer):
80
+ """HTTP streaming MCP server using mcp.client.streamablehttp_client."""
81
+
82
+ async def connect(self):
83
+ if self.session is not None:
84
+ logging.info(f"Using existing session for MCP server: {self.name}")
85
+ return self.session
86
+
87
+ logging.info(f"Establishing new connection to HTTP MCP server: {self.name}")
88
+ try:
89
+ url = self.config.get("url")
90
+ headers = self.config.get("headers", {})
91
+ http_transport = await self.exit_stack.enter_async_context(
92
+ streamablehttp_client(url, headers=headers)
93
+ )
94
+ read, write, _response = http_transport
95
+
96
+ session = await self.exit_stack.enter_async_context(ClientSession(read, write))
97
+ await session.initialize()
98
+ self.session = session
99
+ return session
100
+ except Exception as e:
101
+ logging.error(f"Error initializing HTTP server {self.name}: {e}")
102
+ await self.disconnect()
103
+ raise
104
+
105
+
106
+ class SseServer(McpServer):
107
+ """SSE (Server-Sent Events) MCP server using mcp.client.sse_client."""
108
+
109
+ async def connect(self):
110
+ if self.session is not None:
111
+ logging.info(f"Using existing session for SSE MCP server: {self.name}")
112
+ return self.session
113
+
114
+ logging.info(f"Establishing new connection to SSE MCP server: {self.name}")
115
+ try:
116
+ url = self.config.get("url")
117
+ headers = self.config.get("headers", {})
118
+ sse_transport = await self.exit_stack.enter_async_context(
119
+ sse_client(url, headers=headers)
120
+ )
121
+ read, write, _response = sse_transport
122
+ session = await self.exit_stack.enter_async_context(ClientSession(read, write))
123
+ await session.initialize()
124
+ self.session = session
125
+ return session
126
+ except Exception as e:
127
+ logging.error(f"Error initializing SSE server {self.name}: {e}")
128
+ await self.disconnect()
129
+ raise
130
+
131
+
132
+ class LocalServer(McpServer):
133
+ """
134
+ A dummy McpServer for executing local, in-process tools
135
+ that are not provided by an external MCP server.
136
+ """
137
+
138
+ async def connect(self):
139
+ """Local tools don't need a connection."""
140
+ if self.session is not None:
141
+ logging.info(f"Using existing session for local tools: {self.name}")
142
+ return self.session
143
+
144
+ self.session = object() # Dummy session object
145
+ return self.session
146
+
147
+ async def disconnect(self):
148
+ """Disconnect from the MCP server and clean up resources."""
149
+ self.session = None
aider/mdstream.py ADDED
@@ -0,0 +1,243 @@
1
+ #!/usr/bin/env python
2
+
3
+ import io
4
+ import time
5
+
6
+ from rich import box
7
+ from rich.console import Console
8
+ from rich.live import Live
9
+ from rich.markdown import CodeBlock, Heading, Markdown
10
+ from rich.panel import Panel
11
+ from rich.syntax import Syntax
12
+ from rich.text import Text
13
+
14
+ from aider.dump import dump # noqa: F401
15
+
16
+ _text_prefix = """
17
+ # Header
18
+
19
+ Lorem Ipsum is simply dummy text of the printing and typesetting industry.
20
+ Lorem Ipsum has been the industry's standard dummy text ever since the 1500s,
21
+ when an unknown printer took a galley of type and scrambled it to make a type
22
+ specimen book. It has survived not only five centuries, but also the leap into
23
+ electronic typesetting, remaining essentially unchanged. It was popularised in
24
+ the 1960s with the release of Letraset sheets containing Lorem Ipsum passages,
25
+ and more recently with desktop publishing software like Aldus PageMaker
26
+ including versions of Lorem Ipsum.
27
+
28
+
29
+
30
+ ## Sub header
31
+
32
+ - List 1
33
+ - List 2
34
+ - List me
35
+ - List you
36
+
37
+
38
+
39
+ ```python
40
+ """
41
+
42
+ _text_suffix = """
43
+ ```
44
+
45
+ ## Sub header too
46
+
47
+ The end.
48
+
49
+ """ # noqa: E501
50
+
51
+
52
+ class NoInsetCodeBlock(CodeBlock):
53
+ """A code block with syntax highlighting and no padding."""
54
+
55
+ def __rich_console__(self, console, options):
56
+ code = str(self.text).rstrip()
57
+ syntax = Syntax(code, self.lexer_name, theme=self.theme, word_wrap=True, padding=(1, 0))
58
+ yield syntax
59
+
60
+
61
+ class LeftHeading(Heading):
62
+ """A heading class that renders left-justified."""
63
+
64
+ def __rich_console__(self, console, options):
65
+ text = self.text
66
+ text.justify = "left" # Override justification
67
+ if self.tag == "h1":
68
+ # Draw a border around h1s, but keep text left-aligned
69
+ yield Panel(
70
+ text,
71
+ box=box.HEAVY,
72
+ style="markdown.h1.border",
73
+ )
74
+ else:
75
+ # Styled text for h2 and beyond
76
+ if self.tag == "h2":
77
+ yield Text("") # Keep the blank line before h2
78
+ yield text
79
+
80
+
81
+ class NoInsetMarkdown(Markdown):
82
+ """Markdown with code blocks that have no padding and left-justified headings."""
83
+
84
+ elements = {
85
+ **Markdown.elements,
86
+ "fence": NoInsetCodeBlock,
87
+ "code_block": NoInsetCodeBlock,
88
+ "heading_open": LeftHeading,
89
+ }
90
+
91
+
92
+ class MarkdownStream:
93
+ """Streaming markdown renderer that progressively displays content with a live updating window.
94
+
95
+ Uses rich.console and rich.live to render markdown content with smooth scrolling
96
+ and partial updates. Maintains a sliding window of visible content while streaming
97
+ in new markdown text.
98
+ """
99
+
100
+ live = None # Rich Live display instance
101
+ when = 0 # Timestamp of last update
102
+ min_delay = 1.0 / 20 # Minimum time between updates (20fps)
103
+ live_window = 6 # Number of lines to keep visible at bottom during streaming
104
+
105
+ def __init__(self, mdargs=None):
106
+ """Initialize the markdown stream.
107
+
108
+ Args:
109
+ mdargs (dict, optional): Additional arguments to pass to rich Markdown renderer
110
+ """
111
+ self.printed = [] # Stores lines that have already been printed
112
+
113
+ if mdargs:
114
+ self.mdargs = mdargs
115
+ else:
116
+ self.mdargs = dict()
117
+
118
+ # Defer Live creation until the first update.
119
+ self.live = None
120
+ self._live_started = False
121
+
122
+ def _render_markdown_to_lines(self, text):
123
+ """Render markdown text to a list of lines.
124
+
125
+ Args:
126
+ text (str): Markdown text to render
127
+
128
+ Returns:
129
+ list: List of rendered lines with line endings preserved
130
+ """
131
+ # Render the markdown to a string buffer
132
+ string_io = io.StringIO()
133
+ console = Console(file=string_io, force_terminal=True)
134
+ markdown = NoInsetMarkdown(text, **self.mdargs)
135
+ console.print(markdown)
136
+ output = string_io.getvalue()
137
+
138
+ # Split rendered output into lines
139
+ return output.splitlines(keepends=True)
140
+
141
+ def __del__(self):
142
+ """Destructor to ensure Live display is properly cleaned up."""
143
+ if self.live:
144
+ try:
145
+ self.live.stop()
146
+ except Exception:
147
+ pass # Ignore any errors during cleanup
148
+
149
+ def update(self, text, final=False):
150
+ """Update the displayed markdown content.
151
+
152
+ Args:
153
+ text (str): The markdown text received so far
154
+ final (bool): If True, this is the final update and we should clean up
155
+
156
+ Splits the output into "stable" older lines and the "last few" lines
157
+ which aren't considered stable. They may shift around as new chunks
158
+ are appended to the markdown text.
159
+
160
+ The stable lines emit to the console above the Live window.
161
+ The unstable lines emit into the Live window so they can be repainted.
162
+
163
+ Markdown going to the console works better in terminal scrollback buffers.
164
+ The live window doesn't play nice with terminal scrollback.
165
+ """
166
+ # On the first call, stop the spinner and start the Live renderer
167
+ if not getattr(self, "_live_started", False):
168
+ self.live = Live(Text(""), refresh_per_second=1.0 / self.min_delay)
169
+ self.live.start()
170
+ self._live_started = True
171
+
172
+ now = time.time()
173
+ # Throttle updates to maintain smooth rendering
174
+ if not final and now - self.when < self.min_delay:
175
+ return
176
+ self.when = now
177
+
178
+ # Measure render time and adjust min_delay to maintain smooth rendering
179
+ start = time.time()
180
+ lines = self._render_markdown_to_lines(text)
181
+ render_time = time.time() - start
182
+
183
+ # Set min_delay to render time plus a small buffer
184
+ self.min_delay = min(max(render_time * 10, 1.0 / 20), 2)
185
+
186
+ num_lines = len(lines)
187
+
188
+ # How many lines have "left" the live window and are now considered stable?
189
+ # Or if final, consider all lines to be stable.
190
+ if not final:
191
+ num_lines -= self.live_window
192
+
193
+ # If we have stable content to display...
194
+ if final or num_lines > 0:
195
+ # How many stable lines do we need to newly show above the live window?
196
+ num_printed = len(self.printed)
197
+ show = num_lines - num_printed
198
+
199
+ # Skip if no new lines to show above live window
200
+ if show <= 0:
201
+ return
202
+
203
+ # Get the new lines and display them
204
+ show = lines[num_printed:num_lines]
205
+ show = "".join(show)
206
+ show = Text.from_ansi(show)
207
+ self.live.console.print(show) # to the console above the live area
208
+
209
+ # Update our record of printed lines
210
+ self.printed = lines[:num_lines]
211
+
212
+ # Handle final update cleanup
213
+ if final:
214
+ self.live.update(Text(""))
215
+ self.live.stop()
216
+ self.live = None
217
+ return
218
+
219
+ # Update the live window with remaining lines
220
+ rest = lines[num_lines:]
221
+ rest = "".join(rest)
222
+ rest = Text.from_ansi(rest)
223
+ self.live.update(rest)
224
+
225
+ def find_minimal_suffix(self, text, match_lines=50):
226
+ """
227
+ Splits text into chunks on blank lines "\n\n".
228
+ """
229
+
230
+
231
+ if __name__ == "__main__":
232
+ with open("aider/io.py", "r") as f:
233
+ code = f.read()
234
+ _text = _text_prefix + code + _text_suffix
235
+ _text = _text * 10
236
+
237
+ pm = MarkdownStream()
238
+ print("Using NoInsetMarkdown for code blocks with padding=0")
239
+ for i in range(6, len(_text), 5):
240
+ pm.update(_text[:i])
241
+ time.sleep(0.01)
242
+
243
+ pm.update(_text, final=True)