basic-memory 0.17.1__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 (171) hide show
  1. basic_memory/__init__.py +7 -0
  2. basic_memory/alembic/alembic.ini +119 -0
  3. basic_memory/alembic/env.py +185 -0
  4. basic_memory/alembic/migrations.py +24 -0
  5. basic_memory/alembic/script.py.mako +26 -0
  6. basic_memory/alembic/versions/314f1ea54dc4_add_postgres_full_text_search_support_.py +131 -0
  7. basic_memory/alembic/versions/3dae7c7b1564_initial_schema.py +93 -0
  8. basic_memory/alembic/versions/502b60eaa905_remove_required_from_entity_permalink.py +51 -0
  9. basic_memory/alembic/versions/5fe1ab1ccebe_add_projects_table.py +120 -0
  10. basic_memory/alembic/versions/647e7a75e2cd_project_constraint_fix.py +112 -0
  11. basic_memory/alembic/versions/9d9c1cb7d8f5_add_mtime_and_size_columns_to_entity_.py +49 -0
  12. basic_memory/alembic/versions/a1b2c3d4e5f6_fix_project_foreign_keys.py +49 -0
  13. basic_memory/alembic/versions/a2b3c4d5e6f7_add_search_index_entity_cascade.py +56 -0
  14. basic_memory/alembic/versions/b3c3938bacdb_relation_to_name_unique_index.py +44 -0
  15. basic_memory/alembic/versions/cc7172b46608_update_search_index_schema.py +113 -0
  16. basic_memory/alembic/versions/e7e1f4367280_add_scan_watermark_tracking_to_project.py +37 -0
  17. basic_memory/alembic/versions/f8a9b2c3d4e5_add_pg_trgm_for_fuzzy_link_resolution.py +239 -0
  18. basic_memory/api/__init__.py +5 -0
  19. basic_memory/api/app.py +131 -0
  20. basic_memory/api/routers/__init__.py +11 -0
  21. basic_memory/api/routers/directory_router.py +84 -0
  22. basic_memory/api/routers/importer_router.py +152 -0
  23. basic_memory/api/routers/knowledge_router.py +318 -0
  24. basic_memory/api/routers/management_router.py +80 -0
  25. basic_memory/api/routers/memory_router.py +90 -0
  26. basic_memory/api/routers/project_router.py +448 -0
  27. basic_memory/api/routers/prompt_router.py +260 -0
  28. basic_memory/api/routers/resource_router.py +249 -0
  29. basic_memory/api/routers/search_router.py +36 -0
  30. basic_memory/api/routers/utils.py +169 -0
  31. basic_memory/api/template_loader.py +292 -0
  32. basic_memory/api/v2/__init__.py +35 -0
  33. basic_memory/api/v2/routers/__init__.py +21 -0
  34. basic_memory/api/v2/routers/directory_router.py +93 -0
  35. basic_memory/api/v2/routers/importer_router.py +182 -0
  36. basic_memory/api/v2/routers/knowledge_router.py +413 -0
  37. basic_memory/api/v2/routers/memory_router.py +130 -0
  38. basic_memory/api/v2/routers/project_router.py +342 -0
  39. basic_memory/api/v2/routers/prompt_router.py +270 -0
  40. basic_memory/api/v2/routers/resource_router.py +286 -0
  41. basic_memory/api/v2/routers/search_router.py +73 -0
  42. basic_memory/cli/__init__.py +1 -0
  43. basic_memory/cli/app.py +84 -0
  44. basic_memory/cli/auth.py +277 -0
  45. basic_memory/cli/commands/__init__.py +18 -0
  46. basic_memory/cli/commands/cloud/__init__.py +6 -0
  47. basic_memory/cli/commands/cloud/api_client.py +112 -0
  48. basic_memory/cli/commands/cloud/bisync_commands.py +110 -0
  49. basic_memory/cli/commands/cloud/cloud_utils.py +101 -0
  50. basic_memory/cli/commands/cloud/core_commands.py +195 -0
  51. basic_memory/cli/commands/cloud/rclone_commands.py +371 -0
  52. basic_memory/cli/commands/cloud/rclone_config.py +110 -0
  53. basic_memory/cli/commands/cloud/rclone_installer.py +263 -0
  54. basic_memory/cli/commands/cloud/upload.py +233 -0
  55. basic_memory/cli/commands/cloud/upload_command.py +124 -0
  56. basic_memory/cli/commands/command_utils.py +77 -0
  57. basic_memory/cli/commands/db.py +44 -0
  58. basic_memory/cli/commands/format.py +198 -0
  59. basic_memory/cli/commands/import_chatgpt.py +84 -0
  60. basic_memory/cli/commands/import_claude_conversations.py +87 -0
  61. basic_memory/cli/commands/import_claude_projects.py +86 -0
  62. basic_memory/cli/commands/import_memory_json.py +87 -0
  63. basic_memory/cli/commands/mcp.py +76 -0
  64. basic_memory/cli/commands/project.py +889 -0
  65. basic_memory/cli/commands/status.py +174 -0
  66. basic_memory/cli/commands/telemetry.py +81 -0
  67. basic_memory/cli/commands/tool.py +341 -0
  68. basic_memory/cli/main.py +28 -0
  69. basic_memory/config.py +616 -0
  70. basic_memory/db.py +394 -0
  71. basic_memory/deps.py +705 -0
  72. basic_memory/file_utils.py +478 -0
  73. basic_memory/ignore_utils.py +297 -0
  74. basic_memory/importers/__init__.py +27 -0
  75. basic_memory/importers/base.py +79 -0
  76. basic_memory/importers/chatgpt_importer.py +232 -0
  77. basic_memory/importers/claude_conversations_importer.py +180 -0
  78. basic_memory/importers/claude_projects_importer.py +148 -0
  79. basic_memory/importers/memory_json_importer.py +108 -0
  80. basic_memory/importers/utils.py +61 -0
  81. basic_memory/markdown/__init__.py +21 -0
  82. basic_memory/markdown/entity_parser.py +279 -0
  83. basic_memory/markdown/markdown_processor.py +160 -0
  84. basic_memory/markdown/plugins.py +242 -0
  85. basic_memory/markdown/schemas.py +70 -0
  86. basic_memory/markdown/utils.py +117 -0
  87. basic_memory/mcp/__init__.py +1 -0
  88. basic_memory/mcp/async_client.py +139 -0
  89. basic_memory/mcp/project_context.py +141 -0
  90. basic_memory/mcp/prompts/__init__.py +19 -0
  91. basic_memory/mcp/prompts/ai_assistant_guide.py +70 -0
  92. basic_memory/mcp/prompts/continue_conversation.py +62 -0
  93. basic_memory/mcp/prompts/recent_activity.py +188 -0
  94. basic_memory/mcp/prompts/search.py +57 -0
  95. basic_memory/mcp/prompts/utils.py +162 -0
  96. basic_memory/mcp/resources/ai_assistant_guide.md +283 -0
  97. basic_memory/mcp/resources/project_info.py +71 -0
  98. basic_memory/mcp/server.py +81 -0
  99. basic_memory/mcp/tools/__init__.py +48 -0
  100. basic_memory/mcp/tools/build_context.py +120 -0
  101. basic_memory/mcp/tools/canvas.py +152 -0
  102. basic_memory/mcp/tools/chatgpt_tools.py +190 -0
  103. basic_memory/mcp/tools/delete_note.py +242 -0
  104. basic_memory/mcp/tools/edit_note.py +324 -0
  105. basic_memory/mcp/tools/list_directory.py +168 -0
  106. basic_memory/mcp/tools/move_note.py +551 -0
  107. basic_memory/mcp/tools/project_management.py +201 -0
  108. basic_memory/mcp/tools/read_content.py +281 -0
  109. basic_memory/mcp/tools/read_note.py +267 -0
  110. basic_memory/mcp/tools/recent_activity.py +534 -0
  111. basic_memory/mcp/tools/search.py +385 -0
  112. basic_memory/mcp/tools/utils.py +540 -0
  113. basic_memory/mcp/tools/view_note.py +78 -0
  114. basic_memory/mcp/tools/write_note.py +230 -0
  115. basic_memory/models/__init__.py +15 -0
  116. basic_memory/models/base.py +10 -0
  117. basic_memory/models/knowledge.py +226 -0
  118. basic_memory/models/project.py +87 -0
  119. basic_memory/models/search.py +85 -0
  120. basic_memory/repository/__init__.py +11 -0
  121. basic_memory/repository/entity_repository.py +503 -0
  122. basic_memory/repository/observation_repository.py +73 -0
  123. basic_memory/repository/postgres_search_repository.py +379 -0
  124. basic_memory/repository/project_info_repository.py +10 -0
  125. basic_memory/repository/project_repository.py +128 -0
  126. basic_memory/repository/relation_repository.py +146 -0
  127. basic_memory/repository/repository.py +385 -0
  128. basic_memory/repository/search_index_row.py +95 -0
  129. basic_memory/repository/search_repository.py +94 -0
  130. basic_memory/repository/search_repository_base.py +241 -0
  131. basic_memory/repository/sqlite_search_repository.py +439 -0
  132. basic_memory/schemas/__init__.py +86 -0
  133. basic_memory/schemas/base.py +297 -0
  134. basic_memory/schemas/cloud.py +50 -0
  135. basic_memory/schemas/delete.py +37 -0
  136. basic_memory/schemas/directory.py +30 -0
  137. basic_memory/schemas/importer.py +35 -0
  138. basic_memory/schemas/memory.py +285 -0
  139. basic_memory/schemas/project_info.py +212 -0
  140. basic_memory/schemas/prompt.py +90 -0
  141. basic_memory/schemas/request.py +112 -0
  142. basic_memory/schemas/response.py +229 -0
  143. basic_memory/schemas/search.py +117 -0
  144. basic_memory/schemas/sync_report.py +72 -0
  145. basic_memory/schemas/v2/__init__.py +27 -0
  146. basic_memory/schemas/v2/entity.py +129 -0
  147. basic_memory/schemas/v2/resource.py +46 -0
  148. basic_memory/services/__init__.py +8 -0
  149. basic_memory/services/context_service.py +601 -0
  150. basic_memory/services/directory_service.py +308 -0
  151. basic_memory/services/entity_service.py +864 -0
  152. basic_memory/services/exceptions.py +37 -0
  153. basic_memory/services/file_service.py +541 -0
  154. basic_memory/services/initialization.py +216 -0
  155. basic_memory/services/link_resolver.py +121 -0
  156. basic_memory/services/project_service.py +880 -0
  157. basic_memory/services/search_service.py +404 -0
  158. basic_memory/services/service.py +15 -0
  159. basic_memory/sync/__init__.py +6 -0
  160. basic_memory/sync/background_sync.py +26 -0
  161. basic_memory/sync/sync_service.py +1259 -0
  162. basic_memory/sync/watch_service.py +510 -0
  163. basic_memory/telemetry.py +249 -0
  164. basic_memory/templates/prompts/continue_conversation.hbs +110 -0
  165. basic_memory/templates/prompts/search.hbs +101 -0
  166. basic_memory/utils.py +468 -0
  167. basic_memory-0.17.1.dist-info/METADATA +617 -0
  168. basic_memory-0.17.1.dist-info/RECORD +171 -0
  169. basic_memory-0.17.1.dist-info/WHEEL +4 -0
  170. basic_memory-0.17.1.dist-info/entry_points.txt +3 -0
  171. basic_memory-0.17.1.dist-info/licenses/LICENSE +661 -0
@@ -0,0 +1,242 @@
1
+ from textwrap import dedent
2
+ from typing import Optional
3
+
4
+ from loguru import logger
5
+ from fastmcp import Context
6
+ from mcp.server.fastmcp.exceptions import ToolError
7
+
8
+ from basic_memory.mcp.project_context import get_active_project
9
+ from basic_memory.mcp.tools.utils import call_delete, resolve_entity_id
10
+ from basic_memory.mcp.server import mcp
11
+ from basic_memory.mcp.async_client import get_client
12
+ from basic_memory.telemetry import track_mcp_tool
13
+ from basic_memory.schemas import DeleteEntitiesResponse
14
+
15
+
16
+ def _format_delete_error_response(project: str, error_message: str, identifier: str) -> str:
17
+ """Format helpful error responses for delete failures that guide users to successful deletions."""
18
+
19
+ # Note not found errors
20
+ if "entity not found" in error_message.lower() or "not found" in error_message.lower():
21
+ search_term = identifier.split("/")[-1] if "/" in identifier else identifier
22
+ title_format = (
23
+ identifier.split("/")[-1].replace("-", " ").title() if "/" in identifier else identifier
24
+ )
25
+ permalink_format = identifier.lower().replace(" ", "-")
26
+
27
+ return dedent(f"""
28
+ # Delete Failed - Note Not Found
29
+
30
+ The note '{identifier}' could not be found for deletion in {project}.
31
+
32
+ ## This might mean:
33
+ 1. **Already deleted**: The note may have been deleted previously
34
+ 2. **Wrong identifier**: The identifier format might be incorrect
35
+ 3. **Different project**: The note might be in a different project
36
+
37
+ ## How to verify:
38
+ 1. **Search for the note**: Use `search_notes("{project}", "{search_term}")` to find it
39
+ 2. **Try different formats**:
40
+ - If you used a permalink like "folder/note-title", try just the title: "{title_format}"
41
+ - If you used a title, try the permalink format: "{permalink_format}"
42
+
43
+ 3. **Check if already deleted**: Use `list_directory("/")` to see what notes exist
44
+ 4. **List notes in project**: Use `list_directory("/")` to see what notes exist in the current project
45
+
46
+ ## If the note actually exists:
47
+ ```
48
+ # First, find the correct identifier:
49
+ search_notes("{project}", "{identifier}")
50
+
51
+ # Then delete using the correct identifier:
52
+ delete_note("{project}", "correct-identifier-from-search")
53
+ ```
54
+
55
+ ## If you want to delete multiple similar notes:
56
+ Use search to find all related notes and delete them one by one.
57
+ """).strip()
58
+
59
+ # Permission/access errors
60
+ if (
61
+ "permission" in error_message.lower()
62
+ or "access" in error_message.lower()
63
+ or "forbidden" in error_message.lower()
64
+ ):
65
+ return f"""# Delete Failed - Permission Error
66
+
67
+ You don't have permission to delete '{identifier}': {error_message}
68
+
69
+ ## How to resolve:
70
+ 1. **Check permissions**: Verify you have delete/write access to this project
71
+ 2. **File locks**: The note might be open in another application
72
+ 3. **Project access**: Ensure you're in the correct project with proper permissions
73
+
74
+ ## Alternative actions:
75
+ - List available projects: `list_memory_projects()`
76
+ - Specify the correct project: `delete_note("{identifier}", project="project-name")`
77
+ - Verify note exists first: `read_note("{identifier}", project="project-name")`
78
+
79
+ ## If you have read-only access:
80
+ Ask someone with write access to delete the note."""
81
+
82
+ # Server/filesystem errors
83
+ if (
84
+ "server error" in error_message.lower()
85
+ or "filesystem" in error_message.lower()
86
+ or "disk" in error_message.lower()
87
+ ):
88
+ return f"""# Delete Failed - System Error
89
+
90
+ A system error occurred while deleting '{identifier}': {error_message}
91
+
92
+ ## Immediate steps:
93
+ 1. **Try again**: The error might be temporary
94
+ 2. **Check file status**: Verify the file isn't locked or in use
95
+ 3. **Check disk space**: Ensure the system has adequate storage
96
+
97
+ ## Troubleshooting:
98
+ - Verify note exists: `read_note("{project}","{identifier}")`
99
+ - Try again in a few moments
100
+
101
+ ## If problem persists:
102
+ Send a message to support@basicmachines.co - there may be a filesystem or database issue."""
103
+
104
+ # Database/sync errors
105
+ if "database" in error_message.lower() or "sync" in error_message.lower():
106
+ return f"""# Delete Failed - Database Error
107
+
108
+ A database error occurred while deleting '{identifier}': {error_message}
109
+
110
+ ## This usually means:
111
+ 1. **Sync conflict**: The file system and database are out of sync
112
+ 2. **Database lock**: Another operation is accessing the database
113
+ 3. **Corrupted entry**: The database entry might be corrupted
114
+
115
+ ## Steps to resolve:
116
+ 1. **Try again**: Wait a moment and retry the deletion
117
+ 2. **Check note status**: `read_note("{project}","{identifier}")` to see current state
118
+ 3. **Manual verification**: Use `list_directory()` to see if file still exists
119
+
120
+ ## If the note appears gone but database shows it exists:
121
+ Send a message to support@basicmachines.co - a manual database cleanup may be needed."""
122
+
123
+ # Generic fallback
124
+ return f"""# Delete Failed
125
+
126
+ Error deleting note '{identifier}': {error_message}
127
+
128
+ ## General troubleshooting:
129
+ 1. **Verify the note exists**: `read_note("{project}", "{identifier}")` or `search_notes("{project}", "{identifier}")`
130
+ 2. **Check permissions**: Ensure you can edit/delete files in this project
131
+ 3. **Try again**: The error might be temporary
132
+ 4. **Check project**: Make sure you're in the correct project
133
+
134
+ ## Step-by-step approach:
135
+ ```
136
+ # 1. Confirm note exists and get correct identifier
137
+ search_notes("{project}", "{identifier}")
138
+
139
+ # 2. Read the note to verify access
140
+ read_note("{project}", "correct-identifier-from-search")
141
+
142
+ # 3. Try deletion with correct identifier
143
+ delete_note("{project}", "correct-identifier-from-search")
144
+ ```
145
+
146
+ ## Alternative approaches:
147
+ - Check what notes exist: `list_directory("{project}", "/")`
148
+
149
+ ## Need help?
150
+ If the note should be deleted but the operation keeps failing, send a message to support@basicmemory.com."""
151
+
152
+
153
+ @mcp.tool(description="Delete a note by title or permalink")
154
+ async def delete_note(
155
+ identifier: str, project: Optional[str] = None, context: Context | None = None
156
+ ) -> bool | str:
157
+ """Delete a note from the knowledge base.
158
+
159
+ Permanently removes a note from the specified project. The note is identified
160
+ by title or permalink. If the note doesn't exist, the operation returns False
161
+ without error. If deletion fails due to other issues, helpful error messages are provided.
162
+
163
+ Project Resolution:
164
+ Server resolves projects in this order: Single Project Mode → project parameter → default project.
165
+ If project unknown, use list_memory_projects() or recent_activity() first.
166
+
167
+ Args:
168
+ project: Project name to delete from. Optional - server will resolve using hierarchy.
169
+ If unknown, use list_memory_projects() to discover available projects.
170
+ identifier: Note title or permalink to delete
171
+ Can be a title like "Meeting Notes" or permalink like "notes/meeting-notes"
172
+ context: Optional FastMCP context for performance caching.
173
+
174
+ Returns:
175
+ True if note was successfully deleted, False if note was not found.
176
+ On errors, returns a formatted string with helpful troubleshooting guidance.
177
+
178
+ Examples:
179
+ # Delete by title
180
+ delete_note("my-project", "Meeting Notes: Project Planning")
181
+
182
+ # Delete by permalink
183
+ delete_note("work-docs", "notes/project-planning")
184
+
185
+ # Delete with exact path
186
+ delete_note("research", "experiments/ml-model-results")
187
+
188
+ # Common usage pattern
189
+ if delete_note("my-project", "old-draft"):
190
+ print("Note deleted successfully")
191
+ else:
192
+ print("Note not found or already deleted")
193
+
194
+ Raises:
195
+ HTTPError: If project doesn't exist or is inaccessible
196
+ SecurityError: If identifier attempts path traversal
197
+
198
+ Warning:
199
+ This operation is permanent and cannot be undone. The note file
200
+ will be removed from the filesystem and all references will be lost.
201
+
202
+ Note:
203
+ If the note is not found, this function provides helpful error messages
204
+ with suggestions for finding the correct identifier, including search
205
+ commands and alternative formats to try.
206
+ """
207
+ track_mcp_tool("delete_note")
208
+ async with get_client() as client:
209
+ active_project = await get_active_project(client, project, context)
210
+
211
+ try:
212
+ # Resolve identifier to entity ID
213
+ entity_id = await resolve_entity_id(client, active_project.id, identifier)
214
+ except ToolError as e:
215
+ # If entity not found, return False (note doesn't exist)
216
+ if "Entity not found" in str(e) or "not found" in str(e).lower():
217
+ logger.warning(f"Note not found for deletion: {identifier}")
218
+ return False
219
+ # For other resolution errors, return formatted error message
220
+ logger.error(f"Delete failed for '{identifier}': {e}, project: {active_project.name}")
221
+ return _format_delete_error_response(active_project.name, str(e), identifier)
222
+
223
+ try:
224
+ # Call the DELETE endpoint
225
+ response = await call_delete(
226
+ client, f"/v2/projects/{active_project.id}/knowledge/entities/{entity_id}"
227
+ )
228
+ result = DeleteEntitiesResponse.model_validate(response.json())
229
+
230
+ if result.deleted:
231
+ logger.info(
232
+ f"Successfully deleted note: {identifier} in project: {active_project.name}"
233
+ )
234
+ return True
235
+ else:
236
+ logger.warning(f"Delete operation completed but note was not deleted: {identifier}")
237
+ return False
238
+
239
+ except Exception as e: # pragma: no cover
240
+ logger.error(f"Delete failed for '{identifier}': {e}, project: {active_project.name}")
241
+ # Return formatted error message for better user experience
242
+ return _format_delete_error_response(active_project.name, str(e), identifier)
@@ -0,0 +1,324 @@
1
+ """Edit note tool for Basic Memory MCP server."""
2
+
3
+ from typing import Optional
4
+
5
+ from loguru import logger
6
+ from fastmcp import Context
7
+
8
+ from basic_memory.mcp.async_client import get_client
9
+ from basic_memory.mcp.project_context import get_active_project, add_project_metadata
10
+ from basic_memory.mcp.server import mcp
11
+ from basic_memory.mcp.tools.utils import call_patch, resolve_entity_id
12
+ from basic_memory.telemetry import track_mcp_tool
13
+ from basic_memory.schemas import EntityResponse
14
+
15
+
16
+ def _format_error_response(
17
+ error_message: str,
18
+ operation: str,
19
+ identifier: str,
20
+ find_text: Optional[str] = None,
21
+ expected_replacements: int = 1,
22
+ project: Optional[str] = None,
23
+ ) -> str:
24
+ """Format helpful error responses for edit_note failures that guide the AI to retry successfully."""
25
+
26
+ # Entity not found errors
27
+ if "Entity not found" in error_message or "entity not found" in error_message.lower():
28
+ return f"""# Edit Failed - Note Not Found
29
+
30
+ The note with identifier '{identifier}' could not be found. Edit operations require an exact match (no fuzzy matching).
31
+
32
+ ## Suggestions to try:
33
+ 1. **Search for the note first**: Use `search_notes("{project or "project-name"}", "{identifier.split("/")[-1]}")` to find similar notes with exact identifiers
34
+ 2. **Try different exact identifier formats**:
35
+ - If you used a permalink like "folder/note-title", try the exact title: "{identifier.split("/")[-1].replace("-", " ").title()}"
36
+ - If you used a title, try the exact permalink format: "{identifier.lower().replace(" ", "-")}"
37
+ - Use `read_note("{project or "project-name"}", "{identifier}")` first to verify the note exists and get the exact identifier
38
+
39
+ ## Alternative approach:
40
+ Use `write_note("{project or "project-name"}", "title", "content", "folder")` to create the note first, then edit it."""
41
+
42
+ # Find/replace specific errors
43
+ if operation == "find_replace":
44
+ if "Text to replace not found" in error_message:
45
+ return f"""# Edit Failed - Text Not Found
46
+
47
+ The text '{find_text}' was not found in the note '{identifier}'.
48
+
49
+ ## Suggestions to try:
50
+ 1. **Read the note first**: Use `read_note("{project or "project-name"}", "{identifier}")` to see the current content
51
+ 2. **Check for exact matches**: The search is case-sensitive and must match exactly
52
+ 3. **Try a broader search**: Search for just part of the text you want to replace
53
+ 4. **Use expected_replacements=0**: If you want to verify the text doesn't exist
54
+
55
+ ## Alternative approaches:
56
+ - Use `append` or `prepend` to add new content instead
57
+ - Use `replace_section` if you're trying to update a specific section"""
58
+
59
+ if "Expected" in error_message and "occurrences" in error_message:
60
+ # Extract the actual count from error message if possible
61
+ import re
62
+
63
+ match = re.search(r"found (\d+)", error_message)
64
+ actual_count = match.group(1) if match else "a different number of"
65
+
66
+ return f"""# Edit Failed - Wrong Replacement Count
67
+
68
+ Expected {expected_replacements} occurrences of '{find_text}' but found {actual_count}.
69
+
70
+ ## How to fix:
71
+ 1. **Read the note first**: Use `read_note("{project or "project-name"}", "{identifier}")` to see how many times '{find_text}' appears
72
+ 2. **Update expected_replacements**: Set expected_replacements={actual_count} in your edit_note call
73
+ 3. **Be more specific**: If you only want to replace some occurrences, make your find_text more specific
74
+
75
+ ## Example:
76
+ ```
77
+ edit_note("{project or "project-name"}", "{identifier}", "find_replace", "new_text", find_text="{find_text}", expected_replacements={actual_count})
78
+ ```"""
79
+
80
+ # Section replacement errors
81
+ if operation == "replace_section" and "Multiple sections" in error_message:
82
+ return f"""# Edit Failed - Duplicate Section Headers
83
+
84
+ Multiple sections found with the same header in note '{identifier}'.
85
+
86
+ ## How to fix:
87
+ 1. **Read the note first**: Use `read_note("{project or "project-name"}", "{identifier}")` to see the document structure
88
+ 2. **Make headers unique**: Add more specific text to distinguish sections
89
+ 3. **Use append instead**: Add content at the end rather than replacing a specific section
90
+
91
+ ## Alternative approach:
92
+ Use `find_replace` to update specific text within the duplicate sections."""
93
+
94
+ # Generic server/request errors
95
+ if (
96
+ "Invalid request" in error_message or "malformed" in error_message.lower()
97
+ ): # pragma: no cover
98
+ return f"""# Edit Failed - Request Error
99
+
100
+ There was a problem with the edit request to note '{identifier}': {error_message}.
101
+
102
+ ## Common causes and fixes:
103
+ 1. **Note doesn't exist**: Use `search_notes("{project or "project-name"}", "query")` or `read_note("{project or "project-name"}", "{identifier}")` to verify the note exists
104
+ 2. **Invalid identifier format**: Try different identifier formats (title vs permalink)
105
+ 3. **Empty or invalid content**: Check that your content is properly formatted
106
+ 4. **Server error**: Try the operation again, or use `read_note()` first to verify the note state
107
+
108
+ ## Troubleshooting steps:
109
+ 1. Verify the note exists: `read_note("{project or "project-name"}", "{identifier}")`
110
+ 2. If not found, search for it: `search_notes("{project or "project-name"}", "{identifier.split("/")[-1]}")`
111
+ 3. Try again with the correct identifier from the search results"""
112
+
113
+ # Fallback for other errors
114
+ return f"""# Edit Failed
115
+
116
+ Error editing note '{identifier}': {error_message}
117
+
118
+ ## General troubleshooting:
119
+ 1. **Verify the note exists**: Use `read_note("{project or "project-name"}", "{identifier}")` to check
120
+ 2. **Check your parameters**: Ensure all required parameters are provided correctly
121
+ 3. **Read the note content first**: Use `read_note("{project or "project-name"}", "{identifier}")` to understand the current structure
122
+ 4. **Try a simpler operation**: Start with `append` if other operations fail
123
+
124
+ ## Need help?
125
+ - Use `search_notes("{project or "project-name"}", "query")` to find notes
126
+ - Use `read_note("{project or "project-name"}", "identifier")` to examine content before editing
127
+ - Check that identifiers, section headers, and find_text match exactly"""
128
+
129
+
130
+ @mcp.tool(
131
+ description="Edit an existing markdown note using various operations like append, prepend, find_replace, or replace_section.",
132
+ )
133
+ async def edit_note(
134
+ identifier: str,
135
+ operation: str,
136
+ content: str,
137
+ project: Optional[str] = None,
138
+ section: Optional[str] = None,
139
+ find_text: Optional[str] = None,
140
+ expected_replacements: int = 1,
141
+ context: Context | None = None,
142
+ ) -> str:
143
+ """Edit an existing markdown note in the knowledge base.
144
+
145
+ Makes targeted changes to existing notes without rewriting the entire content.
146
+
147
+ Project Resolution:
148
+ Server resolves projects in this order: Single Project Mode → project parameter → default project.
149
+ If project unknown, use list_memory_projects() or recent_activity() first.
150
+
151
+ Args:
152
+ identifier: The exact title, permalink, or memory:// URL of the note to edit.
153
+ Must be an exact match - fuzzy matching is not supported for edit operations.
154
+ Use search_notes() or read_note() first to find the correct identifier if uncertain.
155
+ operation: The editing operation to perform:
156
+ - "append": Add content to the end of the note
157
+ - "prepend": Add content to the beginning of the note
158
+ - "find_replace": Replace occurrences of find_text with content
159
+ - "replace_section": Replace content under a specific markdown header
160
+ content: The content to add or use for replacement
161
+ project: Project name to edit in. Optional - server will resolve using hierarchy.
162
+ If unknown, use list_memory_projects() to discover available projects.
163
+ section: For replace_section operation - the markdown header to replace content under (e.g., "## Notes", "### Implementation")
164
+ find_text: For find_replace operation - the text to find and replace
165
+ expected_replacements: For find_replace operation - the expected number of replacements (validation will fail if actual doesn't match)
166
+ context: Optional FastMCP context for performance caching.
167
+
168
+ Returns:
169
+ A markdown formatted summary of the edit operation and resulting semantic content,
170
+ including operation details, file path, observations, relations, and project metadata.
171
+
172
+ Examples:
173
+ # Add new content to end of note
174
+ edit_note("my-project", "project-planning", "append", "\\n## New Requirements\\n- Feature X\\n- Feature Y")
175
+
176
+ # Add timestamp at beginning (frontmatter-aware)
177
+ edit_note("work-docs", "meeting-notes", "prepend", "## 2025-05-25 Update\\n- Progress update...\\n\\n")
178
+
179
+ # Update version number (single occurrence)
180
+ edit_note("api-project", "config-spec", "find_replace", "v0.13.0", find_text="v0.12.0")
181
+
182
+ # Update version in multiple places with validation
183
+ edit_note("docs-project", "api-docs", "find_replace", "v2.1.0", find_text="v2.0.0", expected_replacements=3)
184
+
185
+ # Replace text that appears multiple times - validate count first
186
+ edit_note("team-docs", "docs/guide", "find_replace", "new-api", find_text="old-api", expected_replacements=5)
187
+
188
+ # Replace implementation section
189
+ edit_note("specs", "api-spec", "replace_section", "New implementation approach...\\n", section="## Implementation")
190
+
191
+ # Replace subsection with more specific header
192
+ edit_note("docs", "docs/setup", "replace_section", "Updated install steps\\n", section="### Installation")
193
+
194
+ # Using different identifier formats (must be exact matches)
195
+ edit_note("work-project", "Meeting Notes", "append", "\\n- Follow up on action items") # exact title
196
+ edit_note("work-project", "docs/meeting-notes", "append", "\\n- Follow up tasks") # exact permalink
197
+
198
+ # If uncertain about identifier, search first:
199
+ # search_notes("work-project", "meeting") # Find available notes
200
+ # edit_note("work-project", "docs/meeting-notes-2025", "append", "content") # Use exact result
201
+
202
+ # Add new section to document
203
+ edit_note("planning", "project-plan", "replace_section", "TBD - needs research\\n", section="## Future Work")
204
+
205
+ # Update status across document (expecting exactly 2 occurrences)
206
+ edit_note("reports", "status-report", "find_replace", "In Progress", find_text="Not Started", expected_replacements=2)
207
+
208
+ Raises:
209
+ HTTPError: If project doesn't exist or is inaccessible
210
+ ValueError: If operation is invalid or required parameters are missing
211
+ SecurityError: If identifier attempts path traversal
212
+
213
+ Note:
214
+ Edit operations require exact identifier matches. If unsure, use read_note() or
215
+ search_notes() first to find the correct identifier. The tool provides detailed
216
+ error messages with suggestions if operations fail.
217
+ """
218
+ track_mcp_tool("edit_note")
219
+ async with get_client() as client:
220
+ active_project = await get_active_project(client, project, context)
221
+
222
+ logger.info("MCP tool call", tool="edit_note", identifier=identifier, operation=operation)
223
+
224
+ # Validate operation
225
+ valid_operations = ["append", "prepend", "find_replace", "replace_section"]
226
+ if operation not in valid_operations:
227
+ raise ValueError(
228
+ f"Invalid operation '{operation}'. Must be one of: {', '.join(valid_operations)}"
229
+ )
230
+
231
+ # Validate required parameters for specific operations
232
+ if operation == "find_replace" and not find_text:
233
+ raise ValueError("find_text parameter is required for find_replace operation")
234
+ if operation == "replace_section" and not section:
235
+ raise ValueError("section parameter is required for replace_section operation")
236
+
237
+ # Use the PATCH endpoint to edit the entity
238
+ try:
239
+ # Resolve identifier to entity ID
240
+ entity_id = await resolve_entity_id(client, active_project.id, identifier)
241
+
242
+ # Prepare the edit request data
243
+ edit_data = {
244
+ "operation": operation,
245
+ "content": content,
246
+ }
247
+
248
+ # Add optional parameters
249
+ if section:
250
+ edit_data["section"] = section
251
+ if find_text:
252
+ edit_data["find_text"] = find_text
253
+ if expected_replacements != 1: # Only send if different from default
254
+ edit_data["expected_replacements"] = str(expected_replacements)
255
+
256
+ # Call the PATCH endpoint
257
+ url = f"/v2/projects/{active_project.id}/knowledge/entities/{entity_id}"
258
+ response = await call_patch(client, url, json=edit_data)
259
+ result = EntityResponse.model_validate(response.json())
260
+
261
+ # Format summary
262
+ summary = [
263
+ f"# Edited note ({operation})",
264
+ f"project: {active_project.name}",
265
+ f"file_path: {result.file_path}",
266
+ f"permalink: {result.permalink}",
267
+ f"checksum: {result.checksum[:8] if result.checksum else 'unknown'}",
268
+ ]
269
+
270
+ # Add operation-specific details
271
+ if operation == "append":
272
+ lines_added = len(content.split("\n"))
273
+ summary.append(f"operation: Added {lines_added} lines to end of note")
274
+ elif operation == "prepend":
275
+ lines_added = len(content.split("\n"))
276
+ summary.append(f"operation: Added {lines_added} lines to beginning of note")
277
+ elif operation == "find_replace":
278
+ # For find_replace, we can't easily count replacements from here
279
+ # since we don't have the original content, but the server handled it
280
+ summary.append("operation: Find and replace operation completed")
281
+ elif operation == "replace_section":
282
+ summary.append(f"operation: Replaced content under section '{section}'")
283
+
284
+ # Count observations by category (reuse logic from write_note)
285
+ categories = {}
286
+ if result.observations:
287
+ for obs in result.observations:
288
+ categories[obs.category] = categories.get(obs.category, 0) + 1
289
+
290
+ summary.append("\\n## Observations")
291
+ for category, count in sorted(categories.items()):
292
+ summary.append(f"- {category}: {count}")
293
+
294
+ # Count resolved/unresolved relations
295
+ unresolved = 0
296
+ resolved = 0
297
+ if result.relations:
298
+ unresolved = sum(1 for r in result.relations if not r.to_id)
299
+ resolved = len(result.relations) - unresolved
300
+
301
+ summary.append("\\n## Relations")
302
+ summary.append(f"- Resolved: {resolved}")
303
+ if unresolved:
304
+ summary.append(f"- Unresolved: {unresolved}")
305
+
306
+ logger.info(
307
+ "MCP tool response",
308
+ tool="edit_note",
309
+ operation=operation,
310
+ project=active_project.name,
311
+ permalink=result.permalink,
312
+ observations_count=len(result.observations),
313
+ relations_count=len(result.relations),
314
+ status_code=response.status_code,
315
+ )
316
+
317
+ result = "\n".join(summary)
318
+ return add_project_metadata(result, active_project.name)
319
+
320
+ except Exception as e:
321
+ logger.error(f"Error editing note: {e}")
322
+ return _format_error_response(
323
+ str(e), operation, identifier, find_text, expected_replacements, active_project.name
324
+ )