pasm-mcp-server 0.2.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.
- pasm_mcp_server/__init__.py +26 -0
- pasm_mcp_server/__main__.py +11 -0
- pasm_mcp_server/bridge.py +160 -0
- pasm_mcp_server/protocol.py +75 -0
- pasm_mcp_server/py.typed +0 -0
- pasm_mcp_server/server.py +268 -0
- pasm_mcp_server/tools.py +647 -0
- pasm_mcp_server-0.2.0.dist-info/METADATA +235 -0
- pasm_mcp_server-0.2.0.dist-info/RECORD +13 -0
- pasm_mcp_server-0.2.0.dist-info/WHEEL +5 -0
- pasm_mcp_server-0.2.0.dist-info/entry_points.txt +2 -0
- pasm_mcp_server-0.2.0.dist-info/licenses/LICENSE +21 -0
- pasm_mcp_server-0.2.0.dist-info/top_level.txt +1 -0
|
@@ -0,0 +1,26 @@
|
|
|
1
|
+
"""pasm-mcp-server —— 把 PASM 认知内核暴露成标准 MCP 工具。
|
|
2
|
+
|
|
3
|
+
PASM 的核心资产是**长期记忆、连续情绪、被反馈塑形的行为倾向** ——
|
|
4
|
+
这些恰好是大模型原生缺失的。本包不提供"又一个聊天模型",
|
|
5
|
+
而是做一个**认知器官**:任何支持 MCP 的客户端(桌面 AI 客户端、IDE 插件、自建 Agent、
|
|
6
|
+
Cursor、自研 Agent)都能把它挂上去,让自己的模型获得跨会话的认知连续性。
|
|
7
|
+
|
|
8
|
+
三分钟上手
|
|
9
|
+
----------
|
|
10
|
+
|
|
11
|
+
pip install pasm-mcp-server
|
|
12
|
+
pasm-mcp-server --selftest # 先自检,确认安装可用
|
|
13
|
+
|
|
14
|
+
然后在客户端里注册一个 stdio server:
|
|
15
|
+
|
|
16
|
+
command: python
|
|
17
|
+
args: ["-m", "pasm_mcp_server"]
|
|
18
|
+
|
|
19
|
+
最常用的是 `pasm_context`:它返回"此刻该记得什么 + 情绪如何 + 倾向做什么",
|
|
20
|
+
客户端把它拼进自己的提示词,就得到了一个**有记忆、有情绪、会成长**的智能体。
|
|
21
|
+
"""
|
|
22
|
+
from __future__ import annotations
|
|
23
|
+
|
|
24
|
+
__version__ = "0.2.0"
|
|
25
|
+
|
|
26
|
+
__all__ = ["__version__"]
|
|
@@ -0,0 +1,160 @@
|
|
|
1
|
+
"""PASM 认知桥 —— 把 `pasm_skills.sdk.BaseAgent` 包成 MCP 工具能直接调用的接口。
|
|
2
|
+
|
|
3
|
+
设计要点
|
|
4
|
+
--------
|
|
5
|
+
1. **每个 agent_id 一个实例**,进程内缓存。同 id 多次调用共享同一份记忆/情绪/动作权重 ——
|
|
6
|
+
这正是 PASM 的价值所在(跨调用连续的认知状态),而不是每次调用新建。
|
|
7
|
+
2. **档位透明**:`tier` 字段照抄 BaseAgent(light / core / bionic)。
|
|
8
|
+
降级不隐藏 —— 客户端能知道自己用的是哪档。
|
|
9
|
+
3. **不内置 LLM**:`_render_reply` 走模板渲染。
|
|
10
|
+
本包定位是"认知器官",不是"对话引擎" —— 真正的语言生成交给客户端的大模型,
|
|
11
|
+
PASM 负责给它**记忆、情绪、倾向**。想接 LLM 的在自己那一侧接。
|
|
12
|
+
"""
|
|
13
|
+
from __future__ import annotations
|
|
14
|
+
|
|
15
|
+
import json
|
|
16
|
+
import os
|
|
17
|
+
import sys
|
|
18
|
+
from pathlib import Path
|
|
19
|
+
from typing import Any, Dict, List, Optional
|
|
20
|
+
|
|
21
|
+
from . import __version__ # noqa: F401 保证包版本号单一来源
|
|
22
|
+
|
|
23
|
+
# 本地开发逃生口:还没把 pasm-skills 装进当前解释器时,
|
|
24
|
+
# PASM_SKILLS_PATH=/path/to/pasm-skills pasm-mcp-server --selftest
|
|
25
|
+
# 正式部署不需要它(pip install pasm-skills 即可)。
|
|
26
|
+
_skill_path = os.environ.get("PASM_SKILLS_PATH")
|
|
27
|
+
if _skill_path:
|
|
28
|
+
sys.path.insert(0, _skill_path)
|
|
29
|
+
|
|
30
|
+
try:
|
|
31
|
+
from pasm_skills.sdk import BaseAgent
|
|
32
|
+
except ImportError as ex: # pragma: no cover
|
|
33
|
+
raise SystemExit(
|
|
34
|
+
"找不到 pasm-skills 基座。请先安装:pip install pasm-skills>=0.4.4\n"
|
|
35
|
+
"本地开发也可设 PASM_SKILLS_PATH 指向 pasm-skills 仓库根目录。\n"
|
|
36
|
+
"(原始错误:%s)" % ex
|
|
37
|
+
)
|
|
38
|
+
|
|
39
|
+
#: 未显式配置动作池时的默认动作。
|
|
40
|
+
#: 名字里刻意带 BaseAgent._fallback_weights 认得的关键词
|
|
41
|
+
#: (talk/share/teach/give → temper;hop/dance/run → energy;peek/play/joke → play),
|
|
42
|
+
#: 这样即使装在 light 档、没有真学习层,性格参数也仍然起作用。
|
|
43
|
+
DEFAULT_ACTIONS: List[str] = ["greet", "ask", "share", "teach", "listen"]
|
|
44
|
+
|
|
45
|
+
#: 默认人格。客户端可通过 pasm_persona 覆盖任一键。
|
|
46
|
+
DEFAULT_PERSONA: Dict[str, Any] = {
|
|
47
|
+
"name": "小墨",
|
|
48
|
+
"role": "认知陪伴",
|
|
49
|
+
"tone": "温和、简洁",
|
|
50
|
+
"temper": 0.5, # 主动性
|
|
51
|
+
"energy": 0.5, # 活跃度
|
|
52
|
+
"play": 0.5, # 俏皮度
|
|
53
|
+
}
|
|
54
|
+
|
|
55
|
+
|
|
56
|
+
class McpAgent(BaseAgent):
|
|
57
|
+
"""MCP 场景下的 PASM 智能体:动作池与回复模板都可配置,其余交给基座。"""
|
|
58
|
+
|
|
59
|
+
def action_pool(self) -> List[str]:
|
|
60
|
+
acts = self.persona.get("actions")
|
|
61
|
+
if isinstance(acts, list) and acts:
|
|
62
|
+
return [str(a) for a in acts]
|
|
63
|
+
return list(DEFAULT_ACTIONS)
|
|
64
|
+
|
|
65
|
+
def bootstrap_event(self) -> List[Dict[str, Any]]:
|
|
66
|
+
"""首次启动时写一条初始记忆 —— 让 pasm_context 第一次调用就不空手。"""
|
|
67
|
+
name = self.persona.get("name", "小墨")
|
|
68
|
+
return [{
|
|
69
|
+
"title": "初次相遇",
|
|
70
|
+
"brief": f"{name}第一次接入 MCP 客户端,还没有任何共同经历。",
|
|
71
|
+
"tags": ["初次", "相遇"],
|
|
72
|
+
"salience": 3,
|
|
73
|
+
"category": "关系",
|
|
74
|
+
}]
|
|
75
|
+
|
|
76
|
+
def _render_reply(self, text: str, facts: List[Dict[str, Any]], mood: float) -> str:
|
|
77
|
+
"""模板渲染。不带 LLM —— 保证无网、无 key、无 GPU 也能回话。"""
|
|
78
|
+
name = self.persona.get("name", "小墨")
|
|
79
|
+
tone = self.persona.get("tone", "温和")
|
|
80
|
+
parts: List[str] = []
|
|
81
|
+
if facts:
|
|
82
|
+
head = ";".join(str(f.get("title", "")) for f in facts[:2] if f.get("title"))
|
|
83
|
+
if head:
|
|
84
|
+
parts.append(f"我记得「{head}」")
|
|
85
|
+
if mood > 0.25:
|
|
86
|
+
parts.append("现在心情不错")
|
|
87
|
+
elif mood < -0.25:
|
|
88
|
+
parts.append("这会儿有点低落")
|
|
89
|
+
if text:
|
|
90
|
+
parts.append(f"你刚才说的是:{text[:40]}")
|
|
91
|
+
body = ",".join(parts) if parts else "我还在熟悉你"
|
|
92
|
+
return f"{name}({tone}):{body}。"
|
|
93
|
+
|
|
94
|
+
# ------- 人格热更新 -----------------------------------------
|
|
95
|
+
|
|
96
|
+
def set_persona(self, patch: Dict[str, Any]) -> Dict[str, Any]:
|
|
97
|
+
"""合并式更新人格(不是整体替换 —— 漏传的键不该被抹掉)。"""
|
|
98
|
+
if not isinstance(patch, dict):
|
|
99
|
+
raise ValueError("persona 必须是对象")
|
|
100
|
+
self.persona.update(patch)
|
|
101
|
+
if hasattr(self, "state") and isinstance(self.state.persona, dict):
|
|
102
|
+
self.state.persona.update(patch)
|
|
103
|
+
return dict(self.persona)
|
|
104
|
+
|
|
105
|
+
|
|
106
|
+
class CognitiveBridge:
|
|
107
|
+
"""按 agent_id 管理 McpAgent 实例。"""
|
|
108
|
+
|
|
109
|
+
def __init__(self, persist_root: Optional[str | Path] = None,
|
|
110
|
+
default_persona: Optional[Dict[str, Any]] = None):
|
|
111
|
+
root = persist_root or os.environ.get("PASM_MCP_PERSIST_DIR")
|
|
112
|
+
self.persist_root = Path(root) if root else (Path.home() / ".pasm-mcp")
|
|
113
|
+
self.persist_root.mkdir(parents=True, exist_ok=True)
|
|
114
|
+
self._default_persona = dict(DEFAULT_PERSONA)
|
|
115
|
+
if default_persona:
|
|
116
|
+
self._default_persona.update(default_persona)
|
|
117
|
+
# 允许用环境变量整体覆盖默认人格(JSON 字符串)
|
|
118
|
+
env_persona = os.environ.get("PASM_MCP_PERSONA")
|
|
119
|
+
if env_persona:
|
|
120
|
+
try:
|
|
121
|
+
self._default_persona.update(json.loads(env_persona))
|
|
122
|
+
except Exception:
|
|
123
|
+
pass
|
|
124
|
+
self._agents: Dict[str, McpAgent] = {}
|
|
125
|
+
|
|
126
|
+
def get(self, agent_id: str = "default",
|
|
127
|
+
persona: Optional[Dict[str, Any]] = None) -> McpAgent:
|
|
128
|
+
"""取(或创建)一个智能体。persona 只在**首次创建**时生效。
|
|
129
|
+
|
|
130
|
+
已存在的 agent 想改人格请走 pasm_persona 工具 —— 否则每次调用传不同 persona
|
|
131
|
+
会造成"人格抖动",而 persona 是长期资产,不该被单次调用覆盖。
|
|
132
|
+
"""
|
|
133
|
+
if agent_id not in self._agents:
|
|
134
|
+
p = dict(self._default_persona)
|
|
135
|
+
if persona:
|
|
136
|
+
p.update(persona)
|
|
137
|
+
self._agents[agent_id] = McpAgent(
|
|
138
|
+
agent_id=agent_id,
|
|
139
|
+
persona=p,
|
|
140
|
+
persist_dir=self.persist_root / agent_id,
|
|
141
|
+
)
|
|
142
|
+
return self._agents[agent_id]
|
|
143
|
+
|
|
144
|
+
def agent_ids(self) -> List[str]:
|
|
145
|
+
"""已加载的智能体 id 列表。"""
|
|
146
|
+
return sorted(self._agents.keys())
|
|
147
|
+
|
|
148
|
+
def save_all(self) -> List[str]:
|
|
149
|
+
"""落盘所有已加载的智能体(进程退出前调用)。"""
|
|
150
|
+
saved = []
|
|
151
|
+
for aid, ag in self._agents.items():
|
|
152
|
+
try:
|
|
153
|
+
ag.save()
|
|
154
|
+
saved.append(aid)
|
|
155
|
+
except Exception:
|
|
156
|
+
pass
|
|
157
|
+
return saved
|
|
158
|
+
|
|
159
|
+
def __repr__(self) -> str: # pragma: no cover
|
|
160
|
+
return f"<CognitiveBridge root={self.persist_root} agents={list(self._agents)}>"
|
|
@@ -0,0 +1,75 @@
|
|
|
1
|
+
"""MCP 协议常量、版本协商与 JSON-RPC 错误码。
|
|
2
|
+
|
|
3
|
+
只依赖标准库 —— 本包刻意**不依赖**官方 `mcp` Python SDK:
|
|
4
|
+
stdio 上的 MCP 就是「换行分隔的 JSON-RPC 2.0」,自己实现可以做到零依赖、
|
|
5
|
+
启动快(<100ms),也让本包能直接被任意语言的客户端(Node / Python / Electron 外壳)拉起。
|
|
6
|
+
|
|
7
|
+
版本协商策略(重要)
|
|
8
|
+
--------------------
|
|
9
|
+
客户端会在 `initialize` 里带上自己的 `protocolVersion`。
|
|
10
|
+
- 客户端版本在我们支持列表里 → **原样回显**(最安全,双方都认这个版本);
|
|
11
|
+
- 不在列表里 → 回我们默认支持的最新版本,并在 stderr 记一条警告,
|
|
12
|
+
由客户端决定是否继续(规范允许客户端此时断开)。
|
|
13
|
+
|
|
14
|
+
不要把服务端版本写死成一个常量然后无视客户端 —— 那样遇到只认旧版的客户端
|
|
15
|
+
(如部分 2024 年实现的 SDK)会直接握手失败。
|
|
16
|
+
"""
|
|
17
|
+
from __future__ import annotations
|
|
18
|
+
|
|
19
|
+
#: 本服务端支持的协议版本(按时间升序)。
|
|
20
|
+
SUPPORTED_PROTOCOL_VERSIONS = (
|
|
21
|
+
"2024-11-05",
|
|
22
|
+
"2025-03-26",
|
|
23
|
+
"2025-06-18",
|
|
24
|
+
"2026-07-28",
|
|
25
|
+
)
|
|
26
|
+
|
|
27
|
+
#: 客户端没带版本 / 带了不认识的版本时,回这个。
|
|
28
|
+
#: 选 2025-03-26 是因为它在 2025-2026 的客户端里覆盖最广。
|
|
29
|
+
DEFAULT_PROTOCOL_VERSION = "2025-03-26"
|
|
30
|
+
|
|
31
|
+
SERVER_NAME = "pasm-mcp-server"
|
|
32
|
+
SERVER_VERSION = "0.2.0"
|
|
33
|
+
|
|
34
|
+
#: 服务端能力声明。只声明 tools —— 不声明就是不支持,别虚报。
|
|
35
|
+
CAPABILITIES = {"tools": {}}
|
|
36
|
+
|
|
37
|
+
# JSON-RPC 2.0 标准错误码
|
|
38
|
+
PARSE_ERROR = -32700
|
|
39
|
+
INVALID_REQUEST = -32600
|
|
40
|
+
METHOD_NOT_FOUND = -32601
|
|
41
|
+
INVALID_PARAMS = -32602
|
|
42
|
+
INTERNAL_ERROR = -32603
|
|
43
|
+
|
|
44
|
+
|
|
45
|
+
def negotiate(client_version: str | None) -> str:
|
|
46
|
+
"""版本协商:客户端认得的就回显,否则回默认版本。"""
|
|
47
|
+
if client_version and client_version in SUPPORTED_PROTOCOL_VERSIONS:
|
|
48
|
+
return client_version
|
|
49
|
+
return DEFAULT_PROTOCOL_VERSION
|
|
50
|
+
|
|
51
|
+
|
|
52
|
+
def initialize_result(client_version: str | None) -> dict:
|
|
53
|
+
"""构造 `initialize` 的响应 result。"""
|
|
54
|
+
return {
|
|
55
|
+
"protocolVersion": negotiate(client_version),
|
|
56
|
+
"serverInfo": {"name": SERVER_NAME, "version": SERVER_VERSION},
|
|
57
|
+
"capabilities": CAPABILITIES,
|
|
58
|
+
# 2025-06-18 起部分客户端会读这个字段做能力提示,给了无害。
|
|
59
|
+
"instructions": (
|
|
60
|
+
"PASM 认知内核:提供长期记忆、情绪状态与动作倾向。"
|
|
61
|
+
"典型用法是先 pasm_context 取认知上下文,再据此回复;"
|
|
62
|
+
"有值得记住的事就 pasm_observe 写进去;被夸/被凶就用 pasm_feedback 塑形。"
|
|
63
|
+
),
|
|
64
|
+
}
|
|
65
|
+
|
|
66
|
+
|
|
67
|
+
def error_response(req_id, code: int, message: str, data=None) -> dict:
|
|
68
|
+
err: dict = {"code": code, "message": message}
|
|
69
|
+
if data is not None:
|
|
70
|
+
err["data"] = data
|
|
71
|
+
return {"jsonrpc": "2.0", "id": req_id, "error": err}
|
|
72
|
+
|
|
73
|
+
|
|
74
|
+
def result_response(req_id, result: dict) -> dict:
|
|
75
|
+
return {"jsonrpc": "2.0", "id": req_id, "result": result}
|
pasm_mcp_server/py.typed
ADDED
|
File without changes
|
|
@@ -0,0 +1,268 @@
|
|
|
1
|
+
"""stdio MCP 服务器主循环。
|
|
2
|
+
|
|
3
|
+
为什么不用官方 `mcp` SDK
|
|
4
|
+
------------------------
|
|
5
|
+
官方 Python SDK 会拉进 pydantic / starlette / anyio 一串依赖,冷启动明显变慢,
|
|
6
|
+
而 stdio server 是**每个客户端每次会话都要拉起**的进程 —— 启动开销会被放大。
|
|
7
|
+
stdio 上的 MCP 就是「换行分隔的 JSON-RPC 2.0」,本文件用标准库实现全部必需方法
|
|
8
|
+
(initialize / ping / tools/list / tools/call / notifications),零第三方依赖。
|
|
9
|
+
|
|
10
|
+
三条硬约束(踩过就知道)
|
|
11
|
+
------------------------
|
|
12
|
+
1. **stdout 只能有 JSON-RPC**。任何 print / traceback 都必须走 stderr,
|
|
13
|
+
否则客户端解析失败,且报错信息极其难查(表现为"server 无响应")。
|
|
14
|
+
2. **每行一条完整 JSON**,写完立刻 flush —— stdio 是流式的,不 flush 客户端会一直等。
|
|
15
|
+
3. **Windows 下用 buffer 读写**,避免系统把 \\n 自动转成 \\r\\n 破坏协议。
|
|
16
|
+
"""
|
|
17
|
+
from __future__ import annotations
|
|
18
|
+
|
|
19
|
+
import argparse
|
|
20
|
+
import json
|
|
21
|
+
import sys
|
|
22
|
+
from typing import Any, Dict, Optional
|
|
23
|
+
|
|
24
|
+
from . import protocol as P
|
|
25
|
+
from .bridge import CognitiveBridge
|
|
26
|
+
from .tools import call_tool, list_tools
|
|
27
|
+
|
|
28
|
+
|
|
29
|
+
def _log(msg: str) -> None:
|
|
30
|
+
"""日志一律走 stderr —— stdout 是协议通道,不能污染。
|
|
31
|
+
|
|
32
|
+
宿主客户端若把 stderr 也收进自己的日志,可设 ``PASM_MCP_QUIET=1`` 静默
|
|
33
|
+
(工具失败信息仍会通过 isError 内容回给模型,不影响纠错)。
|
|
34
|
+
"""
|
|
35
|
+
import os
|
|
36
|
+
if os.environ.get("PASM_MCP_QUIET") == "1":
|
|
37
|
+
return
|
|
38
|
+
print("[pasm-mcp] %s" % msg, file=sys.stderr, flush=True)
|
|
39
|
+
|
|
40
|
+
|
|
41
|
+
def _write(out, obj: Dict[str, Any]) -> None:
|
|
42
|
+
data = (json.dumps(obj, ensure_ascii=False) + "\n").encode("utf-8")
|
|
43
|
+
out.write(data)
|
|
44
|
+
out.flush()
|
|
45
|
+
|
|
46
|
+
|
|
47
|
+
def handle_message(msg: Dict[str, Any], bridge: CognitiveBridge) -> Optional[Dict[str, Any]]:
|
|
48
|
+
"""处理一条 JSON-RPC 消息。返回 None 表示无需回复(通知类)。"""
|
|
49
|
+
if not isinstance(msg, dict) or msg.get("jsonrpc") != "2.0":
|
|
50
|
+
return P.error_response(msg.get("id") if isinstance(msg, dict) else None,
|
|
51
|
+
P.INVALID_REQUEST, "Invalid Request: jsonrpc must be '2.0'")
|
|
52
|
+
|
|
53
|
+
method = msg.get("method")
|
|
54
|
+
req_id = msg.get("id")
|
|
55
|
+
params = msg.get("params") or {}
|
|
56
|
+
|
|
57
|
+
# 通知类:无 id,不回复
|
|
58
|
+
if method == "notifications/initialized":
|
|
59
|
+
return None
|
|
60
|
+
if isinstance(method, str) and method.startswith("notifications/"):
|
|
61
|
+
return None
|
|
62
|
+
|
|
63
|
+
if method == "initialize":
|
|
64
|
+
client_version = (params or {}).get("protocolVersion")
|
|
65
|
+
return P.result_response(req_id, P.initialize_result(client_version))
|
|
66
|
+
|
|
67
|
+
if method == "ping":
|
|
68
|
+
return P.result_response(req_id, {})
|
|
69
|
+
|
|
70
|
+
if method == "tools/list":
|
|
71
|
+
return P.result_response(req_id, {"tools": list_tools()})
|
|
72
|
+
|
|
73
|
+
if method == "tools/call":
|
|
74
|
+
name = (params or {}).get("name")
|
|
75
|
+
args = (params or {}).get("arguments") or {}
|
|
76
|
+
try:
|
|
77
|
+
result = call_tool(name, args, bridge)
|
|
78
|
+
except KeyError:
|
|
79
|
+
# 未知工具:按规范是协议错误,不是工具执行错误
|
|
80
|
+
return P.error_response(req_id, P.INVALID_PARAMS,
|
|
81
|
+
"Unknown tool: %s" % name)
|
|
82
|
+
except Exception as ex: # noqa: BLE001
|
|
83
|
+
# 工具执行失败:用 isError 内容返回,让大模型看得懂并自行纠错
|
|
84
|
+
_log("tool %s failed: %s" % (name, ex))
|
|
85
|
+
return P.result_response(req_id, {
|
|
86
|
+
"content": [{"type": "text", "text": "PASM 工具 %s 执行失败:%s" % (name, ex)}],
|
|
87
|
+
"isError": True,
|
|
88
|
+
})
|
|
89
|
+
text = json.dumps(result, ensure_ascii=False, indent=2)
|
|
90
|
+
payload: Dict[str, Any] = {
|
|
91
|
+
"content": [{"type": "text", "text": text}],
|
|
92
|
+
"isError": False,
|
|
93
|
+
}
|
|
94
|
+
# 2025-06-18+ 的客户端支持结构化结果,老客户端会忽略这个字段。
|
|
95
|
+
payload["structuredContent"] = result
|
|
96
|
+
return P.result_response(req_id, payload)
|
|
97
|
+
|
|
98
|
+
if method == "shutdown":
|
|
99
|
+
bridge.save_all()
|
|
100
|
+
return P.result_response(req_id, {})
|
|
101
|
+
|
|
102
|
+
return P.error_response(req_id, P.METHOD_NOT_FOUND,
|
|
103
|
+
"Method not found: %s" % method)
|
|
104
|
+
|
|
105
|
+
|
|
106
|
+
def serve(bridge: Optional[CognitiveBridge] = None) -> int:
|
|
107
|
+
"""跑 stdio 主循环,直到 stdin 关闭。"""
|
|
108
|
+
bridge = bridge or CognitiveBridge()
|
|
109
|
+
stdin = sys.stdin.buffer
|
|
110
|
+
out = sys.stdout.buffer
|
|
111
|
+
_log("starting (persist=%s)" % bridge.persist_root)
|
|
112
|
+
try:
|
|
113
|
+
for raw in stdin:
|
|
114
|
+
line = raw.strip()
|
|
115
|
+
if not line:
|
|
116
|
+
continue
|
|
117
|
+
try:
|
|
118
|
+
msg = json.loads(line.decode("utf-8"))
|
|
119
|
+
except Exception:
|
|
120
|
+
_write(out, P.error_response(None, P.PARSE_ERROR, "Parse error"))
|
|
121
|
+
continue
|
|
122
|
+
resp = handle_message(msg, bridge)
|
|
123
|
+
if resp is not None:
|
|
124
|
+
_write(out, resp)
|
|
125
|
+
except KeyboardInterrupt: # pragma: no cover
|
|
126
|
+
pass
|
|
127
|
+
finally:
|
|
128
|
+
# 客户端断开时把状态落盘 —— 记忆不该因为退出而丢
|
|
129
|
+
saved = bridge.save_all()
|
|
130
|
+
if saved:
|
|
131
|
+
_log("saved on exit: %s" % ", ".join(saved))
|
|
132
|
+
return 0
|
|
133
|
+
|
|
134
|
+
|
|
135
|
+
def selftest() -> int:
|
|
136
|
+
"""本地自检:不起 stdio,直接把协议与工具跑一遍。"""
|
|
137
|
+
import tempfile
|
|
138
|
+
ok = True
|
|
139
|
+
|
|
140
|
+
def check(cond: bool, msg: str) -> None:
|
|
141
|
+
nonlocal ok
|
|
142
|
+
print(" %s %s" % ("v" if cond else "x", msg))
|
|
143
|
+
if not cond:
|
|
144
|
+
ok = False
|
|
145
|
+
|
|
146
|
+
print("pasm-mcp-server selftest v%s" % P.SERVER_VERSION)
|
|
147
|
+
with tempfile.TemporaryDirectory() as td:
|
|
148
|
+
bridge = CognitiveBridge(persist_root=td)
|
|
149
|
+
|
|
150
|
+
# initialize
|
|
151
|
+
r = handle_message(
|
|
152
|
+
{"jsonrpc": "2.0", "id": 1, "method": "initialize",
|
|
153
|
+
"params": {"protocolVersion": "2024-11-05"}}, bridge)
|
|
154
|
+
check(r["result"]["protocolVersion"] == "2024-11-05", "版本协商回显客户端版本")
|
|
155
|
+
check(r["result"]["serverInfo"]["name"] == P.SERVER_NAME, "serverInfo 正确")
|
|
156
|
+
|
|
157
|
+
# tools/list
|
|
158
|
+
r = handle_message({"jsonrpc": "2.0", "id": 2, "method": "tools/list"}, bridge)
|
|
159
|
+
names = [t["name"] for t in r["result"]["tools"]]
|
|
160
|
+
check(len(names) >= 10, "tools/list 返回 %d 个工具" % len(names))
|
|
161
|
+
check("fn" not in r["result"]["tools"][0], "对外清单不含内部 fn 字段")
|
|
162
|
+
|
|
163
|
+
# tools/call: observe
|
|
164
|
+
r = handle_message(
|
|
165
|
+
{"jsonrpc": "2.0", "id": 3, "method": "tools/call",
|
|
166
|
+
"params": {"name": "pasm_observe",
|
|
167
|
+
"arguments": {"title": "用户叫小志", "brief": "他在做 PASM",
|
|
168
|
+
"tags": ["姓名"], "salience": 5}}}, bridge)
|
|
169
|
+
check(r["result"]["isError"] is False, "pasm_observe 写入成功")
|
|
170
|
+
|
|
171
|
+
# tools/call: recall(应命中刚写的记忆)
|
|
172
|
+
r = handle_message(
|
|
173
|
+
{"jsonrpc": "2.0", "id": 4, "method": "tools/call",
|
|
174
|
+
"params": {"name": "pasm_recall", "arguments": {"query": "小志"}}}, bridge)
|
|
175
|
+
hits = r["result"]["structuredContent"]["hits"]
|
|
176
|
+
check(len(hits) >= 1, "pasm_recall 能检索到刚写入的记忆")
|
|
177
|
+
|
|
178
|
+
# tools/call: context
|
|
179
|
+
r = handle_message(
|
|
180
|
+
{"jsonrpc": "2.0", "id": 5, "method": "tools/call",
|
|
181
|
+
"params": {"name": "pasm_context", "arguments": {"query": "姓名"}}}, bridge)
|
|
182
|
+
ctx = r["result"]["structuredContent"]
|
|
183
|
+
check("mood" in ctx and "recalled" in ctx, "pasm_context 返回情绪与记忆")
|
|
184
|
+
|
|
185
|
+
# tools/call: feedback
|
|
186
|
+
r = handle_message(
|
|
187
|
+
{"jsonrpc": "2.0", "id": 6, "method": "tools/call",
|
|
188
|
+
"params": {"name": "pasm_feedback",
|
|
189
|
+
"arguments": {"kind": "praise", "action": "teach"}}}, bridge)
|
|
190
|
+
w = r["result"]["structuredContent"]["weights"]
|
|
191
|
+
check("teach" in w, "pasm_feedback 作用于指定动作")
|
|
192
|
+
|
|
193
|
+
# tools/call: 语义检索(换说法命中:存的是"用户叫小志",问"我叫什么名字")
|
|
194
|
+
r = handle_message(
|
|
195
|
+
{"jsonrpc": "2.0", "id": 9, "method": "tools/call",
|
|
196
|
+
"params": {"name": "pasm_semantic", "arguments": {"query": "我叫什么名字"}}}, bridge)
|
|
197
|
+
sem = r["result"].get("structuredContent") or {}
|
|
198
|
+
check(r["result"]["isError"] is False,
|
|
199
|
+
"pasm_semantic 可执行(mode=%s)" % sem.get("mode", "?"))
|
|
200
|
+
if sem.get("mode") == "semantic":
|
|
201
|
+
check(bool(sem.get("hits")), "语义检索:换说法也能命中")
|
|
202
|
+
check("score" in (sem.get("hits") or [{}])[0], "语义检索给出可解释打分")
|
|
203
|
+
|
|
204
|
+
# tools/call: 焦点栈
|
|
205
|
+
r = handle_message(
|
|
206
|
+
{"jsonrpc": "2.0", "id": 10, "method": "tools/call",
|
|
207
|
+
"params": {"name": "pasm_focus",
|
|
208
|
+
"arguments": {"topic": "身份信息", "entities": ["小志"]}}}, bridge)
|
|
209
|
+
check(r["result"]["isError"] is False, "pasm_focus 可压入话题")
|
|
210
|
+
|
|
211
|
+
# tools/call: 巩固(默认只出建议,不落盘)
|
|
212
|
+
r = handle_message(
|
|
213
|
+
{"jsonrpc": "2.0", "id": 11, "method": "tools/call",
|
|
214
|
+
"params": {"name": "pasm_consolidate", "arguments": {}}}, bridge)
|
|
215
|
+
con = r["result"].get("structuredContent") or {}
|
|
216
|
+
check(r["result"]["isError"] is False and con.get("applied") is False,
|
|
217
|
+
"pasm_consolidate 默认只出建议(不落盘)")
|
|
218
|
+
|
|
219
|
+
# 状态里能看到认知层
|
|
220
|
+
r = handle_message(
|
|
221
|
+
{"jsonrpc": "2.0", "id": 12, "method": "tools/call",
|
|
222
|
+
"params": {"name": "pasm_status", "arguments": {}}}, bridge)
|
|
223
|
+
st = r["result"].get("structuredContent") or {}
|
|
224
|
+
check("cognition" in st, "pasm_status 报告认知层状态")
|
|
225
|
+
|
|
226
|
+
# 未知工具 → 协议错误
|
|
227
|
+
r = handle_message(
|
|
228
|
+
{"jsonrpc": "2.0", "id": 7, "method": "tools/call",
|
|
229
|
+
"params": {"name": "nope", "arguments": {}}}, bridge)
|
|
230
|
+
check("error" in r and r["error"]["code"] == P.INVALID_PARAMS, "未知工具返回协议错误")
|
|
231
|
+
|
|
232
|
+
# 工具内部报错 → isError 内容
|
|
233
|
+
r = handle_message(
|
|
234
|
+
{"jsonrpc": "2.0", "id": 8, "method": "tools/call",
|
|
235
|
+
"params": {"name": "pasm_observe", "arguments": {}}}, bridge)
|
|
236
|
+
check(r["result"]["isError"] is True, "参数缺失返回 isError 内容")
|
|
237
|
+
|
|
238
|
+
# 通知类不回复
|
|
239
|
+
check(handle_message({"jsonrpc": "2.0", "method": "notifications/initialized"},
|
|
240
|
+
bridge) is None, "通知类消息不回复")
|
|
241
|
+
|
|
242
|
+
# 落盘
|
|
243
|
+
saved = bridge.save_all()
|
|
244
|
+
check(len(saved) >= 1, "状态可落盘")
|
|
245
|
+
|
|
246
|
+
print("pasm-mcp-server selftest:", "通过" if ok else "失败")
|
|
247
|
+
return 0 if ok else 1
|
|
248
|
+
|
|
249
|
+
|
|
250
|
+
def main(argv: Optional[list] = None) -> int:
|
|
251
|
+
ap = argparse.ArgumentParser(
|
|
252
|
+
prog="pasm-mcp-server",
|
|
253
|
+
description="PASM 认知内核的 MCP 服务器(stdio)")
|
|
254
|
+
ap.add_argument("--persist-dir", default=None,
|
|
255
|
+
help="状态落盘根目录,默认 ~/.pasm-mcp")
|
|
256
|
+
ap.add_argument("--selftest", action="store_true",
|
|
257
|
+
help="本地自检(不起 stdio),用于验证安装是否可用")
|
|
258
|
+
ap.add_argument("--version", action="version",
|
|
259
|
+
version="%(prog)s " + P.SERVER_VERSION)
|
|
260
|
+
args = ap.parse_args(argv)
|
|
261
|
+
|
|
262
|
+
if args.selftest:
|
|
263
|
+
return selftest()
|
|
264
|
+
return serve(CognitiveBridge(persist_root=args.persist_dir))
|
|
265
|
+
|
|
266
|
+
|
|
267
|
+
if __name__ == "__main__":
|
|
268
|
+
raise SystemExit(main())
|