francischung222 commited on
Commit
e5fcf9f
·
1 Parent(s): 9e4dfcf
servers/emotion_server.py CHANGED
@@ -1,55 +1,4 @@
1
- # # servers/emotion_server.py
2
- # from fastmcp import FastMCP, tool
3
- # import re
4
-
5
- # app = FastMCP("emotion-server")
6
-
7
- # _PATTERNS = {
8
- # "happy": r"\b(happy|grateful|excited|joy|delighted|content|optimistic)\b",
9
- # "sad": r"\b(sad|down|depressed|cry|lonely|upset|miserable)\b",
10
- # "angry": r"\b(angry|mad|furious|irritated|pissed|annoyed|resentful)\b",
11
- # "anxious": r"\b(worried|anxious|nervous|stressed|overwhelmed|scared)\b",
12
- # "tired": r"\b(tired|exhausted|drained|burnt|sleepy|fatigued)\b",
13
- # "love": r"\b(love|affection|caring|fond|admire|cherish)\b",
14
- # "fear": r"\b(afraid|fear|terrified|panicked|shaken)\b",
15
- # }
16
-
17
- # _TONES = {"happy":"light","love":"light","sad":"gentle","fear":"gentle",
18
- # "angry":"calming","anxious":"calming","tired":"gentle"}
19
-
20
- # def _analyze(text: str) -> dict:
21
- # t = text.lower()
22
- # found = [k for k,pat in _PATTERNS.items() if re.search(pat, t)]
23
- # valence = 0.0
24
- # if "happy" in found or "love" in found: valence += 0.6
25
- # if "sad" in found or "fear" in found: valence -= 0.6
26
- # if "angry" in found: valence -= 0.4
27
- # if "anxious" in found: valence -= 0.3
28
- # if "tired" in found: valence -= 0.2
29
- # arousal = 0.5 + (0.3 if ("angry" in found or "anxious" in found) else 0) - (0.2 if "tired" in found else 0)
30
- # tone = "neutral"
31
- # for e in found:
32
- # if e in _TONES: tone = _TONES[e]; break
33
- # return {
34
- # "labels": found or ["neutral"],
35
- # "valence": max(-1, min(1, round(valence, 2))),
36
- # "arousal": max(0, min(1, round(arousal, 2))),
37
- # "tone": tone,
38
- # }
39
-
40
- # @tool
41
- # def analyze(text: str) -> dict:
42
- # """
43
- # Analyze user text for emotion.
44
- # Args:
45
- # text: str - user message
46
- # Returns: dict {labels, valence, arousal, tone}
47
- # """
48
- # return _analyze(text)
49
-
50
- # if __name__ == "__main__":
51
- # app.run() # serves MCP over stdio
52
- # servers/emotion_server.py
53
  from __future__ import annotations
54
 
55
  # ---- FastMCP import shim (works across versions) ----
 
1
+
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
2
  from __future__ import annotations
3
 
4
  # ---- FastMCP import shim (works across versions) ----
servers/emotion_server.py.bak DELETED
@@ -1,377 +0,0 @@
1
- # # servers/emotion_server.py
2
- # from fastmcp import FastMCP, tool
3
- # import re
4
-
5
- # app = FastMCP("emotion-server")
6
-
7
- # _PATTERNS = {
8
- # "happy": r"\b(happy|grateful|excited|joy|delighted|content|optimistic)\b",
9
- # "sad": r"\b(sad|down|depressed|cry|lonely|upset|miserable)\b",
10
- # "angry": r"\b(angry|mad|furious|irritated|pissed|annoyed|resentful)\b",
11
- # "anxious": r"\b(worried|anxious|nervous|stressed|overwhelmed|scared)\b",
12
- # "tired": r"\b(tired|exhausted|drained|burnt|sleepy|fatigued)\b",
13
- # "love": r"\b(love|affection|caring|fond|admire|cherish)\b",
14
- # "fear": r"\b(afraid|fear|terrified|panicked|shaken)\b",
15
- # }
16
-
17
- # _TONES = {"happy":"light","love":"light","sad":"gentle","fear":"gentle",
18
- # "angry":"calming","anxious":"calming","tired":"gentle"}
19
-
20
- # def _analyze(text: str) -> dict:
21
- # t = text.lower()
22
- # found = [k for k,pat in _PATTERNS.items() if re.search(pat, t)]
23
- # valence = 0.0
24
- # if "happy" in found or "love" in found: valence += 0.6
25
- # if "sad" in found or "fear" in found: valence -= 0.6
26
- # if "angry" in found: valence -= 0.4
27
- # if "anxious" in found: valence -= 0.3
28
- # if "tired" in found: valence -= 0.2
29
- # arousal = 0.5 + (0.3 if ("angry" in found or "anxious" in found) else 0) - (0.2 if "tired" in found else 0)
30
- # tone = "neutral"
31
- # for e in found:
32
- # if e in _TONES: tone = _TONES[e]; break
33
- # return {
34
- # "labels": found or ["neutral"],
35
- # "valence": max(-1, min(1, round(valence, 2))),
36
- # "arousal": max(0, min(1, round(arousal, 2))),
37
- # "tone": tone,
38
- # }
39
-
40
- # @tool
41
- # def analyze(text: str) -> dict:
42
- # """
43
- # Analyze user text for emotion.
44
- # Args:
45
- # text: str - user message
46
- # Returns: dict {labels, valence, arousal, tone}
47
- # """
48
- # return _analyze(text)
49
-
50
- # if __name__ == "__main__":
51
- # app.run() # serves MCP over stdio
52
- # servers/emotion_server.py
53
- from __future__ import annotations
54
- # ---- FastMCP import shim (works across versions) ----
55
- # Ensures: FastMCP is imported and `@tool` is ALWAYS a callable decorator.
56
- from typing import Callable, Any
57
-
58
- try:
59
- from fastmcp import FastMCP # present across versions
60
- except Exception as e:
61
- raise ImportError(f"FastMCP missing: {e}")
62
-
63
- _tool_candidate: Any = None
64
- # Try common locations
65
- try:
66
- from fastmcp import tool as _tool_candidate # newer API: function
67
- except Exception:
68
- try:
69
- from fastmcp.tools import tool as _tool_candidate # older API: function
70
- except Exception:
71
- _tool_candidate = None
72
-
73
- # If we somehow got a module instead of a function, try attribute
74
- if _tool_candidate is not None and not callable(_tool_candidate):
75
- try:
76
- _tool_candidate = _tool_candidate.tool # some builds expose module.tools.tool
77
- except Exception:
78
- _tool_candidate = None
79
-
80
- def tool(*dargs, **dkwargs):
81
- """
82
- Wrapper that behaves correctly in both usages:
83
- @tool
84
- @tool(...)
85
- If real decorator exists, delegate. Otherwise:
86
- - If called as @tool (i.e., first arg is fn), return fn (no-op).
87
- - If called as @tool(...), return a decorator that returns fn (no-op).
88
- """
89
- if callable(_tool_candidate):
90
- return _tool_candidate(*dargs, **dkwargs)
91
-
92
- # No real decorator available — provide no-op behavior.
93
- if dargs and callable(dargs[0]) and not dkwargs:
94
- # Used as @tool
95
- fn = dargs[0]
96
- return fn
97
-
98
- # Used as @tool(...)
99
- def _noop_decorator(fn):
100
- return fn
101
- return _noop_decorator
102
- # ---- end shim ----
103
-
104
-
105
- import re, math, time
106
- from typing import Dict, List, Tuple, Optional
107
-
108
- app = FastMCP("emotion-server")
109
-
110
- # ---------------------------
111
- # Lexicons & heuristics
112
- # ---------------------------
113
- EMO_LEX = {
114
- "happy": r"\b(happy|grateful|excited|joy(?:ful)?|delighted|content|optimistic|glad|thrilled|yay)\b",
115
- "sad": r"\b(sad|down|depress(?:ed|ing)|cry(?:ing)?|lonely|upset|miserable|heartbroken)\b",
116
- "angry": r"\b(angry|mad|furious|irritated|pissed|annoyed|resentful|rage|hate)\b",
117
- "anxious": r"\b(worried|anxious|nervous|stressed|overwhelmed|scared|uneasy|tense|on edge)\b",
118
- "tired": r"\b(tired|exhaust(?:ed|ing)|drained|burnt(?:\s*out)?|sleepy|fatigued|worn out)\b",
119
- "love": r"\b(love|affection|caring|fond|admire|cherish|adore)\b",
120
- "fear": r"\b(afraid|fear|terrified|panic(?:ky|ked)?|panicked|shaken|petrified)\b",
121
- }
122
-
123
- # Emojis contribute signals even without words
124
- EMOJI_SIGNAL = {
125
- "happy": ["😀","😄","😊","🙂","😁","🥳","✨"],
126
- "sad": ["😢","😭","😞","😔","☹️"],
127
- "angry": ["😠","😡","🤬","💢"],
128
- "anxious":["😰","😱","😬","😟","😧"],
129
- "tired": ["🥱","😪","😴"],
130
- "love": ["❤️","💖","💕","😍","🤍","💗","💓","😘"],
131
- "fear": ["🫣","😨","😱","👀"],
132
- }
133
-
134
- NEGATORS = r"\b(no|not|never|hardly|barely|scarcely|isn['’]t|aren['’]t|can['’]t|don['’]t|doesn['’]t|won['’]t|without)\b"
135
- INTENSIFIERS = {
136
- r"\b(very|really|super|so|extremely|incredibly|totally|absolutely)\b": 1.35,
137
- r"\b(kinda|kind of|somewhat|slightly|a bit|a little)\b": 0.75,
138
- }
139
- SARCASM_CUES = [
140
- r"\byeah right\b", r"\bsure\b", r"\".+\"", r"/s\b", r"\bokayyy+\b", r"\blol\b(?!\w)"
141
- ]
142
-
143
- # Tone map by quadrant
144
- # arousal high/low × valence pos/neg
145
- def quad_tone(valence: float, arousal: float) -> str:
146
- if arousal >= 0.6 and valence >= 0.1: return "excited"
147
- if arousal >= 0.6 and valence < -0.1: return "concerned"
148
- if arousal < 0.6 and valence < -0.1: return "gentle"
149
- if arousal < 0.6 and valence >= 0.1: return "calm"
150
- return "neutral"
151
-
152
- # ---------------------------
153
- # Utilities
154
- # ---------------------------
155
- _compiled = {k: re.compile(p, re.I) for k, p in EMO_LEX.items()}
156
- _neg_pat = re.compile(NEGATORS, re.I)
157
- _int_pats = [(re.compile(p, re.I), w) for p, w in INTENSIFIERS.items()]
158
- _sarcasm = [re.compile(p, re.I) for p in SARCASM_CUES]
159
-
160
- def _emoji_hits(text: str) -> Dict[str, int]:
161
- hits = {k: 0 for k in EMO_LEX}
162
- for emo, arr in EMOJI_SIGNAL.items():
163
- for e in arr:
164
- hits[emo] += text.count(e)
165
- return hits
166
-
167
- def _intensity_multiplier(text: str) -> float:
168
- mult = 1.0
169
- for pat, w in _int_pats:
170
- if pat.search(text):
171
- mult *= w
172
- # Exclamation marks increase arousal a bit (cap effect)
173
- bangs = min(text.count("!"), 5)
174
- mult *= (1.0 + 0.04 * bangs)
175
- # ALL CAPS word run nudges intensity
176
- if re.search(r"\b[A-Z]{3,}\b", text):
177
- mult *= 1.08
178
- return max(0.5, min(1.8, mult))
179
-
180
- def _negation_factor(text: str, span_start: int) -> float:
181
- """
182
- Look 5 words (~40 chars) backwards for a negator.
183
- If present, invert or dampen signal.
184
- """
185
- window_start = max(0, span_start - 40)
186
- window = text[window_start:span_start]
187
- if _neg_pat.search(window):
188
- return -0.7 # invert and dampen
189
- return 1.0
190
-
191
- def _sarcasm_penalty(text: str) -> float:
192
- return 0.85 if any(p.search(text) for p in _sarcasm) else 1.0
193
-
194
- def _softmax(d: Dict[str, float]) -> Dict[str, float]:
195
- xs = list(d.values())
196
- if not xs: return d
197
- m = max(xs)
198
- exps = [math.exp(x - m) for x in xs]
199
- s = sum(exps) or 1.0
200
- return {k: exps[i] / s for i, k in enumerate(d.keys())}
201
-
202
- # ---------------------------
203
- # Per-user calibration (in-memory)
204
- # ---------------------------
205
- CALIBRATION: Dict[str, Dict[str, float]] = {} # user_id -> {bias_emo: float, arousal_bias: float, valence_bias: float}
206
-
207
- def _apply_calibration(user_id: Optional[str], emo_scores: Dict[str, float], valence: float, arousal: float):
208
- if not user_id or user_id not in CALIBRATION:
209
- return emo_scores, valence, arousal
210
- calib = CALIBRATION[user_id]
211
- # shift emotions
212
- for k, bias in calib.items():
213
- if k in emo_scores:
214
- emo_scores[k] += bias * 0.2
215
- # dedicated valence/arousal bias keys if present
216
- valence += calib.get("valence_bias", 0.0) * 0.15
217
- arousal += calib.get("arousal_bias", 0.0) * 0.15
218
- return emo_scores, valence, arousal
219
-
220
- # ---------------------------
221
- # Core analysis
222
- # ---------------------------
223
- def _analyze(text: str, user_id: Optional[str] = None) -> dict:
224
- t = text or ""
225
- tl = t.lower()
226
-
227
- # Base scores from lexicon hits
228
- emo_scores: Dict[str, float] = {k: 0.0 for k in EMO_LEX}
229
- spans: Dict[str, List[Tuple[int, int, str]]] = {k: [] for k in EMO_LEX}
230
-
231
- for emo, pat in _compiled.items():
232
- for m in pat.finditer(tl):
233
- factor = _negation_factor(tl, m.start())
234
- emo_scores[emo] += 1.0 * factor
235
- spans[emo].append((m.start(), m.end(), tl[m.start():m.end()]))
236
-
237
- # Emoji contributions
238
- e_hits = _emoji_hits(t)
239
- for emo, c in e_hits.items():
240
- if c:
241
- emo_scores[emo] += 0.6 * c
242
-
243
- # Intensifiers / sarcasm / punctuation adjustments (global)
244
- intensity = _intensity_multiplier(t)
245
- sarcasm_mult = _sarcasm_penalty(t)
246
-
247
- for emo in emo_scores:
248
- emo_scores[emo] *= intensity * sarcasm_mult
249
-
250
- # Map to valence/arousal
251
- pos = emo_scores["happy"] + emo_scores["love"]
252
- neg = emo_scores["sad"] + emo_scores["fear"] + 0.9 * emo_scores["angry"] + 0.6 * emo_scores["anxious"]
253
- valence = max(-1.0, min(1.0, round((pos - neg) * 0.4, 3)))
254
-
255
- base_arousal = 0.5
256
- arousal = base_arousal \
257
- + 0.12 * (emo_scores["angry"] > 0) \
258
- + 0.08 * (emo_scores["anxious"] > 0) \
259
- - 0.10 * (emo_scores["tired"] > 0) \
260
- + 0.02 * min(t.count("!"), 5)
261
-
262
- arousal = max(0.0, min(1.0, round(arousal, 3)))
263
-
264
- # Confidence: count signals + consistency
265
- hits = sum(1 for v in emo_scores.values() if abs(v) > 0.01) + sum(e_hits.values())
266
- consistency = 0.0
267
- if hits:
268
- top2 = sorted(emo_scores.items(), key=lambda kv: kv[1], reverse=True)[:2]
269
- if len(top2) == 2 and top2[1][1] > 0:
270
- ratio = top2[0][1] / (top2[1][1] + 1e-6)
271
- consistency = max(0.0, min(1.0, (ratio - 1) / 3)) # >1 means some separation
272
- elif len(top2) == 1:
273
- consistency = 0.6
274
- conf = max(0.0, min(1.0, 0.25 + 0.1 * hits + 0.5 * consistency))
275
- # downweight very short texts
276
- if len(t.strip()) < 6:
277
- conf *= 0.6
278
-
279
- # Normalize emotions to pseudo-probs (softmax over positive scores)
280
- pos_scores = {k: max(0.0, v) for k, v in emo_scores.items()}
281
- probs = _softmax(pos_scores)
282
-
283
- # Apply per-user calibration
284
- probs, valence, arousal = _apply_calibration(user_id, probs, valence, arousal)
285
-
286
- # Tone
287
- tone = quad_tone(valence, arousal)
288
-
289
- # Explanations
290
- reasons = []
291
- if intensity > 1.0: reasons.append(f"intensifiers x{intensity:.2f}")
292
- if sarcasm_mult < 1.0: reasons.append("sarcasm cues detected")
293
- if any(_neg_pat.search(tl[max(0,s-40):s]) for emo, spans_ in spans.items() for (s,_,_) in spans_):
294
- reasons.append("negation near emotion tokens")
295
- if any(e_hits.values()): reasons.append("emoji signals")
296
-
297
- labels_sorted = sorted(probs.items(), key=lambda kv: kv[1], reverse=True)
298
- top_labels = [k for k, v in labels_sorted[:3] if v > 0.05] or ["neutral"]
299
-
300
- return {
301
- "labels": top_labels,
302
- "scores": {k: round(v, 3) for k, v in probs.items()},
303
- "valence": round(valence, 3),
304
- "arousal": round(arousal, 3),
305
- "tone": tone,
306
- "confidence": round(conf, 3),
307
- "reasons": reasons,
308
- "spans": {k: spans[k] for k in top_labels if spans.get(k)},
309
- "ts": time.time(),
310
- "user_id": user_id,
311
- }
312
-
313
- # ---------------------------
314
- # MCP tools
315
- # ---------------------------
316
-
317
- @app.tool()
318
- def analyze(text: str, user_id: Optional[str] = None) -> dict:
319
- """
320
- Analyze text for emotion.
321
- Args:
322
- text: user message
323
- user_id: optional user key for calibration
324
- Returns:
325
- dict with labels, scores (per emotion), valence [-1..1], arousal [0..1],
326
- tone (calm/neutral/excited/concerned/gentle), confidence, reasons, spans.
327
- """
328
- return _analyze(text, user_id=user_id)
329
-
330
- @app.tool()
331
- def batch_analyze(messages: List[str], user_id: Optional[str] = None) -> List[dict]:
332
- """
333
- Batch analyze a list of messages.
334
- """
335
- return [_analyze(m or "", user_id=user_id) for m in messages]
336
-
337
- @app.tool()
338
- def calibrate(user_id: str, bias: Dict[str, float] = None, arousal_bias: float = 0.0, valence_bias: float = 0.0) -> dict:
339
- """
340
- Adjust per-user calibration.
341
- - bias: e.g. {"anxious": -0.1, "love": 0.1}
342
- - arousal_bias/valence_bias: small nudges (-1..1) applied after scoring.
343
- """
344
- if user_id not in CALIBRATION:
345
- CALIBRATION[user_id] = {}
346
- if bias:
347
- for k, v in bias.items():
348
- CALIBRATION[user_id][k] = float(v)
349
- if arousal_bias:
350
- CALIBRATION[user_id]["arousal_bias"] = float(arousal_bias)
351
- if valence_bias:
352
- CALIBRATION[user_id]["valence_bias"] = float(valence_bias)
353
- return {"ok": True, "calibration": CALIBRATION[user_id]}
354
-
355
- @app.tool()
356
- def reset_calibration(user_id: str) -> dict:
357
- """Remove per-user calibration."""
358
- CALIBRATION.pop(user_id, None)
359
- return {"ok": True}
360
-
361
- @app.tool()
362
- def health() -> dict:
363
- """Simple health check for MCP status chips."""
364
- return {"status": "ok", "version": "1.2.0", "time": time.time()}
365
-
366
- @app.tool()
367
- def version() -> dict:
368
- """Return server version & feature flags."""
369
- return {
370
- "name": "emotion-server",
371
- "version": "1.2.0",
372
- "features": ["negation", "intensifiers", "emoji", "sarcasm", "confidence", "batch", "calibration"],
373
- "emotions": list(EMO_LEX.keys()),
374
- }
375
-
376
- if __name__ == "__main__":
377
- app.run() # serves MCP over stdio
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
servers/memory_server.py CHANGED
@@ -1,47 +1,4 @@
1
- # # servers/memory_server.py
2
- # from fastmcp import FastMCP, tool
3
- # import json, os, time
4
-
5
- # app = FastMCP("memory-server")
6
- # FILE = os.environ.get("GM_MEMORY_FILE", "memory.json")
7
-
8
- # def _load():
9
- # if os.path.exists(FILE):
10
- # with open(FILE) as f: return json.load(f)
11
- # return []
12
-
13
- # def _save(history):
14
- # with open(FILE, "w") as f: json.dump(history[-50:], f) # keep up to 50
15
-
16
- # @tool
17
- # def remember(text: str, meta: dict | None = None) -> dict:
18
- # """
19
- # Append an entry to memory.
20
- # Args:
21
- # text: str - content to store
22
- # meta: dict - optional info like {"tone":"gentle","labels":["sad"]}
23
- # Returns: {"ok": True, "size": <n>}
24
- # """
25
- # data = _load()
26
- # data.append({"t": int(time.time()), "text": text, "meta": meta or {}})
27
- # _save(data)
28
- # return {"ok": True, "size": len(data)}
29
-
30
- # @tool
31
- # def recall(k: int = 3) -> dict:
32
- # """
33
- # Return last k entries from memory (most recent last).
34
- # Args:
35
- # k: int - how many items
36
- # Returns: {"items":[...]}
37
- # """
38
- # data = _load()
39
- # return {"items": data[-k:]}
40
-
41
- # if __name__ == "__main__":
42
- # app.run()
43
- # servers/memory_server.py
44
- # servers/memory_server.py
45
  from __future__ import annotations
46
  # ---- FastMCP import shim (works across versions) ----
47
  # Ensures: FastMCP is imported and `@tool` is ALWAYS a callable decorator.
 
1
+
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
2
  from __future__ import annotations
3
  # ---- FastMCP import shim (works across versions) ----
4
  # Ensures: FastMCP is imported and `@tool` is ALWAYS a callable decorator.
servers/memory_server.py.bak DELETED
@@ -1,570 +0,0 @@
1
- # # servers/memory_server.py
2
- # from fastmcp import FastMCP, tool
3
- # import json, os, time
4
-
5
- # app = FastMCP("memory-server")
6
- # FILE = os.environ.get("GM_MEMORY_FILE", "memory.json")
7
-
8
- # def _load():
9
- # if os.path.exists(FILE):
10
- # with open(FILE) as f: return json.load(f)
11
- # return []
12
-
13
- # def _save(history):
14
- # with open(FILE, "w") as f: json.dump(history[-50:], f) # keep up to 50
15
-
16
- # @tool
17
- # def remember(text: str, meta: dict | None = None) -> dict:
18
- # """
19
- # Append an entry to memory.
20
- # Args:
21
- # text: str - content to store
22
- # meta: dict - optional info like {"tone":"gentle","labels":["sad"]}
23
- # Returns: {"ok": True, "size": <n>}
24
- # """
25
- # data = _load()
26
- # data.append({"t": int(time.time()), "text": text, "meta": meta or {}})
27
- # _save(data)
28
- # return {"ok": True, "size": len(data)}
29
-
30
- # @tool
31
- # def recall(k: int = 3) -> dict:
32
- # """
33
- # Return last k entries from memory (most recent last).
34
- # Args:
35
- # k: int - how many items
36
- # Returns: {"items":[...]}
37
- # """
38
- # data = _load()
39
- # return {"items": data[-k:]}
40
-
41
- # if __name__ == "__main__":
42
- # app.run()
43
- # servers/memory_server.py
44
- # servers/memory_server.py
45
- from __future__ import annotations
46
- # ---- FastMCP import shim (works across versions) ----
47
- # Ensures: FastMCP is imported and `@tool` is ALWAYS a callable decorator.
48
- from typing import Callable, Any
49
-
50
- try:
51
- from fastmcp import FastMCP # present across versions
52
- except Exception as e:
53
- raise ImportError(f"FastMCP missing: {e}")
54
-
55
- _tool_candidate: Any = None
56
- # Try common locations
57
- try:
58
- from fastmcp import tool as _tool_candidate # newer API: function
59
- except Exception:
60
- try:
61
- from fastmcp.tools import tool as _tool_candidate # older API: function
62
- except Exception:
63
- _tool_candidate = None
64
-
65
- # If we somehow got a module instead of a function, try attribute
66
- if _tool_candidate is not None and not callable(_tool_candidate):
67
- try:
68
- _tool_candidate = _tool_candidate.tool # some builds expose module.tools.tool
69
- except Exception:
70
- _tool_candidate = None
71
-
72
- def tool(*dargs, **dkwargs):
73
- """
74
- Wrapper that behaves correctly in both usages:
75
- @tool
76
- @tool(...)
77
- If real decorator exists, delegate. Otherwise:
78
- - If called as @tool (i.e., first arg is fn), return fn (no-op).
79
- - If called as @tool(...), return a decorator that returns fn (no-op).
80
- """
81
- if callable(_tool_candidate):
82
- return _tool_candidate(*dargs, **dkwargs)
83
-
84
- # No real decorator available — provide no-op behavior.
85
- if dargs and callable(dargs[0]) and not dkwargs:
86
- # Used as @tool
87
- fn = dargs[0]
88
- return fn
89
-
90
- # Used as @tool(...)
91
- def _noop_decorator(fn):
92
- return fn
93
- return _noop_decorator
94
- # ---- end shim ----
95
-
96
-
97
- import json, os, time, math, re
98
- from typing import Dict, List, Optional, Any, Tuple
99
- from collections import Counter
100
-
101
- app = FastMCP("memory-server")
102
-
103
- # ---------------------------
104
- # Storage & limits
105
- # ---------------------------
106
- FILE = os.environ.get("GM_MEMORY_FILE", "memory.json")
107
- STM_MAX = int(os.environ.get("GM_STM_MAX", "120"))
108
- EP_MAX = int(os.environ.get("GM_EPISODES_MAX", "240"))
109
- FACT_MAX= int(os.environ.get("GM_FACTS_MAX", "200"))
110
- # ---------------------------
111
- # Emotion Drift Analysis
112
- # ---------------------------
113
- def compute_emotional_direction(trajectory: List[Dict[str, Any]]) -> str:
114
- """
115
- Analyze emotion trajectory to detect escalation/de-escalation/volatility/stability.
116
- trajectory: list of {"label": str, "valence": float, "arousal": float, "ts": int}
117
- """
118
- if len(trajectory) < 2:
119
- return "stable"
120
-
121
- # Get last 5 emotions for trend
122
- recent = trajectory[-5:]
123
- valences = [e.get("valence", 0.0) for e in recent]
124
- arousals = [e.get("arousal", 0.5) for e in recent]
125
-
126
- # Detect trend
127
- valence_trend = valences[-1] - valences[0] # negative = more negative, positive = more positive
128
- arousal_trend = arousals[-1] - arousals[0] # positive = escalating
129
-
130
- # Classify
131
- if arousal_trend > 0.15 and valence_trend < -0.1:
132
- return "escalating" # Getting more activated and negative
133
- elif arousal_trend < -0.15 and valence_trend > 0.1:
134
- return "de-escalating" # Calming down and more positive
135
- elif max(arousals) - min(arousals) > 0.3:
136
- return "volatile" # Wide swings in arousal
137
- else:
138
- return "stable"
139
-
140
- def get_emotion_trajectory(store: Dict[str, Any], k: int = 10) -> Tuple[List[Dict[str, Any]], str]:
141
- """
142
- Returns last k emotion events from memory and the trajectory direction.
143
- """
144
- stm = store.get("stm", [])
145
- trajectory = []
146
-
147
- for item in stm[-k:]:
148
- event = item.get("event", {})
149
- emotion = event.get("emotion", {})
150
- if emotion and emotion.get("labels"):
151
- trajectory.append({
152
- "label": (emotion.get("labels") or ["neutral"])[0],
153
- "valence": float(emotion.get("valence", 0.0)),
154
- "arousal": float(emotion.get("arousal", 0.5)),
155
- "ts": event.get("ts", int(time.time())),
156
- "text": event.get("text", "")[:50] # First 50 chars
157
- })
158
-
159
- direction = compute_emotional_direction(trajectory)
160
- return trajectory, direction
161
- # ---------------------------
162
- # File helpers & migrations
163
- # ---------------------------
164
- def _default_store() -> Dict[str, Any]:
165
- return {"stm": [], "episodes": [], "facts": [], "meta": {"created": int(time.time()), "version": "1.3.0"}}
166
-
167
- def _load() -> Dict[str, Any]:
168
- if os.path.exists(FILE):
169
- with open(FILE) as f:
170
- try:
171
- data = json.load(f)
172
- # migrate flat list → tiered
173
- if isinstance(data, list):
174
- data = {"stm": data[-STM_MAX:], "episodes": [], "facts": [], "meta": {"created": int(time.time()), "version": "1.3.0"}}
175
- # backfill ids in stm
176
- changed = False
177
- for i, it in enumerate(data.get("stm", [])):
178
- if "id" not in it:
179
- it["id"] = f"stm-{it.get('t', int(time.time()))}-{i}"
180
- changed = True
181
- if changed:
182
- _save(data)
183
- return data
184
- except Exception:
185
- return _default_store()
186
- return _default_store()
187
-
188
- def _save(store: Dict[str, Any]) -> None:
189
- store["stm"] = store.get("stm", [])[-STM_MAX:]
190
- store["episodes"] = store.get("episodes", [])[-EP_MAX:]
191
- store["facts"] = store.get("facts", [])[-FACT_MAX:]
192
- with open(FILE, "w") as f:
193
- json.dump(store, f, ensure_ascii=False)
194
-
195
- # ---------------------------
196
- # Salience & decay (same as before)
197
- # ---------------------------
198
- def time_decay(ts: float, now: Optional[float] = None, half_life_hours: float = 72.0) -> float:
199
- now = now or time.time()
200
- dt_h = max(0.0, (now - ts) / 3600.0)
201
- return 0.5 ** (dt_h / half_life_hours)
202
-
203
- _WORD = re.compile(r"[a-zA-Z']+")
204
-
205
- def keyword_set(text: str) -> set:
206
- return set(w.lower() for w in _WORD.findall(text or "") if len(w) > 2)
207
-
208
- def novelty_score(text: str, recent_texts: List[str], k: int = 10) -> float:
209
- if not text:
210
- return 0.0
211
- A = keyword_set(text)
212
- if not A:
213
- return 0.0
214
- recent = [keyword_set(t) for t in recent_texts[-k:] if t]
215
- if not recent:
216
- return 1.0
217
- sims = []
218
- for B in recent:
219
- inter = len(A & B)
220
- union = len(A | B) or 1
221
- sims.append(inter / union)
222
- sim = max(sims) if sims else 0.0
223
- return max(0.0, 1.0 - sim)
224
-
225
- def compute_salience(ev: Dict[str, Any], recent_texts: List[str]) -> float:
226
- labels = ev.get("emotion", {}).get("labels") or []
227
- conf = float(ev.get("emotion", {}).get("confidence") or 0.0)
228
- valence= float(ev.get("emotion", {}).get("valence") or 0.0)
229
- arousal= float(ev.get("emotion", {}).get("arousal") or 0.5)
230
- sinc = float(ev.get("sincerity") or 0.0) / 100.0
231
- text = ev.get("text", "")
232
-
233
- affect = abs(valence) * (0.7 + 0.3 * arousal) * conf
234
- nov = novelty_score(text, recent_texts)
235
- user_flag = 1.0 if ev.get("user_pinned") else 0.0
236
- boundary = 1.0 if ev.get("task_boundary") else 0.0
237
-
238
- sal = 0.45 * affect + 0.25 * nov + 0.18 * user_flag + 0.12 * boundary + 0.10 * sinc
239
- return round(max(0.0, min(1.0, sal)), 3)
240
-
241
- # ---------------------------
242
- # Episode & fact synthesis
243
- # ---------------------------
244
- def make_episode(ev: Dict[str, Any], salience: float) -> Dict[str, Any]:
245
- emo = ev.get("emotion", {})
246
- return {
247
- "episode_id": ev.get("id") or f"ep-{int(time.time()*1000)}",
248
- "ts_start": ev.get("ts") or int(time.time()),
249
- "ts_end": ev.get("ts") or int(time.time()),
250
- "summary": ev.get("summary") or (ev.get("text")[:140] if ev.get("text") else ""),
251
- "topics": list(set(emo.get("labels") or [])) or ["misc"],
252
- "emotion_peak": (emo.get("labels") or ["neutral"])[0],
253
- "emotion_conf": float(emo.get("confidence") or 0.0),
254
- "tone": emo.get("tone") or "neutral",
255
- "salience": float(salience),
256
- "provenance_event": ev.get("id"),
257
- }
258
-
259
- def cluster_topics(episodes: List[Dict[str, Any]]) -> Dict[str, List[Dict[str, Any]]]:
260
- buckets: Dict[str, List[Dict[str, Any]]] = {}
261
- for ep in episodes:
262
- for t in ep.get("topics") or ["misc"]:
263
- buckets.setdefault(t, []).append(ep)
264
- return buckets
265
-
266
- def synthesize_fact(topic: str, eps: List[Dict[str, Any]]) -> Optional[Dict[str, Any]]:
267
- if not eps:
268
- return None
269
- support = len(eps)
270
- avg_sal = sum(e.get("salience", 0.0) for e in eps) / max(1, support)
271
- avg_conf= sum(e.get("emotion_conf", 0.0) for e in eps) / max(1, support)
272
- conf = max(0.0, min(1.0, 0.5 * avg_sal + 0.5 * avg_conf))
273
- if support < 3 or conf < 0.6:
274
- return None
275
- tones = {}
276
- for e in eps: tones[e.get("tone", "neutral")] = tones.get(e.get("tone", "neutral"), 0) + 1
277
- top_tone = sorted(tones.items(), key=lambda kv: kv[1], reverse=True)[0][0]
278
- return {
279
- "fact_id": f"fact-{topic}-{int(time.time())}",
280
- "proposition": f"Prefers {top_tone} tone for topic '{topic}'",
281
- "support": support,
282
- "confidence": round(conf, 2),
283
- "last_updated": int(time.time()),
284
- "topics": [topic],
285
- "provenance_episode_ids": [e["episode_id"] for e in eps],
286
- }
287
-
288
- # ---------------------------
289
- # ID helpers
290
- # ---------------------------
291
- def _ensure_stm_id(item: Dict[str, Any], idx: int) -> Dict[str, Any]:
292
- if "id" not in item:
293
- item["id"] = f"stm-{item.get('t', int(time.time()))}-{idx}"
294
- return item
295
-
296
- def _stm_text(item: Dict[str, Any]) -> str:
297
- if "text" in item and isinstance(item["text"], str):
298
- return item["text"]
299
- return (item.get("event") or {}).get("text", "") or ""
300
-
301
- def _collect_docs(store: Dict[str, Any], tier: Optional[str] = None) -> List[Tuple[str,str,str,int]]:
302
- """
303
- Returns list of (id, tier, text, ts)
304
- """
305
- docs: List[Tuple[str,str,str,int]] = []
306
- if tier in (None, "stm"):
307
- for i, it in enumerate(store.get("stm", [])):
308
- it = _ensure_stm_id(it, i)
309
- docs.append((it["id"], "stm", _stm_text(it), int(it.get("t", time.time()))))
310
- if tier in (None, "episodes"):
311
- for ep in store.get("episodes", []):
312
- docs.append((ep.get("episode_id",""), "episodes", ep.get("summary",""), int(ep.get("ts_end", time.time()))))
313
- if tier in (None, "facts"):
314
- for f in store.get("facts", []):
315
- docs.append((f.get("fact_id",""), "facts", f.get("proposition",""), int(f.get("last_updated", time.time()))))
316
- return [d for d in docs if d[0] and d[2]]
317
-
318
- # ---------------------------
319
- # Simple TF-IDF search
320
- # ---------------------------
321
- def _tfidf_rank(query: str, docs: List[Tuple[str,str,str,int]], k: int = 5):
322
- q_terms = [w for w in keyword_set(query)]
323
- if not q_terms or not docs:
324
- return []
325
- # DF
326
- df = Counter()
327
- doc_terms = {}
328
- for _id, _tier, text, _ts in docs:
329
- terms = [w for w in keyword_set(text)]
330
- doc_terms[_id] = terms
331
- for t in set(terms):
332
- df[t] += 1
333
- N = len(docs)
334
- idf = {t: math.log((N + 1) / (df[t] + 1)) + 1.0 for t in df}
335
- # Score
336
- scored = []
337
- qset = set(q_terms)
338
- for _id, _tier, text, _ts in docs:
339
- terms = doc_terms[_id]
340
- tf = Counter(terms)
341
- score = 0.0
342
- matched = []
343
- for t in q_terms:
344
- if tf[t] > 0:
345
- score += tf[t] * idf.get(t, 1.0)
346
- matched.append(t)
347
- if score > 0:
348
- scored.append((_id, _tier, text, _ts, score, matched))
349
- scored.sort(key=lambda x: (-x[4], -x[3])) # score desc, then recent
350
- return scored[:k]
351
-
352
- # ---------------------------
353
- # Tools (API)
354
- # ---------------------------
355
-
356
- @tool
357
- def remember(text: str, meta: dict | None = None) -> dict:
358
- store = _load()
359
- item = {"t": int(time.time()), "text": text, "meta": meta or {}}
360
- item["id"] = f"stm-{item['t']}-{len(store.get('stm', []))}"
361
- store["stm"].append(item)
362
- _save(store)
363
- return {"ok": True, "stm_size": len(store["stm"]), "id": item["id"]}
364
-
365
- @tool
366
- def remember_event(event: dict, promote: bool = True) -> dict:
367
- store = _load()
368
- ev = dict(event or {})
369
- ev.setdefault("ts", int(time.time()))
370
- ev.setdefault("role", "user")
371
- ev.setdefault("text", "")
372
- if "salience" not in ev:
373
- recent_texts = [it.get("text","") for it in store.get("stm", [])[-10:]]
374
- ev["salience"] = compute_salience(ev, recent_texts)
375
- stm_item = {
376
- "id": f"stm-{ev['ts']}-{len(store.get('stm', []))}",
377
- "t": ev["ts"],
378
- "text": ev.get("text",""),
379
- "event": ev
380
- }
381
- store["stm"].append(stm_item)
382
- if promote:
383
- aff_conf = float(ev.get("emotion", {}).get("confidence") or 0.0)
384
- if ev["salience"] >= 0.45 or ev.get("user_pinned") or ev.get("task_boundary"):
385
- ep = make_episode(ev, ev["salience"])
386
- store["episodes"].append(ep)
387
- _save(store)
388
- return {"ok": True, "salience": ev["salience"], "id": stm_item["id"],
389
- "sizes": {"stm": len(store["stm"]), "episodes": len(store["episodes"]), "facts": len(store["facts"])}}
390
-
391
- @tool
392
- def recall(k: int = 3) -> dict:
393
- store = _load()
394
- items = store.get("stm", [])[-k:]
395
- return {"items": items}
396
-
397
- @tool
398
- def recall_episodes(k: int = 5, topic: str | None = None) -> dict:
399
- store = _load()
400
- eps = store.get("episodes", [])
401
- if topic:
402
- eps = [e for e in eps if topic in (e.get("topics") or [])]
403
- return {"items": eps[-k:]}
404
-
405
- @tool
406
- def recall_facts() -> dict:
407
- store = _load()
408
- return {"facts": store.get("facts", [])}
409
-
410
- @tool
411
- def reflect() -> dict:
412
- store = _load()
413
- eps = store.get("episodes", [])
414
- if not eps:
415
- return {"ok": True, "updated": 0, "facts": store.get("facts", [])}
416
- buckets = cluster_topics(eps)
417
- new_facts = []
418
- for topic, group in buckets.items():
419
- fact = synthesize_fact(topic, group)
420
- if fact:
421
- existing = next((f for f in store["facts"] if f.get("proposition") == fact["proposition"]), None)
422
- if existing:
423
- existing["support"] = max(existing.get("support", 0), fact["support"])
424
- existing["confidence"] = round(max(existing.get("confidence", 0.0), fact["confidence"]), 2)
425
- existing["last_updated"] = int(time.time())
426
- else:
427
- new_facts.append(fact)
428
- store["facts"].extend(new_facts)
429
- _save(store)
430
- return {"ok": True, "updated": len(new_facts), "facts": store["facts"]}
431
-
432
- @tool
433
- def prune(before_ts: int | None = None) -> dict:
434
- store = _load()
435
- stm = store.get("stm", [])
436
- if before_ts:
437
- stm = [it for it in stm if it.get("t", 0) >= int(before_ts)]
438
- else:
439
- cut = int(len(stm) * 0.75)
440
- stm = stm[cut:]
441
- store["stm"] = stm
442
- _save(store)
443
- return {"ok": True, "stm_size": len(store["stm"])}
444
-
445
- # -------- NEW: search / get / delete / list --------
446
-
447
- @tool
448
- def search(query: str, tier: str | None = None, k: int = 5) -> dict:
449
- """
450
- TF-IDF search across memory.
451
- Args:
452
- query: text to search
453
- tier: one of {"stm","episodes","facts"} or None for all
454
- k: number of results
455
- Returns: {"results":[{"id","tier","text","ts","score","matched"}]}
456
- """
457
- store = _load()
458
- docs = _collect_docs(store, tier=tier)
459
- ranked = _tfidf_rank(query, docs, k=k)
460
- results = [{"id": _id, "tier": _tier, "text": text, "ts": ts, "score": round(score,3), "matched": matched}
461
- for (_id, _tier, text, ts, score, matched) in ranked]
462
- return {"results": results}
463
-
464
- @tool
465
- def get(item_id: str) -> dict:
466
- """
467
- Fetch a single item by id from any tier.
468
- """
469
- s = _load()
470
- for it in s.get("stm", []):
471
- if it.get("id") == item_id:
472
- return {"tier": "stm", "item": it}
473
- for ep in s.get("episodes", []):
474
- if ep.get("episode_id") == item_id:
475
- return {"tier": "episodes", "item": ep}
476
- for f in s.get("facts", []):
477
- if f.get("fact_id") == item_id:
478
- return {"tier": "facts", "item": f}
479
- return {"tier": None, "item": None}
480
-
481
- @tool
482
- def delete_by_id(item_id: str, tier: str | None = None) -> dict:
483
- """
484
- Delete a single item by id. If tier is None, searches all tiers.
485
- Returns {"ok": bool, "removed_from": <tier>|None}
486
- """
487
- s = _load()
488
- removed_from = None
489
- if tier in (None, "stm"):
490
- before = len(s["stm"])
491
- s["stm"] = [it for it in s["stm"] if it.get("id") != item_id]
492
- if len(s["stm"]) != before: removed_from = "stm"
493
- if not removed_from and tier in (None, "episodes"):
494
- before = len(s["episodes"])
495
- s["episodes"] = [e for e in s["episodes"] if e.get("episode_id") != item_id]
496
- if len(s["episodes"]) != before: removed_from = "episodes"
497
- if not removed_from and tier in (None, "facts"):
498
- before = len(s["facts"])
499
- s["facts"] = [f for f in s["facts"] if f.get("fact_id") != item_id]
500
- if len(s["facts"]) != before: removed_from = "facts"
501
- if removed_from:
502
- _save(s)
503
- return {"ok": True, "removed_from": removed_from}
504
- return {"ok": False, "removed_from": None}
505
-
506
- @tool
507
- def list_items(tier: str, k: int = 10) -> dict:
508
- """
509
- List last k items in a tier.
510
- tier ∈ {"stm","episodes","facts"}
511
- """
512
- s = _load()
513
- if tier == "stm":
514
- return {"items": s.get("stm", [])[-k:]}
515
- if tier == "episodes":
516
- return {"items": s.get("episodes", [])[-k:]}
517
- if tier == "facts":
518
- return {"items": s.get("facts", [])[-k:]}
519
- return {"items": []}
520
-
521
- # -------- Diagnostics --------
522
-
523
- @tool
524
- def stats() -> dict:
525
- s = _load()
526
- return {
527
- "stm": len(s.get("stm", [])),
528
- "episodes": len(s.get("episodes", [])),
529
- "facts": len(s.get("facts", [])),
530
- "file": FILE,
531
- "created": s.get("meta", {}).get("created"),
532
- "version": s.get("meta", {}).get("version", "1.3.0"),
533
- }
534
-
535
- @tool
536
- def health() -> dict:
537
- try:
538
- s = _load()
539
- return {"status": "ok", "stm": len(s.get("stm", [])), "episodes": len(s.get("episodes", [])), "facts": len(s.get("facts", [])), "time": time.time(), "version": "1.3.0"}
540
- except Exception as e:
541
- return {"status": "error", "error": str(e), "time": time.time()}
542
-
543
- @tool
544
- def version() -> dict:
545
- return {"name": "memory-server", "version": "1.3.0", "tiers": ["stm","episodes","facts"], "file": FILE}
546
-
547
- @tool
548
- def get_emotion_arc(k: int = 10) -> dict:
549
- """
550
- Get the emotion trajectory (arc) for the last k events.
551
- Returns: {"trajectory": [...], "direction": "escalating|de-escalating|volatile|stable", "summary": str}
552
- """
553
- store = _load()
554
- trajectory, direction = get_emotion_trajectory(store, k=k)
555
-
556
- if not trajectory:
557
- return {"trajectory": [], "direction": "unknown", "summary": "No emotion history"}
558
-
559
- # Create readable summary
560
- emotions = [t["label"] for t in trajectory]
561
- summary = " → ".join(emotions[-5:]) if len(emotions) >= 5 else " → ".join(emotions)
562
-
563
- return {
564
- "trajectory": trajectory,
565
- "direction": direction,
566
- "summary": summary
567
- }
568
-
569
- if __name__ == "__main__":
570
- app.run() # serves MCP over stdio
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
utils/servers/emotion_server.py.bak DELETED
@@ -1,377 +0,0 @@
1
- # # servers/emotion_server.py
2
- # from fastmcp import FastMCP, tool
3
- # import re
4
-
5
- # app = FastMCP("emotion-server")
6
-
7
- # _PATTERNS = {
8
- # "happy": r"\b(happy|grateful|excited|joy|delighted|content|optimistic)\b",
9
- # "sad": r"\b(sad|down|depressed|cry|lonely|upset|miserable)\b",
10
- # "angry": r"\b(angry|mad|furious|irritated|pissed|annoyed|resentful)\b",
11
- # "anxious": r"\b(worried|anxious|nervous|stressed|overwhelmed|scared)\b",
12
- # "tired": r"\b(tired|exhausted|drained|burnt|sleepy|fatigued)\b",
13
- # "love": r"\b(love|affection|caring|fond|admire|cherish)\b",
14
- # "fear": r"\b(afraid|fear|terrified|panicked|shaken)\b",
15
- # }
16
-
17
- # _TONES = {"happy":"light","love":"light","sad":"gentle","fear":"gentle",
18
- # "angry":"calming","anxious":"calming","tired":"gentle"}
19
-
20
- # def _analyze(text: str) -> dict:
21
- # t = text.lower()
22
- # found = [k for k,pat in _PATTERNS.items() if re.search(pat, t)]
23
- # valence = 0.0
24
- # if "happy" in found or "love" in found: valence += 0.6
25
- # if "sad" in found or "fear" in found: valence -= 0.6
26
- # if "angry" in found: valence -= 0.4
27
- # if "anxious" in found: valence -= 0.3
28
- # if "tired" in found: valence -= 0.2
29
- # arousal = 0.5 + (0.3 if ("angry" in found or "anxious" in found) else 0) - (0.2 if "tired" in found else 0)
30
- # tone = "neutral"
31
- # for e in found:
32
- # if e in _TONES: tone = _TONES[e]; break
33
- # return {
34
- # "labels": found or ["neutral"],
35
- # "valence": max(-1, min(1, round(valence, 2))),
36
- # "arousal": max(0, min(1, round(arousal, 2))),
37
- # "tone": tone,
38
- # }
39
-
40
- # @tool
41
- # def analyze(text: str) -> dict:
42
- # """
43
- # Analyze user text for emotion.
44
- # Args:
45
- # text: str - user message
46
- # Returns: dict {labels, valence, arousal, tone}
47
- # """
48
- # return _analyze(text)
49
-
50
- # if __name__ == "__main__":
51
- # app.run() # serves MCP over stdio
52
- # servers/emotion_server.py
53
- from __future__ import annotations
54
- # ---- FastMCP import shim (works across versions) ----
55
- # Ensures: FastMCP is imported and `@tool` is ALWAYS a callable decorator.
56
- from typing import Callable, Any
57
-
58
- try:
59
- from fastmcp import FastMCP # present across versions
60
- except Exception as e:
61
- raise ImportError(f"FastMCP missing: {e}")
62
-
63
- _tool_candidate: Any = None
64
- # Try common locations
65
- try:
66
- from fastmcp import tool as _tool_candidate # newer API: function
67
- except Exception:
68
- try:
69
- from fastmcp.tools import tool as _tool_candidate # older API: function
70
- except Exception:
71
- _tool_candidate = None
72
-
73
- # If we somehow got a module instead of a function, try attribute
74
- if _tool_candidate is not None and not callable(_tool_candidate):
75
- try:
76
- _tool_candidate = _tool_candidate.tool # some builds expose module.tools.tool
77
- except Exception:
78
- _tool_candidate = None
79
-
80
- def tool(*dargs, **dkwargs):
81
- """
82
- Wrapper that behaves correctly in both usages:
83
- @tool
84
- @tool(...)
85
- If real decorator exists, delegate. Otherwise:
86
- - If called as @tool (i.e., first arg is fn), return fn (no-op).
87
- - If called as @tool(...), return a decorator that returns fn (no-op).
88
- """
89
- if callable(_tool_candidate):
90
- return _tool_candidate(*dargs, **dkwargs)
91
-
92
- # No real decorator available — provide no-op behavior.
93
- if dargs and callable(dargs[0]) and not dkwargs:
94
- # Used as @tool
95
- fn = dargs[0]
96
- return fn
97
-
98
- # Used as @tool(...)
99
- def _noop_decorator(fn):
100
- return fn
101
- return _noop_decorator
102
- # ---- end shim ----
103
-
104
-
105
- import re, math, time
106
- from typing import Dict, List, Tuple, Optional
107
-
108
- app = FastMCP("emotion-server")
109
-
110
- # ---------------------------
111
- # Lexicons & heuristics
112
- # ---------------------------
113
- EMO_LEX = {
114
- "happy": r"\b(happy|grateful|excited|joy(?:ful)?|delighted|content|optimistic|glad|thrilled|yay)\b",
115
- "sad": r"\b(sad|down|depress(?:ed|ing)|cry(?:ing)?|lonely|upset|miserable|heartbroken)\b",
116
- "angry": r"\b(angry|mad|furious|irritated|pissed|annoyed|resentful|rage|hate)\b",
117
- "anxious": r"\b(worried|anxious|nervous|stressed|overwhelmed|scared|uneasy|tense|on edge)\b",
118
- "tired": r"\b(tired|exhaust(?:ed|ing)|drained|burnt(?:\s*out)?|sleepy|fatigued|worn out)\b",
119
- "love": r"\b(love|affection|caring|fond|admire|cherish|adore)\b",
120
- "fear": r"\b(afraid|fear|terrified|panic(?:ky|ked)?|panicked|shaken|petrified)\b",
121
- }
122
-
123
- # Emojis contribute signals even without words
124
- EMOJI_SIGNAL = {
125
- "happy": ["😀","😄","😊","🙂","😁","🥳","✨"],
126
- "sad": ["😢","😭","😞","😔","☹️"],
127
- "angry": ["😠","😡","🤬","💢"],
128
- "anxious":["😰","😱","😬","😟","😧"],
129
- "tired": ["🥱","😪","😴"],
130
- "love": ["❤️","💖","💕","😍","🤍","💗","💓","😘"],
131
- "fear": ["🫣","😨","😱","👀"],
132
- }
133
-
134
- NEGATORS = r"\b(no|not|never|hardly|barely|scarcely|isn['’]t|aren['’]t|can['’]t|don['’]t|doesn['’]t|won['’]t|without)\b"
135
- INTENSIFIERS = {
136
- r"\b(very|really|super|so|extremely|incredibly|totally|absolutely)\b": 1.35,
137
- r"\b(kinda|kind of|somewhat|slightly|a bit|a little)\b": 0.75,
138
- }
139
- SARCASM_CUES = [
140
- r"\byeah right\b", r"\bsure\b", r"\".+\"", r"/s\b", r"\bokayyy+\b", r"\blol\b(?!\w)"
141
- ]
142
-
143
- # Tone map by quadrant
144
- # arousal high/low × valence pos/neg
145
- def quad_tone(valence: float, arousal: float) -> str:
146
- if arousal >= 0.6 and valence >= 0.1: return "excited"
147
- if arousal >= 0.6 and valence < -0.1: return "concerned"
148
- if arousal < 0.6 and valence < -0.1: return "gentle"
149
- if arousal < 0.6 and valence >= 0.1: return "calm"
150
- return "neutral"
151
-
152
- # ---------------------------
153
- # Utilities
154
- # ---------------------------
155
- _compiled = {k: re.compile(p, re.I) for k, p in EMO_LEX.items()}
156
- _neg_pat = re.compile(NEGATORS, re.I)
157
- _int_pats = [(re.compile(p, re.I), w) for p, w in INTENSIFIERS.items()]
158
- _sarcasm = [re.compile(p, re.I) for p in SARCASM_CUES]
159
-
160
- def _emoji_hits(text: str) -> Dict[str, int]:
161
- hits = {k: 0 for k in EMO_LEX}
162
- for emo, arr in EMOJI_SIGNAL.items():
163
- for e in arr:
164
- hits[emo] += text.count(e)
165
- return hits
166
-
167
- def _intensity_multiplier(text: str) -> float:
168
- mult = 1.0
169
- for pat, w in _int_pats:
170
- if pat.search(text):
171
- mult *= w
172
- # Exclamation marks increase arousal a bit (cap effect)
173
- bangs = min(text.count("!"), 5)
174
- mult *= (1.0 + 0.04 * bangs)
175
- # ALL CAPS word run nudges intensity
176
- if re.search(r"\b[A-Z]{3,}\b", text):
177
- mult *= 1.08
178
- return max(0.5, min(1.8, mult))
179
-
180
- def _negation_factor(text: str, span_start: int) -> float:
181
- """
182
- Look 5 words (~40 chars) backwards for a negator.
183
- If present, invert or dampen signal.
184
- """
185
- window_start = max(0, span_start - 40)
186
- window = text[window_start:span_start]
187
- if _neg_pat.search(window):
188
- return -0.7 # invert and dampen
189
- return 1.0
190
-
191
- def _sarcasm_penalty(text: str) -> float:
192
- return 0.85 if any(p.search(text) for p in _sarcasm) else 1.0
193
-
194
- def _softmax(d: Dict[str, float]) -> Dict[str, float]:
195
- xs = list(d.values())
196
- if not xs: return d
197
- m = max(xs)
198
- exps = [math.exp(x - m) for x in xs]
199
- s = sum(exps) or 1.0
200
- return {k: exps[i] / s for i, k in enumerate(d.keys())}
201
-
202
- # ---------------------------
203
- # Per-user calibration (in-memory)
204
- # ---------------------------
205
- CALIBRATION: Dict[str, Dict[str, float]] = {} # user_id -> {bias_emo: float, arousal_bias: float, valence_bias: float}
206
-
207
- def _apply_calibration(user_id: Optional[str], emo_scores: Dict[str, float], valence: float, arousal: float):
208
- if not user_id or user_id not in CALIBRATION:
209
- return emo_scores, valence, arousal
210
- calib = CALIBRATION[user_id]
211
- # shift emotions
212
- for k, bias in calib.items():
213
- if k in emo_scores:
214
- emo_scores[k] += bias * 0.2
215
- # dedicated valence/arousal bias keys if present
216
- valence += calib.get("valence_bias", 0.0) * 0.15
217
- arousal += calib.get("arousal_bias", 0.0) * 0.15
218
- return emo_scores, valence, arousal
219
-
220
- # ---------------------------
221
- # Core analysis
222
- # ---------------------------
223
- def _analyze(text: str, user_id: Optional[str] = None) -> dict:
224
- t = text or ""
225
- tl = t.lower()
226
-
227
- # Base scores from lexicon hits
228
- emo_scores: Dict[str, float] = {k: 0.0 for k in EMO_LEX}
229
- spans: Dict[str, List[Tuple[int, int, str]]] = {k: [] for k in EMO_LEX}
230
-
231
- for emo, pat in _compiled.items():
232
- for m in pat.finditer(tl):
233
- factor = _negation_factor(tl, m.start())
234
- emo_scores[emo] += 1.0 * factor
235
- spans[emo].append((m.start(), m.end(), tl[m.start():m.end()]))
236
-
237
- # Emoji contributions
238
- e_hits = _emoji_hits(t)
239
- for emo, c in e_hits.items():
240
- if c:
241
- emo_scores[emo] += 0.6 * c
242
-
243
- # Intensifiers / sarcasm / punctuation adjustments (global)
244
- intensity = _intensity_multiplier(t)
245
- sarcasm_mult = _sarcasm_penalty(t)
246
-
247
- for emo in emo_scores:
248
- emo_scores[emo] *= intensity * sarcasm_mult
249
-
250
- # Map to valence/arousal
251
- pos = emo_scores["happy"] + emo_scores["love"]
252
- neg = emo_scores["sad"] + emo_scores["fear"] + 0.9 * emo_scores["angry"] + 0.6 * emo_scores["anxious"]
253
- valence = max(-1.0, min(1.0, round((pos - neg) * 0.4, 3)))
254
-
255
- base_arousal = 0.5
256
- arousal = base_arousal \
257
- + 0.12 * (emo_scores["angry"] > 0) \
258
- + 0.08 * (emo_scores["anxious"] > 0) \
259
- - 0.10 * (emo_scores["tired"] > 0) \
260
- + 0.02 * min(t.count("!"), 5)
261
-
262
- arousal = max(0.0, min(1.0, round(arousal, 3)))
263
-
264
- # Confidence: count signals + consistency
265
- hits = sum(1 for v in emo_scores.values() if abs(v) > 0.01) + sum(e_hits.values())
266
- consistency = 0.0
267
- if hits:
268
- top2 = sorted(emo_scores.items(), key=lambda kv: kv[1], reverse=True)[:2]
269
- if len(top2) == 2 and top2[1][1] > 0:
270
- ratio = top2[0][1] / (top2[1][1] + 1e-6)
271
- consistency = max(0.0, min(1.0, (ratio - 1) / 3)) # >1 means some separation
272
- elif len(top2) == 1:
273
- consistency = 0.6
274
- conf = max(0.0, min(1.0, 0.25 + 0.1 * hits + 0.5 * consistency))
275
- # downweight very short texts
276
- if len(t.strip()) < 6:
277
- conf *= 0.6
278
-
279
- # Normalize emotions to pseudo-probs (softmax over positive scores)
280
- pos_scores = {k: max(0.0, v) for k, v in emo_scores.items()}
281
- probs = _softmax(pos_scores)
282
-
283
- # Apply per-user calibration
284
- probs, valence, arousal = _apply_calibration(user_id, probs, valence, arousal)
285
-
286
- # Tone
287
- tone = quad_tone(valence, arousal)
288
-
289
- # Explanations
290
- reasons = []
291
- if intensity > 1.0: reasons.append(f"intensifiers x{intensity:.2f}")
292
- if sarcasm_mult < 1.0: reasons.append("sarcasm cues detected")
293
- if any(_neg_pat.search(tl[max(0,s-40):s]) for emo, spans_ in spans.items() for (s,_,_) in spans_):
294
- reasons.append("negation near emotion tokens")
295
- if any(e_hits.values()): reasons.append("emoji signals")
296
-
297
- labels_sorted = sorted(probs.items(), key=lambda kv: kv[1], reverse=True)
298
- top_labels = [k for k, v in labels_sorted[:3] if v > 0.05] or ["neutral"]
299
-
300
- return {
301
- "labels": top_labels,
302
- "scores": {k: round(v, 3) for k, v in probs.items()},
303
- "valence": round(valence, 3),
304
- "arousal": round(arousal, 3),
305
- "tone": tone,
306
- "confidence": round(conf, 3),
307
- "reasons": reasons,
308
- "spans": {k: spans[k] for k in top_labels if spans.get(k)},
309
- "ts": time.time(),
310
- "user_id": user_id,
311
- }
312
-
313
- # ---------------------------
314
- # MCP tools
315
- # ---------------------------
316
-
317
- @app.tool()
318
- def analyze(text: str, user_id: Optional[str] = None) -> dict:
319
- """
320
- Analyze text for emotion.
321
- Args:
322
- text: user message
323
- user_id: optional user key for calibration
324
- Returns:
325
- dict with labels, scores (per emotion), valence [-1..1], arousal [0..1],
326
- tone (calm/neutral/excited/concerned/gentle), confidence, reasons, spans.
327
- """
328
- return _analyze(text, user_id=user_id)
329
-
330
- @app.tool()
331
- def batch_analyze(messages: List[str], user_id: Optional[str] = None) -> List[dict]:
332
- """
333
- Batch analyze a list of messages.
334
- """
335
- return [_analyze(m or "", user_id=user_id) for m in messages]
336
-
337
- @app.tool()
338
- def calibrate(user_id: str, bias: Dict[str, float] = None, arousal_bias: float = 0.0, valence_bias: float = 0.0) -> dict:
339
- """
340
- Adjust per-user calibration.
341
- - bias: e.g. {"anxious": -0.1, "love": 0.1}
342
- - arousal_bias/valence_bias: small nudges (-1..1) applied after scoring.
343
- """
344
- if user_id not in CALIBRATION:
345
- CALIBRATION[user_id] = {}
346
- if bias:
347
- for k, v in bias.items():
348
- CALIBRATION[user_id][k] = float(v)
349
- if arousal_bias:
350
- CALIBRATION[user_id]["arousal_bias"] = float(arousal_bias)
351
- if valence_bias:
352
- CALIBRATION[user_id]["valence_bias"] = float(valence_bias)
353
- return {"ok": True, "calibration": CALIBRATION[user_id]}
354
-
355
- @app.tool()
356
- def reset_calibration(user_id: str) -> dict:
357
- """Remove per-user calibration."""
358
- CALIBRATION.pop(user_id, None)
359
- return {"ok": True}
360
-
361
- @app.tool()
362
- def health() -> dict:
363
- """Simple health check for MCP status chips."""
364
- return {"status": "ok", "version": "1.2.0", "time": time.time()}
365
-
366
- @app.tool()
367
- def version() -> dict:
368
- """Return server version & feature flags."""
369
- return {
370
- "name": "emotion-server",
371
- "version": "1.2.0",
372
- "features": ["negation", "intensifiers", "emoji", "sarcasm", "confidence", "batch", "calibration"],
373
- "emotions": list(EMO_LEX.keys()),
374
- }
375
-
376
- if __name__ == "__main__":
377
- app.run() # serves MCP over stdio
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
utils/servers/memory_server.py.bak DELETED
@@ -1,570 +0,0 @@
1
- # # servers/memory_server.py
2
- # from fastmcp import FastMCP, tool
3
- # import json, os, time
4
-
5
- # app = FastMCP("memory-server")
6
- # FILE = os.environ.get("GM_MEMORY_FILE", "memory.json")
7
-
8
- # def _load():
9
- # if os.path.exists(FILE):
10
- # with open(FILE) as f: return json.load(f)
11
- # return []
12
-
13
- # def _save(history):
14
- # with open(FILE, "w") as f: json.dump(history[-50:], f) # keep up to 50
15
-
16
- # @tool
17
- # def remember(text: str, meta: dict | None = None) -> dict:
18
- # """
19
- # Append an entry to memory.
20
- # Args:
21
- # text: str - content to store
22
- # meta: dict - optional info like {"tone":"gentle","labels":["sad"]}
23
- # Returns: {"ok": True, "size": <n>}
24
- # """
25
- # data = _load()
26
- # data.append({"t": int(time.time()), "text": text, "meta": meta or {}})
27
- # _save(data)
28
- # return {"ok": True, "size": len(data)}
29
-
30
- # @tool
31
- # def recall(k: int = 3) -> dict:
32
- # """
33
- # Return last k entries from memory (most recent last).
34
- # Args:
35
- # k: int - how many items
36
- # Returns: {"items":[...]}
37
- # """
38
- # data = _load()
39
- # return {"items": data[-k:]}
40
-
41
- # if __name__ == "__main__":
42
- # app.run()
43
- # servers/memory_server.py
44
- # servers/memory_server.py
45
- from __future__ import annotations
46
- # ---- FastMCP import shim (works across versions) ----
47
- # Ensures: FastMCP is imported and `@tool` is ALWAYS a callable decorator.
48
- from typing import Callable, Any
49
-
50
- try:
51
- from fastmcp import FastMCP # present across versions
52
- except Exception as e:
53
- raise ImportError(f"FastMCP missing: {e}")
54
-
55
- _tool_candidate: Any = None
56
- # Try common locations
57
- try:
58
- from fastmcp import tool as _tool_candidate # newer API: function
59
- except Exception:
60
- try:
61
- from fastmcp.tools import tool as _tool_candidate # older API: function
62
- except Exception:
63
- _tool_candidate = None
64
-
65
- # If we somehow got a module instead of a function, try attribute
66
- if _tool_candidate is not None and not callable(_tool_candidate):
67
- try:
68
- _tool_candidate = _tool_candidate.tool # some builds expose module.tools.tool
69
- except Exception:
70
- _tool_candidate = None
71
-
72
- def tool(*dargs, **dkwargs):
73
- """
74
- Wrapper that behaves correctly in both usages:
75
- @tool
76
- @tool(...)
77
- If real decorator exists, delegate. Otherwise:
78
- - If called as @tool (i.e., first arg is fn), return fn (no-op).
79
- - If called as @tool(...), return a decorator that returns fn (no-op).
80
- """
81
- if callable(_tool_candidate):
82
- return _tool_candidate(*dargs, **dkwargs)
83
-
84
- # No real decorator available — provide no-op behavior.
85
- if dargs and callable(dargs[0]) and not dkwargs:
86
- # Used as @tool
87
- fn = dargs[0]
88
- return fn
89
-
90
- # Used as @tool(...)
91
- def _noop_decorator(fn):
92
- return fn
93
- return _noop_decorator
94
- # ---- end shim ----
95
-
96
-
97
- import json, os, time, math, re
98
- from typing import Dict, List, Optional, Any, Tuple
99
- from collections import Counter
100
-
101
- app = FastMCP("memory-server")
102
-
103
- # ---------------------------
104
- # Storage & limits
105
- # ---------------------------
106
- FILE = os.environ.get("GM_MEMORY_FILE", "memory.json")
107
- STM_MAX = int(os.environ.get("GM_STM_MAX", "120"))
108
- EP_MAX = int(os.environ.get("GM_EPISODES_MAX", "240"))
109
- FACT_MAX= int(os.environ.get("GM_FACTS_MAX", "200"))
110
- # ---------------------------
111
- # Emotion Drift Analysis
112
- # ---------------------------
113
- def compute_emotional_direction(trajectory: List[Dict[str, Any]]) -> str:
114
- """
115
- Analyze emotion trajectory to detect escalation/de-escalation/volatility/stability.
116
- trajectory: list of {"label": str, "valence": float, "arousal": float, "ts": int}
117
- """
118
- if len(trajectory) < 2:
119
- return "stable"
120
-
121
- # Get last 5 emotions for trend
122
- recent = trajectory[-5:]
123
- valences = [e.get("valence", 0.0) for e in recent]
124
- arousals = [e.get("arousal", 0.5) for e in recent]
125
-
126
- # Detect trend
127
- valence_trend = valences[-1] - valences[0] # negative = more negative, positive = more positive
128
- arousal_trend = arousals[-1] - arousals[0] # positive = escalating
129
-
130
- # Classify
131
- if arousal_trend > 0.15 and valence_trend < -0.1:
132
- return "escalating" # Getting more activated and negative
133
- elif arousal_trend < -0.15 and valence_trend > 0.1:
134
- return "de-escalating" # Calming down and more positive
135
- elif max(arousals) - min(arousals) > 0.3:
136
- return "volatile" # Wide swings in arousal
137
- else:
138
- return "stable"
139
-
140
- def get_emotion_trajectory(store: Dict[str, Any], k: int = 10) -> Tuple[List[Dict[str, Any]], str]:
141
- """
142
- Returns last k emotion events from memory and the trajectory direction.
143
- """
144
- stm = store.get("stm", [])
145
- trajectory = []
146
-
147
- for item in stm[-k:]:
148
- event = item.get("event", {})
149
- emotion = event.get("emotion", {})
150
- if emotion and emotion.get("labels"):
151
- trajectory.append({
152
- "label": (emotion.get("labels") or ["neutral"])[0],
153
- "valence": float(emotion.get("valence", 0.0)),
154
- "arousal": float(emotion.get("arousal", 0.5)),
155
- "ts": event.get("ts", int(time.time())),
156
- "text": event.get("text", "")[:50] # First 50 chars
157
- })
158
-
159
- direction = compute_emotional_direction(trajectory)
160
- return trajectory, direction
161
- # ---------------------------
162
- # File helpers & migrations
163
- # ---------------------------
164
- def _default_store() -> Dict[str, Any]:
165
- return {"stm": [], "episodes": [], "facts": [], "meta": {"created": int(time.time()), "version": "1.3.0"}}
166
-
167
- def _load() -> Dict[str, Any]:
168
- if os.path.exists(FILE):
169
- with open(FILE) as f:
170
- try:
171
- data = json.load(f)
172
- # migrate flat list → tiered
173
- if isinstance(data, list):
174
- data = {"stm": data[-STM_MAX:], "episodes": [], "facts": [], "meta": {"created": int(time.time()), "version": "1.3.0"}}
175
- # backfill ids in stm
176
- changed = False
177
- for i, it in enumerate(data.get("stm", [])):
178
- if "id" not in it:
179
- it["id"] = f"stm-{it.get('t', int(time.time()))}-{i}"
180
- changed = True
181
- if changed:
182
- _save(data)
183
- return data
184
- except Exception:
185
- return _default_store()
186
- return _default_store()
187
-
188
- def _save(store: Dict[str, Any]) -> None:
189
- store["stm"] = store.get("stm", [])[-STM_MAX:]
190
- store["episodes"] = store.get("episodes", [])[-EP_MAX:]
191
- store["facts"] = store.get("facts", [])[-FACT_MAX:]
192
- with open(FILE, "w") as f:
193
- json.dump(store, f, ensure_ascii=False)
194
-
195
- # ---------------------------
196
- # Salience & decay (same as before)
197
- # ---------------------------
198
- def time_decay(ts: float, now: Optional[float] = None, half_life_hours: float = 72.0) -> float:
199
- now = now or time.time()
200
- dt_h = max(0.0, (now - ts) / 3600.0)
201
- return 0.5 ** (dt_h / half_life_hours)
202
-
203
- _WORD = re.compile(r"[a-zA-Z']+")
204
-
205
- def keyword_set(text: str) -> set:
206
- return set(w.lower() for w in _WORD.findall(text or "") if len(w) > 2)
207
-
208
- def novelty_score(text: str, recent_texts: List[str], k: int = 10) -> float:
209
- if not text:
210
- return 0.0
211
- A = keyword_set(text)
212
- if not A:
213
- return 0.0
214
- recent = [keyword_set(t) for t in recent_texts[-k:] if t]
215
- if not recent:
216
- return 1.0
217
- sims = []
218
- for B in recent:
219
- inter = len(A & B)
220
- union = len(A | B) or 1
221
- sims.append(inter / union)
222
- sim = max(sims) if sims else 0.0
223
- return max(0.0, 1.0 - sim)
224
-
225
- def compute_salience(ev: Dict[str, Any], recent_texts: List[str]) -> float:
226
- labels = ev.get("emotion", {}).get("labels") or []
227
- conf = float(ev.get("emotion", {}).get("confidence") or 0.0)
228
- valence= float(ev.get("emotion", {}).get("valence") or 0.0)
229
- arousal= float(ev.get("emotion", {}).get("arousal") or 0.5)
230
- sinc = float(ev.get("sincerity") or 0.0) / 100.0
231
- text = ev.get("text", "")
232
-
233
- affect = abs(valence) * (0.7 + 0.3 * arousal) * conf
234
- nov = novelty_score(text, recent_texts)
235
- user_flag = 1.0 if ev.get("user_pinned") else 0.0
236
- boundary = 1.0 if ev.get("task_boundary") else 0.0
237
-
238
- sal = 0.45 * affect + 0.25 * nov + 0.18 * user_flag + 0.12 * boundary + 0.10 * sinc
239
- return round(max(0.0, min(1.0, sal)), 3)
240
-
241
- # ---------------------------
242
- # Episode & fact synthesis
243
- # ---------------------------
244
- def make_episode(ev: Dict[str, Any], salience: float) -> Dict[str, Any]:
245
- emo = ev.get("emotion", {})
246
- return {
247
- "episode_id": ev.get("id") or f"ep-{int(time.time()*1000)}",
248
- "ts_start": ev.get("ts") or int(time.time()),
249
- "ts_end": ev.get("ts") or int(time.time()),
250
- "summary": ev.get("summary") or (ev.get("text")[:140] if ev.get("text") else ""),
251
- "topics": list(set(emo.get("labels") or [])) or ["misc"],
252
- "emotion_peak": (emo.get("labels") or ["neutral"])[0],
253
- "emotion_conf": float(emo.get("confidence") or 0.0),
254
- "tone": emo.get("tone") or "neutral",
255
- "salience": float(salience),
256
- "provenance_event": ev.get("id"),
257
- }
258
-
259
- def cluster_topics(episodes: List[Dict[str, Any]]) -> Dict[str, List[Dict[str, Any]]]:
260
- buckets: Dict[str, List[Dict[str, Any]]] = {}
261
- for ep in episodes:
262
- for t in ep.get("topics") or ["misc"]:
263
- buckets.setdefault(t, []).append(ep)
264
- return buckets
265
-
266
- def synthesize_fact(topic: str, eps: List[Dict[str, Any]]) -> Optional[Dict[str, Any]]:
267
- if not eps:
268
- return None
269
- support = len(eps)
270
- avg_sal = sum(e.get("salience", 0.0) for e in eps) / max(1, support)
271
- avg_conf= sum(e.get("emotion_conf", 0.0) for e in eps) / max(1, support)
272
- conf = max(0.0, min(1.0, 0.5 * avg_sal + 0.5 * avg_conf))
273
- if support < 3 or conf < 0.6:
274
- return None
275
- tones = {}
276
- for e in eps: tones[e.get("tone", "neutral")] = tones.get(e.get("tone", "neutral"), 0) + 1
277
- top_tone = sorted(tones.items(), key=lambda kv: kv[1], reverse=True)[0][0]
278
- return {
279
- "fact_id": f"fact-{topic}-{int(time.time())}",
280
- "proposition": f"Prefers {top_tone} tone for topic '{topic}'",
281
- "support": support,
282
- "confidence": round(conf, 2),
283
- "last_updated": int(time.time()),
284
- "topics": [topic],
285
- "provenance_episode_ids": [e["episode_id"] for e in eps],
286
- }
287
-
288
- # ---------------------------
289
- # ID helpers
290
- # ---------------------------
291
- def _ensure_stm_id(item: Dict[str, Any], idx: int) -> Dict[str, Any]:
292
- if "id" not in item:
293
- item["id"] = f"stm-{item.get('t', int(time.time()))}-{idx}"
294
- return item
295
-
296
- def _stm_text(item: Dict[str, Any]) -> str:
297
- if "text" in item and isinstance(item["text"], str):
298
- return item["text"]
299
- return (item.get("event") or {}).get("text", "") or ""
300
-
301
- def _collect_docs(store: Dict[str, Any], tier: Optional[str] = None) -> List[Tuple[str,str,str,int]]:
302
- """
303
- Returns list of (id, tier, text, ts)
304
- """
305
- docs: List[Tuple[str,str,str,int]] = []
306
- if tier in (None, "stm"):
307
- for i, it in enumerate(store.get("stm", [])):
308
- it = _ensure_stm_id(it, i)
309
- docs.append((it["id"], "stm", _stm_text(it), int(it.get("t", time.time()))))
310
- if tier in (None, "episodes"):
311
- for ep in store.get("episodes", []):
312
- docs.append((ep.get("episode_id",""), "episodes", ep.get("summary",""), int(ep.get("ts_end", time.time()))))
313
- if tier in (None, "facts"):
314
- for f in store.get("facts", []):
315
- docs.append((f.get("fact_id",""), "facts", f.get("proposition",""), int(f.get("last_updated", time.time()))))
316
- return [d for d in docs if d[0] and d[2]]
317
-
318
- # ---------------------------
319
- # Simple TF-IDF search
320
- # ---------------------------
321
- def _tfidf_rank(query: str, docs: List[Tuple[str,str,str,int]], k: int = 5):
322
- q_terms = [w for w in keyword_set(query)]
323
- if not q_terms or not docs:
324
- return []
325
- # DF
326
- df = Counter()
327
- doc_terms = {}
328
- for _id, _tier, text, _ts in docs:
329
- terms = [w for w in keyword_set(text)]
330
- doc_terms[_id] = terms
331
- for t in set(terms):
332
- df[t] += 1
333
- N = len(docs)
334
- idf = {t: math.log((N + 1) / (df[t] + 1)) + 1.0 for t in df}
335
- # Score
336
- scored = []
337
- qset = set(q_terms)
338
- for _id, _tier, text, _ts in docs:
339
- terms = doc_terms[_id]
340
- tf = Counter(terms)
341
- score = 0.0
342
- matched = []
343
- for t in q_terms:
344
- if tf[t] > 0:
345
- score += tf[t] * idf.get(t, 1.0)
346
- matched.append(t)
347
- if score > 0:
348
- scored.append((_id, _tier, text, _ts, score, matched))
349
- scored.sort(key=lambda x: (-x[4], -x[3])) # score desc, then recent
350
- return scored[:k]
351
-
352
- # ---------------------------
353
- # Tools (API)
354
- # ---------------------------
355
-
356
- @tool
357
- def remember(text: str, meta: dict | None = None) -> dict:
358
- store = _load()
359
- item = {"t": int(time.time()), "text": text, "meta": meta or {}}
360
- item["id"] = f"stm-{item['t']}-{len(store.get('stm', []))}"
361
- store["stm"].append(item)
362
- _save(store)
363
- return {"ok": True, "stm_size": len(store["stm"]), "id": item["id"]}
364
-
365
- @tool
366
- def remember_event(event: dict, promote: bool = True) -> dict:
367
- store = _load()
368
- ev = dict(event or {})
369
- ev.setdefault("ts", int(time.time()))
370
- ev.setdefault("role", "user")
371
- ev.setdefault("text", "")
372
- if "salience" not in ev:
373
- recent_texts = [it.get("text","") for it in store.get("stm", [])[-10:]]
374
- ev["salience"] = compute_salience(ev, recent_texts)
375
- stm_item = {
376
- "id": f"stm-{ev['ts']}-{len(store.get('stm', []))}",
377
- "t": ev["ts"],
378
- "text": ev.get("text",""),
379
- "event": ev
380
- }
381
- store["stm"].append(stm_item)
382
- if promote:
383
- aff_conf = float(ev.get("emotion", {}).get("confidence") or 0.0)
384
- if ev["salience"] >= 0.45 or ev.get("user_pinned") or ev.get("task_boundary"):
385
- ep = make_episode(ev, ev["salience"])
386
- store["episodes"].append(ep)
387
- _save(store)
388
- return {"ok": True, "salience": ev["salience"], "id": stm_item["id"],
389
- "sizes": {"stm": len(store["stm"]), "episodes": len(store["episodes"]), "facts": len(store["facts"])}}
390
-
391
- @tool
392
- def recall(k: int = 3) -> dict:
393
- store = _load()
394
- items = store.get("stm", [])[-k:]
395
- return {"items": items}
396
-
397
- @tool
398
- def recall_episodes(k: int = 5, topic: str | None = None) -> dict:
399
- store = _load()
400
- eps = store.get("episodes", [])
401
- if topic:
402
- eps = [e for e in eps if topic in (e.get("topics") or [])]
403
- return {"items": eps[-k:]}
404
-
405
- @tool
406
- def recall_facts() -> dict:
407
- store = _load()
408
- return {"facts": store.get("facts", [])}
409
-
410
- @tool
411
- def reflect() -> dict:
412
- store = _load()
413
- eps = store.get("episodes", [])
414
- if not eps:
415
- return {"ok": True, "updated": 0, "facts": store.get("facts", [])}
416
- buckets = cluster_topics(eps)
417
- new_facts = []
418
- for topic, group in buckets.items():
419
- fact = synthesize_fact(topic, group)
420
- if fact:
421
- existing = next((f for f in store["facts"] if f.get("proposition") == fact["proposition"]), None)
422
- if existing:
423
- existing["support"] = max(existing.get("support", 0), fact["support"])
424
- existing["confidence"] = round(max(existing.get("confidence", 0.0), fact["confidence"]), 2)
425
- existing["last_updated"] = int(time.time())
426
- else:
427
- new_facts.append(fact)
428
- store["facts"].extend(new_facts)
429
- _save(store)
430
- return {"ok": True, "updated": len(new_facts), "facts": store["facts"]}
431
-
432
- @tool
433
- def prune(before_ts: int | None = None) -> dict:
434
- store = _load()
435
- stm = store.get("stm", [])
436
- if before_ts:
437
- stm = [it for it in stm if it.get("t", 0) >= int(before_ts)]
438
- else:
439
- cut = int(len(stm) * 0.75)
440
- stm = stm[cut:]
441
- store["stm"] = stm
442
- _save(store)
443
- return {"ok": True, "stm_size": len(store["stm"])}
444
-
445
- # -------- NEW: search / get / delete / list --------
446
-
447
- @tool
448
- def search(query: str, tier: str | None = None, k: int = 5) -> dict:
449
- """
450
- TF-IDF search across memory.
451
- Args:
452
- query: text to search
453
- tier: one of {"stm","episodes","facts"} or None for all
454
- k: number of results
455
- Returns: {"results":[{"id","tier","text","ts","score","matched"}]}
456
- """
457
- store = _load()
458
- docs = _collect_docs(store, tier=tier)
459
- ranked = _tfidf_rank(query, docs, k=k)
460
- results = [{"id": _id, "tier": _tier, "text": text, "ts": ts, "score": round(score,3), "matched": matched}
461
- for (_id, _tier, text, ts, score, matched) in ranked]
462
- return {"results": results}
463
-
464
- @tool
465
- def get(item_id: str) -> dict:
466
- """
467
- Fetch a single item by id from any tier.
468
- """
469
- s = _load()
470
- for it in s.get("stm", []):
471
- if it.get("id") == item_id:
472
- return {"tier": "stm", "item": it}
473
- for ep in s.get("episodes", []):
474
- if ep.get("episode_id") == item_id:
475
- return {"tier": "episodes", "item": ep}
476
- for f in s.get("facts", []):
477
- if f.get("fact_id") == item_id:
478
- return {"tier": "facts", "item": f}
479
- return {"tier": None, "item": None}
480
-
481
- @tool
482
- def delete_by_id(item_id: str, tier: str | None = None) -> dict:
483
- """
484
- Delete a single item by id. If tier is None, searches all tiers.
485
- Returns {"ok": bool, "removed_from": <tier>|None}
486
- """
487
- s = _load()
488
- removed_from = None
489
- if tier in (None, "stm"):
490
- before = len(s["stm"])
491
- s["stm"] = [it for it in s["stm"] if it.get("id") != item_id]
492
- if len(s["stm"]) != before: removed_from = "stm"
493
- if not removed_from and tier in (None, "episodes"):
494
- before = len(s["episodes"])
495
- s["episodes"] = [e for e in s["episodes"] if e.get("episode_id") != item_id]
496
- if len(s["episodes"]) != before: removed_from = "episodes"
497
- if not removed_from and tier in (None, "facts"):
498
- before = len(s["facts"])
499
- s["facts"] = [f for f in s["facts"] if f.get("fact_id") != item_id]
500
- if len(s["facts"]) != before: removed_from = "facts"
501
- if removed_from:
502
- _save(s)
503
- return {"ok": True, "removed_from": removed_from}
504
- return {"ok": False, "removed_from": None}
505
-
506
- @tool
507
- def list_items(tier: str, k: int = 10) -> dict:
508
- """
509
- List last k items in a tier.
510
- tier ∈ {"stm","episodes","facts"}
511
- """
512
- s = _load()
513
- if tier == "stm":
514
- return {"items": s.get("stm", [])[-k:]}
515
- if tier == "episodes":
516
- return {"items": s.get("episodes", [])[-k:]}
517
- if tier == "facts":
518
- return {"items": s.get("facts", [])[-k:]}
519
- return {"items": []}
520
-
521
- # -------- Diagnostics --------
522
-
523
- @tool
524
- def stats() -> dict:
525
- s = _load()
526
- return {
527
- "stm": len(s.get("stm", [])),
528
- "episodes": len(s.get("episodes", [])),
529
- "facts": len(s.get("facts", [])),
530
- "file": FILE,
531
- "created": s.get("meta", {}).get("created"),
532
- "version": s.get("meta", {}).get("version", "1.3.0"),
533
- }
534
-
535
- @tool
536
- def health() -> dict:
537
- try:
538
- s = _load()
539
- return {"status": "ok", "stm": len(s.get("stm", [])), "episodes": len(s.get("episodes", [])), "facts": len(s.get("facts", [])), "time": time.time(), "version": "1.3.0"}
540
- except Exception as e:
541
- return {"status": "error", "error": str(e), "time": time.time()}
542
-
543
- @tool
544
- def version() -> dict:
545
- return {"name": "memory-server", "version": "1.3.0", "tiers": ["stm","episodes","facts"], "file": FILE}
546
-
547
- @tool
548
- def get_emotion_arc(k: int = 10) -> dict:
549
- """
550
- Get the emotion trajectory (arc) for the last k events.
551
- Returns: {"trajectory": [...], "direction": "escalating|de-escalating|volatile|stable", "summary": str}
552
- """
553
- store = _load()
554
- trajectory, direction = get_emotion_trajectory(store, k=k)
555
-
556
- if not trajectory:
557
- return {"trajectory": [], "direction": "unknown", "summary": "No emotion history"}
558
-
559
- # Create readable summary
560
- emotions = [t["label"] for t in trajectory]
561
- summary = " → ".join(emotions[-5:]) if len(emotions) >= 5 else " → ".join(emotions)
562
-
563
- return {
564
- "trajectory": trajectory,
565
- "direction": direction,
566
- "summary": summary
567
- }
568
-
569
- if __name__ == "__main__":
570
- app.run() # serves MCP over stdio