豆包复刻:原生安卓(Compose + 内嵌 Termux)+ Web / Windows
一个界面照着豆包抠的 AI 助手。主力是安卓端,完全离线自主:不依赖电脑、 不需要另外装 Termux。 安卓端 - 原生 Jetpack Compose,7 个页面,配色/圆角/间距对着真机截图量出来的 - 完整动效:抽屉滑入、页面切换、气泡淡入上移、面板底部升起、typing 三点、按钮回弹 - 内置 Termux:bash/apt/pkg 388 个命令、真 pty 终端; pty 不可用的 ROM 上自动降级成命令控制台 - APK 内嵌 CPython 3.13(Chaquopy),AI 内核跑在手机上 - 设备能力:定位 / 陀螺仪 / 加速度计 / 光线 / 电量 / 剪贴板 - 语音:朗读 + 语音输入,火山豆包音色 / OpenAI 兼容 / 设备自带三级引擎 AI 能力 - 10 家 OpenAI 兼容提供商:方舟 / OpenAI / DeepSeek / Kimi / 智谱 / 通义 / 硅基流动 / OpenRouter / 本地 Ollama / 自定义 - 思考强度按各家支持情况发不同字段(thinking / reasoning_effort / 不发), 认不出来的一律不发,避免给不支持的厂商发字段直接 400 - MCP 三种传输(http / stdio / inproc)、工具热加载、文件上传、权限模式 跨端 - 安卓走原生 Compose,Web / Windows 走 Lynx - Node 与 Python 两份内核接口逐字段一致,关键路径都有对拍脚本 自检脚本(都不需要真 Key) - verify-phone.mjs 设备端 24 项验收 - verify-speech.mjs 语音链路 31 项,两份内核各跑一遍 - parity-thinking.mjs 思考强度映射对拍 - probe-settings-wipe.mjs 设置防清空攻击测试 - mock-llm.mjs 假的 OpenAI + 火山语音服务 许可 MIT;第三方组件(Termux Apache-2.0、Chaquopy、Compose、LynxJS、Electron) 的授权见 LICENSE。
This commit is contained in:
160
tools/_mcp_python_example.py
Normal file
160
tools/_mcp_python_example.py
Normal file
@@ -0,0 +1,160 @@
|
||||
#!/usr/bin/env python3
|
||||
"""
|
||||
示例:用 Python 写的 MCP 服务(同时支持两种跑法)。
|
||||
|
||||
1) 桌面/服务器 —— stdio 模式:内核把它当子进程起,走标准输入输出收发 JSON-RPC
|
||||
|
||||
{
|
||||
"name": "py-demo",
|
||||
"transport": "stdio",
|
||||
"command": "python",
|
||||
"args": ["C:\\\\path\\\\to\\\\tools\\\\mcp_python_example.py"]
|
||||
}
|
||||
|
||||
2) 安卓端 —— inproc 模式:手机上没有独立 python 可执行文件,起不了子进程。
|
||||
内核(Chaquopy 内嵌的 CPython)会直接 import 这个文件,调用下面的 handle()。
|
||||
|
||||
{ "name": "py-demo", "transport": "inproc", "path": "/sdcard/.../mcp_python_example.py" }
|
||||
|
||||
所以这个文件里:协议实现完全一样,只是入口不同 —— `handle()` 给 inproc 用,
|
||||
`main()` 给 stdio 用。你自己写 MCP 工具时照抄这个骨架即可。
|
||||
"""
|
||||
|
||||
import json
|
||||
import os
|
||||
import platform
|
||||
import sys
|
||||
import urllib.request
|
||||
|
||||
PROTOCOL_VERSION = "2024-11-05"
|
||||
SERVER_INFO = {"name": "py-demo", "version": "0.1.0"}
|
||||
|
||||
TOOLS = [
|
||||
{
|
||||
"name": "word_count",
|
||||
"description": "统计一段文本的字数、词数和行数",
|
||||
"inputSchema": {
|
||||
"type": "object",
|
||||
"properties": {"text": {"type": "string", "description": "要统计的文本"}},
|
||||
"required": ["text"],
|
||||
},
|
||||
},
|
||||
{
|
||||
"name": "http_get",
|
||||
"description": "用 Python 抓一个 URL 并返回前 2000 个字符(演示网络能力)",
|
||||
"inputSchema": {
|
||||
"type": "object",
|
||||
"properties": {"url": {"type": "string", "description": "http/https 地址"}},
|
||||
"required": ["url"],
|
||||
},
|
||||
},
|
||||
{
|
||||
"name": "host_info",
|
||||
"description": "返回运行这个 MCP 服务的机器/手机信息",
|
||||
"inputSchema": {"type": "object", "properties": {}},
|
||||
},
|
||||
]
|
||||
|
||||
|
||||
def call_tool(name, args):
|
||||
"""真正干活的地方。返回字符串就是工具结果。"""
|
||||
if name == "word_count":
|
||||
text = str(args.get("text", ""))
|
||||
return json.dumps(
|
||||
{
|
||||
"chars": len(text),
|
||||
"chars_no_space": len(text.replace(" ", "").replace("\n", "")),
|
||||
"words": len(text.split()),
|
||||
"lines": len(text.splitlines()) or 1,
|
||||
},
|
||||
ensure_ascii=False,
|
||||
)
|
||||
|
||||
if name == "http_get":
|
||||
url = str(args.get("url", ""))
|
||||
if not url.startswith(("http://", "https://")):
|
||||
raise ValueError("url 必须是 http/https")
|
||||
req = urllib.request.Request(url, headers={"User-Agent": "py-demo-mcp/0.1"})
|
||||
with urllib.request.urlopen(req, timeout=20) as resp:
|
||||
body = resp.read(200_000).decode("utf-8", errors="replace")
|
||||
return body[:2000]
|
||||
|
||||
if name == "host_info":
|
||||
return json.dumps(
|
||||
{
|
||||
"python": sys.version.split()[0],
|
||||
"os": f"{platform.system()} {platform.release()}",
|
||||
"machine": platform.machine(),
|
||||
"cwd": os.getcwd(),
|
||||
"android": "ANDROID_ROOT" in os.environ or "ANDROID_DATA" in os.environ,
|
||||
},
|
||||
ensure_ascii=False,
|
||||
)
|
||||
|
||||
raise ValueError(f"未知工具:{name}")
|
||||
|
||||
|
||||
def handle(request: dict) -> dict:
|
||||
"""
|
||||
处理一条 JSON-RPC 请求,返回响应 dict(通知类请求返回 None)。
|
||||
安卓 inproc 模式直接调它;stdio 模式的 main() 也是调它。
|
||||
"""
|
||||
method = request.get("method")
|
||||
req_id = request.get("id")
|
||||
params = request.get("params") or {}
|
||||
|
||||
# 通知没有 id,不需要回
|
||||
if req_id is None and method and method.startswith("notifications/"):
|
||||
return None
|
||||
|
||||
def ok(result):
|
||||
return {"jsonrpc": "2.0", "id": req_id, "result": result}
|
||||
|
||||
def err(code, message):
|
||||
return {"jsonrpc": "2.0", "id": req_id, "error": {"code": code, "message": message}}
|
||||
|
||||
if method == "initialize":
|
||||
return ok(
|
||||
{
|
||||
"protocolVersion": PROTOCOL_VERSION,
|
||||
"capabilities": {"tools": {}},
|
||||
"serverInfo": SERVER_INFO,
|
||||
}
|
||||
)
|
||||
|
||||
if method == "ping":
|
||||
return ok({})
|
||||
|
||||
if method == "tools/list":
|
||||
return ok({"tools": TOOLS})
|
||||
|
||||
if method == "tools/call":
|
||||
name = params.get("name")
|
||||
args = params.get("arguments") or {}
|
||||
try:
|
||||
text = call_tool(name, args)
|
||||
return ok({"content": [{"type": "text", "text": text}], "isError": False})
|
||||
except Exception as exc: # noqa: BLE001 - 错误要回给模型看
|
||||
return ok({"content": [{"type": "text", "text": f"{type(exc).__name__}: {exc}"}], "isError": True})
|
||||
|
||||
return err(-32601, f"不支持的方法:{method}")
|
||||
|
||||
|
||||
def main():
|
||||
"""stdio 模式:一行一条 JSON-RPC。"""
|
||||
for line in sys.stdin:
|
||||
line = line.strip()
|
||||
if not line:
|
||||
continue
|
||||
try:
|
||||
request = json.loads(line)
|
||||
except json.JSONDecodeError:
|
||||
continue
|
||||
response = handle(request)
|
||||
if response is not None:
|
||||
sys.stdout.write(json.dumps(response, ensure_ascii=False) + "\n")
|
||||
sys.stdout.flush()
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
main()
|
||||
Reference in New Issue
Block a user