forked from BasedHardware/omi
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathserver.py
More file actions
419 lines (357 loc) · 15.1 KB
/
Copy pathserver.py
File metadata and controls
419 lines (357 loc) · 15.1 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
import os
from enum import Enum
import json
from typing import List, Optional
from datetime import datetime, timedelta
import requests
import logging
from mcp.server import Server
from mcp.server.stdio import stdio_server
from mcp.types import TextContent, Tool
from pydantic import BaseModel, Field
# Shared FieldInfo for the api_key parameter repeated across every MCP tool.
_API_KEY_FIELD = Field(
description="The user's MCP API key. If not provided, it will be read from the OMI_API_KEY environment variable. For more details, see https://docs.omi.me/doc/developer/MCP",
default=None,
)
class MemoryCategory(str, Enum):
core = "core"
hobbies = "hobbies"
lifestyle = "lifestyle"
interests = "interests"
habits = "habits"
work = "work"
skills = "skills"
learnings = "learnings"
other = "other"
class ConversationCategory(str, Enum):
personal = "personal"
education = "education"
health = "health"
finance = "finance"
legal = "legal"
philosophy = "philosophy"
spiritual = "spiritual"
science = "science"
entrepreneurship = "entrepreneurship"
parenting = "parenting"
romance = "romantic"
travel = "travel"
inspiration = "inspiration"
technology = "technology"
business = "business"
social = "social"
work = "work"
sports = "sports"
politics = "politics"
literature = "literature"
history = "history"
architecture = "architecture"
music = "music"
weather = "weather"
news = "news"
entertainment = "entertainment"
psychology = "psychology"
real = "real"
design = "design"
family = "family"
economics = "economics"
environment = "environment"
other = "other"
base_url = os.getenv("OMI_API_BASE_URL", "https://api.omi.me/v1/mcp/")
if not base_url or base_url == "":
raise Exception("Base URL not found")
class OmiTools(str, Enum):
GET_MEMORIES = "get_memories"
SEARCH_MEMORIES = "search_memories"
CREATE_MEMORY = "create_memory"
DELETE_MEMORY = "delete_memory"
EDIT_MEMORY = "edit_memory"
GET_CONVERSATIONS = "get_conversations"
GET_CONVERSATION_BY_ID = "get_conversation_by_id"
SEARCH_CONVERSATIONS = "search_conversations"
class GetMemories(BaseModel):
api_key: Optional[str] = _API_KEY_FIELD
categories: List[MemoryCategory] = Field(description="The categories of memories to filter by.", default=[])
limit: int = Field(description="The number of memories to retrieve.", default=100)
offset: int = Field(description="The offset of the memories to retrieve.", default=0)
class CreateMemory(BaseModel):
api_key: Optional[str] = _API_KEY_FIELD
content: str = Field(description="The content of the memory.")
category: MemoryCategory = Field(description="The category of the memory to create.")
class DeleteMemory(BaseModel):
api_key: Optional[str] = _API_KEY_FIELD
memory_id: str = Field(description="The ID of the memory to delete.")
class EditMemory(BaseModel):
api_key: Optional[str] = _API_KEY_FIELD
memory_id: str = Field(description="The ID of the memory to edit.")
content: str = Field(description="The new content for the memory.")
class SearchMemories(BaseModel):
api_key: Optional[str] = _API_KEY_FIELD
query: str = Field(description="Natural language search query to find relevant memories.")
limit: int = Field(description="Maximum number of results to return.", default=10)
class GetConversations(BaseModel):
api_key: Optional[str] = _API_KEY_FIELD
start_date: Optional[str] = Field(description="Filter conversations after this date (yyyy-mm-dd)", default=None)
end_date: Optional[str] = Field(description="Filter conversations before this date (yyyy-mm-dd)", default=None)
categories: List[ConversationCategory] = Field(description="Filter by conversation categories.", default=[])
limit: int = Field(description="The number of conversations to retrieve.", default=100)
offset: int = Field(description="The offset of the conversations to retrieve.", default=0)
class GetConversationById(BaseModel):
api_key: Optional[str] = _API_KEY_FIELD
conversation_id: str = Field(description="The ID of the conversation to retrieve.")
class SearchConversations(BaseModel):
api_key: Optional[str] = _API_KEY_FIELD
query: str = Field(description="Natural language search query to find relevant conversations.")
limit: int = Field(description="Maximum number of results to return.", default=10)
start_date: Optional[str] = Field(description="Filter conversations after this date (yyyy-mm-dd).", default=None)
end_date: Optional[str] = Field(description="Filter conversations before this date (yyyy-mm-dd).", default=None)
def get_memories(
logger: logging.Logger,
api_key: str,
offset: int = 0,
limit: int = 100,
categories: List[MemoryCategory] = [],
) -> List:
logger.info(f"Getting memories with params: {offset}, {limit}, {categories}")
params = {"offset": offset, "limit": limit}
if categories:
params["categories"] = ",".join([c.value for c in categories])
logger.info(f"get_memories params: {params}")
try:
response = requests.get(
f"{base_url}memories",
params=params,
headers={"Authorization": f"Bearer {api_key}"},
)
logger.info(f"get_memories response: {response.json()}")
return response.json()
except Exception as e:
logger.error(f"Error getting memories: {e}")
raise e
def create_memory(api_key: str, content: str, category: MemoryCategory) -> dict:
response = requests.post(
f"{base_url}memories",
headers={"Authorization": f"Bearer {api_key}"},
json={"content": content, "category": category},
)
return response.json()
def delete_memory(api_key: str, memory_id: str) -> dict:
response = requests.delete(
f"{base_url}memories/{memory_id}",
headers={"Authorization": f"Bearer {api_key}"},
)
return response.json()
def edit_memory(api_key: str, memory_id: str, content: str) -> dict:
response = requests.patch(
f"{base_url}memories/{memory_id}",
headers={"Authorization": f"Bearer {api_key}"},
params={"value": content},
)
return response.json()
def search_memories(
logger: logging.Logger,
api_key: str,
query: str,
limit: int = 10,
) -> List:
logger.info(f"Searching memories with limit={limit}")
response = requests.get(
f"{base_url}memories/search",
params={"query": query, "limit": limit},
headers={"Authorization": f"Bearer {api_key}"},
)
response.raise_for_status()
return response.json()
def get_conversations(
logger: logging.Logger,
api_key: str,
start_date: Optional[str] = None,
end_date: Optional[str] = None,
categories: List[ConversationCategory] = [],
limit: int = 100,
offset: int = 0,
) -> List:
params = {"limit": limit, "offset": offset}
if start_date:
try:
params["start_date"] = datetime.strptime(start_date, "%Y-%m-%d").isoformat()
except ValueError:
logger.warning(f"Could not parse start date: {start_date}")
if end_date:
try:
# Set to end of day (23:59:59) so the entire day is included
params["end_date"] = (datetime.strptime(end_date, "%Y-%m-%d") + timedelta(days=1) - timedelta(seconds=1)).isoformat()
except ValueError:
logger.warning(f"Could not parse end date: {end_date}")
if categories:
params["categories"] = ",".join([c.value for c in categories])
logger.info(f"Getting conversations with params: {params}")
response = requests.get(
f"{base_url}conversations",
params=params,
headers={"Authorization": f"Bearer {api_key}"},
)
return response.json()
def get_conversation_by_id(api_key: str, conversation_id: str) -> dict:
response = requests.get(
f"{base_url}conversations/{conversation_id}",
headers={"Authorization": f"Bearer {api_key}"},
)
return response.json()
def search_conversations(
logger: logging.Logger,
api_key: str,
query: str,
limit: int = 10,
start_date: Optional[str] = None,
end_date: Optional[str] = None,
) -> List:
params = {"query": query, "limit": limit}
if start_date:
params["start_date"] = start_date
if end_date:
params["end_date"] = end_date
logger.info(f"Searching conversations with limit={limit}")
response = requests.get(
f"{base_url}conversations/search",
params=params,
headers={"Authorization": f"Bearer {api_key}"},
)
response.raise_for_status()
return response.json()
async def serve(uid: str | None) -> None:
logger = logging.getLogger(__name__)
# if uid is not None:
# logger.info(f"Using uid: {uid}")
server = Server("mcp-omi")
logger.info("mcp-omi server started")
@server.list_tools()
async def list_tools() -> list[Tool]:
return [
Tool(
name=OmiTools.GET_MEMORIES,
description="Retrieve a list of memories. A memory is a known fact about the user across multiple domains.",
inputSchema=GetMemories.model_json_schema(),
),
Tool(
name=OmiTools.SEARCH_MEMORIES,
description="Semantic search across memories. Returns memories ranked by relevance to a natural language query.",
inputSchema=SearchMemories.model_json_schema(),
),
Tool(
name=OmiTools.CREATE_MEMORY,
description="Create a new memory. A memory is a known fact about the user across multiple domains.",
inputSchema=CreateMemory.model_json_schema(),
),
Tool(
name=OmiTools.DELETE_MEMORY,
description="Delete a memory by ID. A memory is a known fact about the user across multiple domains.",
inputSchema=DeleteMemory.model_json_schema(),
),
Tool(
name=OmiTools.EDIT_MEMORY,
description="Edit a memory's content. A memory is a known fact about the user across multiple domains.",
inputSchema=EditMemory.model_json_schema(),
),
Tool(
name=OmiTools.GET_CONVERSATIONS,
description="Retrieve a list of conversation metadata. To get full transcripts, use get_conversation_by_id.",
inputSchema=GetConversations.model_json_schema(),
),
Tool(
name=OmiTools.GET_CONVERSATION_BY_ID,
description="Retrieve a conversation by ID including each segment of the transcript.",
inputSchema=GetConversationById.model_json_schema(),
),
Tool(
name=OmiTools.SEARCH_CONVERSATIONS,
description="Semantic search across conversations. Returns conversations ranked by relevance to a natural language query.",
inputSchema=SearchConversations.model_json_schema(),
),
]
@server.call_tool()
async def call_tool(name: str, arguments: dict) -> list[TextContent]:
logger.info(f"Calling tool: {name} with arguments: {arguments}")
api_key = arguments.get("api_key") or os.getenv("OMI_API_KEY")
if not api_key:
raise ValueError("API key not provided and OMI_API_KEY environment variable not set.")
if name == OmiTools.GET_MEMORIES:
# return [TextContent(type="text", text=json.dumps(arguments, indent=2))]
categories: List[str] = arguments.get("categories", [])
if not isinstance(categories, list):
raise ValueError(f"categories must be a list, got {type(categories)}")
categories_enum = []
for category in categories:
try:
categories_enum.append(MemoryCategory(category))
except ValueError:
logger.warning(f"Could not parse category: {category}")
result = get_memories(
logger,
api_key,
offset=arguments.get("offset", 0),
limit=arguments.get("limit", 100),
categories=categories_enum,
)
return [TextContent(type="text", text=json.dumps(result, indent=2))]
elif name == OmiTools.SEARCH_MEMORIES:
query = arguments.get("query")
if not query:
raise ValueError("query is required for search_memories")
result = search_memories(
logger,
api_key,
query=query,
limit=arguments.get("limit", 10),
)
return [TextContent(type="text", text=json.dumps(result, indent=2))]
elif name == OmiTools.CREATE_MEMORY:
# return [TextContent(type="text", text=json.dumps(arguments, indent=2))]
result = create_memory(
api_key,
content=arguments["content"],
category=arguments["category"],
)
return [TextContent(type="text", text=json.dumps(result, indent=2))]
elif name == OmiTools.DELETE_MEMORY:
result = delete_memory(api_key, memory_id=arguments["memory_id"])
return [TextContent(type="text", text=json.dumps(result, indent=2))]
elif name == OmiTools.EDIT_MEMORY:
result = edit_memory(
api_key,
memory_id=arguments["memory_id"],
content=arguments["content"],
)
return [TextContent(type="text", text=json.dumps(result, indent=2))]
elif name == OmiTools.GET_CONVERSATIONS:
result = get_conversations(
logger,
api_key,
start_date=arguments.get("start_date"),
end_date=arguments.get("end_date"),
categories=arguments.get("categories", []),
limit=arguments.get("limit", 20),
offset=arguments.get("offset", 0),
)
return [TextContent(type="text", text=json.dumps(result, indent=2))]
elif name == OmiTools.GET_CONVERSATION_BY_ID:
result = get_conversation_by_id(api_key, conversation_id=arguments["conversation_id"])
return [TextContent(type="text", text=json.dumps(result, indent=2))]
elif name == OmiTools.SEARCH_CONVERSATIONS:
query = arguments.get("query")
if not query:
raise ValueError("query is required for search_conversations")
result = search_conversations(
logger,
api_key,
query=query,
limit=arguments.get("limit", 10),
start_date=arguments.get("start_date"),
end_date=arguments.get("end_date"),
)
return [TextContent(type="text", text=json.dumps(result, indent=2))]
raise ValueError(f"Unknown tool: {name}")
options = server.create_initialization_options()
async with stdio_server() as (read_stream, write_stream):
await server.run(read_stream, write_stream, options, raise_exceptions=True)