basic-memory 0.13.0b4__py3-none-any.whl → 0.13.0b6__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.
- basic_memory/__init__.py +2 -7
- basic_memory/api/routers/knowledge_router.py +13 -0
- basic_memory/api/routers/memory_router.py +3 -4
- basic_memory/api/routers/project_router.py +6 -5
- basic_memory/api/routers/prompt_router.py +2 -2
- basic_memory/cli/commands/project.py +3 -3
- basic_memory/cli/commands/status.py +1 -1
- basic_memory/cli/commands/sync.py +1 -1
- basic_memory/cli/commands/tool.py +6 -6
- basic_memory/mcp/prompts/__init__.py +2 -0
- basic_memory/mcp/prompts/recent_activity.py +1 -1
- basic_memory/mcp/prompts/sync_status.py +116 -0
- basic_memory/mcp/server.py +6 -6
- basic_memory/mcp/tools/__init__.py +4 -0
- basic_memory/mcp/tools/build_context.py +32 -7
- basic_memory/mcp/tools/canvas.py +2 -1
- basic_memory/mcp/tools/delete_note.py +159 -4
- basic_memory/mcp/tools/edit_note.py +17 -11
- basic_memory/mcp/tools/move_note.py +252 -40
- basic_memory/mcp/tools/project_management.py +35 -3
- basic_memory/mcp/tools/read_note.py +11 -4
- basic_memory/mcp/tools/search.py +180 -8
- basic_memory/mcp/tools/sync_status.py +254 -0
- basic_memory/mcp/tools/utils.py +47 -0
- basic_memory/mcp/tools/view_note.py +66 -0
- basic_memory/mcp/tools/write_note.py +13 -2
- basic_memory/repository/search_repository.py +116 -38
- basic_memory/schemas/base.py +33 -5
- basic_memory/schemas/memory.py +58 -1
- basic_memory/services/entity_service.py +18 -5
- basic_memory/services/initialization.py +32 -5
- basic_memory/services/link_resolver.py +20 -5
- basic_memory/services/migration_service.py +168 -0
- basic_memory/services/project_service.py +121 -50
- basic_memory/services/sync_status_service.py +181 -0
- basic_memory/sync/sync_service.py +91 -13
- {basic_memory-0.13.0b4.dist-info → basic_memory-0.13.0b6.dist-info}/METADATA +2 -2
- {basic_memory-0.13.0b4.dist-info → basic_memory-0.13.0b6.dist-info}/RECORD +41 -36
- {basic_memory-0.13.0b4.dist-info → basic_memory-0.13.0b6.dist-info}/WHEEL +0 -0
- {basic_memory-0.13.0b4.dist-info → basic_memory-0.13.0b6.dist-info}/entry_points.txt +0 -0
- {basic_memory-0.13.0b4.dist-info → basic_memory-0.13.0b6.dist-info}/licenses/LICENSE +0 -0
basic_memory/mcp/tools/search.py
CHANGED
|
@@ -1,5 +1,6 @@
|
|
|
1
1
|
"""Search tools for Basic Memory MCP server."""
|
|
2
2
|
|
|
3
|
+
from textwrap import dedent
|
|
3
4
|
from typing import List, Optional
|
|
4
5
|
|
|
5
6
|
from loguru import logger
|
|
@@ -11,6 +12,162 @@ from basic_memory.mcp.project_session import get_active_project
|
|
|
11
12
|
from basic_memory.schemas.search import SearchItemType, SearchQuery, SearchResponse
|
|
12
13
|
|
|
13
14
|
|
|
15
|
+
def _format_search_error_response(error_message: str, query: str, search_type: str = "text") -> str:
|
|
16
|
+
"""Format helpful error responses for search failures that guide users to successful searches."""
|
|
17
|
+
|
|
18
|
+
# FTS5 syntax errors
|
|
19
|
+
if "syntax error" in error_message.lower() or "fts5" in error_message.lower():
|
|
20
|
+
clean_query = (
|
|
21
|
+
query.replace('"', "")
|
|
22
|
+
.replace("(", "")
|
|
23
|
+
.replace(")", "")
|
|
24
|
+
.replace("+", "")
|
|
25
|
+
.replace("*", "")
|
|
26
|
+
)
|
|
27
|
+
return dedent(f"""
|
|
28
|
+
# Search Failed - Invalid Syntax
|
|
29
|
+
|
|
30
|
+
The search query '{query}' contains invalid syntax that the search engine cannot process.
|
|
31
|
+
|
|
32
|
+
## Common syntax issues:
|
|
33
|
+
1. **Special characters**: Characters like `+`, `*`, `"`, `(`, `)` have special meaning in search
|
|
34
|
+
2. **Unmatched quotes**: Make sure quotes are properly paired
|
|
35
|
+
3. **Invalid operators**: Check AND, OR, NOT operators are used correctly
|
|
36
|
+
|
|
37
|
+
## How to fix:
|
|
38
|
+
1. **Simplify your search**: Try using simple words instead: `{clean_query}`
|
|
39
|
+
2. **Remove special characters**: Use alphanumeric characters and spaces
|
|
40
|
+
3. **Use basic boolean operators**: `word1 AND word2`, `word1 OR word2`, `word1 NOT word2`
|
|
41
|
+
|
|
42
|
+
## Examples of valid searches:
|
|
43
|
+
- Simple text: `project planning`
|
|
44
|
+
- Boolean AND: `project AND planning`
|
|
45
|
+
- Boolean OR: `meeting OR discussion`
|
|
46
|
+
- Boolean NOT: `project NOT archived`
|
|
47
|
+
- Grouped: `(project OR planning) AND notes`
|
|
48
|
+
|
|
49
|
+
## Try again with:
|
|
50
|
+
```
|
|
51
|
+
search_notes("INSERT_CLEAN_QUERY_HERE")
|
|
52
|
+
```
|
|
53
|
+
|
|
54
|
+
Replace INSERT_CLEAN_QUERY_HERE with your simplified search terms.
|
|
55
|
+
""").strip()
|
|
56
|
+
|
|
57
|
+
# Project not found errors (check before general "not found")
|
|
58
|
+
if "project not found" in error_message.lower():
|
|
59
|
+
return dedent(f"""
|
|
60
|
+
# Search Failed - Project Not Found
|
|
61
|
+
|
|
62
|
+
The current project is not accessible or doesn't exist: {error_message}
|
|
63
|
+
|
|
64
|
+
## How to resolve:
|
|
65
|
+
1. **Check available projects**: `list_projects()`
|
|
66
|
+
2. **Switch to valid project**: `switch_project("valid-project-name")`
|
|
67
|
+
3. **Verify project setup**: Ensure your project is properly configured
|
|
68
|
+
|
|
69
|
+
## Current session info:
|
|
70
|
+
- Check current project: `get_current_project()`
|
|
71
|
+
- See available projects: `list_projects()`
|
|
72
|
+
""").strip()
|
|
73
|
+
|
|
74
|
+
# No results found
|
|
75
|
+
if "no results" in error_message.lower() or "not found" in error_message.lower():
|
|
76
|
+
simplified_query = (
|
|
77
|
+
" ".join(query.split()[:2])
|
|
78
|
+
if len(query.split()) > 2
|
|
79
|
+
else query.split()[0]
|
|
80
|
+
if query.split()
|
|
81
|
+
else "notes"
|
|
82
|
+
)
|
|
83
|
+
return dedent(f"""
|
|
84
|
+
# Search Complete - No Results Found
|
|
85
|
+
|
|
86
|
+
No content found matching '{query}' in the current project.
|
|
87
|
+
|
|
88
|
+
## Suggestions to try:
|
|
89
|
+
1. **Broaden your search**: Try fewer or more general terms
|
|
90
|
+
- Instead of: `{query}`
|
|
91
|
+
- Try: `{simplified_query}`
|
|
92
|
+
|
|
93
|
+
2. **Check spelling**: Verify terms are spelled correctly
|
|
94
|
+
3. **Try different search types**:
|
|
95
|
+
- Text search: `search_notes("{query}", search_type="text")`
|
|
96
|
+
- Title search: `search_notes("{query}", search_type="title")`
|
|
97
|
+
- Permalink search: `search_notes("{query}", search_type="permalink")`
|
|
98
|
+
|
|
99
|
+
4. **Use boolean operators**:
|
|
100
|
+
- Try OR search for broader results
|
|
101
|
+
|
|
102
|
+
## Check what content exists:
|
|
103
|
+
- Recent activity: `recent_activity(timeframe="7d")`
|
|
104
|
+
- List files: `list_directory("/")`
|
|
105
|
+
- Browse by folder: `list_directory("/notes")` or `list_directory("/docs")`
|
|
106
|
+
""").strip()
|
|
107
|
+
|
|
108
|
+
# Server/API errors
|
|
109
|
+
if "server error" in error_message.lower() or "internal" in error_message.lower():
|
|
110
|
+
return dedent(f"""
|
|
111
|
+
# Search Failed - Server Error
|
|
112
|
+
|
|
113
|
+
The search service encountered an error while processing '{query}': {error_message}
|
|
114
|
+
|
|
115
|
+
## Immediate steps:
|
|
116
|
+
1. **Try again**: The error might be temporary
|
|
117
|
+
2. **Simplify the query**: Use simpler search terms
|
|
118
|
+
3. **Check project status**: Ensure your project is properly synced
|
|
119
|
+
|
|
120
|
+
## Alternative approaches:
|
|
121
|
+
- Browse files directly: `list_directory("/")`
|
|
122
|
+
- Check recent activity: `recent_activity(timeframe="7d")`
|
|
123
|
+
- Try a different search type: `search_notes("{query}", search_type="title")`
|
|
124
|
+
|
|
125
|
+
## If the problem persists:
|
|
126
|
+
The search index might need to be rebuilt. Send a message to support@basicmachines.co or check the project sync status.
|
|
127
|
+
""").strip()
|
|
128
|
+
|
|
129
|
+
# Permission/access errors
|
|
130
|
+
if (
|
|
131
|
+
"permission" in error_message.lower()
|
|
132
|
+
or "access" in error_message.lower()
|
|
133
|
+
or "forbidden" in error_message.lower()
|
|
134
|
+
):
|
|
135
|
+
return f"""# Search Failed - Access Error
|
|
136
|
+
|
|
137
|
+
You don't have permission to search in the current project: {error_message}
|
|
138
|
+
|
|
139
|
+
## How to resolve:
|
|
140
|
+
1. **Check your project access**: Verify you have read permissions for this project
|
|
141
|
+
2. **Switch projects**: Try searching in a different project you have access to
|
|
142
|
+
3. **Check authentication**: You might need to re-authenticate
|
|
143
|
+
|
|
144
|
+
## Alternative actions:
|
|
145
|
+
- List available projects: `list_projects()`
|
|
146
|
+
- Switch to accessible project: `switch_project("project-name")`
|
|
147
|
+
- Check current project: `get_current_project()`"""
|
|
148
|
+
|
|
149
|
+
# Generic fallback
|
|
150
|
+
return f"""# Search Failed
|
|
151
|
+
|
|
152
|
+
Error searching for '{query}': {error_message}
|
|
153
|
+
|
|
154
|
+
## General troubleshooting:
|
|
155
|
+
1. **Check your query**: Ensure it uses valid search syntax
|
|
156
|
+
2. **Try simpler terms**: Use basic words without special characters
|
|
157
|
+
3. **Verify project access**: Make sure you can access the current project
|
|
158
|
+
4. **Check recent activity**: `recent_activity(timeframe="7d")` to see if content exists
|
|
159
|
+
|
|
160
|
+
## Alternative approaches:
|
|
161
|
+
- Browse files: `list_directory("/")`
|
|
162
|
+
- Try different search type: `search_notes("{query}", search_type="title")`
|
|
163
|
+
- Search with filters: `search_notes("{query}", types=["entity"])`
|
|
164
|
+
|
|
165
|
+
## Need help?
|
|
166
|
+
- View recent changes: `recent_activity()`
|
|
167
|
+
- List projects: `list_projects()`
|
|
168
|
+
- Check current project: `get_current_project()`"""
|
|
169
|
+
|
|
170
|
+
|
|
14
171
|
@mcp.tool(
|
|
15
172
|
description="Search across all content in the knowledge base.",
|
|
16
173
|
)
|
|
@@ -23,7 +180,7 @@ async def search_notes(
|
|
|
23
180
|
entity_types: Optional[List[str]] = None,
|
|
24
181
|
after_date: Optional[str] = None,
|
|
25
182
|
project: Optional[str] = None,
|
|
26
|
-
) -> SearchResponse:
|
|
183
|
+
) -> SearchResponse | str:
|
|
27
184
|
"""Search across all content in the knowledge base.
|
|
28
185
|
|
|
29
186
|
This tool searches the knowledge base using full-text search, pattern matching,
|
|
@@ -113,10 +270,25 @@ async def search_notes(
|
|
|
113
270
|
project_url = active_project.project_url
|
|
114
271
|
|
|
115
272
|
logger.info(f"Searching for {search_query}")
|
|
116
|
-
|
|
117
|
-
|
|
118
|
-
|
|
119
|
-
|
|
120
|
-
|
|
121
|
-
|
|
122
|
-
|
|
273
|
+
|
|
274
|
+
try:
|
|
275
|
+
response = await call_post(
|
|
276
|
+
client,
|
|
277
|
+
f"{project_url}/search/",
|
|
278
|
+
json=search_query.model_dump(),
|
|
279
|
+
params={"page": page, "page_size": page_size},
|
|
280
|
+
)
|
|
281
|
+
result = SearchResponse.model_validate(response.json())
|
|
282
|
+
|
|
283
|
+
# Check if we got no results and provide helpful guidance
|
|
284
|
+
if not result.results:
|
|
285
|
+
logger.info(f"Search returned no results for query: {query}")
|
|
286
|
+
# Don't treat this as an error, but the user might want guidance
|
|
287
|
+
# We return the empty result as normal - the user can decide if they need help
|
|
288
|
+
|
|
289
|
+
return result
|
|
290
|
+
|
|
291
|
+
except Exception as e:
|
|
292
|
+
logger.error(f"Search failed for query '{query}': {e}")
|
|
293
|
+
# Return formatted error message as string for better user experience
|
|
294
|
+
return _format_search_error_response(str(e), query, search_type)
|
|
@@ -0,0 +1,254 @@
|
|
|
1
|
+
"""Sync status tool for Basic Memory MCP server."""
|
|
2
|
+
|
|
3
|
+
from typing import Optional
|
|
4
|
+
|
|
5
|
+
from loguru import logger
|
|
6
|
+
|
|
7
|
+
from basic_memory.mcp.server import mcp
|
|
8
|
+
from basic_memory.mcp.project_session import get_active_project
|
|
9
|
+
|
|
10
|
+
|
|
11
|
+
def _get_all_projects_status() -> list[str]:
|
|
12
|
+
"""Get status lines for all configured projects."""
|
|
13
|
+
status_lines = []
|
|
14
|
+
|
|
15
|
+
try:
|
|
16
|
+
from basic_memory.config import app_config
|
|
17
|
+
from basic_memory.services.sync_status_service import sync_status_tracker
|
|
18
|
+
|
|
19
|
+
if app_config.projects:
|
|
20
|
+
status_lines.extend(["", "---", "", "**All Projects Status:**"])
|
|
21
|
+
|
|
22
|
+
for project_name, project_path in app_config.projects.items():
|
|
23
|
+
# Check if this project has sync status
|
|
24
|
+
project_sync_status = sync_status_tracker.get_project_status(project_name)
|
|
25
|
+
|
|
26
|
+
if project_sync_status:
|
|
27
|
+
# Project has tracked sync activity
|
|
28
|
+
if project_sync_status.status.value == "watching":
|
|
29
|
+
# Project is actively watching for changes (steady state)
|
|
30
|
+
status_icon = "👁️"
|
|
31
|
+
status_text = "Watching for changes"
|
|
32
|
+
elif project_sync_status.status.value == "completed":
|
|
33
|
+
# Sync completed but not yet watching - transitional state
|
|
34
|
+
status_icon = "✅"
|
|
35
|
+
status_text = "Sync completed"
|
|
36
|
+
elif project_sync_status.status.value in ["scanning", "syncing"]:
|
|
37
|
+
status_icon = "🔄"
|
|
38
|
+
status_text = "Sync in progress"
|
|
39
|
+
if project_sync_status.files_total > 0:
|
|
40
|
+
progress_pct = (
|
|
41
|
+
project_sync_status.files_processed
|
|
42
|
+
/ project_sync_status.files_total
|
|
43
|
+
) * 100
|
|
44
|
+
status_text += f" ({project_sync_status.files_processed}/{project_sync_status.files_total}, {progress_pct:.0f}%)"
|
|
45
|
+
elif project_sync_status.status.value == "failed":
|
|
46
|
+
status_icon = "❌"
|
|
47
|
+
status_text = f"Sync error: {project_sync_status.error or 'Unknown error'}"
|
|
48
|
+
else:
|
|
49
|
+
status_icon = "⏸️"
|
|
50
|
+
status_text = project_sync_status.status.value.title()
|
|
51
|
+
else:
|
|
52
|
+
# Project has no tracked sync activity - will be synced automatically
|
|
53
|
+
status_icon = "⏳"
|
|
54
|
+
status_text = "Pending sync"
|
|
55
|
+
|
|
56
|
+
status_lines.append(f"- {status_icon} **{project_name}**: {status_text}")
|
|
57
|
+
|
|
58
|
+
except Exception as e:
|
|
59
|
+
logger.debug(f"Could not get project config for comprehensive status: {e}")
|
|
60
|
+
|
|
61
|
+
return status_lines
|
|
62
|
+
|
|
63
|
+
|
|
64
|
+
@mcp.tool(
|
|
65
|
+
description="""Check the status of file synchronization and background operations.
|
|
66
|
+
|
|
67
|
+
Use this tool to:
|
|
68
|
+
- Check if file sync is in progress or completed
|
|
69
|
+
- Get detailed sync progress information
|
|
70
|
+
- Understand if your files are fully indexed
|
|
71
|
+
- Get specific error details if sync operations failed
|
|
72
|
+
- Monitor initial project setup and legacy migration
|
|
73
|
+
|
|
74
|
+
This covers all sync operations including:
|
|
75
|
+
- Initial project setup and file indexing
|
|
76
|
+
- Legacy project migration to unified database
|
|
77
|
+
- Ongoing file monitoring and updates
|
|
78
|
+
- Background processing of knowledge graphs
|
|
79
|
+
""",
|
|
80
|
+
)
|
|
81
|
+
async def sync_status(project: Optional[str] = None) -> str:
|
|
82
|
+
"""Get current sync status and system readiness information.
|
|
83
|
+
|
|
84
|
+
This tool provides detailed information about any ongoing or completed
|
|
85
|
+
sync operations, helping users understand when their files are ready.
|
|
86
|
+
|
|
87
|
+
Args:
|
|
88
|
+
project: Optional project name to get project-specific context
|
|
89
|
+
|
|
90
|
+
Returns:
|
|
91
|
+
Formatted sync status with progress, readiness, and guidance
|
|
92
|
+
"""
|
|
93
|
+
logger.info("MCP tool call tool=sync_status")
|
|
94
|
+
|
|
95
|
+
status_lines = []
|
|
96
|
+
|
|
97
|
+
try:
|
|
98
|
+
from basic_memory.services.sync_status_service import sync_status_tracker
|
|
99
|
+
|
|
100
|
+
# Get overall summary
|
|
101
|
+
summary = sync_status_tracker.get_summary()
|
|
102
|
+
is_ready = sync_status_tracker.is_ready
|
|
103
|
+
|
|
104
|
+
# Header
|
|
105
|
+
status_lines.extend(
|
|
106
|
+
[
|
|
107
|
+
"# Basic Memory Sync Status",
|
|
108
|
+
"",
|
|
109
|
+
f"**Current Status**: {summary}",
|
|
110
|
+
f"**System Ready**: {'✅ Yes' if is_ready else '🔄 Processing'}",
|
|
111
|
+
"",
|
|
112
|
+
]
|
|
113
|
+
)
|
|
114
|
+
|
|
115
|
+
if is_ready:
|
|
116
|
+
status_lines.extend(
|
|
117
|
+
[
|
|
118
|
+
"✅ **All sync operations completed**",
|
|
119
|
+
"",
|
|
120
|
+
"- File indexing is complete",
|
|
121
|
+
"- Knowledge graphs are up to date",
|
|
122
|
+
"- All Basic Memory tools are fully operational",
|
|
123
|
+
"",
|
|
124
|
+
"Your knowledge base is ready for use!",
|
|
125
|
+
]
|
|
126
|
+
)
|
|
127
|
+
|
|
128
|
+
# Show all projects status even when ready
|
|
129
|
+
status_lines.extend(_get_all_projects_status())
|
|
130
|
+
else:
|
|
131
|
+
# System is still processing - show both active and all projects
|
|
132
|
+
all_sync_projects = sync_status_tracker.get_all_projects()
|
|
133
|
+
|
|
134
|
+
active_projects = [
|
|
135
|
+
p for p in all_sync_projects.values() if p.status.value in ["scanning", "syncing"]
|
|
136
|
+
]
|
|
137
|
+
failed_projects = [p for p in all_sync_projects.values() if p.status.value == "failed"]
|
|
138
|
+
|
|
139
|
+
if active_projects:
|
|
140
|
+
status_lines.extend(
|
|
141
|
+
[
|
|
142
|
+
"🔄 **File synchronization in progress**",
|
|
143
|
+
"",
|
|
144
|
+
"Basic Memory is automatically processing all configured projects and building knowledge graphs.",
|
|
145
|
+
"This typically takes 1-3 minutes depending on the amount of content.",
|
|
146
|
+
"",
|
|
147
|
+
"**Currently Processing:**",
|
|
148
|
+
]
|
|
149
|
+
)
|
|
150
|
+
|
|
151
|
+
for project_status in active_projects:
|
|
152
|
+
progress = ""
|
|
153
|
+
if project_status.files_total > 0:
|
|
154
|
+
progress_pct = (
|
|
155
|
+
project_status.files_processed / project_status.files_total
|
|
156
|
+
) * 100
|
|
157
|
+
progress = f" ({project_status.files_processed}/{project_status.files_total}, {progress_pct:.0f}%)"
|
|
158
|
+
|
|
159
|
+
status_lines.append(
|
|
160
|
+
f"- **{project_status.project_name}**: {project_status.message}{progress}"
|
|
161
|
+
)
|
|
162
|
+
|
|
163
|
+
status_lines.extend(
|
|
164
|
+
[
|
|
165
|
+
"",
|
|
166
|
+
"**What's happening:**",
|
|
167
|
+
"- Scanning and indexing markdown files",
|
|
168
|
+
"- Building entity and relationship graphs",
|
|
169
|
+
"- Setting up full-text search indexes",
|
|
170
|
+
"- Processing file changes and updates",
|
|
171
|
+
"",
|
|
172
|
+
"**What you can do:**",
|
|
173
|
+
"- Wait for automatic processing to complete - no action needed",
|
|
174
|
+
"- Use this tool again to check progress",
|
|
175
|
+
"- Simple operations may work already",
|
|
176
|
+
"- All projects will be available once sync finishes",
|
|
177
|
+
]
|
|
178
|
+
)
|
|
179
|
+
|
|
180
|
+
# Handle failed projects (independent of active projects)
|
|
181
|
+
if failed_projects:
|
|
182
|
+
status_lines.extend(["", "❌ **Some projects failed to sync:**", ""])
|
|
183
|
+
|
|
184
|
+
for project_status in failed_projects:
|
|
185
|
+
status_lines.append(
|
|
186
|
+
f"- **{project_status.project_name}**: {project_status.error or 'Unknown error'}"
|
|
187
|
+
)
|
|
188
|
+
|
|
189
|
+
status_lines.extend(
|
|
190
|
+
[
|
|
191
|
+
"",
|
|
192
|
+
"**Next steps:**",
|
|
193
|
+
"1. Check the logs for detailed error information",
|
|
194
|
+
"2. Ensure file permissions allow read/write access",
|
|
195
|
+
"3. Try restarting the MCP server",
|
|
196
|
+
"4. If issues persist, consider filing a support issue",
|
|
197
|
+
]
|
|
198
|
+
)
|
|
199
|
+
elif not active_projects:
|
|
200
|
+
# No active or failed projects - must be pending
|
|
201
|
+
status_lines.extend(
|
|
202
|
+
[
|
|
203
|
+
"⏳ **Sync operations pending**",
|
|
204
|
+
"",
|
|
205
|
+
"File synchronization has been queued but hasn't started yet.",
|
|
206
|
+
"This usually resolves automatically within a few seconds.",
|
|
207
|
+
]
|
|
208
|
+
)
|
|
209
|
+
|
|
210
|
+
# Add comprehensive project status for all configured projects
|
|
211
|
+
all_projects_status = _get_all_projects_status()
|
|
212
|
+
if all_projects_status:
|
|
213
|
+
status_lines.extend(all_projects_status)
|
|
214
|
+
|
|
215
|
+
# Add explanation about automatic syncing if there are unsynced projects
|
|
216
|
+
unsynced_count = sum(1 for line in all_projects_status if "⏳" in line)
|
|
217
|
+
if unsynced_count > 0 and not is_ready:
|
|
218
|
+
status_lines.extend(
|
|
219
|
+
[
|
|
220
|
+
"",
|
|
221
|
+
"**Note**: All configured projects will be automatically synced during startup.",
|
|
222
|
+
"You don't need to manually switch projects - Basic Memory handles this for you.",
|
|
223
|
+
]
|
|
224
|
+
)
|
|
225
|
+
|
|
226
|
+
# Add project context if provided
|
|
227
|
+
if project:
|
|
228
|
+
try:
|
|
229
|
+
active_project = get_active_project(project)
|
|
230
|
+
status_lines.extend(
|
|
231
|
+
[
|
|
232
|
+
"",
|
|
233
|
+
"---",
|
|
234
|
+
"",
|
|
235
|
+
f"**Active Project**: {active_project.name}",
|
|
236
|
+
f"**Project Path**: {active_project.home}",
|
|
237
|
+
]
|
|
238
|
+
)
|
|
239
|
+
except Exception as e:
|
|
240
|
+
logger.debug(f"Could not get project info: {e}")
|
|
241
|
+
|
|
242
|
+
return "\n".join(status_lines)
|
|
243
|
+
|
|
244
|
+
except Exception as e:
|
|
245
|
+
return f"""# Sync Status - Error
|
|
246
|
+
|
|
247
|
+
❌ **Unable to check sync status**: {str(e)}
|
|
248
|
+
|
|
249
|
+
**Troubleshooting:**
|
|
250
|
+
- The system may still be starting up
|
|
251
|
+
- Try waiting a few seconds and checking again
|
|
252
|
+
- Check logs for detailed error information
|
|
253
|
+
- Consider restarting if the issue persists
|
|
254
|
+
"""
|
basic_memory/mcp/tools/utils.py
CHANGED
|
@@ -506,3 +506,50 @@ async def call_delete(
|
|
|
506
506
|
|
|
507
507
|
except HTTPStatusError as e:
|
|
508
508
|
raise ToolError(error_message) from e
|
|
509
|
+
|
|
510
|
+
|
|
511
|
+
def check_migration_status() -> Optional[str]:
|
|
512
|
+
"""Check if sync/migration is in progress and return status message if so.
|
|
513
|
+
|
|
514
|
+
Returns:
|
|
515
|
+
Status message if sync is in progress, None if system is ready
|
|
516
|
+
"""
|
|
517
|
+
try:
|
|
518
|
+
from basic_memory.services.sync_status_service import sync_status_tracker
|
|
519
|
+
|
|
520
|
+
if not sync_status_tracker.is_ready:
|
|
521
|
+
return sync_status_tracker.get_summary()
|
|
522
|
+
return None
|
|
523
|
+
except Exception:
|
|
524
|
+
# If there's any error checking sync status, assume ready
|
|
525
|
+
return None
|
|
526
|
+
|
|
527
|
+
|
|
528
|
+
async def wait_for_migration_or_return_status(timeout: float = 5.0) -> Optional[str]:
|
|
529
|
+
"""Wait briefly for sync/migration to complete, or return status message.
|
|
530
|
+
|
|
531
|
+
Args:
|
|
532
|
+
timeout: Maximum time to wait for sync completion
|
|
533
|
+
|
|
534
|
+
Returns:
|
|
535
|
+
Status message if sync is still in progress, None if ready
|
|
536
|
+
"""
|
|
537
|
+
try:
|
|
538
|
+
from basic_memory.services.sync_status_service import sync_status_tracker
|
|
539
|
+
import asyncio
|
|
540
|
+
|
|
541
|
+
if sync_status_tracker.is_ready:
|
|
542
|
+
return None
|
|
543
|
+
|
|
544
|
+
# Wait briefly for sync to complete
|
|
545
|
+
start_time = asyncio.get_event_loop().time()
|
|
546
|
+
while (asyncio.get_event_loop().time() - start_time) < timeout:
|
|
547
|
+
if sync_status_tracker.is_ready:
|
|
548
|
+
return None
|
|
549
|
+
await asyncio.sleep(0.1) # Check every 100ms
|
|
550
|
+
|
|
551
|
+
# Still not ready after timeout
|
|
552
|
+
return sync_status_tracker.get_summary()
|
|
553
|
+
except Exception: # pragma: no cover
|
|
554
|
+
# If there's any error, assume ready
|
|
555
|
+
return None
|
|
@@ -0,0 +1,66 @@
|
|
|
1
|
+
"""View note tool for Basic Memory MCP server."""
|
|
2
|
+
|
|
3
|
+
from textwrap import dedent
|
|
4
|
+
from typing import Optional
|
|
5
|
+
|
|
6
|
+
from loguru import logger
|
|
7
|
+
|
|
8
|
+
from basic_memory.mcp.server import mcp
|
|
9
|
+
from basic_memory.mcp.tools.read_note import read_note
|
|
10
|
+
|
|
11
|
+
|
|
12
|
+
@mcp.tool(
|
|
13
|
+
description="View a note as a formatted artifact for better readability.",
|
|
14
|
+
)
|
|
15
|
+
async def view_note(
|
|
16
|
+
identifier: str, page: int = 1, page_size: int = 10, project: Optional[str] = None
|
|
17
|
+
) -> str:
|
|
18
|
+
"""View a markdown note as a formatted artifact.
|
|
19
|
+
|
|
20
|
+
This tool reads a note using the same logic as read_note but displays the content
|
|
21
|
+
as a markdown artifact for better viewing experience in Claude Desktop.
|
|
22
|
+
|
|
23
|
+
After calling this tool, create an artifact using the returned content to display
|
|
24
|
+
the note in a readable format. The tool returns the note content that should be
|
|
25
|
+
used to create a markdown artifact.
|
|
26
|
+
|
|
27
|
+
Args:
|
|
28
|
+
identifier: The title or permalink of the note to view
|
|
29
|
+
page: Page number for paginated results (default: 1)
|
|
30
|
+
page_size: Number of items per page (default: 10)
|
|
31
|
+
project: Optional project name to read from. If not provided, uses current active project.
|
|
32
|
+
|
|
33
|
+
Returns:
|
|
34
|
+
The note content as a markdown artifact with a confirmation message.
|
|
35
|
+
"""
|
|
36
|
+
|
|
37
|
+
logger.info(f"Viewing note: {identifier}")
|
|
38
|
+
|
|
39
|
+
# Call the existing read_note logic
|
|
40
|
+
content = await read_note.fn(identifier, page, page_size, project)
|
|
41
|
+
|
|
42
|
+
# Check if this is an error message (note not found)
|
|
43
|
+
if "# Note Not Found:" in content:
|
|
44
|
+
return content # Return error message directly instead of creating artifact
|
|
45
|
+
|
|
46
|
+
# Extract title from content if possible
|
|
47
|
+
title = identifier
|
|
48
|
+
lines = content.split("\n")
|
|
49
|
+
for line in lines:
|
|
50
|
+
if line.startswith("title:"):
|
|
51
|
+
# Extract title from frontmatter
|
|
52
|
+
title = line.split("title:", 1)[1].strip().strip('"').strip("'")
|
|
53
|
+
break
|
|
54
|
+
elif line.startswith("# "):
|
|
55
|
+
# Extract title from first heading
|
|
56
|
+
title = line[2:].strip()
|
|
57
|
+
break
|
|
58
|
+
|
|
59
|
+
# Return the artifact XML as part of the response
|
|
60
|
+
artifact = f'<artifact identifier="note-{hash(identifier) & 0x7FFFFFFF}" type="text/markdown" title="{title}">\n{content}\n</artifact>'
|
|
61
|
+
|
|
62
|
+
return dedent(f"""
|
|
63
|
+
<instructions>
|
|
64
|
+
Create an artifact using the returned artifact content to display the note in a readable format.
|
|
65
|
+
</instructions>
|
|
66
|
+
{artifact}\n\n✅ Note displayed as artifact: **{title}**""")
|
|
@@ -54,7 +54,8 @@ async def write_note(
|
|
|
54
54
|
Args:
|
|
55
55
|
title: The title of the note
|
|
56
56
|
content: Markdown content for the note, can include observations and relations
|
|
57
|
-
folder:
|
|
57
|
+
folder: Folder path relative to project root where the file should be saved.
|
|
58
|
+
Use forward slashes (/) as separators. Examples: "notes", "projects/2025", "research/ml"
|
|
58
59
|
tags: Tags to categorize the note. Can be a list of strings, a comma-separated string, or None.
|
|
59
60
|
Note: If passing from external MCP clients, use a string format (e.g. "tag1,tag2,tag3")
|
|
60
61
|
project: Optional project name to write to. If not provided, uses current active project.
|
|
@@ -69,6 +70,13 @@ async def write_note(
|
|
|
69
70
|
"""
|
|
70
71
|
logger.info(f"MCP tool call tool=write_note folder={folder}, title={title}, tags={tags}")
|
|
71
72
|
|
|
73
|
+
# Check migration status and wait briefly if needed
|
|
74
|
+
from basic_memory.mcp.tools.utils import wait_for_migration_or_return_status
|
|
75
|
+
|
|
76
|
+
migration_status = await wait_for_migration_or_return_status(timeout=5.0)
|
|
77
|
+
if migration_status: # pragma: no cover
|
|
78
|
+
return f"# System Status\n\n{migration_status}\n\nPlease wait for migration to complete before creating notes."
|
|
79
|
+
|
|
72
80
|
# Process tags using the helper function
|
|
73
81
|
tag_list = parse_tags(tags)
|
|
74
82
|
# Create the entity request
|
|
@@ -120,7 +128,10 @@ async def write_note(
|
|
|
120
128
|
summary.append(f"- Resolved: {resolved}")
|
|
121
129
|
if unresolved:
|
|
122
130
|
summary.append(f"- Unresolved: {unresolved}")
|
|
123
|
-
summary.append("\
|
|
131
|
+
summary.append("\nNote: Unresolved relations point to entities that don't exist yet.")
|
|
132
|
+
summary.append(
|
|
133
|
+
"They will be automatically resolved when target entities are created or during sync operations."
|
|
134
|
+
)
|
|
124
135
|
|
|
125
136
|
if tag_list:
|
|
126
137
|
summary.append(f"\n## Tags\n- {', '.join(tag_list)}")
|