basic-memory 0.9.0__py3-none-any.whl → 0.10.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.
- basic_memory/__init__.py +1 -1
- basic_memory/api/routers/project_info_router.py +3 -4
- basic_memory/cli/commands/__init__.py +1 -2
- basic_memory/cli/commands/import_chatgpt.py +5 -6
- basic_memory/cli/commands/import_claude_conversations.py +5 -6
- basic_memory/cli/commands/import_claude_projects.py +5 -6
- basic_memory/cli/commands/project.py +168 -2
- basic_memory/cli/commands/tool.py +5 -1
- basic_memory/config.py +3 -4
- basic_memory/file_utils.py +3 -3
- basic_memory/markdown/entity_parser.py +13 -10
- basic_memory/markdown/markdown_processor.py +1 -1
- basic_memory/markdown/schemas.py +1 -1
- basic_memory/mcp/prompts/ai_assistant_guide.py +3 -4
- basic_memory/mcp/resources/ai_assistant_guide.md +413 -0
- basic_memory/mcp/tools/search.py +2 -2
- basic_memory/mcp/tools/write_note.py +17 -7
- basic_memory/services/entity_service.py +11 -1
- basic_memory/services/file_service.py +3 -5
- basic_memory/sync/watch_service.py +22 -12
- basic_memory/utils.py +27 -1
- basic_memory-0.10.1.dist-info/METADATA +398 -0
- {basic_memory-0.9.0.dist-info → basic_memory-0.10.1.dist-info}/RECORD +26 -26
- basic_memory/cli/commands/project_info.py +0 -167
- basic_memory-0.9.0.dist-info/METADATA +0 -736
- {basic_memory-0.9.0.dist-info → basic_memory-0.10.1.dist-info}/WHEEL +0 -0
- {basic_memory-0.9.0.dist-info → basic_memory-0.10.1.dist-info}/entry_points.txt +0 -0
- {basic_memory-0.9.0.dist-info → basic_memory-0.10.1.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(
|
|
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() 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("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("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()` 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
|
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
14
|
async def search(query: SearchQuery, page: int = 1, page_size: int = 10) -> SearchResponse:
|
|
15
|
-
"""Search across all content in
|
|
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,
|
|
@@ -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
|
|
@@ -5,8 +5,6 @@ from os import stat_result
|
|
|
5
5
|
from pathlib import Path
|
|
6
6
|
from typing import Any, Dict, Tuple, Union
|
|
7
7
|
|
|
8
|
-
from loguru import logger
|
|
9
|
-
|
|
10
8
|
from basic_memory import file_utils
|
|
11
9
|
from basic_memory.file_utils import FileError
|
|
12
10
|
from basic_memory.markdown.markdown_processor import MarkdownProcessor
|
|
@@ -14,6 +12,7 @@ from basic_memory.models import Entity as EntityModel
|
|
|
14
12
|
from basic_memory.schemas import Entity as EntitySchema
|
|
15
13
|
from basic_memory.services.exceptions import FileOperationError
|
|
16
14
|
from basic_memory.utils import FilePath
|
|
15
|
+
from loguru import logger
|
|
17
16
|
|
|
18
17
|
|
|
19
18
|
class FileService:
|
|
@@ -171,8 +170,7 @@ class FileService:
|
|
|
171
170
|
|
|
172
171
|
try:
|
|
173
172
|
logger.debug("Reading file", operation="read_file", path=str(full_path))
|
|
174
|
-
|
|
175
|
-
content = full_path.read_text()
|
|
173
|
+
content = full_path.read_text(encoding="utf-8")
|
|
176
174
|
checksum = await file_utils.compute_checksum(content)
|
|
177
175
|
|
|
178
176
|
logger.debug(
|
|
@@ -236,7 +234,7 @@ class FileService:
|
|
|
236
234
|
try:
|
|
237
235
|
if self.is_markdown(path):
|
|
238
236
|
# read str
|
|
239
|
-
content = full_path.read_text()
|
|
237
|
+
content = full_path.read_text(encoding="utf-8")
|
|
240
238
|
else:
|
|
241
239
|
# read bytes
|
|
242
240
|
content = full_path.read_bytes()
|
|
@@ -5,16 +5,15 @@ from datetime import datetime
|
|
|
5
5
|
from pathlib import Path
|
|
6
6
|
from typing import List, Optional, Set
|
|
7
7
|
|
|
8
|
+
from basic_memory.config import ProjectConfig
|
|
9
|
+
from basic_memory.services.file_service import FileService
|
|
10
|
+
from basic_memory.sync.sync_service import SyncService
|
|
8
11
|
from loguru import logger
|
|
9
12
|
from pydantic import BaseModel
|
|
10
13
|
from rich.console import Console
|
|
11
14
|
from watchfiles import awatch
|
|
12
15
|
from watchfiles.main import FileChange, Change
|
|
13
16
|
|
|
14
|
-
from basic_memory.config import ProjectConfig
|
|
15
|
-
from basic_memory.services.file_service import FileService
|
|
16
|
-
from basic_memory.sync.sync_service import SyncService
|
|
17
|
-
|
|
18
17
|
WATCH_STATUS_JSON = "watch-status.json"
|
|
19
18
|
|
|
20
19
|
|
|
@@ -138,6 +137,10 @@ class WatchService:
|
|
|
138
137
|
if part.startswith("."):
|
|
139
138
|
return False
|
|
140
139
|
|
|
140
|
+
# Skip temp files used in atomic operations
|
|
141
|
+
if path.endswith(".tmp"):
|
|
142
|
+
return False
|
|
143
|
+
|
|
141
144
|
return True
|
|
142
145
|
|
|
143
146
|
async def write_status(self):
|
|
@@ -161,6 +164,11 @@ class WatchService:
|
|
|
161
164
|
for change, path in changes:
|
|
162
165
|
# convert to relative path
|
|
163
166
|
relative_path = str(Path(path).relative_to(directory))
|
|
167
|
+
|
|
168
|
+
# Skip .tmp files - they're temporary and shouldn't be synced
|
|
169
|
+
if relative_path.endswith(".tmp"):
|
|
170
|
+
continue
|
|
171
|
+
|
|
164
172
|
if change == Change.added:
|
|
165
173
|
adds.append(relative_path)
|
|
166
174
|
elif change == Change.deleted:
|
|
@@ -184,8 +192,8 @@ class WatchService:
|
|
|
184
192
|
# We don't need to process directories, only the files inside them
|
|
185
193
|
# This prevents errors when trying to compute checksums or read directories as files
|
|
186
194
|
added_full_path = directory / added_path
|
|
187
|
-
if added_full_path.is_dir():
|
|
188
|
-
logger.debug("Skipping
|
|
195
|
+
if not added_full_path.exists() or added_full_path.is_dir():
|
|
196
|
+
logger.debug("Skipping non-existent or directory path", path=added_path)
|
|
189
197
|
processed.add(added_path)
|
|
190
198
|
continue
|
|
191
199
|
|
|
@@ -247,10 +255,12 @@ class WatchService:
|
|
|
247
255
|
if path not in processed:
|
|
248
256
|
# Skip directories - only process files
|
|
249
257
|
full_path = directory / path
|
|
250
|
-
if full_path.is_dir():
|
|
251
|
-
logger.debug(
|
|
252
|
-
|
|
253
|
-
|
|
258
|
+
if not full_path.exists() or full_path.is_dir():
|
|
259
|
+
logger.debug(
|
|
260
|
+
"Skipping non-existent or directory path", path=path
|
|
261
|
+
) # pragma: no cover
|
|
262
|
+
processed.add(path) # pragma: no cover
|
|
263
|
+
continue # pragma: no cover
|
|
254
264
|
|
|
255
265
|
logger.debug("Processing new file", path=path)
|
|
256
266
|
entity, checksum = await self.sync_service.sync_file(path, new=True)
|
|
@@ -281,8 +291,8 @@ class WatchService:
|
|
|
281
291
|
if path not in processed:
|
|
282
292
|
# Skip directories - only process files
|
|
283
293
|
full_path = directory / path
|
|
284
|
-
if full_path.is_dir():
|
|
285
|
-
logger.debug("Skipping directory", path=path)
|
|
294
|
+
if not full_path.exists() or full_path.is_dir():
|
|
295
|
+
logger.debug("Skipping non-existent or directory path", path=path)
|
|
286
296
|
processed.add(path)
|
|
287
297
|
continue
|
|
288
298
|
|
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 []
|