basic-memory 0.10.0__py3-none-any.whl → 0.11.0__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 +1 -1
- basic_memory/cli/commands/__init__.py +1 -2
- basic_memory/cli/commands/db.py +15 -2
- basic_memory/cli/commands/project.py +168 -2
- basic_memory/cli/commands/tool.py +8 -4
- basic_memory/config.py +45 -10
- basic_memory/markdown/entity_parser.py +13 -10
- basic_memory/markdown/schemas.py +1 -1
- basic_memory/mcp/prompts/ai_assistant_guide.py +1 -3
- basic_memory/mcp/prompts/continue_conversation.py +3 -3
- basic_memory/mcp/prompts/search.py +4 -4
- basic_memory/mcp/resources/ai_assistant_guide.md +413 -0
- basic_memory/mcp/tools/__init__.py +2 -2
- basic_memory/mcp/tools/read_note.py +3 -3
- basic_memory/mcp/tools/search.py +11 -11
- basic_memory/mcp/tools/write_note.py +17 -7
- basic_memory/services/entity_service.py +11 -1
- basic_memory/sync/watch_service.py +1 -1
- basic_memory/utils.py +27 -1
- {basic_memory-0.10.0.dist-info → basic_memory-0.11.0.dist-info}/METADATA +17 -4
- {basic_memory-0.10.0.dist-info → basic_memory-0.11.0.dist-info}/RECORD +24 -24
- {basic_memory-0.10.0.dist-info → basic_memory-0.11.0.dist-info}/entry_points.txt +1 -0
- basic_memory/cli/commands/project_info.py +0 -167
- {basic_memory-0.10.0.dist-info → basic_memory-0.11.0.dist-info}/WHEEL +0 -0
- {basic_memory-0.10.0.dist-info → basic_memory-0.11.0.dist-info}/licenses/LICENSE +0 -0
|
@@ -0,0 +1,413 @@
|
|
|
1
|
+
# AI Assistant Guide for Basic Memory
|
|
2
|
+
|
|
3
|
+
This guide helps AIs use Basic Memory tools effectively when working with users. It covers reading, writing, and
|
|
4
|
+
navigating knowledge through the Model Context Protocol (MCP).
|
|
5
|
+
|
|
6
|
+
## Overview
|
|
7
|
+
|
|
8
|
+
Basic Memory allows you and users to record context in local Markdown files, building a rich knowledge base through
|
|
9
|
+
natural conversations. The system automatically creates a semantic knowledge graph from simple text patterns.
|
|
10
|
+
|
|
11
|
+
- **Local-First**: All data is stored in plain text files on the user's computer
|
|
12
|
+
- **Real-Time**: Users see content updates immediately
|
|
13
|
+
- **Bi-Directional**: Both you and users can read and edit notes
|
|
14
|
+
- **Semantic**: Simple patterns create a structured knowledge graph
|
|
15
|
+
- **Persistent**: Knowledge persists across sessions and conversations
|
|
16
|
+
|
|
17
|
+
## The Importance of the Knowledge Graph
|
|
18
|
+
|
|
19
|
+
**Basic Memory's value comes from connections between notes, not just the notes themselves.**
|
|
20
|
+
|
|
21
|
+
When writing notes, your primary goal should be creating a rich, interconnected knowledge graph:
|
|
22
|
+
|
|
23
|
+
1. **Increase Semantic Density**: Add multiple observations and relations to each note
|
|
24
|
+
2. **Use Accurate References**: Aim to reference existing entities by their exact titles
|
|
25
|
+
3. **Create Forward References**: Feel free to reference entities that don't exist yet - Basic Memory will resolve these
|
|
26
|
+
when they're created later
|
|
27
|
+
4. **Create Bidirectional Links**: When appropriate, connect entities from both directions
|
|
28
|
+
5. **Use Meaningful Categories**: Add semantic context with appropriate observation categories
|
|
29
|
+
6. **Choose Precise Relations**: Use specific relation types that convey meaning
|
|
30
|
+
|
|
31
|
+
Remember: A knowledge graph with 10 heavily connected notes is more valuable than 20 isolated notes. Your job is to help
|
|
32
|
+
build these connections!
|
|
33
|
+
|
|
34
|
+
## Core Tools Reference
|
|
35
|
+
|
|
36
|
+
```python
|
|
37
|
+
# Writing knowledge - THE MOST IMPORTANT TOOL!
|
|
38
|
+
response = await write_note(
|
|
39
|
+
title="Search Design", # Required: Note title
|
|
40
|
+
content="# Search Design\n...", # Required: Note content
|
|
41
|
+
folder="specs", # Optional: Folder to save in
|
|
42
|
+
tags=["search", "design"], # Optional: Tags for categorization
|
|
43
|
+
verbose=True # Optional: Get parsing details
|
|
44
|
+
)
|
|
45
|
+
|
|
46
|
+
# Reading knowledge
|
|
47
|
+
content = await read_note("Search Design") # By title
|
|
48
|
+
content = await read_note("specs/search-design") # By path
|
|
49
|
+
content = await read_note("memory://specs/search") # By memory URL
|
|
50
|
+
|
|
51
|
+
# Searching for knowledge
|
|
52
|
+
results = await search_notes(
|
|
53
|
+
query="authentication system", # Text to search for
|
|
54
|
+
page=1, # Optional: Pagination
|
|
55
|
+
page_size=10 # Optional: Results per page
|
|
56
|
+
)
|
|
57
|
+
|
|
58
|
+
# Building context from the knowledge graph
|
|
59
|
+
context = await build_context(
|
|
60
|
+
url="memory://specs/search", # Starting point
|
|
61
|
+
depth=2, # Optional: How many hops to follow
|
|
62
|
+
timeframe="1 month" # Optional: Recent timeframe
|
|
63
|
+
)
|
|
64
|
+
|
|
65
|
+
# Checking recent changes
|
|
66
|
+
activity = await recent_activity(
|
|
67
|
+
type="all", # Optional: Entity types to include
|
|
68
|
+
depth=1, # Optional: Related items to include
|
|
69
|
+
timeframe="1 week" # Optional: Time window
|
|
70
|
+
)
|
|
71
|
+
|
|
72
|
+
# Creating a knowledge visualization
|
|
73
|
+
canvas_result = await canvas(
|
|
74
|
+
nodes=[{"id": "note1", "label": "Search Design"}], # Nodes to display
|
|
75
|
+
edges=[{"from": "note1", "to": "note2"}], # Connections
|
|
76
|
+
title="Project Overview", # Canvas title
|
|
77
|
+
folder="diagrams" # Storage location
|
|
78
|
+
)
|
|
79
|
+
```
|
|
80
|
+
|
|
81
|
+
## memory:// URLs Explained
|
|
82
|
+
|
|
83
|
+
Basic Memory uses a special URL format to reference entities in the knowledge graph:
|
|
84
|
+
|
|
85
|
+
- `memory://title` - Reference by title
|
|
86
|
+
- `memory://folder/title` - Reference by folder and title
|
|
87
|
+
- `memory://permalink` - Reference by permalink
|
|
88
|
+
- `memory://path/relation_type/*` - Follow all relations of a specific type
|
|
89
|
+
- `memory://path/*/target` - Find all entities with relations to target
|
|
90
|
+
|
|
91
|
+
## Semantic Markdown Format
|
|
92
|
+
|
|
93
|
+
Knowledge is encoded in standard markdown using simple patterns:
|
|
94
|
+
|
|
95
|
+
**Observations** - Facts about an entity:
|
|
96
|
+
|
|
97
|
+
```markdown
|
|
98
|
+
- [category] This is an observation #tag1 #tag2 (optional context)
|
|
99
|
+
```
|
|
100
|
+
|
|
101
|
+
**Relations** - Links between entities:
|
|
102
|
+
|
|
103
|
+
```markdown
|
|
104
|
+
- relation_type [[Target Entity]] (optional context)
|
|
105
|
+
```
|
|
106
|
+
|
|
107
|
+
**Common Categories & Relation Types:**
|
|
108
|
+
|
|
109
|
+
- Categories: `[idea]`, `[decision]`, `[question]`, `[fact]`, `[requirement]`, `[technique]`, `[recipe]`, `[preference]`
|
|
110
|
+
- Relations: `relates_to`, `implements`, `requires`, `extends`, `part_of`, `pairs_with`, `inspired_by`,
|
|
111
|
+
`originated_from`
|
|
112
|
+
|
|
113
|
+
## When to Record Context
|
|
114
|
+
|
|
115
|
+
**Always consider recording context when**:
|
|
116
|
+
|
|
117
|
+
1. Users make decisions or reach conclusions
|
|
118
|
+
2. Important information emerges during conversation
|
|
119
|
+
3. Multiple related topics are discussed
|
|
120
|
+
4. The conversation contains information that might be useful later
|
|
121
|
+
5. Plans, tasks, or action items are mentioned
|
|
122
|
+
|
|
123
|
+
**Protocol for recording context**:
|
|
124
|
+
|
|
125
|
+
1. Identify valuable information in the conversation
|
|
126
|
+
2. Ask the user: "Would you like me to record our discussion about [topic] in Basic Memory?"
|
|
127
|
+
3. If they agree, use `write_note` to capture the information
|
|
128
|
+
4. If they decline, continue without recording
|
|
129
|
+
5. Let the user know when information has been recorded: "I've saved our discussion about [topic] to Basic Memory."
|
|
130
|
+
|
|
131
|
+
## Understanding User Interactions
|
|
132
|
+
|
|
133
|
+
Users will interact with Basic Memory in patterns like:
|
|
134
|
+
|
|
135
|
+
1. **Creating knowledge**:
|
|
136
|
+
```
|
|
137
|
+
Human: "Let's write up what we discussed about search."
|
|
138
|
+
|
|
139
|
+
You: I'll create a note capturing our discussion about the search functionality.
|
|
140
|
+
[Use write_note() to record the conversation details]
|
|
141
|
+
```
|
|
142
|
+
|
|
143
|
+
2. **Referencing existing knowledge**:
|
|
144
|
+
```
|
|
145
|
+
Human: "Take a look at memory://specs/search"
|
|
146
|
+
|
|
147
|
+
You: I'll examine that information.
|
|
148
|
+
[Use build_context() to gather related information]
|
|
149
|
+
[Then read_note() to access specific content]
|
|
150
|
+
```
|
|
151
|
+
|
|
152
|
+
3. **Finding information**:
|
|
153
|
+
```
|
|
154
|
+
Human: "What were our decisions about auth?"
|
|
155
|
+
|
|
156
|
+
You: Let me find that information for you.
|
|
157
|
+
[Use search_notes() to find relevant notes]
|
|
158
|
+
[Then build_context() to understand connections]
|
|
159
|
+
```
|
|
160
|
+
|
|
161
|
+
## Key Things to Remember
|
|
162
|
+
|
|
163
|
+
1. **Files are Truth**
|
|
164
|
+
- All knowledge lives in local files on the user's computer
|
|
165
|
+
- Users can edit files outside your interaction
|
|
166
|
+
- Changes need to be synced by the user (usually automatic)
|
|
167
|
+
- Always verify information is current with `recent_activity()`
|
|
168
|
+
|
|
169
|
+
2. **Building Context Effectively**
|
|
170
|
+
- Start with specific entities
|
|
171
|
+
- Follow meaningful relations
|
|
172
|
+
- Check recent changes
|
|
173
|
+
- Build context incrementally
|
|
174
|
+
- Combine related information
|
|
175
|
+
|
|
176
|
+
3. **Writing Knowledge Wisely**
|
|
177
|
+
- Using the same title+folder will overwrite existing notes
|
|
178
|
+
- Structure content with clear headings and sections
|
|
179
|
+
- Use semantic markup for observations and relations
|
|
180
|
+
- Keep files organized in logical folders
|
|
181
|
+
|
|
182
|
+
## Common Knowledge Patterns
|
|
183
|
+
|
|
184
|
+
### Capturing Decisions
|
|
185
|
+
|
|
186
|
+
```markdown
|
|
187
|
+
# Coffee Brewing Methods
|
|
188
|
+
|
|
189
|
+
## Context
|
|
190
|
+
|
|
191
|
+
I've experimented with various brewing methods including French press, pour over, and espresso.
|
|
192
|
+
|
|
193
|
+
## Decision
|
|
194
|
+
|
|
195
|
+
Pour over is my preferred method for light to medium roasts because it highlights subtle flavors and offers more control
|
|
196
|
+
over the extraction.
|
|
197
|
+
|
|
198
|
+
## Observations
|
|
199
|
+
|
|
200
|
+
- [technique] Blooming the coffee grounds for 30 seconds improves extraction #brewing
|
|
201
|
+
- [preference] Water temperature between 195-205°F works best #temperature
|
|
202
|
+
- [equipment] Gooseneck kettle provides better control of water flow #tools
|
|
203
|
+
|
|
204
|
+
## Relations
|
|
205
|
+
|
|
206
|
+
- pairs_with [[Light Roast Beans]]
|
|
207
|
+
- contrasts_with [[French Press Method]]
|
|
208
|
+
- requires [[Proper Grinding Technique]]
|
|
209
|
+
```
|
|
210
|
+
|
|
211
|
+
### Recording Project Structure
|
|
212
|
+
|
|
213
|
+
```markdown
|
|
214
|
+
# Garden Planning
|
|
215
|
+
|
|
216
|
+
## Overview
|
|
217
|
+
|
|
218
|
+
This document outlines the garden layout and planting strategy for this season.
|
|
219
|
+
|
|
220
|
+
## Observations
|
|
221
|
+
|
|
222
|
+
- [structure] Raised beds in south corner for sun exposure #layout
|
|
223
|
+
- [structure] Drip irrigation system installed for efficiency #watering
|
|
224
|
+
- [pattern] Companion planting used to deter pests naturally #technique
|
|
225
|
+
|
|
226
|
+
## Relations
|
|
227
|
+
|
|
228
|
+
- contains [[Vegetable Section]]
|
|
229
|
+
- contains [[Herb Garden]]
|
|
230
|
+
- implements [[Organic Gardening Principles]]
|
|
231
|
+
```
|
|
232
|
+
|
|
233
|
+
### Technical Discussions
|
|
234
|
+
|
|
235
|
+
```markdown
|
|
236
|
+
# Recipe Improvement Discussion
|
|
237
|
+
|
|
238
|
+
## Key Points
|
|
239
|
+
|
|
240
|
+
Discussed strategies for improving the chocolate chip cookie recipe.
|
|
241
|
+
|
|
242
|
+
## Observations
|
|
243
|
+
|
|
244
|
+
- [issue] Cookies spread too thin when baked at 350°F #texture
|
|
245
|
+
- [solution] Chilling dough for 24 hours improves flavor and reduces spreading #technique
|
|
246
|
+
- [decision] Will use brown butter instead of regular butter #flavor
|
|
247
|
+
|
|
248
|
+
## Relations
|
|
249
|
+
|
|
250
|
+
- improves [[Basic Cookie Recipe]]
|
|
251
|
+
- inspired_by [[Bakery-Style Cookies]]
|
|
252
|
+
- pairs_with [[Homemade Ice Cream]]
|
|
253
|
+
```
|
|
254
|
+
|
|
255
|
+
### Creating Effective Relations
|
|
256
|
+
|
|
257
|
+
When creating relations, you can:
|
|
258
|
+
|
|
259
|
+
1. Reference existing entities by their exact title
|
|
260
|
+
2. Create forward references to entities that don't exist yet
|
|
261
|
+
|
|
262
|
+
```python
|
|
263
|
+
# Example workflow for creating notes with effective relations
|
|
264
|
+
async def create_note_with_effective_relations():
|
|
265
|
+
# Search for existing entities to reference
|
|
266
|
+
search_results = await search_notes("travel")
|
|
267
|
+
existing_entities = [result.title for result in search_results.primary_results]
|
|
268
|
+
|
|
269
|
+
# Check if specific entities exist
|
|
270
|
+
packing_tips_exists = "Packing Tips" in existing_entities
|
|
271
|
+
japan_travel_exists = "Japan Travel Guide" in existing_entities
|
|
272
|
+
|
|
273
|
+
# Prepare relations section - include both existing and forward references
|
|
274
|
+
relations_section = "## Relations\n"
|
|
275
|
+
|
|
276
|
+
# Existing reference - exact match to known entity
|
|
277
|
+
if packing_tips_exists:
|
|
278
|
+
relations_section += "- references [[Packing Tips]]\n"
|
|
279
|
+
else:
|
|
280
|
+
# Forward reference - will be linked when that entity is created later
|
|
281
|
+
relations_section += "- references [[Packing Tips]]\n"
|
|
282
|
+
|
|
283
|
+
# Another possible reference
|
|
284
|
+
if japan_travel_exists:
|
|
285
|
+
relations_section += "- part_of [[Japan Travel Guide]]\n"
|
|
286
|
+
|
|
287
|
+
# You can also check recently modified notes to reference them
|
|
288
|
+
recent = await recent_activity(timeframe="1 week")
|
|
289
|
+
recent_titles = [item.title for item in recent.primary_results]
|
|
290
|
+
|
|
291
|
+
if "Transportation Options" in recent_titles:
|
|
292
|
+
relations_section += "- relates_to [[Transportation Options]]\n"
|
|
293
|
+
|
|
294
|
+
# Always include meaningful forward references, even if they don't exist yet
|
|
295
|
+
relations_section += "- located_in [[Tokyo]]\n"
|
|
296
|
+
relations_section += "- visited_during [[Spring 2023 Trip]]\n"
|
|
297
|
+
|
|
298
|
+
# Now create the note with both verified and forward relations
|
|
299
|
+
content = f"""# Tokyo Neighborhood Guide
|
|
300
|
+
|
|
301
|
+
## Overview
|
|
302
|
+
Details about different Tokyo neighborhoods and their unique characteristics.
|
|
303
|
+
|
|
304
|
+
## Observations
|
|
305
|
+
- [area] Shibuya is a busy shopping district #shopping
|
|
306
|
+
- [transportation] Yamanote Line connects major neighborhoods #transit
|
|
307
|
+
- [recommendation] Visit Shimokitazawa for vintage shopping #unique
|
|
308
|
+
- [tip] Get a Suica card for easy train travel #convenience
|
|
309
|
+
|
|
310
|
+
{relations_section}
|
|
311
|
+
"""
|
|
312
|
+
|
|
313
|
+
result = await write_note(
|
|
314
|
+
title="Tokyo Neighborhood Guide",
|
|
315
|
+
content=content,
|
|
316
|
+
verbose=True
|
|
317
|
+
)
|
|
318
|
+
|
|
319
|
+
# You can check which relations were resolved and which are forward references
|
|
320
|
+
if result and 'relations' in result:
|
|
321
|
+
resolved = [r['to_name'] for r in result['relations'] if r.get('target_id')]
|
|
322
|
+
forward_refs = [r['to_name'] for r in result['relations'] if not r.get('target_id')]
|
|
323
|
+
|
|
324
|
+
print(f"Resolved relations: {resolved}")
|
|
325
|
+
print(f"Forward references that will be resolved later: {forward_refs}")
|
|
326
|
+
```
|
|
327
|
+
|
|
328
|
+
## Error Handling
|
|
329
|
+
|
|
330
|
+
Common issues to watch for:
|
|
331
|
+
|
|
332
|
+
1. **Missing Content**
|
|
333
|
+
```python
|
|
334
|
+
try:
|
|
335
|
+
content = await read_note("Document")
|
|
336
|
+
except:
|
|
337
|
+
# Try search instead
|
|
338
|
+
results = await search_notes("Document")
|
|
339
|
+
if results and results.primary_results:
|
|
340
|
+
# Found something similar
|
|
341
|
+
content = await read_note(results.primary_results[0].permalink)
|
|
342
|
+
```
|
|
343
|
+
|
|
344
|
+
2. **Forward References (Unresolved Relations)**
|
|
345
|
+
```python
|
|
346
|
+
response = await write_note(..., verbose=True)
|
|
347
|
+
# Check for forward references (unresolved relations)
|
|
348
|
+
forward_refs = []
|
|
349
|
+
for relation in response.get('relations', []):
|
|
350
|
+
if not relation.get('target_id'):
|
|
351
|
+
forward_refs.append(relation.get('to_name'))
|
|
352
|
+
|
|
353
|
+
if forward_refs:
|
|
354
|
+
# This is a feature, not an error! Inform the user about forward references
|
|
355
|
+
print(f"Note created with forward references to: {forward_refs}")
|
|
356
|
+
print("These will be automatically linked when those notes are created.")
|
|
357
|
+
|
|
358
|
+
# Optionally suggest creating those entities now
|
|
359
|
+
print("Would you like me to create any of these notes now to complete the connections?")
|
|
360
|
+
```
|
|
361
|
+
|
|
362
|
+
3. **Sync Issues**
|
|
363
|
+
```python
|
|
364
|
+
# If information seems outdated
|
|
365
|
+
activity = await recent_activity(timeframe="1 hour")
|
|
366
|
+
if not activity or not activity.primary_results:
|
|
367
|
+
print("It seems there haven't been recent updates. You might need to run 'basic-memory sync'.")
|
|
368
|
+
```
|
|
369
|
+
|
|
370
|
+
## Best Practices
|
|
371
|
+
|
|
372
|
+
1. **Proactively Record Context**
|
|
373
|
+
- Offer to capture important discussions
|
|
374
|
+
- Record decisions, rationales, and conclusions
|
|
375
|
+
- Link to related topics
|
|
376
|
+
- Ask for permission first: "Would you like me to save our discussion about [topic]?"
|
|
377
|
+
- Confirm when complete: "I've saved our discussion to Basic Memory"
|
|
378
|
+
|
|
379
|
+
2. **Create a Rich Semantic Graph**
|
|
380
|
+
- **Add meaningful observations**: Include at least 3-5 categorized observations in each note
|
|
381
|
+
- **Create deliberate relations**: Connect each note to at least 2-3 related entities
|
|
382
|
+
- **Use existing entities**: Before creating a new relation, search for existing entities
|
|
383
|
+
- **Verify wikilinks**: When referencing `[[Entity]]`, use exact titles of existing notes
|
|
384
|
+
- **Check accuracy**: Use `search_notes()` or `recent_activity()` to confirm entity titles
|
|
385
|
+
- **Use precise relation types**: Choose specific relation types that convey meaning (e.g., "implements" instead
|
|
386
|
+
of "relates_to")
|
|
387
|
+
- **Consider bidirectional relations**: When appropriate, create inverse relations in both entities
|
|
388
|
+
|
|
389
|
+
3. **Structure Content Thoughtfully**
|
|
390
|
+
- Use clear, descriptive titles
|
|
391
|
+
- Organize with logical sections (Context, Decision, Implementation, etc.)
|
|
392
|
+
- Include relevant context and background
|
|
393
|
+
- Add semantic observations with appropriate categories
|
|
394
|
+
- Use a consistent format for similar types of notes
|
|
395
|
+
- Balance detail with conciseness
|
|
396
|
+
|
|
397
|
+
4. **Navigate Knowledge Effectively**
|
|
398
|
+
- Start with specific searches
|
|
399
|
+
- Follow relation paths
|
|
400
|
+
- Combine information from multiple sources
|
|
401
|
+
- Verify information is current
|
|
402
|
+
- Build a complete picture before responding
|
|
403
|
+
|
|
404
|
+
5. **Help Users Maintain Their Knowledge**
|
|
405
|
+
- Suggest organizing related topics
|
|
406
|
+
- Identify potential duplicates
|
|
407
|
+
- Recommend adding relations between topics
|
|
408
|
+
- Offer to create summaries of scattered information
|
|
409
|
+
- Suggest potential missing relations: "I notice this might relate to [topic], would you like me to add that
|
|
410
|
+
connection?"
|
|
411
|
+
|
|
412
|
+
Built with ♥️ b
|
|
413
|
+
y Basic Machines
|
|
@@ -12,7 +12,7 @@ from basic_memory.mcp.tools.build_context import build_context
|
|
|
12
12
|
from basic_memory.mcp.tools.recent_activity import recent_activity
|
|
13
13
|
from basic_memory.mcp.tools.read_note import read_note
|
|
14
14
|
from basic_memory.mcp.tools.write_note import write_note
|
|
15
|
-
from basic_memory.mcp.tools.search import
|
|
15
|
+
from basic_memory.mcp.tools.search import search_notes
|
|
16
16
|
from basic_memory.mcp.tools.canvas import canvas
|
|
17
17
|
|
|
18
18
|
__all__ = [
|
|
@@ -22,6 +22,6 @@ __all__ = [
|
|
|
22
22
|
"read_content",
|
|
23
23
|
"read_note",
|
|
24
24
|
"recent_activity",
|
|
25
|
-
"
|
|
25
|
+
"search_notes",
|
|
26
26
|
"write_note",
|
|
27
27
|
]
|
|
@@ -6,7 +6,7 @@ from loguru import logger
|
|
|
6
6
|
|
|
7
7
|
from basic_memory.mcp.async_client import client
|
|
8
8
|
from basic_memory.mcp.server import mcp
|
|
9
|
-
from basic_memory.mcp.tools.search import
|
|
9
|
+
from basic_memory.mcp.tools.search import search_notes
|
|
10
10
|
from basic_memory.mcp.tools.utils import call_get
|
|
11
11
|
from basic_memory.schemas.memory import memory_url_path
|
|
12
12
|
from basic_memory.schemas.search import SearchQuery
|
|
@@ -63,7 +63,7 @@ async def read_note(identifier: str, page: int = 1, page_size: int = 10) -> str:
|
|
|
63
63
|
|
|
64
64
|
# Fallback 1: Try title search via API
|
|
65
65
|
logger.info(f"Search title for: {identifier}")
|
|
66
|
-
title_results = await
|
|
66
|
+
title_results = await search_notes(SearchQuery(title=identifier))
|
|
67
67
|
|
|
68
68
|
if title_results and title_results.results:
|
|
69
69
|
result = title_results.results[0] # Get the first/best match
|
|
@@ -87,7 +87,7 @@ async def read_note(identifier: str, page: int = 1, page_size: int = 10) -> str:
|
|
|
87
87
|
|
|
88
88
|
# Fallback 2: Text search as a last resort
|
|
89
89
|
logger.info(f"Title search failed, trying text search for: {identifier}")
|
|
90
|
-
text_results = await
|
|
90
|
+
text_results = await search_notes(SearchQuery(text=identifier))
|
|
91
91
|
|
|
92
92
|
# We didn't find a direct match, construct a helpful error message
|
|
93
93
|
if not text_results or not text_results.results:
|
basic_memory/mcp/tools/search.py
CHANGED
|
@@ -9,10 +9,10 @@ from basic_memory.mcp.async_client import client
|
|
|
9
9
|
|
|
10
10
|
|
|
11
11
|
@mcp.tool(
|
|
12
|
-
description="Search across all content in
|
|
12
|
+
description="Search across all content in the knowledge base.",
|
|
13
13
|
)
|
|
14
|
-
async def
|
|
15
|
-
"""Search across all content in
|
|
14
|
+
async def search_notes(query: SearchQuery, page: int = 1, page_size: int = 10) -> SearchResponse:
|
|
15
|
+
"""Search across all content in the knowledge base.
|
|
16
16
|
|
|
17
17
|
This tool searches the knowledge base using full-text search, pattern matching,
|
|
18
18
|
or exact permalink lookup. It supports filtering by content type, entity type,
|
|
@@ -36,34 +36,34 @@ async def search(query: SearchQuery, page: int = 1, page_size: int = 10) -> Sear
|
|
|
36
36
|
|
|
37
37
|
Examples:
|
|
38
38
|
# Basic text search
|
|
39
|
-
results = await
|
|
39
|
+
results = await search_notes(SearchQuery(text="project planning"))
|
|
40
40
|
|
|
41
41
|
# Boolean AND search (both terms must be present)
|
|
42
|
-
results = await
|
|
42
|
+
results = await search_notes(SearchQuery(text="project AND planning"))
|
|
43
43
|
|
|
44
44
|
# Boolean OR search (either term can be present)
|
|
45
|
-
results = await
|
|
45
|
+
results = await search_notes(SearchQuery(text="project OR meeting"))
|
|
46
46
|
|
|
47
47
|
# Boolean NOT search (exclude terms)
|
|
48
|
-
results = await
|
|
48
|
+
results = await search_notes(SearchQuery(text="project NOT meeting"))
|
|
49
49
|
|
|
50
50
|
# Boolean search with grouping
|
|
51
|
-
results = await
|
|
51
|
+
results = await search_notes(SearchQuery(text="(project OR planning) AND notes"))
|
|
52
52
|
|
|
53
53
|
# Search with type filter
|
|
54
|
-
results = await
|
|
54
|
+
results = await search_notes(SearchQuery(
|
|
55
55
|
text="meeting notes",
|
|
56
56
|
types=["entity"],
|
|
57
57
|
))
|
|
58
58
|
|
|
59
59
|
# Search for recent content
|
|
60
|
-
results = await
|
|
60
|
+
results = await search_notes(SearchQuery(
|
|
61
61
|
text="bug report",
|
|
62
62
|
after_date="1 week"
|
|
63
63
|
))
|
|
64
64
|
|
|
65
65
|
# Pattern matching on permalinks
|
|
66
|
-
results = await
|
|
66
|
+
results = await search_notes(SearchQuery(
|
|
67
67
|
permalink_match="docs/meeting-*"
|
|
68
68
|
))
|
|
69
69
|
"""
|
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
"""Write note tool for Basic Memory MCP server."""
|
|
2
2
|
|
|
3
|
-
from typing import
|
|
3
|
+
from typing import List, Union
|
|
4
4
|
|
|
5
5
|
from loguru import logger
|
|
6
6
|
|
|
@@ -9,6 +9,13 @@ from basic_memory.mcp.server import mcp
|
|
|
9
9
|
from basic_memory.mcp.tools.utils import call_put
|
|
10
10
|
from basic_memory.schemas import EntityResponse
|
|
11
11
|
from basic_memory.schemas.base import Entity
|
|
12
|
+
from basic_memory.utils import parse_tags
|
|
13
|
+
|
|
14
|
+
# Define TagType as a Union that can accept either a string or a list of strings or None
|
|
15
|
+
TagType = Union[List[str], str, None]
|
|
16
|
+
|
|
17
|
+
# Define TagType as a Union that can accept either a string or a list of strings or None
|
|
18
|
+
TagType = Union[List[str], str, None]
|
|
12
19
|
|
|
13
20
|
|
|
14
21
|
@mcp.tool(
|
|
@@ -18,7 +25,7 @@ async def write_note(
|
|
|
18
25
|
title: str,
|
|
19
26
|
content: str,
|
|
20
27
|
folder: str,
|
|
21
|
-
tags
|
|
28
|
+
tags=None, # Remove type hint completely to avoid schema issues
|
|
22
29
|
) -> str:
|
|
23
30
|
"""Write a markdown note to the knowledge base.
|
|
24
31
|
|
|
@@ -40,13 +47,14 @@ async def write_note(
|
|
|
40
47
|
Examples:
|
|
41
48
|
`- depends_on [[Content Parser]] (Need for semantic extraction)`
|
|
42
49
|
`- implements [[Search Spec]] (Initial implementation)`
|
|
43
|
-
`- This feature extends [[Base Design]]
|
|
50
|
+
`- This feature extends [[Base Design]] andst uses [[Core Utils]]`
|
|
44
51
|
|
|
45
52
|
Args:
|
|
46
53
|
title: The title of the note
|
|
47
54
|
content: Markdown content for the note, can include observations and relations
|
|
48
55
|
folder: the folder where the file should be saved
|
|
49
|
-
tags:
|
|
56
|
+
tags: Tags to categorize the note. Can be a list of strings, a comma-separated string, or None.
|
|
57
|
+
Note: If passing from external MCP clients, use a string format (e.g. "tag1,tag2,tag3")
|
|
50
58
|
|
|
51
59
|
Returns:
|
|
52
60
|
A markdown formatted summary of the semantic content, including:
|
|
@@ -58,8 +66,10 @@ async def write_note(
|
|
|
58
66
|
"""
|
|
59
67
|
logger.info("MCP tool call", tool="write_note", folder=folder, title=title, tags=tags)
|
|
60
68
|
|
|
69
|
+
# Process tags using the helper function
|
|
70
|
+
tag_list = parse_tags(tags)
|
|
61
71
|
# Create the entity request
|
|
62
|
-
metadata = {"tags": [f"#{tag}" for tag in
|
|
72
|
+
metadata = {"tags": [f"#{tag}" for tag in tag_list]} if tag_list else None
|
|
63
73
|
entity = Entity(
|
|
64
74
|
title=title,
|
|
65
75
|
folder=folder,
|
|
@@ -105,8 +115,8 @@ async def write_note(
|
|
|
105
115
|
summary.append(f"- Unresolved: {unresolved}")
|
|
106
116
|
summary.append("\nUnresolved relations will be retried on next sync.")
|
|
107
117
|
|
|
108
|
-
if
|
|
109
|
-
summary.append(f"\n## Tags\n- {', '.join(
|
|
118
|
+
if tag_list:
|
|
119
|
+
summary.append(f"\n## Tags\n- {', '.join(tag_list)}")
|
|
110
120
|
|
|
111
121
|
# Log the response with structured data
|
|
112
122
|
logger.info(
|
|
@@ -141,10 +141,20 @@ class EntityService(BaseService[EntityModel]):
|
|
|
141
141
|
# Convert file path string to Path
|
|
142
142
|
file_path = Path(entity.file_path)
|
|
143
143
|
|
|
144
|
+
# Read existing frontmatter from the file if it exists
|
|
145
|
+
existing_markdown = await self.entity_parser.parse_file(file_path)
|
|
146
|
+
|
|
147
|
+
# Create post with new content from schema
|
|
144
148
|
post = await schema_to_markdown(schema)
|
|
145
149
|
|
|
150
|
+
# Merge new metadata with existing metadata
|
|
151
|
+
existing_markdown.frontmatter.metadata.update(post.metadata)
|
|
152
|
+
|
|
153
|
+
# Create a new post with merged metadata
|
|
154
|
+
merged_post = frontmatter.Post(post.content, **existing_markdown.frontmatter.metadata)
|
|
155
|
+
|
|
146
156
|
# write file
|
|
147
|
-
final_content = frontmatter.dumps(
|
|
157
|
+
final_content = frontmatter.dumps(merged_post, sort_keys=False)
|
|
148
158
|
checksum = await self.file_service.write_file(file_path, final_content)
|
|
149
159
|
|
|
150
160
|
# parse entity from file
|
basic_memory/utils.py
CHANGED
|
@@ -6,7 +6,7 @@ import logging
|
|
|
6
6
|
import re
|
|
7
7
|
import sys
|
|
8
8
|
from pathlib import Path
|
|
9
|
-
from typing import Optional, Protocol, Union, runtime_checkable
|
|
9
|
+
from typing import Optional, Protocol, Union, runtime_checkable, List
|
|
10
10
|
|
|
11
11
|
from loguru import logger
|
|
12
12
|
from unidecode import unidecode
|
|
@@ -128,3 +128,29 @@ def setup_logging(
|
|
|
128
128
|
# Set log levels for noisy loggers
|
|
129
129
|
for logger_name, level in noisy_loggers.items():
|
|
130
130
|
logging.getLogger(logger_name).setLevel(level)
|
|
131
|
+
|
|
132
|
+
|
|
133
|
+
def parse_tags(tags: Union[List[str], str, None]) -> List[str]:
|
|
134
|
+
"""Parse tags from various input formats into a consistent list.
|
|
135
|
+
|
|
136
|
+
Args:
|
|
137
|
+
tags: Can be a list of strings, a comma-separated string, or None
|
|
138
|
+
|
|
139
|
+
Returns:
|
|
140
|
+
A list of tag strings, or an empty list if no tags
|
|
141
|
+
"""
|
|
142
|
+
if tags is None:
|
|
143
|
+
return []
|
|
144
|
+
|
|
145
|
+
if isinstance(tags, list):
|
|
146
|
+
return tags
|
|
147
|
+
|
|
148
|
+
if isinstance(tags, str):
|
|
149
|
+
return [tag.strip() for tag in tags.split(",") if tag.strip()]
|
|
150
|
+
|
|
151
|
+
# For any other type, try to convert to string and parse
|
|
152
|
+
try: # pragma: no cover
|
|
153
|
+
return parse_tags(str(tags))
|
|
154
|
+
except (ValueError, TypeError): # pragma: no cover
|
|
155
|
+
logger.warning(f"Couldn't parse tags from input of type {type(tags)}: {tags}")
|
|
156
|
+
return []
|