basic-memory 0.14.4__py3-none-any.whl → 0.15.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.

Potentially problematic release.


This version of basic-memory might be problematic. Click here for more details.

Files changed (84) hide show
  1. basic_memory/__init__.py +1 -1
  2. basic_memory/alembic/versions/a1b2c3d4e5f6_fix_project_foreign_keys.py +5 -9
  3. basic_memory/api/app.py +10 -4
  4. basic_memory/api/routers/directory_router.py +23 -2
  5. basic_memory/api/routers/knowledge_router.py +25 -8
  6. basic_memory/api/routers/project_router.py +100 -4
  7. basic_memory/cli/app.py +9 -28
  8. basic_memory/cli/auth.py +277 -0
  9. basic_memory/cli/commands/cloud/__init__.py +5 -0
  10. basic_memory/cli/commands/cloud/api_client.py +112 -0
  11. basic_memory/cli/commands/cloud/bisync_commands.py +818 -0
  12. basic_memory/cli/commands/cloud/core_commands.py +288 -0
  13. basic_memory/cli/commands/cloud/mount_commands.py +295 -0
  14. basic_memory/cli/commands/cloud/rclone_config.py +288 -0
  15. basic_memory/cli/commands/cloud/rclone_installer.py +198 -0
  16. basic_memory/cli/commands/command_utils.py +43 -0
  17. basic_memory/cli/commands/import_memory_json.py +0 -4
  18. basic_memory/cli/commands/mcp.py +77 -60
  19. basic_memory/cli/commands/project.py +154 -152
  20. basic_memory/cli/commands/status.py +25 -22
  21. basic_memory/cli/commands/sync.py +45 -228
  22. basic_memory/cli/commands/tool.py +87 -16
  23. basic_memory/cli/main.py +1 -0
  24. basic_memory/config.py +131 -21
  25. basic_memory/db.py +104 -3
  26. basic_memory/deps.py +27 -8
  27. basic_memory/file_utils.py +37 -13
  28. basic_memory/ignore_utils.py +295 -0
  29. basic_memory/markdown/plugins.py +9 -7
  30. basic_memory/mcp/async_client.py +124 -14
  31. basic_memory/mcp/project_context.py +141 -0
  32. basic_memory/mcp/prompts/ai_assistant_guide.py +49 -4
  33. basic_memory/mcp/prompts/continue_conversation.py +17 -16
  34. basic_memory/mcp/prompts/recent_activity.py +116 -32
  35. basic_memory/mcp/prompts/search.py +13 -12
  36. basic_memory/mcp/prompts/utils.py +11 -4
  37. basic_memory/mcp/resources/ai_assistant_guide.md +211 -341
  38. basic_memory/mcp/resources/project_info.py +27 -11
  39. basic_memory/mcp/server.py +0 -37
  40. basic_memory/mcp/tools/__init__.py +5 -6
  41. basic_memory/mcp/tools/build_context.py +67 -56
  42. basic_memory/mcp/tools/canvas.py +38 -26
  43. basic_memory/mcp/tools/chatgpt_tools.py +187 -0
  44. basic_memory/mcp/tools/delete_note.py +81 -47
  45. basic_memory/mcp/tools/edit_note.py +155 -138
  46. basic_memory/mcp/tools/list_directory.py +112 -99
  47. basic_memory/mcp/tools/move_note.py +181 -101
  48. basic_memory/mcp/tools/project_management.py +113 -277
  49. basic_memory/mcp/tools/read_content.py +91 -74
  50. basic_memory/mcp/tools/read_note.py +152 -115
  51. basic_memory/mcp/tools/recent_activity.py +471 -68
  52. basic_memory/mcp/tools/search.py +105 -92
  53. basic_memory/mcp/tools/sync_status.py +136 -130
  54. basic_memory/mcp/tools/utils.py +4 -0
  55. basic_memory/mcp/tools/view_note.py +44 -33
  56. basic_memory/mcp/tools/write_note.py +151 -90
  57. basic_memory/models/knowledge.py +12 -6
  58. basic_memory/models/project.py +6 -2
  59. basic_memory/repository/entity_repository.py +89 -82
  60. basic_memory/repository/relation_repository.py +13 -0
  61. basic_memory/repository/repository.py +18 -5
  62. basic_memory/repository/search_repository.py +46 -2
  63. basic_memory/schemas/__init__.py +6 -0
  64. basic_memory/schemas/base.py +39 -11
  65. basic_memory/schemas/cloud.py +46 -0
  66. basic_memory/schemas/memory.py +90 -21
  67. basic_memory/schemas/project_info.py +9 -10
  68. basic_memory/schemas/sync_report.py +48 -0
  69. basic_memory/services/context_service.py +25 -11
  70. basic_memory/services/directory_service.py +124 -3
  71. basic_memory/services/entity_service.py +100 -48
  72. basic_memory/services/initialization.py +30 -11
  73. basic_memory/services/project_service.py +101 -24
  74. basic_memory/services/search_service.py +16 -8
  75. basic_memory/sync/sync_service.py +173 -34
  76. basic_memory/sync/watch_service.py +101 -40
  77. basic_memory/utils.py +14 -4
  78. {basic_memory-0.14.4.dist-info → basic_memory-0.15.1.dist-info}/METADATA +57 -9
  79. basic_memory-0.15.1.dist-info/RECORD +146 -0
  80. basic_memory/mcp/project_session.py +0 -120
  81. basic_memory-0.14.4.dist-info/RECORD +0 -133
  82. {basic_memory-0.14.4.dist-info → basic_memory-0.15.1.dist-info}/WHEEL +0 -0
  83. {basic_memory-0.14.4.dist-info → basic_memory-0.15.1.dist-info}/entry_points.txt +0 -0
  84. {basic_memory-0.14.4.dist-info → basic_memory-0.15.1.dist-info}/licenses/LICENSE +0 -0
@@ -3,9 +3,10 @@
3
3
  from typing import Optional
4
4
 
5
5
  from loguru import logger
6
+ from fastmcp import Context
6
7
 
7
- from basic_memory.mcp.async_client import client
8
- from basic_memory.mcp.project_session import get_active_project
8
+ from basic_memory.mcp.async_client import get_client
9
+ from basic_memory.mcp.project_context import get_active_project, add_project_metadata
9
10
  from basic_memory.mcp.server import mcp
10
11
  from basic_memory.mcp.tools.utils import call_patch
11
12
  from basic_memory.schemas import EntityResponse
@@ -17,6 +18,7 @@ def _format_error_response(
17
18
  identifier: str,
18
19
  find_text: Optional[str] = None,
19
20
  expected_replacements: int = 1,
21
+ project: Optional[str] = None,
20
22
  ) -> str:
21
23
  """Format helpful error responses for edit_note failures that guide the AI to retry successfully."""
22
24
 
@@ -27,14 +29,14 @@ def _format_error_response(
27
29
  The note with identifier '{identifier}' could not be found. Edit operations require an exact match (no fuzzy matching).
28
30
 
29
31
  ## Suggestions to try:
30
- 1. **Search for the note first**: Use `search_notes("{identifier.split("/")[-1]}")` to find similar notes with exact identifiers
32
+ 1. **Search for the note first**: Use `search_notes("{project or "project-name"}", "{identifier.split("/")[-1]}")` to find similar notes with exact identifiers
31
33
  2. **Try different exact identifier formats**:
32
34
  - If you used a permalink like "folder/note-title", try the exact title: "{identifier.split("/")[-1].replace("-", " ").title()}"
33
35
  - If you used a title, try the exact permalink format: "{identifier.lower().replace(" ", "-")}"
34
- - Use `read_note()` first to verify the note exists and get the exact identifier
36
+ - Use `read_note("{project or "project-name"}", "{identifier}")` first to verify the note exists and get the exact identifier
35
37
 
36
38
  ## Alternative approach:
37
- Use `write_note()` to create the note first, then edit it."""
39
+ Use `write_note("{project or "project-name"}", "title", "content", "folder")` to create the note first, then edit it."""
38
40
 
39
41
  # Find/replace specific errors
40
42
  if operation == "find_replace":
@@ -44,7 +46,7 @@ Use `write_note()` to create the note first, then edit it."""
44
46
  The text '{find_text}' was not found in the note '{identifier}'.
45
47
 
46
48
  ## Suggestions to try:
47
- 1. **Read the note first**: Use `read_note("{identifier}")` to see the current content
49
+ 1. **Read the note first**: Use `read_note("{project or "project-name"}", "{identifier}")` to see the current content
48
50
  2. **Check for exact matches**: The search is case-sensitive and must match exactly
49
51
  3. **Try a broader search**: Search for just part of the text you want to replace
50
52
  4. **Use expected_replacements=0**: If you want to verify the text doesn't exist
@@ -65,13 +67,13 @@ The text '{find_text}' was not found in the note '{identifier}'.
65
67
  Expected {expected_replacements} occurrences of '{find_text}' but found {actual_count}.
66
68
 
67
69
  ## How to fix:
68
- 1. **Read the note first**: Use `read_note("{identifier}")` to see how many times '{find_text}' appears
70
+ 1. **Read the note first**: Use `read_note("{project or "project-name"}", "{identifier}")` to see how many times '{find_text}' appears
69
71
  2. **Update expected_replacements**: Set expected_replacements={actual_count} in your edit_note call
70
72
  3. **Be more specific**: If you only want to replace some occurrences, make your find_text more specific
71
73
 
72
74
  ## Example:
73
75
  ```
74
- edit_note("{identifier}", "find_replace", "new_text", find_text="{find_text}", expected_replacements={actual_count})
76
+ edit_note("{project or "project-name"}", "{identifier}", "find_replace", "new_text", find_text="{find_text}", expected_replacements={actual_count})
75
77
  ```"""
76
78
 
77
79
  # Section replacement errors
@@ -81,7 +83,7 @@ edit_note("{identifier}", "find_replace", "new_text", find_text="{find_text}", e
81
83
  Multiple sections found with the same header in note '{identifier}'.
82
84
 
83
85
  ## How to fix:
84
- 1. **Read the note first**: Use `read_note("{identifier}")` to see the document structure
86
+ 1. **Read the note first**: Use `read_note("{project or "project-name"}", "{identifier}")` to see the document structure
85
87
  2. **Make headers unique**: Add more specific text to distinguish sections
86
88
  3. **Use append instead**: Add content at the end rather than replacing a specific section
87
89
 
@@ -97,14 +99,14 @@ Use `find_replace` to update specific text within the duplicate sections."""
97
99
  There was a problem with the edit request to note '{identifier}': {error_message}.
98
100
 
99
101
  ## Common causes and fixes:
100
- 1. **Note doesn't exist**: Use `search_notes()` or `read_note()` to verify the note exists
102
+ 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
101
103
  2. **Invalid identifier format**: Try different identifier formats (title vs permalink)
102
104
  3. **Empty or invalid content**: Check that your content is properly formatted
103
105
  4. **Server error**: Try the operation again, or use `read_note()` first to verify the note state
104
106
 
105
107
  ## Troubleshooting steps:
106
- 1. Verify the note exists: `read_note("{identifier}")`
107
- 2. If not found, search for it: `search_notes("{identifier.split("/")[-1]}")`
108
+ 1. Verify the note exists: `read_note("{project or "project-name"}", "{identifier}")`
109
+ 2. If not found, search for it: `search_notes("{project or "project-name"}", "{identifier.split("/")[-1]}")`
108
110
  3. Try again with the correct identifier from the search results"""
109
111
 
110
112
  # Fallback for other errors
@@ -113,14 +115,14 @@ There was a problem with the edit request to note '{identifier}': {error_message
113
115
  Error editing note '{identifier}': {error_message}
114
116
 
115
117
  ## General troubleshooting:
116
- 1. **Verify the note exists**: Use `read_note("{identifier}")` to check
118
+ 1. **Verify the note exists**: Use `read_note("{project or "project-name"}", "{identifier}")` to check
117
119
  2. **Check your parameters**: Ensure all required parameters are provided correctly
118
- 3. **Read the note content first**: Use `read_note()` to understand the current structure
120
+ 3. **Read the note content first**: Use `read_note("{project or "project-name"}", "{identifier}")` to understand the current structure
119
121
  4. **Try a simpler operation**: Start with `append` if other operations fail
120
122
 
121
123
  ## Need help?
122
- - Use `search_notes()` to find notes
123
- - Use `read_note()` to examine content before editing
124
+ - Use `search_notes("{project or "project-name"}", "query")` to find notes
125
+ - Use `read_note("{project or "project-name"}", "identifier")` to examine content before editing
124
126
  - Check that identifiers, section headers, and find_text match exactly"""
125
127
 
126
128
 
@@ -131,15 +133,19 @@ async def edit_note(
131
133
  identifier: str,
132
134
  operation: str,
133
135
  content: str,
136
+ project: Optional[str] = None,
134
137
  section: Optional[str] = None,
135
138
  find_text: Optional[str] = None,
136
139
  expected_replacements: int = 1,
137
- project: Optional[str] = None,
140
+ context: Context | None = None,
138
141
  ) -> str:
139
142
  """Edit an existing markdown note in the knowledge base.
140
143
 
141
- This tool allows you to make targeted changes to existing notes without rewriting the entire content.
142
- It supports various operations for different editing scenarios.
144
+ Makes targeted changes to existing notes without rewriting the entire content.
145
+
146
+ Project Resolution:
147
+ Server resolves projects in this order: Single Project Mode → project parameter → default project.
148
+ If project unknown, use list_memory_projects() or recent_activity() first.
143
149
 
144
150
  Args:
145
151
  identifier: The exact title, permalink, or memory:// URL of the note to edit.
@@ -151,153 +157,164 @@ async def edit_note(
151
157
  - "find_replace": Replace occurrences of find_text with content
152
158
  - "replace_section": Replace content under a specific markdown header
153
159
  content: The content to add or use for replacement
160
+ project: Project name to edit in. Optional - server will resolve using hierarchy.
161
+ If unknown, use list_memory_projects() to discover available projects.
154
162
  section: For replace_section operation - the markdown header to replace content under (e.g., "## Notes", "### Implementation")
155
163
  find_text: For find_replace operation - the text to find and replace
156
164
  expected_replacements: For find_replace operation - the expected number of replacements (validation will fail if actual doesn't match)
157
- project: Optional project name to delete from. If not provided, uses current active project.
165
+ context: Optional FastMCP context for performance caching.
158
166
 
159
167
  Returns:
160
- A markdown formatted summary of the edit operation and resulting semantic content
168
+ A markdown formatted summary of the edit operation and resulting semantic content,
169
+ including operation details, file path, observations, relations, and project metadata.
161
170
 
162
171
  Examples:
163
172
  # Add new content to end of note
164
- edit_note("project-planning", "append", "\\n## New Requirements\\n- Feature X\\n- Feature Y")
173
+ edit_note("my-project", "project-planning", "append", "\\n## New Requirements\\n- Feature X\\n- Feature Y")
165
174
 
166
175
  # Add timestamp at beginning (frontmatter-aware)
167
- edit_note("meeting-notes", "prepend", "## 2025-05-25 Update\\n- Progress update...\\n\\n")
176
+ edit_note("work-docs", "meeting-notes", "prepend", "## 2025-05-25 Update\\n- Progress update...\\n\\n")
168
177
 
169
178
  # Update version number (single occurrence)
170
- edit_note("config-spec", "find_replace", "v0.13.0", find_text="v0.12.0")
179
+ edit_note("api-project", "config-spec", "find_replace", "v0.13.0", find_text="v0.12.0")
171
180
 
172
181
  # Update version in multiple places with validation
173
- edit_note("api-docs", "find_replace", "v2.1.0", find_text="v2.0.0", expected_replacements=3)
182
+ edit_note("docs-project", "api-docs", "find_replace", "v2.1.0", find_text="v2.0.0", expected_replacements=3)
174
183
 
175
184
  # Replace text that appears multiple times - validate count first
176
- edit_note("docs/guide", "find_replace", "new-api", find_text="old-api", expected_replacements=5)
185
+ edit_note("team-docs", "docs/guide", "find_replace", "new-api", find_text="old-api", expected_replacements=5)
177
186
 
178
187
  # Replace implementation section
179
- edit_note("api-spec", "replace_section", "New implementation approach...\\n", section="## Implementation")
188
+ edit_note("specs", "api-spec", "replace_section", "New implementation approach...\\n", section="## Implementation")
180
189
 
181
190
  # Replace subsection with more specific header
182
- edit_note("docs/setup", "replace_section", "Updated install steps\\n", section="### Installation")
191
+ edit_note("docs", "docs/setup", "replace_section", "Updated install steps\\n", section="### Installation")
183
192
 
184
193
  # Using different identifier formats (must be exact matches)
185
- edit_note("Meeting Notes", "append", "\\n- Follow up on action items") # exact title
186
- edit_note("docs/meeting-notes", "append", "\\n- Follow up tasks") # exact permalink
187
- edit_note("docs/Meeting Notes", "append", "\\n- Next steps") # exact folder/title
194
+ edit_note("work-project", "Meeting Notes", "append", "\\n- Follow up on action items") # exact title
195
+ edit_note("work-project", "docs/meeting-notes", "append", "\\n- Follow up tasks") # exact permalink
188
196
 
189
197
  # If uncertain about identifier, search first:
190
- # search_notes("meeting") # Find available notes
191
- # edit_note("docs/meeting-notes-2025", "append", "content") # Use exact result
198
+ # search_notes("work-project", "meeting") # Find available notes
199
+ # edit_note("work-project", "docs/meeting-notes-2025", "append", "content") # Use exact result
192
200
 
193
201
  # Add new section to document
194
- edit_note("project-plan", "replace_section", "TBD - needs research\\n", section="## Future Work")
202
+ edit_note("planning", "project-plan", "replace_section", "TBD - needs research\\n", section="## Future Work")
195
203
 
196
204
  # Update status across document (expecting exactly 2 occurrences)
197
- edit_note("status-report", "find_replace", "In Progress", find_text="Not Started", expected_replacements=2)
205
+ edit_note("reports", "status-report", "find_replace", "In Progress", find_text="Not Started", expected_replacements=2)
198
206
 
199
- # Replace text in a file, specifying project name
200
- edit_note("docs/guide", "find_replace", "new-api", find_text="old-api", project="my-project"))
207
+ Raises:
208
+ HTTPError: If project doesn't exist or is inaccessible
209
+ ValueError: If operation is invalid or required parameters are missing
210
+ SecurityError: If identifier attempts path traversal
201
211
 
212
+ Note:
213
+ Edit operations require exact identifier matches. If unsure, use read_note() or
214
+ search_notes() first to find the correct identifier. The tool provides detailed
215
+ error messages with suggestions if operations fail.
202
216
  """
203
- active_project = get_active_project(project)
204
- project_url = active_project.project_url
205
-
206
- logger.info("MCP tool call", tool="edit_note", identifier=identifier, operation=operation)
207
-
208
- # Validate operation
209
- valid_operations = ["append", "prepend", "find_replace", "replace_section"]
210
- if operation not in valid_operations:
211
- raise ValueError(
212
- f"Invalid operation '{operation}'. Must be one of: {', '.join(valid_operations)}"
213
- )
214
-
215
- # Validate required parameters for specific operations
216
- if operation == "find_replace" and not find_text:
217
- raise ValueError("find_text parameter is required for find_replace operation")
218
- if operation == "replace_section" and not section:
219
- raise ValueError("section parameter is required for replace_section operation")
220
-
221
- # Use the PATCH endpoint to edit the entity
222
- try:
223
- # Prepare the edit request data
224
- edit_data = {
225
- "operation": operation,
226
- "content": content,
227
- }
228
-
229
- # Add optional parameters
230
- if section:
231
- edit_data["section"] = section
232
- if find_text:
233
- edit_data["find_text"] = find_text
234
- if expected_replacements != 1: # Only send if different from default
235
- edit_data["expected_replacements"] = str(expected_replacements)
236
-
237
- # Call the PATCH endpoint
238
- url = f"{project_url}/knowledge/entities/{identifier}"
239
- response = await call_patch(client, url, json=edit_data)
240
- result = EntityResponse.model_validate(response.json())
241
-
242
- # Format summary
243
- summary = [
244
- f"# Edited note ({operation})",
245
- f"project: {active_project.name}",
246
- f"file_path: {result.file_path}",
247
- f"permalink: {result.permalink}",
248
- f"checksum: {result.checksum[:8] if result.checksum else 'unknown'}",
249
- ]
250
-
251
- # Add operation-specific details
252
- if operation == "append":
253
- lines_added = len(content.split("\n"))
254
- summary.append(f"operation: Added {lines_added} lines to end of note")
255
- elif operation == "prepend":
256
- lines_added = len(content.split("\n"))
257
- summary.append(f"operation: Added {lines_added} lines to beginning of note")
258
- elif operation == "find_replace":
259
- # For find_replace, we can't easily count replacements from here
260
- # since we don't have the original content, but the server handled it
261
- summary.append("operation: Find and replace operation completed")
262
- elif operation == "replace_section":
263
- summary.append(f"operation: Replaced content under section '{section}'")
264
-
265
- # Count observations by category (reuse logic from write_note)
266
- categories = {}
267
- if result.observations:
268
- for obs in result.observations:
269
- categories[obs.category] = categories.get(obs.category, 0) + 1
270
-
271
- summary.append("\\n## Observations")
272
- for category, count in sorted(categories.items()):
273
- summary.append(f"- {category}: {count}")
274
-
275
- # Count resolved/unresolved relations
276
- unresolved = 0
277
- resolved = 0
278
- if result.relations:
279
- unresolved = sum(1 for r in result.relations if not r.to_id)
280
- resolved = len(result.relations) - unresolved
281
-
282
- summary.append("\\n## Relations")
283
- summary.append(f"- Resolved: {resolved}")
284
- if unresolved:
285
- summary.append(f"- Unresolved: {unresolved}")
286
-
287
- logger.info(
288
- "MCP tool response",
289
- tool="edit_note",
290
- operation=operation,
291
- permalink=result.permalink,
292
- observations_count=len(result.observations),
293
- relations_count=len(result.relations),
294
- status_code=response.status_code,
295
- )
296
-
297
- return "\n".join(summary)
298
-
299
- except Exception as e:
300
- logger.error(f"Error editing note: {e}")
301
- return _format_error_response(
302
- str(e), operation, identifier, find_text, expected_replacements
303
- )
217
+ async with get_client() as client:
218
+ active_project = await get_active_project(client, project, context)
219
+ project_url = active_project.project_url
220
+
221
+ logger.info("MCP tool call", tool="edit_note", identifier=identifier, operation=operation)
222
+
223
+ # Validate operation
224
+ valid_operations = ["append", "prepend", "find_replace", "replace_section"]
225
+ if operation not in valid_operations:
226
+ raise ValueError(
227
+ f"Invalid operation '{operation}'. Must be one of: {', '.join(valid_operations)}"
228
+ )
229
+
230
+ # Validate required parameters for specific operations
231
+ if operation == "find_replace" and not find_text:
232
+ raise ValueError("find_text parameter is required for find_replace operation")
233
+ if operation == "replace_section" and not section:
234
+ raise ValueError("section parameter is required for replace_section operation")
235
+
236
+ # Use the PATCH endpoint to edit the entity
237
+ try:
238
+ # Prepare the edit request data
239
+ edit_data = {
240
+ "operation": operation,
241
+ "content": content,
242
+ }
243
+
244
+ # Add optional parameters
245
+ if section:
246
+ edit_data["section"] = section
247
+ if find_text:
248
+ edit_data["find_text"] = find_text
249
+ if expected_replacements != 1: # Only send if different from default
250
+ edit_data["expected_replacements"] = str(expected_replacements)
251
+
252
+ # Call the PATCH endpoint
253
+ url = f"{project_url}/knowledge/entities/{identifier}"
254
+ response = await call_patch(client, url, json=edit_data)
255
+ result = EntityResponse.model_validate(response.json())
256
+
257
+ # Format summary
258
+ summary = [
259
+ f"# Edited note ({operation})",
260
+ f"project: {active_project.name}",
261
+ f"file_path: {result.file_path}",
262
+ f"permalink: {result.permalink}",
263
+ f"checksum: {result.checksum[:8] if result.checksum else 'unknown'}",
264
+ ]
265
+
266
+ # Add operation-specific details
267
+ if operation == "append":
268
+ lines_added = len(content.split("\n"))
269
+ summary.append(f"operation: Added {lines_added} lines to end of note")
270
+ elif operation == "prepend":
271
+ lines_added = len(content.split("\n"))
272
+ summary.append(f"operation: Added {lines_added} lines to beginning of note")
273
+ elif operation == "find_replace":
274
+ # For find_replace, we can't easily count replacements from here
275
+ # since we don't have the original content, but the server handled it
276
+ summary.append("operation: Find and replace operation completed")
277
+ elif operation == "replace_section":
278
+ summary.append(f"operation: Replaced content under section '{section}'")
279
+
280
+ # Count observations by category (reuse logic from write_note)
281
+ categories = {}
282
+ if result.observations:
283
+ for obs in result.observations:
284
+ categories[obs.category] = categories.get(obs.category, 0) + 1
285
+
286
+ summary.append("\\n## Observations")
287
+ for category, count in sorted(categories.items()):
288
+ summary.append(f"- {category}: {count}")
289
+
290
+ # Count resolved/unresolved relations
291
+ unresolved = 0
292
+ resolved = 0
293
+ if result.relations:
294
+ unresolved = sum(1 for r in result.relations if not r.to_id)
295
+ resolved = len(result.relations) - unresolved
296
+
297
+ summary.append("\\n## Relations")
298
+ summary.append(f"- Resolved: {resolved}")
299
+ if unresolved:
300
+ summary.append(f"- Unresolved: {unresolved}")
301
+
302
+ logger.info(
303
+ "MCP tool response",
304
+ tool="edit_note",
305
+ operation=operation,
306
+ project=active_project.name,
307
+ permalink=result.permalink,
308
+ observations_count=len(result.observations),
309
+ relations_count=len(result.relations),
310
+ status_code=response.status_code,
311
+ )
312
+
313
+ result = "\n".join(summary)
314
+ return add_project_metadata(result, active_project.name)
315
+
316
+ except Exception as e:
317
+ logger.error(f"Error editing note: {e}")
318
+ return _format_error_response(
319
+ str(e), operation, identifier, find_text, expected_replacements, active_project.name
320
+ )