wengu 1.0.0__py3-none-any.whl

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -0,0 +1,88 @@
1
+ Metadata-Version: 2.4
2
+ Name: wengu
3
+ Version: 1.0.0
4
+ Summary: 温故 - Agent cross-session persistent memory, pure stdlib single file with MCP stdio server
5
+ Author: tanbopiao
6
+ License: MIT
7
+ Keywords: mcp,mcp-server,memory,persistent-memory,agent,cross-session,cli
8
+ Classifier: Development Status :: 4 - Beta
9
+ Classifier: Intended Audience :: Developers
10
+ Classifier: License :: OSI Approved :: MIT License
11
+ Classifier: Programming Language :: Python :: 3
12
+ Classifier: Topic :: Software Development :: Libraries
13
+ Requires-Python: >=3.8
14
+ Description-Content-Type: text/markdown
15
+ License-File: LICENSE
16
+ Dynamic: license-file
17
+
18
+ <!-- mcp-name: io.github.tanbopiao/wengu -->
19
+
20
+ # wengu 温故
21
+
22
+ > 温故而知新,可以为师矣 ——《论语·为政》
23
+
24
+ Agent 跨会话持久记忆,纯标准库单文件 Python,零依赖。
25
+
26
+ Agent 每次新会话都从零开始:重读同样的文件、重问同样的问题、重踩已经一起修过的坑。wengu 把「观察沉淀 → 索引注入 → 按需取详」这三步提炼成一个单文件工具,让下一个会话从上一个会话结束的地方开始。
27
+
28
+ ## 名字出处
29
+
30
+ 「温故而知新,可以为师矣」出自《论语·为政》。旧会话沉淀为「故」,新会话注入为「新」——温故知新正是这套东西的工作方式。
31
+
32
+ ## 用法
33
+
34
+ ```bash
35
+ # 沉淀一条观察(决策/修复/功能/笔记)
36
+ wengu.py add --project myproj --type decision --title "网关改用 FastMCP" \
37
+ --narrative "官方 SDK 无 MCPServer 类,改 FastMCP 构造函数传参" \
38
+ --fact "SDK 1.30.0 无该类" --file kernel_mcp_server.py
39
+
40
+ # 会话结束沉淀摘要(Stop 等价物)
41
+ wengu.py summary --project myproj --text "完成两处网关修复并握手验证"
42
+
43
+ # 新会话启动:注入紧凑索引(每条约 10-20 token)
44
+ wengu.py index --project myproj --limit 50
45
+
46
+ # 三层渐进检索
47
+ wengu.py search --project myproj --query "网关 修复" # 第一层:关键词索引
48
+ wengu.py timeline --project myproj --id 2 # 第二层:时间上下文
49
+ wengu.py get --project myproj --id 1 --id 2 # 第三层:全文详情
50
+
51
+ # 统计
52
+ wengu.py stats --project myproj
53
+ ```
54
+
55
+ 存储为 `~/.wengu/<project>.jsonl`,每行一条观察记录,纯文本、可读、可迁移——复制文件即完成备份与迁移。
56
+
57
+ ## 与上游的取舍
58
+
59
+ 上游 [thedotmack/claude-mem](https://github.com/thedotmack/claude-mem)(Apache-2.0,约 11 万星)是完整的记忆系统:Node.js + Bun 运行时、Express worker 服务、React 界面、SQLite + Chroma 向量库、19 个宿主适配器、遥测与云同步。
60
+
61
+ wengu 只提炼核心三步,外围全砍:
62
+
63
+ | 维度 | claude-mem | wengu |
64
+ | --- | --- | --- |
65
+ | 运行时 | Node.js 20+ / Bun | Python 3 标准库,零依赖 |
66
+ | 组件 | worker + Express + React + SQLite + Chroma | 单文件 ~220 行 |
67
+ | 检索 | 全文 + 向量语义 | 关键词打分 + 三层渐进 |
68
+ | 资源占用 | 完整形态数百 MB 级 | 实测峰值 12.5 MB |
69
+ | 遥测 | PostHog 默认开启 | 无 |
70
+ | 存储 | SQLite + Chroma 二进制 | JSONL 纯文本 |
71
+
72
+ ## 如实边界
73
+
74
+ - 关键词检索不是语义检索:同义改写查不到,需命中字面词。
75
+ - 观察压缩(observer)需外部模型完成,wengu 只负责存取与检索,不生成内容。
76
+ - 无 Web 界面、无云同步、无多宿主适配——单机单用户场景。
77
+
78
+ ## 复刻哲学
79
+
80
+ 功能可以复刻、架构可以复刻、逻辑可以复刻——代码算子由自己生成完善,达到同样的功能与能力,而资源占用降低一个数量级。
81
+
82
+ ## 致谢
83
+
84
+ 本项目为独立重写,与上游无代码血缘。核心场景与三层渐进检索的思路启发自 [thedotmack/claude-mem](https://github.com/thedotmack/claude-mem)(Apache-2.0),感谢上游项目的开源贡献。
85
+
86
+ ## 许可证
87
+
88
+ MIT
@@ -0,0 +1,8 @@
1
+ wengu.py,sha256=6FAc4GZ2okUy9uszphBXJmGN5NyiUxizcy0YwZ24eVw,7006
2
+ wengu_mcp.py,sha256=qT_2H4PLmOQ1C63P3odkjysLpIAgEqoCU0kqKgrlpNs,8062
3
+ wengu-1.0.0.dist-info/licenses/LICENSE,sha256=G2y8vMxJfDnECLStbmZTH-nNorCJwFexqeqof1PBYS8,1066
4
+ wengu-1.0.0.dist-info/METADATA,sha256=LkN0y1bUchOZ9fUhLQGZX-JhKpBkI1A-dCxhZ4puhQo,3804
5
+ wengu-1.0.0.dist-info/WHEEL,sha256=mOdXR9C3wMVov7cSY8PY-XCzo3SmmWCHvGQr5csJoao,91
6
+ wengu-1.0.0.dist-info/entry_points.txt,sha256=Amc68unnt__lB4WkDhYPxL3hd7-MFtNkq4vLp4EJscM,64
7
+ wengu-1.0.0.dist-info/top_level.txt,sha256=Z6WvMk-PY8fxhsabZLol5itSeuBMFs-SxEBQA_Xh194,16
8
+ wengu-1.0.0.dist-info/RECORD,,
@@ -0,0 +1,5 @@
1
+ Wheel-Version: 1.0
2
+ Generator: setuptools (84.2.1)
3
+ Root-Is-Purelib: true
4
+ Tag: py3-none-any
5
+
@@ -0,0 +1,3 @@
1
+ [console_scripts]
2
+ wengu = wengu:main
3
+ wengu-mcp = wengu_mcp:main
@@ -0,0 +1,21 @@
1
+ MIT License
2
+
3
+ Copyright (c) 2026 tanbopiao
4
+
5
+ Permission is hereby granted, free of charge, to any person obtaining a copy
6
+ of this software and associated documentation files (the "Software"), to deal
7
+ in the Software without restriction, including without limitation the rights
8
+ to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
9
+ copies of the Software, and to permit persons to whom the Software is
10
+ furnished to do so, subject to the following conditions:
11
+
12
+ The above copyright notice and this permission notice shall be included in all
13
+ copies or substantial portions of the Software.
14
+
15
+ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
16
+ IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
17
+ FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
18
+ AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
19
+ LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
20
+ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
21
+ SOFTWARE.
@@ -0,0 +1,2 @@
1
+ wengu
2
+ wengu_mcp
wengu.py ADDED
@@ -0,0 +1,218 @@
1
+ #!/usr/bin/env python3
2
+ # -*- coding: utf-8 -*-
3
+ """
4
+ wengu 温故 —— Agent 跨会话持久记忆(纯标准库单文件)
5
+
6
+ 铭文:温故而知新,可以为师矣(《论语·为政》)
7
+ 上游:thedotmack/claude-mem(Apache-2.0)。独立重写,无代码血缘。
8
+ 取舍:只保留核心三步——观察沉淀、索引注入、三层渐进检索(索引→时间线→全文)。
9
+ 外围全砍:Node/Bun 运行时、Express 服务、React 界面、Chroma 向量库、遥测、云同步。
10
+
11
+ 用法:
12
+ wengu.py add --project P --type decision --title T --narrative N [--fact F]... [--file PATH]...
13
+ wengu.py index --project P [--limit 50] # 会话启动注入的紧凑索引
14
+ wengu.py search --project P --query Q [--limit 10] # 第一层:关键词检索索引
15
+ wengu.py timeline --project P --id ID [--around 3] # 第二层:时间上下文
16
+ wengu.py get --project P --id 1 --id 2 ... # 第三层:全文详情
17
+ wengu.py summary --project P --text S # 会话结束摘要(Stop 等价物)
18
+ wengu.py stats --project P
19
+
20
+ 存储:~/.wengu/<project>.jsonl,每行一条观察记录,纯文本可读可迁移。
21
+ """
22
+ import argparse
23
+ import json
24
+ import os
25
+ import re
26
+ import sys
27
+ import time
28
+
29
+ STORE = os.path.join(os.path.expanduser("~"), ".wengu")
30
+ TYPES = ("decision", "bugfix", "feature", "refactor", "note", "summary")
31
+
32
+
33
+ def store_path(project):
34
+ safe = re.sub(r"[^A-Za-z0-9_.-]", "_", project)
35
+ return os.path.join(STORE, safe + ".jsonl")
36
+
37
+
38
+ def load_all(project):
39
+ path = store_path(project)
40
+ if not os.path.exists(path):
41
+ return []
42
+ out = []
43
+ with open(path, "r", encoding="utf-8") as f:
44
+ for line in f:
45
+ line = line.strip()
46
+ if line:
47
+ try:
48
+ out.append(json.loads(line))
49
+ except json.JSONDecodeError:
50
+ continue
51
+ return out
52
+
53
+
54
+ def next_id(records):
55
+ return (max((r["id"] for r in records), default=0)) + 1
56
+
57
+
58
+ def est_tokens(text):
59
+ # 粗估:中文按 1 字 1 token,英文按 4 字符 1 token
60
+ cjk = len(re.findall(r"[\u4e00-\u9fff]", text))
61
+ return cjk + max(0, (len(text) - cjk) // 4)
62
+
63
+
64
+ def index_row(r):
65
+ return "#%d [%s] %s (~%dtok)" % (r["id"], r["type"], r["title"], est_tokens(r["narrative"]))
66
+
67
+
68
+ def cmd_add(args):
69
+ rec = {
70
+ "id": 0,
71
+ "type": args.type,
72
+ "title": args.title,
73
+ "narrative": args.narrative,
74
+ "facts": args.fact or [],
75
+ "files": args.file or [],
76
+ "ts": time.strftime("%Y-%m-%dT%H:%M:%S%z"),
77
+ "project": args.project,
78
+ }
79
+ records = load_all(args.project)
80
+ rec["id"] = next_id(records)
81
+ os.makedirs(STORE, exist_ok=True)
82
+ with open(store_path(args.project), "a", encoding="utf-8") as f:
83
+ f.write(json.dumps(rec, ensure_ascii=False) + "\n")
84
+ print(index_row(rec))
85
+ return 0
86
+
87
+
88
+ def cmd_index(args):
89
+ records = load_all(args.project)
90
+ for r in records[-args.limit:]:
91
+ print(index_row(r))
92
+ return 0
93
+
94
+
95
+ def _score(record, terms):
96
+ hay = " ".join([record["title"], record["narrative"], " ".join(record["facts"]), " ".join(record["files"])]).lower()
97
+ return sum(hay.count(t) for t in terms)
98
+
99
+
100
+ def cmd_search(args):
101
+ terms = [t for t in re.split(r"\s+", args.query.strip().lower()) if t]
102
+ if not terms:
103
+ return 0
104
+ records = load_all(args.project)
105
+ scored = [( _score(r, terms), r) for r in records]
106
+ hits = [r for s, r in scored if s > 0]
107
+ hits.sort(key=lambda r: (-_score(r, terms), r["id"]))
108
+ for r in hits[: args.limit]:
109
+ print(index_row(r))
110
+ return 0
111
+
112
+
113
+ def cmd_timeline(args):
114
+ records = load_all(args.project)
115
+ ids = [r["id"] for r in records]
116
+ if args.id not in ids:
117
+ print("not found: #%d" % args.id, file=sys.stderr)
118
+ return 1
119
+ pos = ids.index(args.id)
120
+ lo = max(0, pos - args.around)
121
+ hi = min(len(records), pos + args.around + 1)
122
+ for r in records[lo:hi]:
123
+ mark = " ->" if r["id"] == args.id else " "
124
+ print("%s #%d %s [%s] %s" % (mark, r["id"], r["ts"], r["type"], r["title"]))
125
+ return 0
126
+
127
+
128
+ def cmd_get(args):
129
+ records = load_all(args.project)
130
+ by_id = {r["id"]: r for r in records}
131
+ for i in args.id:
132
+ r = by_id.get(i)
133
+ if not r:
134
+ print("not found: #%d" % i, file=sys.stderr)
135
+ continue
136
+ print(json.dumps(r, ensure_ascii=False, indent=2))
137
+ return 0
138
+
139
+
140
+ def cmd_summary(args):
141
+ rec = {
142
+ "id": 0,
143
+ "type": "summary",
144
+ "title": (args.text[:40] + "…") if len(args.text) > 40 else args.text,
145
+ "narrative": args.text,
146
+ "facts": [],
147
+ "files": [],
148
+ "ts": time.strftime("%Y-%m-%dT%H:%M:%S%z"),
149
+ "project": args.project,
150
+ }
151
+ records = load_all(args.project)
152
+ rec["id"] = next_id(records)
153
+ os.makedirs(STORE, exist_ok=True)
154
+ with open(store_path(args.project), "a", encoding="utf-8") as f:
155
+ f.write(json.dumps(rec, ensure_ascii=False) + "\n")
156
+ print(index_row(rec))
157
+ return 0
158
+
159
+
160
+ def cmd_stats(args):
161
+ records = load_all(args.project)
162
+ by_type = {}
163
+ for r in records:
164
+ by_type[r["type"]] = by_type.get(r["type"], 0) + 1
165
+ print("project=%s records=%d types=%s" % (args.project, len(records), json.dumps(by_type, ensure_ascii=False)))
166
+ return 0
167
+
168
+
169
+ def main():
170
+ p = argparse.ArgumentParser(prog="wengu", description="温故:Agent 跨会话持久记忆")
171
+ sub = p.add_subparsers(dest="cmd", required=True)
172
+
173
+ a = sub.add_parser("add")
174
+ a.add_argument("--project", required=True)
175
+ a.add_argument("--type", choices=TYPES, default="note")
176
+ a.add_argument("--title", required=True)
177
+ a.add_argument("--narrative", required=True)
178
+ a.add_argument("--fact", action="append")
179
+ a.add_argument("--file", action="append")
180
+ a.set_defaults(func=cmd_add)
181
+
182
+ i = sub.add_parser("index")
183
+ i.add_argument("--project", required=True)
184
+ i.add_argument("--limit", type=int, default=50)
185
+ i.set_defaults(func=cmd_index)
186
+
187
+ s = sub.add_parser("search")
188
+ s.add_argument("--project", required=True)
189
+ s.add_argument("--query", required=True)
190
+ s.add_argument("--limit", type=int, default=10)
191
+ s.set_defaults(func=cmd_search)
192
+
193
+ t = sub.add_parser("timeline")
194
+ t.add_argument("--project", required=True)
195
+ t.add_argument("--id", type=int, required=True)
196
+ t.add_argument("--around", type=int, default=3)
197
+ t.set_defaults(func=cmd_timeline)
198
+
199
+ g = sub.add_parser("get")
200
+ g.add_argument("--project", required=True)
201
+ g.add_argument("--id", type=int, action="append", required=True)
202
+ g.set_defaults(func=cmd_get)
203
+
204
+ su = sub.add_parser("summary")
205
+ su.add_argument("--project", required=True)
206
+ su.add_argument("--text", required=True)
207
+ su.set_defaults(func=cmd_summary)
208
+
209
+ st = sub.add_parser("stats")
210
+ st.add_argument("--project", required=True)
211
+ st.set_defaults(func=cmd_stats)
212
+
213
+ args = p.parse_args()
214
+ sys.exit(args.func(args))
215
+
216
+
217
+ if __name__ == "__main__":
218
+ main()
wengu_mcp.py ADDED
@@ -0,0 +1,226 @@
1
+ #!/usr/bin/env python3
2
+ # -*- coding: utf-8 -*-
3
+ """
4
+ wengu_mcp —— 温故 MCP stdio 服务(JSON-RPC 2.0 over stdio,零依赖)
5
+
6
+ 照道统算子谱模式:initialize → tools/list → tools/call,换行分隔 JSON。
7
+ 与 wengu.py 同目录部署,复用其存储与检索逻辑。
8
+
9
+ 本机验证:
10
+ echo '{"jsonrpc":"2.0","id":0,"method":"initialize","params":{"protocolVersion":"2024-11-05","capabilities":{},"clientInfo":{"name":"test","version":"0"}}}' | python3 wengu_mcp.py
11
+ """
12
+ import contextlib
13
+ import io
14
+ import json
15
+ import sys
16
+
17
+ sys.path.insert(0, __file__.rsplit("/", 1)[0])
18
+
19
+ import wengu # noqa: E402
20
+
21
+
22
+ def quiet(fn, *args):
23
+ """执行 wengu 命令函数并吞掉其 stdout 打印,避免污染 stdio 协议流。"""
24
+ with contextlib.redirect_stdout(io.StringIO()):
25
+ return fn(*args)
26
+
27
+ SERVER_INFO = {"name": "wengu", "version": "1.0.0"}
28
+ PROTOCOL_VERSION = "2024-11-05"
29
+
30
+ TOOLS = [
31
+ {
32
+ "name": "wengu_add",
33
+ "description": "沉淀一条观察记录(决策/修复/功能/笔记)",
34
+ "inputSchema": {
35
+ "type": "object",
36
+ "properties": {
37
+ "project": {"type": "string", "description": "项目名"},
38
+ "type": {"type": "string", "enum": list(wengu.TYPES), "description": "记录类型"},
39
+ "title": {"type": "string", "description": "一句话标题"},
40
+ "narrative": {"type": "string", "description": "叙述"},
41
+ "facts": {"type": "array", "items": {"type": "string"}, "description": "事实清单"},
42
+ "files": {"type": "array", "items": {"type": "string"}, "description": "涉及文件"},
43
+ },
44
+ "required": ["project", "title", "narrative"],
45
+ },
46
+ },
47
+ {
48
+ "name": "wengu_index",
49
+ "description": "会话启动注入的紧凑索引(每条约 10-20 token)",
50
+ "inputSchema": {
51
+ "type": "object",
52
+ "properties": {
53
+ "project": {"type": "string"},
54
+ "limit": {"type": "integer", "default": 50},
55
+ },
56
+ "required": ["project"],
57
+ },
58
+ },
59
+ {
60
+ "name": "wengu_search",
61
+ "description": "第一层检索:关键词打分返回索引行",
62
+ "inputSchema": {
63
+ "type": "object",
64
+ "properties": {
65
+ "project": {"type": "string"},
66
+ "query": {"type": "string"},
67
+ "limit": {"type": "integer", "default": 10},
68
+ },
69
+ "required": ["project", "query"],
70
+ },
71
+ },
72
+ {
73
+ "name": "wengu_timeline",
74
+ "description": "第二层检索:某条记录的时间上下文",
75
+ "inputSchema": {
76
+ "type": "object",
77
+ "properties": {
78
+ "project": {"type": "string"},
79
+ "id": {"type": "integer"},
80
+ "around": {"type": "integer", "default": 3},
81
+ },
82
+ "required": ["project", "id"],
83
+ },
84
+ },
85
+ {
86
+ "name": "wengu_get",
87
+ "description": "第三层检索:按 ID 取全文详情",
88
+ "inputSchema": {
89
+ "type": "object",
90
+ "properties": {
91
+ "project": {"type": "string"},
92
+ "ids": {"type": "array", "items": {"type": "integer"}},
93
+ },
94
+ "required": ["project", "ids"],
95
+ },
96
+ },
97
+ {
98
+ "name": "wengu_summary",
99
+ "description": "会话结束沉淀摘要(Stop 等价物)",
100
+ "inputSchema": {
101
+ "type": "object",
102
+ "properties": {
103
+ "project": {"type": "string"},
104
+ "text": {"type": "string"},
105
+ },
106
+ "required": ["project", "text"],
107
+ },
108
+ },
109
+ {
110
+ "name": "wengu_stats",
111
+ "description": "项目记录统计",
112
+ "inputSchema": {
113
+ "type": "object",
114
+ "properties": {"project": {"type": "string"}},
115
+ "required": ["project"],
116
+ },
117
+ },
118
+ ]
119
+
120
+
121
+ class Args:
122
+ def __init__(self, **kw):
123
+ self.__dict__.update(kw)
124
+
125
+
126
+ def call_tool(name, a):
127
+ if name == "wengu_add":
128
+ quiet(wengu.cmd_add, Args(project=a["project"], type=a.get("type", "note"),
129
+ title=a["title"], narrative=a["narrative"],
130
+ fact=a.get("facts"), file=a.get("files")))
131
+ return "ok"
132
+ if name == "wengu_index":
133
+ lines = []
134
+ records = wengu.load_all(a["project"])
135
+ for r in records[-a.get("limit", 50):]:
136
+ lines.append(wengu.index_row(r))
137
+ return "\n".join(lines) or "(empty)"
138
+ if name == "wengu_search":
139
+ lines = []
140
+ terms = [t for t in a["query"].strip().lower().split() if t]
141
+ records = wengu.load_all(a["project"])
142
+ scored = [(wengu._score(r, terms), r) for r in records]
143
+ hits = [r for s, r in scored if s > 0]
144
+ hits.sort(key=lambda r: (-wengu._score(r, terms), r["id"]))
145
+ for r in hits[: a.get("limit", 10)]:
146
+ lines.append(wengu.index_row(r))
147
+ return "\n".join(lines) or "(no hits)"
148
+ if name == "wengu_timeline":
149
+ records = wengu.load_all(a["project"])
150
+ ids = [r["id"] for r in records]
151
+ target = a["id"]
152
+ if target not in ids:
153
+ return "not found: #%d" % target
154
+ pos = ids.index(target)
155
+ lo = max(0, pos - a.get("around", 3))
156
+ hi = min(len(records), pos + a.get("around", 3) + 1)
157
+ lines = []
158
+ for r in records[lo:hi]:
159
+ mark = " ->" if r["id"] == target else " "
160
+ lines.append("%s #%d %s [%s] %s" % (mark, r["id"], r["ts"], r["type"], r["title"]))
161
+ return "\n".join(lines)
162
+ if name == "wengu_get":
163
+ records = wengu.load_all(a["project"])
164
+ by_id = {r["id"]: r for r in records}
165
+ found = [by_id[i] for i in a["ids"] if i in by_id]
166
+ return json.dumps(found, ensure_ascii=False, indent=2) or "(empty)"
167
+ if name == "wengu_summary":
168
+ quiet(wengu.cmd_summary, Args(project=a["project"], text=a["text"]))
169
+ return "ok"
170
+ if name == "wengu_stats":
171
+ records = wengu.load_all(a["project"])
172
+ by_type = {}
173
+ for r in records:
174
+ by_type[r["type"]] = by_type.get(r["type"], 0) + 1
175
+ return json.dumps({"project": a["project"], "records": len(records), "types": by_type}, ensure_ascii=False)
176
+ raise ValueError("unknown tool: " + name)
177
+
178
+
179
+ def handle(msg):
180
+ method = msg.get("method")
181
+ mid = msg.get("id")
182
+ is_notification = "id" not in msg
183
+
184
+ if method == "initialize":
185
+ return {"jsonrpc": "2.0", "id": mid, "result": {
186
+ "protocolVersion": PROTOCOL_VERSION,
187
+ "capabilities": {"tools": {}},
188
+ "serverInfo": SERVER_INFO,
189
+ }}
190
+ if method == "notifications/initialized":
191
+ return None
192
+ if method == "tools/list":
193
+ return {"jsonrpc": "2.0", "id": mid, "result": {"tools": TOOLS}}
194
+ if method == "tools/call":
195
+ params = msg.get("params", {})
196
+ name = params.get("name")
197
+ arguments = params.get("arguments", {})
198
+ try:
199
+ result = call_tool(name, arguments)
200
+ return {"jsonrpc": "2.0", "id": mid, "result": {
201
+ "content": [{"type": "text", "text": str(result)}], "isError": False}}
202
+ except Exception as e: # noqa: BLE001
203
+ return {"jsonrpc": "2.0", "id": mid, "result": {
204
+ "content": [{"type": "text", "text": "error: %s" % e}], "isError": True}}
205
+ if mid is not None:
206
+ return {"jsonrpc": "2.0", "id": mid, "error": {"code": -32601, "message": "method not found: %s" % method}}
207
+ return None
208
+
209
+
210
+ def main():
211
+ for line in sys.stdin:
212
+ line = line.strip()
213
+ if not line:
214
+ continue
215
+ try:
216
+ msg = json.loads(line)
217
+ except json.JSONDecodeError:
218
+ continue
219
+ resp = handle(msg)
220
+ if resp is not None:
221
+ sys.stdout.write(json.dumps(resp, ensure_ascii=False) + "\n")
222
+ sys.stdout.flush()
223
+
224
+
225
+ if __name__ == "__main__":
226
+ main()