basic-memory 0.7.0__py3-none-any.whl → 0.16.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 (150) hide show
  1. basic_memory/__init__.py +5 -1
  2. basic_memory/alembic/alembic.ini +119 -0
  3. basic_memory/alembic/env.py +27 -3
  4. basic_memory/alembic/migrations.py +4 -9
  5. basic_memory/alembic/versions/502b60eaa905_remove_required_from_entity_permalink.py +51 -0
  6. basic_memory/alembic/versions/5fe1ab1ccebe_add_projects_table.py +108 -0
  7. basic_memory/alembic/versions/647e7a75e2cd_project_constraint_fix.py +104 -0
  8. basic_memory/alembic/versions/9d9c1cb7d8f5_add_mtime_and_size_columns_to_entity_.py +49 -0
  9. basic_memory/alembic/versions/a1b2c3d4e5f6_fix_project_foreign_keys.py +49 -0
  10. basic_memory/alembic/versions/b3c3938bacdb_relation_to_name_unique_index.py +44 -0
  11. basic_memory/alembic/versions/cc7172b46608_update_search_index_schema.py +100 -0
  12. basic_memory/alembic/versions/e7e1f4367280_add_scan_watermark_tracking_to_project.py +37 -0
  13. basic_memory/api/app.py +64 -18
  14. basic_memory/api/routers/__init__.py +4 -1
  15. basic_memory/api/routers/directory_router.py +84 -0
  16. basic_memory/api/routers/importer_router.py +152 -0
  17. basic_memory/api/routers/knowledge_router.py +166 -21
  18. basic_memory/api/routers/management_router.py +80 -0
  19. basic_memory/api/routers/memory_router.py +9 -64
  20. basic_memory/api/routers/project_router.py +406 -0
  21. basic_memory/api/routers/prompt_router.py +260 -0
  22. basic_memory/api/routers/resource_router.py +119 -4
  23. basic_memory/api/routers/search_router.py +5 -5
  24. basic_memory/api/routers/utils.py +130 -0
  25. basic_memory/api/template_loader.py +292 -0
  26. basic_memory/cli/app.py +43 -9
  27. basic_memory/cli/auth.py +277 -0
  28. basic_memory/cli/commands/__init__.py +13 -2
  29. basic_memory/cli/commands/cloud/__init__.py +6 -0
  30. basic_memory/cli/commands/cloud/api_client.py +112 -0
  31. basic_memory/cli/commands/cloud/bisync_commands.py +110 -0
  32. basic_memory/cli/commands/cloud/cloud_utils.py +101 -0
  33. basic_memory/cli/commands/cloud/core_commands.py +195 -0
  34. basic_memory/cli/commands/cloud/rclone_commands.py +301 -0
  35. basic_memory/cli/commands/cloud/rclone_config.py +110 -0
  36. basic_memory/cli/commands/cloud/rclone_installer.py +249 -0
  37. basic_memory/cli/commands/cloud/upload.py +233 -0
  38. basic_memory/cli/commands/cloud/upload_command.py +124 -0
  39. basic_memory/cli/commands/command_utils.py +51 -0
  40. basic_memory/cli/commands/db.py +28 -12
  41. basic_memory/cli/commands/import_chatgpt.py +40 -220
  42. basic_memory/cli/commands/import_claude_conversations.py +41 -168
  43. basic_memory/cli/commands/import_claude_projects.py +46 -157
  44. basic_memory/cli/commands/import_memory_json.py +48 -108
  45. basic_memory/cli/commands/mcp.py +84 -10
  46. basic_memory/cli/commands/project.py +876 -0
  47. basic_memory/cli/commands/status.py +50 -33
  48. basic_memory/cli/commands/tool.py +341 -0
  49. basic_memory/cli/main.py +8 -7
  50. basic_memory/config.py +477 -23
  51. basic_memory/db.py +168 -17
  52. basic_memory/deps.py +251 -25
  53. basic_memory/file_utils.py +113 -58
  54. basic_memory/ignore_utils.py +297 -0
  55. basic_memory/importers/__init__.py +27 -0
  56. basic_memory/importers/base.py +79 -0
  57. basic_memory/importers/chatgpt_importer.py +232 -0
  58. basic_memory/importers/claude_conversations_importer.py +177 -0
  59. basic_memory/importers/claude_projects_importer.py +148 -0
  60. basic_memory/importers/memory_json_importer.py +108 -0
  61. basic_memory/importers/utils.py +58 -0
  62. basic_memory/markdown/entity_parser.py +143 -23
  63. basic_memory/markdown/markdown_processor.py +3 -3
  64. basic_memory/markdown/plugins.py +39 -21
  65. basic_memory/markdown/schemas.py +1 -1
  66. basic_memory/markdown/utils.py +28 -13
  67. basic_memory/mcp/async_client.py +134 -4
  68. basic_memory/mcp/project_context.py +141 -0
  69. basic_memory/mcp/prompts/__init__.py +19 -0
  70. basic_memory/mcp/prompts/ai_assistant_guide.py +70 -0
  71. basic_memory/mcp/prompts/continue_conversation.py +62 -0
  72. basic_memory/mcp/prompts/recent_activity.py +188 -0
  73. basic_memory/mcp/prompts/search.py +57 -0
  74. basic_memory/mcp/prompts/utils.py +162 -0
  75. basic_memory/mcp/resources/ai_assistant_guide.md +283 -0
  76. basic_memory/mcp/resources/project_info.py +71 -0
  77. basic_memory/mcp/server.py +7 -13
  78. basic_memory/mcp/tools/__init__.py +33 -21
  79. basic_memory/mcp/tools/build_context.py +120 -0
  80. basic_memory/mcp/tools/canvas.py +130 -0
  81. basic_memory/mcp/tools/chatgpt_tools.py +187 -0
  82. basic_memory/mcp/tools/delete_note.py +225 -0
  83. basic_memory/mcp/tools/edit_note.py +320 -0
  84. basic_memory/mcp/tools/list_directory.py +167 -0
  85. basic_memory/mcp/tools/move_note.py +545 -0
  86. basic_memory/mcp/tools/project_management.py +200 -0
  87. basic_memory/mcp/tools/read_content.py +271 -0
  88. basic_memory/mcp/tools/read_note.py +255 -0
  89. basic_memory/mcp/tools/recent_activity.py +534 -0
  90. basic_memory/mcp/tools/search.py +369 -23
  91. basic_memory/mcp/tools/utils.py +374 -16
  92. basic_memory/mcp/tools/view_note.py +77 -0
  93. basic_memory/mcp/tools/write_note.py +207 -0
  94. basic_memory/models/__init__.py +3 -2
  95. basic_memory/models/knowledge.py +67 -15
  96. basic_memory/models/project.py +87 -0
  97. basic_memory/models/search.py +10 -6
  98. basic_memory/repository/__init__.py +2 -0
  99. basic_memory/repository/entity_repository.py +229 -7
  100. basic_memory/repository/observation_repository.py +35 -3
  101. basic_memory/repository/project_info_repository.py +10 -0
  102. basic_memory/repository/project_repository.py +103 -0
  103. basic_memory/repository/relation_repository.py +21 -2
  104. basic_memory/repository/repository.py +147 -29
  105. basic_memory/repository/search_repository.py +411 -62
  106. basic_memory/schemas/__init__.py +22 -9
  107. basic_memory/schemas/base.py +97 -8
  108. basic_memory/schemas/cloud.py +50 -0
  109. basic_memory/schemas/directory.py +30 -0
  110. basic_memory/schemas/importer.py +35 -0
  111. basic_memory/schemas/memory.py +187 -25
  112. basic_memory/schemas/project_info.py +211 -0
  113. basic_memory/schemas/prompt.py +90 -0
  114. basic_memory/schemas/request.py +56 -2
  115. basic_memory/schemas/response.py +1 -1
  116. basic_memory/schemas/search.py +31 -35
  117. basic_memory/schemas/sync_report.py +72 -0
  118. basic_memory/services/__init__.py +2 -1
  119. basic_memory/services/context_service.py +241 -104
  120. basic_memory/services/directory_service.py +295 -0
  121. basic_memory/services/entity_service.py +590 -60
  122. basic_memory/services/exceptions.py +21 -0
  123. basic_memory/services/file_service.py +284 -30
  124. basic_memory/services/initialization.py +191 -0
  125. basic_memory/services/link_resolver.py +49 -56
  126. basic_memory/services/project_service.py +863 -0
  127. basic_memory/services/search_service.py +168 -32
  128. basic_memory/sync/__init__.py +3 -2
  129. basic_memory/sync/background_sync.py +26 -0
  130. basic_memory/sync/sync_service.py +1180 -109
  131. basic_memory/sync/watch_service.py +412 -135
  132. basic_memory/templates/prompts/continue_conversation.hbs +110 -0
  133. basic_memory/templates/prompts/search.hbs +101 -0
  134. basic_memory/utils.py +383 -51
  135. basic_memory-0.16.1.dist-info/METADATA +493 -0
  136. basic_memory-0.16.1.dist-info/RECORD +148 -0
  137. {basic_memory-0.7.0.dist-info → basic_memory-0.16.1.dist-info}/entry_points.txt +1 -0
  138. basic_memory/alembic/README +0 -1
  139. basic_memory/cli/commands/sync.py +0 -206
  140. basic_memory/cli/commands/tools.py +0 -157
  141. basic_memory/mcp/tools/knowledge.py +0 -68
  142. basic_memory/mcp/tools/memory.py +0 -170
  143. basic_memory/mcp/tools/notes.py +0 -202
  144. basic_memory/schemas/discovery.py +0 -28
  145. basic_memory/sync/file_change_scanner.py +0 -158
  146. basic_memory/sync/utils.py +0 -31
  147. basic_memory-0.7.0.dist-info/METADATA +0 -378
  148. basic_memory-0.7.0.dist-info/RECORD +0 -82
  149. {basic_memory-0.7.0.dist-info → basic_memory-0.16.1.dist-info}/WHEEL +0 -0
  150. {basic_memory-0.7.0.dist-info → basic_memory-0.16.1.dist-info}/licenses/LICENSE +0 -0
@@ -0,0 +1,141 @@
1
+ """Project context utilities for Basic Memory MCP server.
2
+
3
+ Provides project lookup utilities for MCP tools.
4
+ Handles project validation and context management in one place.
5
+ """
6
+
7
+ import os
8
+ from typing import Optional, List
9
+ from httpx import AsyncClient
10
+ from httpx._types import (
11
+ HeaderTypes,
12
+ )
13
+ from loguru import logger
14
+ from fastmcp import Context
15
+
16
+ from basic_memory.config import ConfigManager
17
+ from basic_memory.mcp.tools.utils import call_get
18
+ from basic_memory.schemas.project_info import ProjectItem, ProjectList
19
+ from basic_memory.utils import generate_permalink
20
+
21
+
22
+ async def resolve_project_parameter(project: Optional[str] = None) -> Optional[str]:
23
+ """Resolve project parameter using three-tier hierarchy.
24
+
25
+ if config.cloud_mode:
26
+ project is required
27
+ else:
28
+ Resolution order:
29
+ 1. Single Project Mode (--project cli arg, or BASIC_MEMORY_MCP_PROJECT env var) - highest priority
30
+ 2. Explicit project parameter - medium priority
31
+ 3. Default project if default_project_mode=true - lowest priority
32
+
33
+ Args:
34
+ project: Optional explicit project parameter
35
+
36
+ Returns:
37
+ Resolved project name or None if no resolution possible
38
+ """
39
+
40
+ config = ConfigManager().config
41
+ # if cloud_mode, project is required
42
+ if config.cloud_mode:
43
+ if project:
44
+ logger.debug(f"project: {project}, cloud_mode: {config.cloud_mode}")
45
+ return project
46
+ else:
47
+ raise ValueError("No project specified. Project is required for cloud mode.")
48
+
49
+ # Priority 1: CLI constraint overrides everything (--project arg sets env var)
50
+ constrained_project = os.environ.get("BASIC_MEMORY_MCP_PROJECT")
51
+ if constrained_project:
52
+ logger.debug(f"Using CLI constrained project: {constrained_project}")
53
+ return constrained_project
54
+
55
+ # Priority 2: Explicit project parameter
56
+ if project:
57
+ logger.debug(f"Using explicit project parameter: {project}")
58
+ return project
59
+
60
+ # Priority 3: Default project mode
61
+ if config.default_project_mode:
62
+ logger.debug(f"Using default project from config: {config.default_project}")
63
+ return config.default_project
64
+
65
+ # No resolution possible
66
+ return None
67
+
68
+
69
+ async def get_project_names(client: AsyncClient, headers: HeaderTypes | None = None) -> List[str]:
70
+ response = await call_get(client, "/projects/projects", headers=headers)
71
+ project_list = ProjectList.model_validate(response.json())
72
+ return [project.name for project in project_list.projects]
73
+
74
+
75
+ async def get_active_project(
76
+ client: AsyncClient,
77
+ project: Optional[str] = None,
78
+ context: Optional[Context] = None,
79
+ headers: HeaderTypes | None = None,
80
+ ) -> ProjectItem:
81
+ """Get and validate project, setting it in context if available.
82
+
83
+ Args:
84
+ client: HTTP client for API calls
85
+ project: Optional project name (resolved using hierarchy)
86
+ context: Optional FastMCP context to cache the result
87
+
88
+ Returns:
89
+ The validated project item
90
+
91
+ Raises:
92
+ ValueError: If no project can be resolved
93
+ HTTPError: If project doesn't exist or is inaccessible
94
+ """
95
+ resolved_project = await resolve_project_parameter(project)
96
+ if not resolved_project:
97
+ project_names = await get_project_names(client, headers)
98
+ raise ValueError(
99
+ "No project specified. "
100
+ "Either set 'default_project_mode=true' in config, or use 'project' argument.\n"
101
+ f"Available projects: {project_names}"
102
+ )
103
+
104
+ project = resolved_project
105
+
106
+ # Check if already cached in context
107
+ if context:
108
+ cached_project = context.get_state("active_project")
109
+ if cached_project and cached_project.name == project:
110
+ logger.debug(f"Using cached project from context: {project}")
111
+ return cached_project
112
+
113
+ # Validate project exists by calling API
114
+ logger.debug(f"Validating project: {project}")
115
+ permalink = generate_permalink(project)
116
+ response = await call_get(client, f"/{permalink}/project/item", headers=headers)
117
+ active_project = ProjectItem.model_validate(response.json())
118
+
119
+ # Cache in context if available
120
+ if context:
121
+ context.set_state("active_project", active_project)
122
+ logger.debug(f"Cached project in context: {project}")
123
+
124
+ logger.debug(f"Validated project: {active_project.name}")
125
+ return active_project
126
+
127
+
128
+ def add_project_metadata(result: str, project_name: str) -> str:
129
+ """Add project context as metadata footer for assistant session tracking.
130
+
131
+ Provides clear project context to help the assistant remember which
132
+ project is being used throughout the conversation session.
133
+
134
+ Args:
135
+ result: The tool result string
136
+ project_name: The project name that was used
137
+
138
+ Returns:
139
+ Result with project session tracking metadata
140
+ """
141
+ return f"{result}\n\n[Session: Using project '{project_name}']"
@@ -0,0 +1,19 @@
1
+ """Basic Memory MCP prompts.
2
+
3
+ Prompts are a special type of tool that returns a string response
4
+ formatted for a user to read, typically invoking one or more tools
5
+ and transforming their results into user-friendly text.
6
+ """
7
+
8
+ # Import individual prompt modules to register them with the MCP server
9
+ from basic_memory.mcp.prompts import continue_conversation
10
+ from basic_memory.mcp.prompts import recent_activity
11
+ from basic_memory.mcp.prompts import search
12
+ from basic_memory.mcp.prompts import ai_assistant_guide
13
+
14
+ __all__ = [
15
+ "ai_assistant_guide",
16
+ "continue_conversation",
17
+ "recent_activity",
18
+ "search",
19
+ ]
@@ -0,0 +1,70 @@
1
+ from pathlib import Path
2
+
3
+ from basic_memory.config import ConfigManager
4
+ from basic_memory.mcp.server import mcp
5
+ from loguru import logger
6
+
7
+
8
+ @mcp.resource(
9
+ uri="memory://ai_assistant_guide",
10
+ name="ai assistant guide",
11
+ description="Give an AI assistant guidance on how to use Basic Memory tools effectively",
12
+ )
13
+ def ai_assistant_guide() -> str:
14
+ """Return a concise guide on Basic Memory tools and how to use them.
15
+
16
+ Dynamically adapts instructions based on configuration:
17
+ - Default project mode: Simplified instructions with automatic project
18
+ - Regular mode: Project discovery and selection guidance
19
+ - CLI constraint mode: Single project constraint information
20
+
21
+ Returns:
22
+ A focused guide on Basic Memory usage.
23
+ """
24
+ logger.info("Loading AI assistant guide resource")
25
+
26
+ # Load base guide content
27
+ guide_doc = Path(__file__).parent.parent / "resources" / "ai_assistant_guide.md"
28
+ content = guide_doc.read_text(encoding="utf-8")
29
+
30
+ # Check configuration for mode-specific instructions
31
+ config = ConfigManager().config
32
+
33
+ # Add mode-specific header
34
+ mode_info = ""
35
+ if config.default_project_mode:
36
+ mode_info = f"""
37
+ # 🎯 Default Project Mode Active
38
+
39
+ **Current Configuration**: All operations automatically use project '{config.default_project}'
40
+
41
+ **Simplified Usage**: You don't need to specify the project parameter in tool calls.
42
+ - `write_note(title="Note", content="...", folder="docs")` ✅
43
+ - Project parameter is optional and will default to '{config.default_project}'
44
+ - To use a different project, explicitly specify: `project="other-project"`
45
+
46
+ ────────────────────────────────────────
47
+
48
+ """
49
+ else:
50
+ mode_info = """
51
+ # 🔧 Multi-Project Mode Active
52
+
53
+ **Current Configuration**: Project parameter required for all operations
54
+
55
+ **Project Discovery Required**: Use these tools to select a project:
56
+ - `list_memory_projects()` - See all available projects
57
+ - `recent_activity()` - Get project activity and recommendations
58
+ - Remember the user's project choice throughout the conversation
59
+
60
+ ────────────────────────────────────────
61
+
62
+ """
63
+
64
+ # Prepend mode info to the guide
65
+ enhanced_content = mode_info + content
66
+
67
+ logger.info(
68
+ f"Loaded AI assistant guide ({len(enhanced_content)} chars) with mode: {'default_project' if config.default_project_mode else 'multi_project'}"
69
+ )
70
+ return enhanced_content
@@ -0,0 +1,62 @@
1
+ """Session continuation prompts for Basic Memory MCP server.
2
+
3
+ These prompts help users continue conversations and work across sessions,
4
+ providing context from previous interactions to maintain continuity.
5
+ """
6
+
7
+ from typing import Annotated, Optional
8
+
9
+ from loguru import logger
10
+ from pydantic import Field
11
+
12
+ from basic_memory.config import get_project_config
13
+ from basic_memory.mcp.async_client import get_client
14
+ from basic_memory.mcp.server import mcp
15
+ from basic_memory.mcp.tools.utils import call_post
16
+ from basic_memory.schemas.base import TimeFrame
17
+ from basic_memory.schemas.prompt import ContinueConversationRequest
18
+
19
+
20
+ @mcp.prompt(
21
+ name="continue_conversation",
22
+ description="Continue a previous conversation",
23
+ )
24
+ async def continue_conversation(
25
+ topic: Annotated[Optional[str], Field(description="Topic or keyword to search for")] = None,
26
+ timeframe: Annotated[
27
+ Optional[TimeFrame],
28
+ Field(description="How far back to look for activity (e.g. '1d', '1 week')"),
29
+ ] = None,
30
+ ) -> str:
31
+ """Continue a previous conversation or work session.
32
+
33
+ This prompt helps you pick up where you left off by finding recent context
34
+ about a specific topic or showing general recent activity.
35
+
36
+ Args:
37
+ topic: Topic or keyword to search for (optional)
38
+ timeframe: How far back to look for activity
39
+
40
+ Returns:
41
+ Context from previous sessions on this topic
42
+ """
43
+ logger.info(f"Continuing session, topic: {topic}, timeframe: {timeframe}")
44
+
45
+ async with get_client() as client:
46
+ # Create request model
47
+ request = ContinueConversationRequest( # pyright: ignore [reportCallIssue]
48
+ topic=topic, timeframe=timeframe
49
+ )
50
+
51
+ project_url = get_project_config().project_url
52
+
53
+ # Call the prompt API endpoint
54
+ response = await call_post(
55
+ client,
56
+ f"{project_url}/prompt/continue-conversation",
57
+ json=request.model_dump(exclude_none=True),
58
+ )
59
+
60
+ # Extract the rendered prompt from the response
61
+ result = response.json()
62
+ return result["prompt"]
@@ -0,0 +1,188 @@
1
+ """Recent activity prompts for Basic Memory MCP server.
2
+
3
+ These prompts help users see what has changed in their knowledge base recently.
4
+ """
5
+
6
+ from typing import Annotated, Optional
7
+
8
+ from loguru import logger
9
+ from pydantic import Field
10
+
11
+ from basic_memory.mcp.prompts.utils import format_prompt_context, PromptContext, PromptContextItem
12
+ from basic_memory.mcp.server import mcp
13
+ from basic_memory.mcp.tools.recent_activity import recent_activity
14
+ from basic_memory.schemas.base import TimeFrame
15
+ from basic_memory.schemas.memory import GraphContext, ProjectActivitySummary
16
+ from basic_memory.schemas.search import SearchItemType
17
+
18
+
19
+ @mcp.prompt(
20
+ name="recent_activity",
21
+ description="Get recent activity from a specific project or across all projects",
22
+ )
23
+ async def recent_activity_prompt(
24
+ timeframe: Annotated[
25
+ TimeFrame,
26
+ Field(description="How far back to look for activity (e.g. '1d', '1 week')"),
27
+ ] = "7d",
28
+ project: Annotated[
29
+ Optional[str],
30
+ Field(
31
+ description="Specific project to get activity from (None for discovery across all projects)"
32
+ ),
33
+ ] = None,
34
+ ) -> str:
35
+ """Get recent activity from a specific project or across all projects.
36
+
37
+ This prompt helps you see what's changed recently in the knowledge base.
38
+ In discovery mode (project=None), it shows activity across all projects.
39
+ In project-specific mode, it shows detailed activity for one project.
40
+
41
+ Args:
42
+ timeframe: How far back to look for activity (e.g. '1d', '1 week')
43
+ project: Specific project to get activity from (None for discovery across all projects)
44
+
45
+ Returns:
46
+ Formatted summary of recent activity
47
+ """
48
+ logger.info(f"Getting recent activity, timeframe: {timeframe}, project: {project}")
49
+
50
+ recent = await recent_activity.fn(
51
+ project=project, timeframe=timeframe, type=[SearchItemType.ENTITY]
52
+ )
53
+
54
+ # Extract primary results from the hierarchical structure
55
+ primary_results = []
56
+ related_results = []
57
+
58
+ if isinstance(recent, ProjectActivitySummary):
59
+ # Discovery mode - extract results from all projects
60
+ for _, project_activity in recent.projects.items():
61
+ if project_activity.activity.results:
62
+ # Take up to 2 primary results per project
63
+ for item in project_activity.activity.results[:2]:
64
+ primary_results.append(item.primary_result)
65
+ # Add up to 1 related result per primary item
66
+ if item.related_results:
67
+ related_results.extend(item.related_results[:1])
68
+
69
+ # Limit total results for readability
70
+ primary_results = primary_results[:8]
71
+ related_results = related_results[:6]
72
+
73
+ elif isinstance(recent, GraphContext):
74
+ # Project-specific mode - use existing logic
75
+ if recent.results:
76
+ # Take up to 5 primary results
77
+ for item in recent.results[:5]:
78
+ primary_results.append(item.primary_result)
79
+ # Add up to 2 related results per primary item
80
+ if item.related_results:
81
+ related_results.extend(item.related_results[:2])
82
+
83
+ # Set topic based on mode
84
+ if project:
85
+ topic = f"Recent Activity in {project} ({timeframe})"
86
+ else:
87
+ topic = f"Recent Activity Across All Projects ({timeframe})"
88
+
89
+ prompt_context = format_prompt_context(
90
+ PromptContext(
91
+ topic=topic,
92
+ timeframe=timeframe,
93
+ results=[
94
+ PromptContextItem(
95
+ primary_results=primary_results,
96
+ related_results=related_results[:10], # Limit total related results
97
+ )
98
+ ],
99
+ )
100
+ )
101
+
102
+ # Add mode-specific suggestions
103
+ first_title = "Recent Topic"
104
+ if primary_results and len(primary_results) > 0:
105
+ first_title = primary_results[0].title
106
+
107
+ if project:
108
+ # Project-specific suggestions
109
+ capture_suggestions = f"""
110
+ ## Opportunity to Capture Activity Summary
111
+
112
+ Consider creating a summary note of recent activity in {project}:
113
+
114
+ ```python
115
+ await write_note(
116
+ "{project}",
117
+ title="Activity Summary {timeframe}",
118
+ content='''
119
+ # Activity Summary for {project} ({timeframe})
120
+
121
+ ## Overview
122
+ [Summary of key changes and developments in this project over this period]
123
+
124
+ ## Key Updates
125
+ [List main updates and their significance within this project]
126
+
127
+ ## Observations
128
+ - [trend] [Observation about patterns in recent activity]
129
+ - [insight] [Connection between different activities]
130
+
131
+ ## Relations
132
+ - summarizes [[{first_title}]]
133
+ - relates_to [[{project} Overview]]
134
+ ''',
135
+ folder="summaries"
136
+ )
137
+ ```
138
+
139
+ Summarizing periodic activity helps create high-level insights and connections within the project.
140
+ """
141
+ else:
142
+ # Discovery mode suggestions
143
+ project_count = len(recent.projects) if isinstance(recent, ProjectActivitySummary) else 0
144
+ most_active = (
145
+ getattr(recent.summary, "most_active_project", "Unknown")
146
+ if isinstance(recent, ProjectActivitySummary)
147
+ else "Unknown"
148
+ )
149
+
150
+ capture_suggestions = f"""
151
+ ## Cross-Project Activity Discovery
152
+
153
+ Found activity across {project_count} projects. Most active: **{most_active}**
154
+
155
+ Consider creating a cross-project summary:
156
+
157
+ ```python
158
+ await write_note(
159
+ "{most_active if most_active != "Unknown" else "main"}",
160
+ title="Cross-Project Activity Summary {timeframe}",
161
+ content='''
162
+ # Cross-Project Activity Summary ({timeframe})
163
+
164
+ ## Overview
165
+ Activity found across {project_count} projects, with {most_active} showing the most activity.
166
+
167
+ ## Key Developments
168
+ [Summarize important changes across all projects]
169
+
170
+ ## Project Insights
171
+ [Note patterns or connections between projects]
172
+
173
+ ## Observations
174
+ - [trend] [Cross-project patterns observed]
175
+ - [insight] [Connections between different project activities]
176
+
177
+ ## Relations
178
+ - summarizes [[{first_title}]]
179
+ - relates_to [[Project Portfolio Overview]]
180
+ ''',
181
+ folder="summaries"
182
+ )
183
+ ```
184
+
185
+ Cross-project summaries help identify broader trends and project interconnections.
186
+ """
187
+
188
+ return prompt_context + capture_suggestions
@@ -0,0 +1,57 @@
1
+ """Search prompts for Basic Memory MCP server.
2
+
3
+ These prompts help users search and explore their knowledge base.
4
+ """
5
+
6
+ from typing import Annotated, Optional
7
+
8
+ from loguru import logger
9
+ from pydantic import Field
10
+
11
+ from basic_memory.config import get_project_config
12
+ from basic_memory.mcp.async_client import get_client
13
+ from basic_memory.mcp.server import mcp
14
+ from basic_memory.mcp.tools.utils import call_post
15
+ from basic_memory.schemas.base import TimeFrame
16
+ from basic_memory.schemas.prompt import SearchPromptRequest
17
+
18
+
19
+ @mcp.prompt(
20
+ name="search_knowledge_base",
21
+ description="Search across all content in basic-memory",
22
+ )
23
+ async def search_prompt(
24
+ query: str,
25
+ timeframe: Annotated[
26
+ Optional[TimeFrame],
27
+ Field(description="How far back to search (e.g. '1d', '1 week')"),
28
+ ] = None,
29
+ ) -> str:
30
+ """Search across all content in basic-memory.
31
+
32
+ This prompt helps search for content in the knowledge base and
33
+ provides helpful context about the results.
34
+
35
+ Args:
36
+ query: The search text to look for
37
+ timeframe: Optional timeframe to limit results (e.g. '1d', '1 week')
38
+
39
+ Returns:
40
+ Formatted search results with context
41
+ """
42
+ logger.info(f"Searching knowledge base, query: {query}, timeframe: {timeframe}")
43
+
44
+ async with get_client() as client:
45
+ # Create request model
46
+ request = SearchPromptRequest(query=query, timeframe=timeframe)
47
+
48
+ project_url = get_project_config().project_url
49
+
50
+ # Call the prompt API endpoint
51
+ response = await call_post(
52
+ client, f"{project_url}/prompt/search", json=request.model_dump(exclude_none=True)
53
+ )
54
+
55
+ # Extract the rendered prompt from the response
56
+ result = response.json()
57
+ return result["prompt"]