cognitive-modules 0.4.0__py3-none-any.whl → 0.5.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,245 @@
1
+ """
2
+ Cognitive Modules MCP Server
3
+
4
+ 提供 MCP (Model Context Protocol) 接口,让 Claude Code、Cursor 等工具可以使用 Cognitive Modules。
5
+
6
+ 启动方式:
7
+ cogn mcp
8
+
9
+ 或直接运行:
10
+ python -m cognitive.mcp_server
11
+ """
12
+
13
+ from typing import Optional, Any
14
+ import json
15
+ import os
16
+
17
+ try:
18
+ from mcp.server.fastmcp import FastMCP
19
+ except ImportError:
20
+ raise ImportError(
21
+ "MCP dependencies not installed. "
22
+ "Install with: pip install cognitive-modules[mcp]"
23
+ )
24
+
25
+ from .registry import list_modules, find_module
26
+ from .loader import load_module
27
+ from .runner import run_module as execute_module
28
+
29
+ # ============================================================
30
+ # MCP Server Setup
31
+ # ============================================================
32
+
33
+ mcp = FastMCP(
34
+ "Cognitive Modules",
35
+ description="可验证的结构化 AI 任务规范 - 提供代码审查、任务排序等模块",
36
+ )
37
+
38
+
39
+ # ============================================================
40
+ # Tools
41
+ # ============================================================
42
+
43
+ @mcp.tool()
44
+ def cognitive_run(
45
+ module: str,
46
+ args: str,
47
+ provider: Optional[str] = None,
48
+ model: Optional[str] = None,
49
+ ) -> dict[str, Any]:
50
+ """
51
+ 运行 Cognitive Module,获取结构化的 AI 分析结果。
52
+
53
+ Args:
54
+ module: 模块名称,如 "code-reviewer", "task-prioritizer"
55
+ args: 输入参数,如代码片段或任务列表
56
+ provider: LLM 提供商(可选),如 "openai", "anthropic"
57
+ model: 模型名称(可选),如 "gpt-4o", "claude-3-5-sonnet-20241022"
58
+
59
+ Returns:
60
+ 结构化结果,包含分析内容、confidence(置信度)和 rationale(推理过程)
61
+
62
+ Example:
63
+ cognitive_run("code-reviewer", "def login(u,p): return db.query(f'SELECT * FROM users WHERE name={u}')")
64
+
65
+ 返回:
66
+ {
67
+ "ok": true,
68
+ "data": {
69
+ "issues": [{"type": "security", "severity": "critical", "description": "SQL 注入"}],
70
+ "confidence": 0.95,
71
+ "rationale": "检测到字符串拼接 SQL"
72
+ }
73
+ }
74
+ """
75
+ # 检查模块是否存在
76
+ module_path = find_module(module)
77
+ if not module_path:
78
+ return {"ok": False, "error": f"Module '{module}' not found"}
79
+
80
+ # 设置 provider(如果指定)
81
+ original_provider = os.environ.get("LLM_PROVIDER")
82
+ original_model = os.environ.get("LLM_MODEL")
83
+
84
+ try:
85
+ if provider:
86
+ os.environ["LLM_PROVIDER"] = provider
87
+ if model:
88
+ os.environ["LLM_MODEL"] = model
89
+
90
+ # 执行模块
91
+ result = execute_module(module, args=args)
92
+
93
+ return {"ok": True, "data": result, "module": module}
94
+ except Exception as e:
95
+ return {"ok": False, "error": str(e), "module": module}
96
+ finally:
97
+ # 恢复原始环境变量
98
+ if original_provider:
99
+ os.environ["LLM_PROVIDER"] = original_provider
100
+ elif "LLM_PROVIDER" in os.environ and provider:
101
+ del os.environ["LLM_PROVIDER"]
102
+
103
+ if original_model:
104
+ os.environ["LLM_MODEL"] = original_model
105
+ elif "LLM_MODEL" in os.environ and model:
106
+ del os.environ["LLM_MODEL"]
107
+
108
+
109
+ @mcp.tool()
110
+ def cognitive_list() -> dict[str, Any]:
111
+ """
112
+ 列出所有已安装的 Cognitive Modules。
113
+
114
+ Returns:
115
+ 模块列表,包含名称、位置和格式信息
116
+
117
+ Example:
118
+ cognitive_list()
119
+
120
+ 返回:
121
+ {
122
+ "modules": [
123
+ {"name": "code-reviewer", "location": "builtin", "format": "v1"},
124
+ {"name": "task-prioritizer", "location": "builtin", "format": "v1"}
125
+ ],
126
+ "count": 2
127
+ }
128
+ """
129
+ modules = list_modules()
130
+ return {
131
+ "modules": [
132
+ {"name": m["name"], "location": m["location"], "format": m["format"]}
133
+ for m in modules
134
+ ],
135
+ "count": len(modules),
136
+ }
137
+
138
+
139
+ @mcp.tool()
140
+ def cognitive_info(module: str) -> dict[str, Any]:
141
+ """
142
+ 获取 Cognitive Module 的详细信息。
143
+
144
+ Args:
145
+ module: 模块名称
146
+
147
+ Returns:
148
+ 模块详情,包含名称、描述、输入输出格式等
149
+
150
+ Example:
151
+ cognitive_info("code-reviewer")
152
+
153
+ 返回:
154
+ {
155
+ "name": "code-reviewer",
156
+ "version": "1.0.0",
157
+ "description": "代码安全和质量审查",
158
+ "responsibility": "分析代码并识别潜在问题"
159
+ }
160
+ """
161
+ module_path = find_module(module)
162
+ if not module_path:
163
+ return {"ok": False, "error": f"Module '{module}' not found"}
164
+
165
+ try:
166
+ m = load_module(module)
167
+ meta = m.get("meta", {})
168
+
169
+ return {
170
+ "ok": True,
171
+ "name": meta.get("name", module),
172
+ "version": meta.get("version"),
173
+ "description": meta.get("description") or meta.get("responsibility"),
174
+ "responsibility": meta.get("responsibility"),
175
+ "input_schema": m.get("input_schema"),
176
+ "output_schema": m.get("output_schema"),
177
+ }
178
+ except Exception as e:
179
+ return {"ok": False, "error": str(e)}
180
+
181
+
182
+ # ============================================================
183
+ # Resources
184
+ # ============================================================
185
+
186
+ @mcp.resource("cognitive://modules")
187
+ def get_modules_resource() -> str:
188
+ """获取所有模块列表(资源形式)"""
189
+ modules = list_modules()
190
+ return json.dumps([m["name"] for m in modules], indent=2)
191
+
192
+
193
+ @mcp.resource("cognitive://module/{name}")
194
+ def get_module_resource(name: str) -> str:
195
+ """获取单个模块的 prompt 内容"""
196
+ module_path = find_module(name)
197
+ if not module_path:
198
+ return f"Module '{name}' not found"
199
+
200
+ try:
201
+ m = load_module(name)
202
+ return m.get("prompt", "")
203
+ except Exception as e:
204
+ return f"Error: {e}"
205
+
206
+
207
+ # ============================================================
208
+ # Prompts
209
+ # ============================================================
210
+
211
+ @mcp.prompt()
212
+ def code_review_prompt(code: str) -> str:
213
+ """生成代码审查提示"""
214
+ return f"""请使用 cognitive_run 工具审查以下代码:
215
+
216
+ ```
217
+ {code}
218
+ ```
219
+
220
+ 调用: cognitive_run("code-reviewer", "{code[:100]}...")
221
+ """
222
+
223
+
224
+ @mcp.prompt()
225
+ def task_prioritize_prompt(tasks: str) -> str:
226
+ """生成任务排序提示"""
227
+ return f"""请使用 cognitive_run 工具对以下任务进行优先级排序:
228
+
229
+ {tasks}
230
+
231
+ 调用: cognitive_run("task-prioritizer", "{tasks}")
232
+ """
233
+
234
+
235
+ # ============================================================
236
+ # 启动入口
237
+ # ============================================================
238
+
239
+ def serve():
240
+ """启动 MCP 服务器"""
241
+ mcp.run(transport="stdio")
242
+
243
+
244
+ if __name__ == "__main__":
245
+ serve()