本文基于 Ktor 异步网关与 MCP(Model Context Protocol)SSE 工具调用技术链,结合 Kotlin Multiplatform(KMP)后端共享逻辑,给出从零搭建生产级 AI Agent 服务的代码实战与架构范式。适合 Android/Kotlin 开发者向全栈智能体架构师进阶。

一、技术基座:为何选 Ktor 做 Agent 服务端

Ktor 是 JetBrains 推出的轻量级、异步、纯 Kotlin 框架,基于协程实现非阻塞 I/O,可用极少线程承载高并发

。其多平台特性(JVM/JS/Native)与 KMP 天然契合,后端逻辑可与移动端共享 commonMain 代码。最新稳定版为 3.5.0,Netty 引擎嵌入式启动仅需数行代码。

二、KMP 后端分层与 MCP 集成架构

参照 KMP 全栈“共享逻辑层 + Agent 服务端”演进,落地分为:

  • shared 模块:定义 ChatRequest、Agent 状态机、工具契约(expect/actual 隔离平台)
  • Ktor 网关层:SSE 路由接收请求,调用 Koog/MCP 引擎
  • MCP 工具层:通过 SSE 暴露标准化工具(如时间、计算),供模型选择性调用

三、实战代码:从零搓一个 Agent 服务

1. Ktor 基础网关(异步非阻塞)


kotlin

fun main() {
    embeddedServer(Netty, port = 8080) {
        install(ContentNegotiation) { json() }
        routing {
            post("/chat") {
                val req = call.receive<ChatRequest>()
                // 调用 Agent 引擎(见下)
                val reply = agentEngine.run(req.sessionId, req.question)
                call.respond(mapOf("answer" to reply))
            }
        }
    }.start(wait = true)
}

该写法利用 suspend 路由处理器实现原生异步,避免线程阻塞

2. MCP SSE 工具端点(Server-Sent Events)


kotlin

routing {
    get("/mcp/sse") {
        call.response.header("Content-Type", "text/event-stream")
        val channel = call.response.channel()
        // 推送工具清单与调用结果
        channel.write("data: ${toolSchemaJson()}\n\n".toByteArray())
        channel.flush()
    }
    post("/mcp/sse/post") {
        val toolCall = call.receive<ToolCall>()
        val result = executeLocalTool(toolCall) // 如 getCurrentTime()
        call.respond(mapOf("result" to result))
    }
}

SSE 双向流使前端/客户端可流式接收 Agent 思考与工具响应。

3. Agent 引擎与工具注册(Koog 风格)


kotlin

val agentEngine = AIAgent(
    executor = simpleOpenAIExecutor(System.getenv("API_KEY")),
    llmModel = OpenAIModels.Chat.GPT4o,
    features = listOf(
        ToolCallingFeature(tools = listOf(TimeTool(), CalcTool())),
        HistoryCompressionFeature()
    )
)

工具以强类型函数声明,编译期生成 JSON Schema,经 MCP SSE 透出[前文 Koog 框架解析]。

4. KMP 共享模型(跨端复用)


kotlin

// commonMain
@Serializable data class ChatRequest(val sessionId: String, val question: String)

Android/iOS/Web 前端与 Ktor 后端共用同一序列化定义,消除双边解析分歧

四、性能与工程避坑

  • 协程隔离:阻塞任务(JDBC/文件)必须用 withContext(Dispatchers.IO),保事件循环不被拖垮。
  • 结构化并发:路由内用 coroutineScope { async {}.await() } 并行工具调用,单失败自动取消兄弟任务。
  • 超时与压缩:生产环境装 RequestTimeout(5s)、CompressionCachingHeaders 防劣化。
  • 资源释放:Native 模型句柄、MCP 会话须显式 shutdown(),防 OOM[前文 KMP 避坑]。

五、小结

以 Ktor 异步网关 + MCP SSE 工具链为骨架,KMP shared 模块复用领域模型,即可在 100 行内搓出跑在 JVM/多端的 AI Agent 服务。该范式已被 Koog、OfflineAI-KMP 等验证,是 2026 年 Android 开发者全栈跃迁的最短路径。

Logo

Agent 垂直技术社区,欢迎活跃、内容共建。

更多推荐