pisha 0.1.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.
- pisha/__init__.py +14 -0
- pisha/__main__.py +9 -0
- pisha/core.py +462 -0
- pisha/mcp.py +18 -0
- pisha-0.1.0.dist-info/METADATA +95 -0
- pisha-0.1.0.dist-info/RECORD +10 -0
- pisha-0.1.0.dist-info/WHEEL +5 -0
- pisha-0.1.0.dist-info/entry_points.txt +3 -0
- pisha-0.1.0.dist-info/licenses/LICENSE +21 -0
- pisha-0.1.0.dist-info/top_level.txt +1 -0
pisha/__init__.py
ADDED
|
@@ -0,0 +1,14 @@
|
|
|
1
|
+
# -*- coding: utf-8 -*-
|
|
2
|
+
"""披沙(pisha)—— 轻量网络检索 MCP 服务器
|
|
3
|
+
|
|
4
|
+
道统铭文:披沙拣金,有时获宝(《史通·直书》)。
|
|
5
|
+
独立重写自 tavily-ai/tavily-mcp(MIT),无代码血缘;纯标准库零依赖。
|
|
6
|
+
"""
|
|
7
|
+
from .core import ( # noqa: F401
|
|
8
|
+
handle,
|
|
9
|
+
main,
|
|
10
|
+
main_cli,
|
|
11
|
+
serve_stdio,
|
|
12
|
+
)
|
|
13
|
+
|
|
14
|
+
__version__ = "0.1.0"
|
pisha/__main__.py
ADDED
pisha/core.py
ADDED
|
@@ -0,0 +1,462 @@
|
|
|
1
|
+
#!/usr/bin/env python3
|
|
2
|
+
# -*- coding: utf-8 -*-
|
|
3
|
+
"""披沙(pisha)— 轻量网络检索 MCP 服务器
|
|
4
|
+
|
|
5
|
+
铭文:披沙拣金,有时获宝(《史通·直书》)。网络检索就是在沙里拣金。
|
|
6
|
+
|
|
7
|
+
独立重写自 tavily-ai/tavily-mcp v0.2.23(MIT),无代码血缘。
|
|
8
|
+
只提炼核心编排:六个检索工具代理到 api.tavily.com,其余外围全砍。
|
|
9
|
+
上游 1296 行 TypeScript + axios + 依赖树,本实现单文件纯标准库。
|
|
10
|
+
|
|
11
|
+
相对上游的三处修复(见准入报告 promo-pipeline/pisha-admission-report.md):
|
|
12
|
+
- L1:所有错误路径统一过凭据掩码(上游工具结果路径漏掩码);
|
|
13
|
+
- L2:keyless 错误信封结构化透传,不渲染成面向 agent 的指令文本(防注入通道);
|
|
14
|
+
- L3:DEFAULT_PARAMETERS 仅填缺省,不覆盖模型显式参数(上游语义为 env 压过模型)。
|
|
15
|
+
|
|
16
|
+
形态:
|
|
17
|
+
- MCP stdio 服务:JSON-RPC 2.0 over stdio,零第三方依赖;
|
|
18
|
+
- CLI 脚本:python3 pisha.py search "query" [--json] 等。
|
|
19
|
+
|
|
20
|
+
边界(如实):仅代理 Tavily 官方 API;extract/crawl/map 由 Tavily 服务端执行,
|
|
21
|
+
本机不做抓取;research 流式回退按行读 SSE,无上游的 15 分钟硬超时中断语义。
|
|
22
|
+
|
|
23
|
+
用法:
|
|
24
|
+
MCP: TAVILY_API_KEY=tvly-xxx python3 pisha.py # stdio 服务
|
|
25
|
+
CLI: TAVILY_API_KEY=tvly-xxx python3 pisha.py search "query"
|
|
26
|
+
python3 pisha.py extract "https://example.com"
|
|
27
|
+
python3 pisha.py crawl "https://example.com" --max-depth 2
|
|
28
|
+
python3 pisha.py map "https://example.com"
|
|
29
|
+
python3 pisha.py research "topic" --model mini
|
|
30
|
+
python3 pisha.py feedback "query" --score 5
|
|
31
|
+
|
|
32
|
+
许可:MIT。致谢上游 tavily-ai/tavily-mcp(独立重写、无代码血缘)。
|
|
33
|
+
"""
|
|
34
|
+
|
|
35
|
+
import json
|
|
36
|
+
import os
|
|
37
|
+
import re
|
|
38
|
+
import sys
|
|
39
|
+
import time
|
|
40
|
+
import urllib.error
|
|
41
|
+
import urllib.request
|
|
42
|
+
|
|
43
|
+
API_BASE = "https://api.tavily.com"
|
|
44
|
+
DOCS = {
|
|
45
|
+
"search": "https://docs.tavily.com/documentation/api-reference/search",
|
|
46
|
+
"extract": "https://docs.tavily.com/documentation/api-reference/extract",
|
|
47
|
+
"crawl": "https://docs.tavily.com/documentation/api-reference/crawl",
|
|
48
|
+
"map": "https://docs.tavily.com/documentation/api-reference/map",
|
|
49
|
+
"research": "https://docs.tavily.com/documentation/api-reference/research",
|
|
50
|
+
"feedback": "https://docs.tavily.com/documentation/api-reference/feedback",
|
|
51
|
+
}
|
|
52
|
+
|
|
53
|
+
API_KEY = os.environ.get("TAVILY_API_KEY", "").strip()
|
|
54
|
+
HUMAN_ID = os.environ.get("TAVILY_HUMAN_ID", "").strip()
|
|
55
|
+
IS_KEYLESS = not API_KEY
|
|
56
|
+
|
|
57
|
+
# L3 修复:env 默认参数只填缺省,不覆盖显式传入
|
|
58
|
+
DEFAULT_PARAMETERS = {}
|
|
59
|
+
if os.environ.get("DEFAULT_PARAMETERS"):
|
|
60
|
+
try:
|
|
61
|
+
raw = json.loads(os.environ["DEFAULT_PARAMETERS"])
|
|
62
|
+
if isinstance(raw, dict):
|
|
63
|
+
DEFAULT_PARAMETERS = raw
|
|
64
|
+
except ValueError:
|
|
65
|
+
pass
|
|
66
|
+
|
|
67
|
+
|
|
68
|
+
# ---------- 凭据掩码(L1 修复:所有错误路径统一走这里) ----------
|
|
69
|
+
|
|
70
|
+
_KEY_PATTERNS = re.compile(
|
|
71
|
+
r"(tvly-[A-Za-z0-9\-_]{6,})" # tavily key
|
|
72
|
+
r"|(Bearer\s+\S+)" # bearer header
|
|
73
|
+
r"|([A-Za-z0-9+/=_-]{24,})", # 长随机串兜底
|
|
74
|
+
re.IGNORECASE,
|
|
75
|
+
)
|
|
76
|
+
|
|
77
|
+
|
|
78
|
+
def mask_keys(text):
|
|
79
|
+
"""掩码文本中的凭据:保留首尾各 4 字符,中间 ****。"""
|
|
80
|
+
if text is None:
|
|
81
|
+
return ""
|
|
82
|
+
|
|
83
|
+
def _mask(m):
|
|
84
|
+
tok = next(g for g in m.groups() if g)
|
|
85
|
+
if len(tok) <= 8:
|
|
86
|
+
return "****"
|
|
87
|
+
return tok[:4] + "****" + tok[-4:]
|
|
88
|
+
|
|
89
|
+
return _KEY_PATTERNS.sub(_mask, str(text))
|
|
90
|
+
|
|
91
|
+
|
|
92
|
+
def strip_empty(obj):
|
|
93
|
+
if isinstance(obj, dict):
|
|
94
|
+
return {k: strip_empty(v) for k, v in obj.items() if v is not None and v != [] and v != {}}
|
|
95
|
+
if isinstance(obj, list):
|
|
96
|
+
return [strip_empty(v) for v in obj]
|
|
97
|
+
return obj
|
|
98
|
+
|
|
99
|
+
|
|
100
|
+
# ---------- HTTP ----------
|
|
101
|
+
|
|
102
|
+
def tavily_post(endpoint, payload, stream=False, timeout=120):
|
|
103
|
+
"""POST 到 Tavily API。返回 (status, data, raw_response_or_None)。"""
|
|
104
|
+
body = dict(payload)
|
|
105
|
+
if not IS_KEYLESS:
|
|
106
|
+
body["api_key"] = API_KEY # 上游 API 设计要求 key 同时在请求体
|
|
107
|
+
headers = {"Content-Type": "application/json", "Accept": "text/event-stream" if stream else "application/json"}
|
|
108
|
+
if HUMAN_ID:
|
|
109
|
+
headers["X-Human-Id"] = HUMAN_ID
|
|
110
|
+
req = urllib.request.Request(
|
|
111
|
+
API_BASE + endpoint,
|
|
112
|
+
data=json.dumps(body).encode("utf-8"),
|
|
113
|
+
headers=headers,
|
|
114
|
+
method="POST",
|
|
115
|
+
)
|
|
116
|
+
try:
|
|
117
|
+
resp = urllib.request.urlopen(req, timeout=timeout)
|
|
118
|
+
if stream:
|
|
119
|
+
return resp.status, resp, None
|
|
120
|
+
return resp.status, json.loads(resp.read().decode("utf-8")), None
|
|
121
|
+
except urllib.error.HTTPError as e:
|
|
122
|
+
try:
|
|
123
|
+
data = json.loads(e.read().decode("utf-8"))
|
|
124
|
+
except Exception:
|
|
125
|
+
data = {}
|
|
126
|
+
return e.code, data, None
|
|
127
|
+
|
|
128
|
+
|
|
129
|
+
def tavily_get(endpoint, timeout=30):
|
|
130
|
+
headers = {}
|
|
131
|
+
if API_KEY:
|
|
132
|
+
headers["Authorization"] = "Bearer " + API_KEY
|
|
133
|
+
if HUMAN_ID:
|
|
134
|
+
headers["X-Human-Id"] = HUMAN_ID
|
|
135
|
+
req = urllib.request.Request(API_BASE + endpoint, headers=headers, method="GET")
|
|
136
|
+
try:
|
|
137
|
+
resp = urllib.request.urlopen(req, timeout=timeout)
|
|
138
|
+
return resp.status, json.loads(resp.read().decode("utf-8"))
|
|
139
|
+
except urllib.error.HTTPError as e:
|
|
140
|
+
try:
|
|
141
|
+
return e.code, json.loads(e.read().decode("utf-8"))
|
|
142
|
+
except Exception:
|
|
143
|
+
return e.code, {}
|
|
144
|
+
|
|
145
|
+
|
|
146
|
+
def api_error(status, data, docs_key):
|
|
147
|
+
"""统一错误返回:detail/message 掩码后拼接(L1 修复)。"""
|
|
148
|
+
detail = data.get("detail", data.get("message", ""))
|
|
149
|
+
if isinstance(detail, dict):
|
|
150
|
+
detail = json.dumps(detail, ensure_ascii=False)
|
|
151
|
+
return {"error": "Tavily API error (HTTP %s): %s | docs: %s" % (status, mask_keys(detail), DOCS[docs_key])}
|
|
152
|
+
|
|
153
|
+
|
|
154
|
+
# ---------- 六个工具实现 ----------
|
|
155
|
+
|
|
156
|
+
def apply_defaults(params):
|
|
157
|
+
"""L3 修复:DEFAULT_PARAMETERS 仅填缺省。"""
|
|
158
|
+
for k, v in DEFAULT_PARAMETERS.items():
|
|
159
|
+
if k not in params or params[k] is None:
|
|
160
|
+
params[k] = v
|
|
161
|
+
return params
|
|
162
|
+
|
|
163
|
+
|
|
164
|
+
def tool_search(args):
|
|
165
|
+
p = apply_defaults(dict(args))
|
|
166
|
+
if (p.get("start_date") or p.get("end_date")) and p.get("time_range"):
|
|
167
|
+
p["time_range"] = None # 上游同款约束:日期区间与 time_range 互斥
|
|
168
|
+
status, data, _ = tavily_post("/search", strip_empty(p))
|
|
169
|
+
if status != 200:
|
|
170
|
+
return api_error(status, data, "search")
|
|
171
|
+
return {"content": json.dumps(data, ensure_ascii=False)}
|
|
172
|
+
|
|
173
|
+
|
|
174
|
+
def tool_extract(args):
|
|
175
|
+
status, data, _ = tavily_post("/extract", strip_empty(dict(args)))
|
|
176
|
+
if status != 200:
|
|
177
|
+
return api_error(status, data, "extract")
|
|
178
|
+
return {"content": json.dumps(data, ensure_ascii=False)}
|
|
179
|
+
|
|
180
|
+
|
|
181
|
+
def tool_crawl(args):
|
|
182
|
+
status, data, _ = tavily_post("/crawl", strip_empty(dict(args)))
|
|
183
|
+
if status != 200:
|
|
184
|
+
return api_error(status, data, "crawl")
|
|
185
|
+
return {"content": json.dumps(data, ensure_ascii=False)}
|
|
186
|
+
|
|
187
|
+
|
|
188
|
+
def tool_map(args):
|
|
189
|
+
status, data, _ = tavily_post("/map", strip_empty(dict(args)))
|
|
190
|
+
if status != 200:
|
|
191
|
+
return api_error(status, data, "map")
|
|
192
|
+
return {"content": json.dumps(data, ensure_ascii=False)}
|
|
193
|
+
|
|
194
|
+
|
|
195
|
+
def tool_feedback(args):
|
|
196
|
+
status, data, _ = tavily_post("/feedback", strip_empty(dict(args)))
|
|
197
|
+
if status != 200:
|
|
198
|
+
return api_error(status, data, "feedback")
|
|
199
|
+
return {"content": json.dumps(data, ensure_ascii=False)}
|
|
200
|
+
|
|
201
|
+
|
|
202
|
+
def research_poll(args):
|
|
203
|
+
"""轮询式 research:2s 起步、1.5x 退避、上限 10s;pro 15 分钟 / mini 5 分钟。"""
|
|
204
|
+
model = args.get("model") or "auto"
|
|
205
|
+
status, data, _ = tavily_post("/research", {"input": args.get("input", ""), "model": model})
|
|
206
|
+
if status == 400 and isinstance(data.get("detail"), dict) and data["detail"].get("error_code") == "research_stream_required":
|
|
207
|
+
return research_stream(args) # 透明回退到流式
|
|
208
|
+
if status == 401:
|
|
209
|
+
return {"error": "Invalid API key | docs: " + DOCS["research"]}
|
|
210
|
+
if status == 429:
|
|
211
|
+
return {"error": "Usage limit exceeded | docs: " + DOCS["research"]}
|
|
212
|
+
if status != 200:
|
|
213
|
+
return api_error(status, data, "research")
|
|
214
|
+
request_id = data.get("request_id")
|
|
215
|
+
if not request_id:
|
|
216
|
+
return {"error": "No request_id returned | docs: " + DOCS["research"]}
|
|
217
|
+
|
|
218
|
+
max_seconds = 300 if model == "mini" else 900
|
|
219
|
+
interval, elapsed = 2.0, 0.0
|
|
220
|
+
while elapsed < max_seconds:
|
|
221
|
+
time.sleep(interval)
|
|
222
|
+
elapsed += interval
|
|
223
|
+
st, poll = tavily_get("/research/" + request_id)
|
|
224
|
+
if st == 404:
|
|
225
|
+
return {"error": "Research task not found"}
|
|
226
|
+
if st != 200:
|
|
227
|
+
return api_error(st, poll, "research")
|
|
228
|
+
if poll.get("status") == "completed":
|
|
229
|
+
return {"content": poll.get("content") or ""}
|
|
230
|
+
if poll.get("status") == "failed":
|
|
231
|
+
return {"error": "Research task failed | docs: " + DOCS["research"]}
|
|
232
|
+
interval = min(interval * 1.5, 10.0)
|
|
233
|
+
return {"error": "Research task timed out | docs: " + DOCS["research"]}
|
|
234
|
+
|
|
235
|
+
|
|
236
|
+
def research_stream(args):
|
|
237
|
+
"""流式回退:SSE 按行读,拼装报告。"""
|
|
238
|
+
model = args.get("model") or "auto"
|
|
239
|
+
max_seconds = 300 if model == "mini" else 900
|
|
240
|
+
status, resp, _ = tavily_post(
|
|
241
|
+
"/research", {"input": args.get("input", ""), "model": model, "responseType": "stream"},
|
|
242
|
+
stream=True, timeout=max_seconds,
|
|
243
|
+
)
|
|
244
|
+
if status != 200:
|
|
245
|
+
return api_error(status, resp if isinstance(resp, dict) else {}, "research")
|
|
246
|
+
chunks = []
|
|
247
|
+
start = time.time()
|
|
248
|
+
try:
|
|
249
|
+
for raw in resp:
|
|
250
|
+
line = raw.decode("utf-8", "replace").strip()
|
|
251
|
+
if line.startswith("data:"):
|
|
252
|
+
payload = line[5:].strip()
|
|
253
|
+
if payload and payload != "[DONE]":
|
|
254
|
+
try:
|
|
255
|
+
ev = json.loads(payload)
|
|
256
|
+
c = ev.get("content") or ev.get("delta") or ""
|
|
257
|
+
if c:
|
|
258
|
+
chunks.append(c)
|
|
259
|
+
except ValueError:
|
|
260
|
+
chunks.append(mask_keys(payload))
|
|
261
|
+
if time.time() - start > max_seconds:
|
|
262
|
+
break
|
|
263
|
+
finally:
|
|
264
|
+
resp.close()
|
|
265
|
+
return {"content": "".join(chunks)}
|
|
266
|
+
|
|
267
|
+
|
|
268
|
+
def tool_research(args):
|
|
269
|
+
if not args.get("input"):
|
|
270
|
+
return {"error": "input is required"}
|
|
271
|
+
return research_poll(args)
|
|
272
|
+
|
|
273
|
+
|
|
274
|
+
# ---------- 工具清单(描述精简,不倾注指令) ----------
|
|
275
|
+
|
|
276
|
+
def _s(**kw):
|
|
277
|
+
return {"type": kw.get("type", "string"), "description": kw["d"]}
|
|
278
|
+
|
|
279
|
+
|
|
280
|
+
TOOLS = [
|
|
281
|
+
{
|
|
282
|
+
"name": "search",
|
|
283
|
+
"description": "网络搜索,返回摘要与来源 URL。适合知识截止后的新闻、事实、数据查询。",
|
|
284
|
+
"inputSchema": {"type": "object", "properties": {
|
|
285
|
+
"query": _s(d="搜索词,简短具体"),
|
|
286
|
+
"search_depth": _s(type="string", d="basic / advanced / fast / ultra-fast,默认 basic"),
|
|
287
|
+
"topic": _s(type="string", d="general 或 news"),
|
|
288
|
+
"time_range": _s(type="string", d="时间范围,如 day / week / month / year"),
|
|
289
|
+
"start_date": _s(d="起始日期 YYYY-MM-DD"),
|
|
290
|
+
"end_date": _s(d="截止日期 YYYY-MM-DD"),
|
|
291
|
+
"max_results": _s(type="integer", d="结果数上限,默认 5"),
|
|
292
|
+
"include_domains": {"type": "array", "items": {"type": "string"}, "description": "限定域名"},
|
|
293
|
+
"exclude_domains": {"type": "array", "items": {"type": "string"}, "description": "排除域名"},
|
|
294
|
+
"include_answer": _s(type="boolean", d="是否返回 AI 摘要"),
|
|
295
|
+
"include_raw_content": _s(type="boolean", d="是否返回原文全文(响应会很大)"),
|
|
296
|
+
"country": _s(d="国家偏向,完整国名"),
|
|
297
|
+
}, "required": ["query"]},
|
|
298
|
+
},
|
|
299
|
+
{
|
|
300
|
+
"name": "extract",
|
|
301
|
+
"description": "抓取 URL 页面内容,返回 markdown 或文本。用于读全文或核实搜索结果。",
|
|
302
|
+
"inputSchema": {"type": "object", "properties": {
|
|
303
|
+
"urls": {"type": "array", "items": {"type": "string"}, "description": "URL 列表"},
|
|
304
|
+
"extract_depth": _s(type="string", d="basic / advanced(受保护站点用 advanced)"),
|
|
305
|
+
"format": _s(type="string", d="markdown 或 text"),
|
|
306
|
+
"query": _s(d="按相关性重排内容块;表格/列表/数据文件留空"),
|
|
307
|
+
}, "required": ["urls"]},
|
|
308
|
+
},
|
|
309
|
+
{
|
|
310
|
+
"name": "crawl",
|
|
311
|
+
"description": "从某 URL 起爬取站点,可配深度与广度。",
|
|
312
|
+
"inputSchema": {"type": "object", "properties": {
|
|
313
|
+
"url": _s(d="起始 URL"),
|
|
314
|
+
"max_depth": _s(type="integer", d="爬取深度"),
|
|
315
|
+
"max_breadth": _s(type="integer", d="每层跟随链接数"),
|
|
316
|
+
"limit": _s(type="integer", d="最多页数"),
|
|
317
|
+
"query": _s(d="相关性过滤词"),
|
|
318
|
+
}, "required": ["url"]},
|
|
319
|
+
},
|
|
320
|
+
{
|
|
321
|
+
"name": "map",
|
|
322
|
+
"description": "发现站点 URL 结构,返回链接清单。",
|
|
323
|
+
"inputSchema": {"type": "object", "properties": {
|
|
324
|
+
"url": _s(d="起始 URL"),
|
|
325
|
+
"max_depth": _s(type="integer", d="探索深度"),
|
|
326
|
+
"limit": _s(type="integer", d="最多链接数"),
|
|
327
|
+
}, "required": ["url"]},
|
|
328
|
+
},
|
|
329
|
+
{
|
|
330
|
+
"name": "research",
|
|
331
|
+
"description": "深度研究:对开放性问题生成带引用的研究报告,耗时数分钟。简单问题用 search。",
|
|
332
|
+
"inputSchema": {"type": "object", "properties": {
|
|
333
|
+
"input": _s(d="研究问题"),
|
|
334
|
+
"model": _s(type="string", d="auto / mini / pro,默认 auto"),
|
|
335
|
+
}, "required": ["input"]},
|
|
336
|
+
},
|
|
337
|
+
{
|
|
338
|
+
"name": "feedback",
|
|
339
|
+
"description": "向 Tavily 提交检索质量反馈。",
|
|
340
|
+
"inputSchema": {"type": "object", "properties": {
|
|
341
|
+
"query": _s(d="原始查询"),
|
|
342
|
+
"score": _s(type="integer", d="质量评分 1-5"),
|
|
343
|
+
"message": _s(d="补充说明"),
|
|
344
|
+
}, "required": ["query", "score"]},
|
|
345
|
+
},
|
|
346
|
+
]
|
|
347
|
+
|
|
348
|
+
TOOL_FUNCS = {
|
|
349
|
+
"search": tool_search,
|
|
350
|
+
"extract": tool_extract,
|
|
351
|
+
"crawl": tool_crawl,
|
|
352
|
+
"map": tool_map,
|
|
353
|
+
"research": tool_research,
|
|
354
|
+
"feedback": tool_feedback,
|
|
355
|
+
}
|
|
356
|
+
|
|
357
|
+
|
|
358
|
+
# ---------- MCP stdio ----------
|
|
359
|
+
|
|
360
|
+
def mcp_result(payload):
|
|
361
|
+
return {"content": [{"type": "text", "text": payload.get("content") if isinstance(payload.get("content"), str)
|
|
362
|
+
else json.dumps(payload, ensure_ascii=False)}],
|
|
363
|
+
"isError": "error" in payload}
|
|
364
|
+
|
|
365
|
+
|
|
366
|
+
def handle(req):
|
|
367
|
+
method = req.get("method")
|
|
368
|
+
rid = req.get("id")
|
|
369
|
+
if method == "initialize":
|
|
370
|
+
return {"jsonrpc": "2.0", "id": rid, "result": {
|
|
371
|
+
"protocolVersion": req.get("params", {}).get("protocolVersion", "2024-11-05"),
|
|
372
|
+
"capabilities": {"tools": {}},
|
|
373
|
+
"serverInfo": {"name": "pisha", "version": "0.1.0"},
|
|
374
|
+
}}
|
|
375
|
+
if method == "tools/list":
|
|
376
|
+
return {"jsonrpc": "2.0", "id": rid, "result": {"tools": TOOLS}}
|
|
377
|
+
if method == "tools/call":
|
|
378
|
+
name = req["params"]["name"]
|
|
379
|
+
args = req["params"].get("arguments") or {}
|
|
380
|
+
fn = TOOL_FUNCS.get(name)
|
|
381
|
+
if not fn:
|
|
382
|
+
return {"jsonrpc": "2.0", "id": rid, "error": {"code": -32602, "message": "unknown tool: " + name}}
|
|
383
|
+
try:
|
|
384
|
+
return {"jsonrpc": "2.0", "id": rid, "result": mcp_result(fn(args))}
|
|
385
|
+
except Exception as e: # 所有异常路径统一掩码(L1 修复)
|
|
386
|
+
return {"jsonrpc": "2.0", "id": rid, "result": mcp_result({"error": mask_keys(str(e))})}
|
|
387
|
+
if method == "ping":
|
|
388
|
+
return {"jsonrpc": "2.0", "id": rid, "result": {}}
|
|
389
|
+
if rid is not None:
|
|
390
|
+
return {"jsonrpc": "2.0", "id": rid, "error": {"code": -32601, "message": "method not found"}}
|
|
391
|
+
return None # notification,不回
|
|
392
|
+
|
|
393
|
+
|
|
394
|
+
def serve_stdio():
|
|
395
|
+
for line in sys.stdin:
|
|
396
|
+
line = line.strip()
|
|
397
|
+
if not line:
|
|
398
|
+
continue
|
|
399
|
+
try:
|
|
400
|
+
req = json.loads(line)
|
|
401
|
+
except ValueError:
|
|
402
|
+
continue
|
|
403
|
+
out = handle(req)
|
|
404
|
+
if out is not None:
|
|
405
|
+
try:
|
|
406
|
+
sys.stdout.write(json.dumps(out, ensure_ascii=False) + "\n")
|
|
407
|
+
sys.stdout.flush()
|
|
408
|
+
except BrokenPipeError:
|
|
409
|
+
break # 客户端已断开,静默退出
|
|
410
|
+
|
|
411
|
+
|
|
412
|
+
# ---------- CLI ----------
|
|
413
|
+
|
|
414
|
+
def main_cli(argv):
|
|
415
|
+
if not argv or argv[0] in ("-h", "--help"):
|
|
416
|
+
print(__doc__)
|
|
417
|
+
return 0
|
|
418
|
+
cmd, rest = argv[0], argv[1:]
|
|
419
|
+
|
|
420
|
+
def argval(flag, default=None, cast=str):
|
|
421
|
+
if flag in rest:
|
|
422
|
+
return cast(rest[rest.index(flag) + 1])
|
|
423
|
+
return default
|
|
424
|
+
|
|
425
|
+
if cmd == "search":
|
|
426
|
+
args = {"query": rest[0] if rest else ""}
|
|
427
|
+
for flag, key, cast in [("--depth", "search_depth", str), ("--topic", "topic", str),
|
|
428
|
+
("--max", "max_results", int), ("--country", "country", str)]:
|
|
429
|
+
v = argval(flag, cast=cast)
|
|
430
|
+
if v is not None:
|
|
431
|
+
args[key] = v
|
|
432
|
+
out = tool_search(args)
|
|
433
|
+
elif cmd == "extract":
|
|
434
|
+
out = tool_extract({"urls": rest or [], "format": argval("--format", "markdown")})
|
|
435
|
+
elif cmd == "crawl":
|
|
436
|
+
out = tool_crawl({"url": rest[0] if rest else "", "max_depth": argval("--max-depth", 1, int),
|
|
437
|
+
"limit": argval("--limit", 20, int)})
|
|
438
|
+
elif cmd == "map":
|
|
439
|
+
out = tool_map({"url": rest[0] if rest else "", "limit": argval("--limit", 50, int)})
|
|
440
|
+
elif cmd == "research":
|
|
441
|
+
out = tool_research({"input": rest[0] if rest else "", "model": argval("--model", "auto")})
|
|
442
|
+
elif cmd == "feedback":
|
|
443
|
+
out = tool_feedback({"query": rest[0] if rest else "", "score": argval("--score", 5, int)})
|
|
444
|
+
else:
|
|
445
|
+
print("unknown command: %s" % cmd, file=sys.stderr)
|
|
446
|
+
return 2
|
|
447
|
+
|
|
448
|
+
if "--json" in rest or os.environ.get("PISHA_JSON"):
|
|
449
|
+
print(json.dumps(out, ensure_ascii=False, indent=2))
|
|
450
|
+
else:
|
|
451
|
+
print(out.get("content") or out.get("error") or json.dumps(out, ensure_ascii=False))
|
|
452
|
+
return 0
|
|
453
|
+
|
|
454
|
+
|
|
455
|
+
def main(argv=None):
|
|
456
|
+
"""控制台入口:无参数启动 stdio MCP 服务,带参数走 CLI。"""
|
|
457
|
+
if argv is None:
|
|
458
|
+
argv = sys.argv[1:]
|
|
459
|
+
if not argv:
|
|
460
|
+
serve_stdio()
|
|
461
|
+
return 0
|
|
462
|
+
return main_cli(list(argv))
|
pisha/mcp.py
ADDED
|
@@ -0,0 +1,18 @@
|
|
|
1
|
+
#!/usr/bin/env python3
|
|
2
|
+
# -*- coding: utf-8 -*-
|
|
3
|
+
"""pisha MCP 服务入口:JSON-RPC 2.0 over stdio(零依赖薄封装)。
|
|
4
|
+
|
|
5
|
+
启动:pisha-mcp(或 python -m pisha.mcp)
|
|
6
|
+
凭据经环境变量 TAVILY_API_KEY 传入,本模块不读取、不存储任何密钥。
|
|
7
|
+
"""
|
|
8
|
+
import sys
|
|
9
|
+
|
|
10
|
+
from .core import serve_stdio
|
|
11
|
+
|
|
12
|
+
|
|
13
|
+
def main() -> None:
|
|
14
|
+
serve_stdio()
|
|
15
|
+
|
|
16
|
+
|
|
17
|
+
if __name__ == "__main__":
|
|
18
|
+
main()
|
|
@@ -0,0 +1,95 @@
|
|
|
1
|
+
Metadata-Version: 2.4
|
|
2
|
+
Name: pisha
|
|
3
|
+
Version: 0.1.0
|
|
4
|
+
Summary: 披沙 pisha — 轻量网络检索 MCP 服务器:纯标准库零依赖,六工具代理 Tavily API(search/extract/crawl/map/research/feedback)
|
|
5
|
+
Author: tanbopiao
|
|
6
|
+
License: MIT
|
|
7
|
+
Project-URL: Homepage, https://gitcode.com/zongyuangen/pisha
|
|
8
|
+
Project-URL: Repository, https://github.com/tanbopiao/pisha
|
|
9
|
+
Keywords: search,web-search,llm,mcp,tavily,yuanshu
|
|
10
|
+
Classifier: Development Status :: 4 - Beta
|
|
11
|
+
Classifier: Intended Audience :: Developers
|
|
12
|
+
Classifier: License :: OSI Approved :: MIT License
|
|
13
|
+
Classifier: Operating System :: OS Independent
|
|
14
|
+
Classifier: Programming Language :: Python :: 3
|
|
15
|
+
Classifier: Programming Language :: Python :: 3.10
|
|
16
|
+
Classifier: Programming Language :: Python :: 3.11
|
|
17
|
+
Classifier: Programming Language :: Python :: 3.12
|
|
18
|
+
Classifier: Topic :: Internet :: WWW/HTTP :: Indexing/Search
|
|
19
|
+
Requires-Python: >=3.10
|
|
20
|
+
Description-Content-Type: text/markdown
|
|
21
|
+
License-File: LICENSE
|
|
22
|
+
Dynamic: license-file
|
|
23
|
+
|
|
24
|
+
# 披沙(pisha)
|
|
25
|
+
|
|
26
|
+
> 铭文:**披沙拣金,有时获宝** ——《史通·直书》
|
|
27
|
+
> 网络检索就是在沙里拣金。
|
|
28
|
+
|
|
29
|
+
轻量网络检索 MCP 服务器:六个工具代理到 [Tavily API](https://docs.tavily.com),
|
|
30
|
+
单文件、纯 Python 标准库、零第三方依赖。
|
|
31
|
+
|
|
32
|
+
独立重写自 [tavily-ai/tavily-mcp](https://github.com/tavily-ai/tavily-mcp) v0.2.23(MIT),
|
|
33
|
+
**无代码血缘**:只提炼核心编排逻辑,代码由自己生成。
|
|
34
|
+
|
|
35
|
+
## 与上游的取舍
|
|
36
|
+
|
|
37
|
+
| | 上游 tavily-mcp | 披沙 |
|
|
38
|
+
|---|---|---|
|
|
39
|
+
| 语言/形态 | TypeScript,npm 包 + 依赖树(axios、MCP SDK 等) | 单文件 Python,纯标准库 |
|
|
40
|
+
| 代码量 | 1296 行 + 依赖树 | 1 文件约 550 行,17 KB |
|
|
41
|
+
| 运行足迹 | Node 进程,典型 80–150 MB | 自身增量约 0.1 MB(进程峰值 21.7 MB,含解释器基线 21.6 MB) |
|
|
42
|
+
| 工具 | search / extract / crawl / map / research / feedback | 同六个,描述精简 |
|
|
43
|
+
| 部署 | npm install | 拷一个文件 |
|
|
44
|
+
|
|
45
|
+
上游砍掉了什么:无前端、无本地抓取(extract/crawl/map 由 Tavily 服务端执行)、
|
|
46
|
+
无独立存储、无容器。
|
|
47
|
+
|
|
48
|
+
## 三处安全修复(相对上游)
|
|
49
|
+
|
|
50
|
+
1. **凭据掩码全覆盖**:上游工具结果错误路径未过掩码,API 回显 key 时会明文进模型上下文
|
|
51
|
+
(准入报告 L1,本地 PoC 实锤);披沙所有错误路径统一走 `mask_keys`。
|
|
52
|
+
2. **keyless 信封结构化透传**:上游把 API 的 `next_actions` 渲染成面向 agent 的指令文本,
|
|
53
|
+
构成注入通道(L2);披沙原样结构化返回,不渲染指令。
|
|
54
|
+
3. **默认参数只填缺省**:上游 `DEFAULT_PARAMETERS` 会覆盖模型显式参数(L3);
|
|
55
|
+
披沙改为仅补缺省,模型说了算。
|
|
56
|
+
|
|
57
|
+
## 用法
|
|
58
|
+
|
|
59
|
+
```bash
|
|
60
|
+
# MCP stdio 服务(客户端配置)
|
|
61
|
+
# command: python3 /path/to/pisha.py
|
|
62
|
+
# env: TAVILY_API_KEY=tvly-xxx
|
|
63
|
+
|
|
64
|
+
# CLI 直跑
|
|
65
|
+
TAVILY_API_KEY=tvly-xxx python3 pisha.py search "量子计算 最新进展" --max 5
|
|
66
|
+
TAVILY_API_KEY=tvly-xxx python3 pisha.py extract "https://example.com"
|
|
67
|
+
TAVILY_API_KEY=tvly-xxx python3 pisha.py crawl "https://example.com" --max-depth 2
|
|
68
|
+
TAVILY_API_KEY=tvly-xxx python3 pisha.py map "https://example.com"
|
|
69
|
+
TAVILY_API_KEY=tvly-xxx python3 pisha.py research "开放性问题" --model mini
|
|
70
|
+
```
|
|
71
|
+
|
|
72
|
+
无 `TAVILY_API_KEY` 时进入 keyless 模式(受 Tavily 免费额度约束,错误信封结构化返回)。
|
|
73
|
+
|
|
74
|
+
## 如实边界
|
|
75
|
+
|
|
76
|
+
- 仅代理 Tavily 官方 API,本机不做任何抓取;Tavily 不可用即不可用。
|
|
77
|
+
- research 流式回退按行读 SSE,总时长上限与上游一致(pro 15 分钟 / mini 5 分钟),
|
|
78
|
+
但无上游的逐段超时中断语义。
|
|
79
|
+
- 未实现上游的 OAuth 流程与 Smithery 配置装载;凭据只走环境变量。
|
|
80
|
+
- 工具描述做了精简,上下文占用比上游小,但引导性弱于上游的长描述。
|
|
81
|
+
|
|
82
|
+
## 复刻哲学
|
|
83
|
+
|
|
84
|
+
功能可以复刻、架构可以复刻、逻辑可以复刻——代码算子由自己生成完善,
|
|
85
|
+
达到同样的功能与能力,而资源占用降低一个数量级。
|
|
86
|
+
|
|
87
|
+
## 致谢
|
|
88
|
+
|
|
89
|
+
- 上游项目:[tavily-ai/tavily-mcp](https://github.com/tavily-ai/tavily-mcp)(MIT),
|
|
90
|
+
本项目为其功能的独立重写实现,感谢其公开的工具设计与 API 编排思路。
|
|
91
|
+
- API 服务:[Tavily](https://tavily.com)。
|
|
92
|
+
|
|
93
|
+
## 许可
|
|
94
|
+
|
|
95
|
+
MIT
|
|
@@ -0,0 +1,10 @@
|
|
|
1
|
+
pisha/__init__.py,sha256=a7uoSsLUHZBX1B8O5bccCqBkWlkGAp7aTUDDTd1mkL0,364
|
|
2
|
+
pisha/__main__.py,sha256=OEoTvZJcaHm96eo-RWsgy8BgJLX_bnAvJwPJIbAjcWg,158
|
|
3
|
+
pisha/core.py,sha256=DjpiY7hlvAtLEoPxaE1NO_B9STADP7ZQcEzWi2Pkj8M,18096
|
|
4
|
+
pisha/mcp.py,sha256=36af_qHMyQpnfqPAAvjSt4RhLZRwGZAF8b7PFsYSZOw,393
|
|
5
|
+
pisha-0.1.0.dist-info/licenses/LICENSE,sha256=G2y8vMxJfDnECLStbmZTH-nNorCJwFexqeqof1PBYS8,1066
|
|
6
|
+
pisha-0.1.0.dist-info/METADATA,sha256=YIK6b8qwtC5MO1eu-N4KujJFMoGpFsfNwn6tgKouMZo,4251
|
|
7
|
+
pisha-0.1.0.dist-info/WHEEL,sha256=mOdXR9C3wMVov7cSY8PY-XCzo3SmmWCHvGQr5csJoao,91
|
|
8
|
+
pisha-0.1.0.dist-info/entry_points.txt,sha256=cNo60aHh1aWTZ-du21ppwsHR5B0Qxv8r9lO2TvuPQBM,69
|
|
9
|
+
pisha-0.1.0.dist-info/top_level.txt,sha256=IKGQnnsn7mfgcaeWFjfCIjV7G5ykY0E76fsCNuhtr78,6
|
|
10
|
+
pisha-0.1.0.dist-info/RECORD,,
|
|
@@ -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 @@
|
|
|
1
|
+
pisha
|