MCP(Model Context Protocol)解决的问题是「工具不写死在提示词里」。接入之后,模型这一侧看到的是工具清单的 schema,具体怎么执行由宿主决定——放到鸿蒙端上,这个「宿主」就是你的应用。
这篇把端侧的注册、分发、生命周期三块说清,代码用 ArkTS。
先厘清角色。一个 MCP 体系里有三样东西:
端侧常见的形态是 Host + Client 都在设备上,Server 有两种:本地(同进程或子进程)和远端(HTTP/SSE)。
对鸿蒙应用来说,关键约束是没有 Node 运行时。官方 MCP SDK 那些基于 child_process、fs 的能力用不了,只能走协议层,自己实现报文。
这不是坏消息。协议本身很轻——JSON-RPC 2.0 上跑几个方法:initialize、tools/list、tools/call。
先看清报文,再谈实现。
初始化:
{
"jsonrpc": "2.0",
"id": 1,
"method": "initialize",
"params": {
"protocolVersion": "2024-11-05",
"capabilities": {},
"clientInfo": { "name": "harmony-agent", "version": "1.0.0" }
}
}拉工具清单:
{ "jsonrpc": "2.0", "id": 2, "method": "tools/list", "params": {} }调工具:
{
"jsonrpc": "2.0",
"id": 3,
"method": "tools/call",
"params": {
"name": "get_weather",
"arguments": { "city": "武汉" }
}
}返回统一是 result 或 error 二者之一。tools/call 的 result 里固定有 content 数组,第一项一般是 { "type": "text", "text": "..." }。
import { http } from '@kit.NetworkKit'
interface RpcReq {
jsonrpc: '2.0'
id: number
method: string
params: Record<string, Object>
}
interface RpcErr {
code: number
message: string
}
interface RpcResp {
jsonrpc: '2.0'
id: number
result?: Record<string, Object>
error?: RpcErr
}
export class McpClient {
private seq = 0
constructor(private endpoint: string, private token: string) {}
private async rpc(method: string, params: Record<string, Object>): Promise<RpcResp> {
const body: RpcReq = { jsonrpc: '2.0', id: ++this.seq, method, params }
const req = http.createHttp()
try {
const res = await req.request(this.endpoint, {
method: http.RequestMethod.POST,
header: {
'Content-Type': 'application/json',
'Authorization': `Bearer ${this.token}`
},
extraData: JSON.stringify(body),
connectTimeout: 8000,
readTimeout: 30000
})
if (res.responseCode !== 200) {
throw new Error(`HTTP ${res.responseCode}`)
}
return JSON.parse(res.result as string) as RpcResp
} finally {
req.destroy()
}
}
async initialize(): Promise<void> {
const r = await this.rpc('initialize', {
protocolVersion: '2024-11-05',
capabilities: {},
clientInfo: { name: 'harmony-agent', version: '1.0.0' }
})
if (r.error) throw new Error(`initialize failed: ${r.error.message}`)
}
async listTools(): Promise<Object[]> {
const r = await this.rpc('tools/list', {})
if (r.error) throw new Error(r.error.message)
return (r.result?.['tools'] as Object[]) ?? []
}
async callTool(name: string, args: Record<string, Object>): Promise<string> {
const r = await this.rpc('tools/call', { name, arguments: args })
if (r.error) throw new Error(r.error.message)
const content = (r.result?.['content'] as Object[]) ?? []
const first = content[0] as Record<string, Object> | undefined
return String(first?.['text'] ?? '')
}
}注意 id 要单调递增且全连接唯一。并发调用时如果 id 撞了,响应就对不上请求——这是常见的实现 bug。
端上的工具(读通讯录、查本地文件、调系统 Kit)不该和远端两套写法。统一成一个 ToolExecutor 接口,本地实现和远程实现都满足它:
export interface ToolExecutor {
name: string
description: string
inputSchema: Record<string, Object>
execute(args: Record<string, Object>): Promise<string>
}
export class LocalToolRegistry {
private map: Map<string, ToolExecutor> = new Map()
register(t: ToolExecutor): void {
if (this.map.has(t.name)) {
throw new Error(`tool already registered: ${t.name}`)
}
this.map.set(t.name, t)
}
list(): Object[] {
return Array.from(this.map.values()).map(t => ({
name: t.name,
description: t.description,
inputSchema: t.inputSchema
}))
}
async dispatch(name: string, args: Record<string, Object>): Promise<string> {
const t = this.map.get(name)
if (!t) throw new Error(`unknown tool: ${name}`)
return t.execute(args)
}
}这样「本地工具」和「远端 MCP 工具」在模型看来没有区别,都是 schema 加一个调用入口。合并清单时去重即可。
冷启动时不要急着初始化。 initialize 会建连接、拉能力,放到首屏之后做。用户打开应用先看到界面,工具清单在后台补。
应用进后台要断开。 鸿蒙的 onBackground 里把连接释放掉,不然系统会算你一直在耗电。回到前台再重连,initialize 要幂等。
断线重连要有退避。 直接 while 循环重试会把服务端打崩。用指数退避:1 秒、2 秒、4 秒、8 秒,封顶 30 秒。
async function connectWithRetry(c: McpClient, maxTry = 5): Promise<boolean> {
for (let i = 0; i < maxTry; i++) {
try {
await c.initialize()
return true
} catch (e) {
const wait = Math.min(30000, 1000 * Math.pow(2, i))
await new Promise<void>(r => setTimeout(() => r(), wait))
}
}
return false
}远端工具只要网络权限。本地工具不一样——读联系人要权限、读文件要权限、定位要权限。这些要在 module.json5 里声明,运行时还要动态申请。
一个实际的做法是:工具注册时就带上所需权限,调度前统一检查一遍。
export interface ToolExecutor {
name: string
description: string
inputSchema: Record<string, Object>
permissions?: string[]
execute(args: Record<string, Object>): Promise<string>
}调度前用 abilityAccessCtrl 检查,缺权限就返回一句「需要授权才能查询通讯录」,而不是抛异常。让模型知道为什么失败,它才能换个方式回答用户。
MCP 不是必须的。工具就三五个、永远不变的项目,直接写死 function calling 更省事——少一层协议,少一堆调试。
MCP 的价值在「工具会变」和「工具跨应用复用」。如果你的智能体要接第三方的工具市场,或者同一套工具要在 App、小程序、Web 三处复用,那这层抽象值得。
协议对接的技术难点,不在 JSON-RPC 本身,在边界条件:id 冲突、并发调用、断线重连、权限拒绝、超时。
这些在 demo 里都不会出现,只有真实用户拿着手机在地铁里用的时候才出现。
MCP 这一层,文档能看懂不等于能接。真正卡人的是版本协商和端侧 Client 该自己实现到什么程度——这两点没有标准答案,只能靠对着一版具体的协议规范把边界条件全走一遍。规范是会升级的,接之前先确认你手上那版是哪一版,再决定 registry 里哪些能力交给端侧。
原创声明:本文系作者授权腾讯云开发者社区发表,未经许可,不得转载。
如有侵权,请联系 cloudcommunity@tencent.com 删除。