Elffuss BraidHub

kikocis/utopia public

dev · 8.2 KiBRawPermalink
1//! MCP 服务端(Streamable HTTP)。
2//!
3//! 一条路由:`POST /api/v1/kbs/{kb_id}/mcp`,收 JSON-RPC 2.0。
4//!
5//! **传输选 Streamable HTTP 不选 stdio**,理由在 `docs/decisions/0014`:Utopia
6//! 本来就是个服务端,stdio 要么起一个子进程反过来连它、要么再开一个连接池;
7//! 而这是多人部署,五个人各连各的应该由同一个部署统一服务。
8//!
9//! **每个 POST 都重新认证一次。** 规范允许把一次握手的结果沿用整条连接,
10//! 而 0014 那条纪律说得很清楚:
11//!
12//! > 校验 scope 要在每个工具入口,不在握手。`revoked_at` 中途被写上时必须
13//! > 立刻生效。
14//!
15//! 这里做成无状态之后,那条性质是白得的——没有「连接」这个东西可以被信任。
16//!
17//! **响应用 `application/json` 而不是 SSE。** 规范允许两者,而这些工具是
18//! 一问一答,没有服务端主动推的东西;SSE 是给通知用的,这一版不需要。
19
20use axum::extract::{Path, State};
21use axum::http::HeaderMap;
22use axum::Json;
23use serde_json::{json, Value};
24use utopia_core::models::Role;
25use uuid::Uuid;
26
27use super::tools::{self, ToolCtx, ToolSink};
28use crate::error::ApiResult;
29use crate::state::AppState;
30
31/// 实现的协议版本。客户端报别的版本时照样按这个答——
32/// 规范要求服务端回自己支持的版本,由客户端决定接不接受
33const PROTOCOL_VERSION: &str = "2025-06-18";
34
35/// 这一版放出去的工具。**只读四个**(0014):
36///
37/// `query_data` 对生产库跑 SQL,`remember` 往账本里写,两者各自还有没答完的
38/// 问题——外部 agent 写进来的事实挂什么证据、跑 SQL 的审计怎么记。先把身份
39/// 这条路走通。
40const EXPOSED: [&str; 4] = ["search_chunks", "search_docs", "find_entities", "changes"];
41/// `entity_facts` 也在内,单列是因为上面那个数组要定长
42const EXPOSED_EXTRA: &str = "entity_facts";
43
44fn is_exposed(name: &str) -> bool {
45 EXPOSED.contains(&name) || name == EXPOSED_EXTRA
46}
47
48/// 认证 + 授权。**两道,不是一道。**
49///
50/// 令牌说「这是谁、这枚钥匙够到哪几个库」;`require_kb` 说「这个人在这个库里
51/// 是什么角色」。前者只收窄,后者才是权限——一枚 scope 全开的令牌落在一个
52/// viewer 手上,仍旧只是 viewer。
53async fn authorize(
54 state: &AppState,
55 headers: &HeaderMap,
56 kb_id: Uuid,
57) -> Result<
58 (
59 utopia_core::models::User,
60 utopia_store::tokens::Authenticated,
61 ),
62 utopia_core::AppError,
63> {
64 let raw = headers
65 .get(axum::http::header::AUTHORIZATION)
66 .and_then(|v| v.to_str().ok())
67 .and_then(|v| v.strip_prefix("Bearer "))
68 .ok_or(utopia_core::AppError::Unauthorized)?;
69 let auth = utopia_store::tokens::authenticate(&state.pool, raw.trim()).await?;
70 // 令牌的范围:限定过库的,够不着别的
71 if !auth.covers(kb_id) {
72 return Err(utopia_core::AppError::Forbidden);
73 }
74 // 人:停用立即生效(find_user_by_id 会挡住)
75 let user = utopia_store::accounts::find_user_by_id(&state.pool, auth.user_id)
76 .await?
77 .ok_or(utopia_core::AppError::Unauthorized)?;
78 // 角色:和网页端走同一个守卫,一行没改
79 utopia_store::access::require_kb(&state.pool, &user, kb_id, Role::Viewer).await?;
80 Ok((user, auth))
81}
82
83/// OpenAI 形状 → MCP 形状。
84///
85/// **共用 `chat.rs` 那一份定义**,而不是在这里另写一套。名字与参数 schema 是
86/// 与 `tools.rs` 执行侧的契约,抄成两份迟早分叉——那正是上一步把工具抽出来
87/// 要避免的事。
88///
89/// 已知的瑕疵:描述是给应用内助手写的,`search_chunks` 那句还提着「可以引用
90/// 成 [n]」,而 MCP 客户端拿不到引用编号。共用一份的好处大过这句话的代价,
91/// 真要分开时再说。
92fn to_mcp_tools(openai: &Value) -> Vec<Value> {
93 openai
94 .as_array()
95 .map(|arr| {
96 arr.iter()
97 .filter_map(|t| {
98 let f = t.get("function")?;
99 let name = f.get("name")?.as_str()?;
100 if !is_exposed(name) {
101 return None;
102 }
103 Some(json!({
104 "name": name,
105 "description": f.get("description").and_then(|d| d.as_str()).unwrap_or(""),
106 "inputSchema": f.get("parameters").cloned().unwrap_or(json!({
107 "type": "object", "properties": {}
108 })),
109 }))
110 })
111 .collect()
112 })
113 .unwrap_or_default()
114}
115
116fn ok(id: Option<Value>, result: Value) -> Json<Value> {
117 Json(json!({ "jsonrpc": "2.0", "id": id, "result": result }))
118}
119
120/// JSON-RPC 的错误不是 HTTP 的错误:**传输成功了,方法失败了**。
121/// 回 200 带 error 体,客户端才解析得动。
122fn rpc_err(id: Option<Value>, code: i64, message: &str) -> Json<Value> {
123 Json(json!({
124 "jsonrpc": "2.0", "id": id,
125 "error": { "code": code, "message": message }
126 }))
127}
128
129pub async fn handle(
130 State(state): State<AppState>,
131 Path(kb_id): Path<Uuid>,
132 headers: HeaderMap,
133 Json(req): Json<Value>,
134) -> ApiResult<Json<Value>> {
135 let (user, auth) = authorize(&state, &headers, kb_id).await?;
136 let id = req.get("id").cloned();
137 let method = req.get("method").and_then(|m| m.as_str()).unwrap_or("");
138 let params = req.get("params").cloned().unwrap_or(json!({}));
139
140 Ok(match method {
141 "initialize" => ok(
142 id,
143 json!({
144 "protocolVersion": PROTOCOL_VERSION,
145 "capabilities": { "tools": { "listChanged": false } },
146 "serverInfo": { "name": "utopia", "version": env!("CARGO_PKG_VERSION") },
147 }),
148 ),
149 // 通知没有 id,按规范不该回响应体;但 HTTP 这一侧总得回点什么,
150 // 回 202 语义更准,这里为了保持处理器签名统一回一个空结果
151 "notifications/initialized" | "notifications/cancelled" => ok(None, json!({})),
152 "ping" => ok(id, json!({})),
153 "tools/list" => ok(
154 id,
155 json!({ "tools": to_mcp_tools(&super::chat::base_tools()) }),
156 ),
157 "tools/call" => {
158 let name = params.get("name").and_then(|n| n.as_str()).unwrap_or("");
159 let args = params.get("arguments").cloned().unwrap_or(json!({}));
160 if !is_exposed(name) {
161 // 未暴露的工具(query_data / remember)要说清是「这一版没放出来」,
162 // 而不是「没有这个工具」——前者客户端不会反复重试
163 return Ok(rpc_err(
164 id,
165 -32601,
166 &format!("Tool '{name}' is not exposed over MCP in this version"),
167 ));
168 }
169 let kb = utopia_store::kbs::get(&state.pool, kb_id).await?;
170 // 这一版只放只读工具,所以 mounted_sources 空、can_write 假:
171 // **就算令牌 scope 是 write 也不放开**——scope 是上限不是授权,
172 // 而这一版的上限由 EXPOSED 定
173 let ctx = ToolCtx {
174 state: &state,
175 kb_id,
176 workspace_id: kb.workspace_id,
177 mounted_sources: &[],
178 can_write: false,
179 actor: Some(user.id),
180 };
181 let mut sink = ToolSink::default();
182 let (text, _step) = tools::dispatch(&ctx, &mut sink, name, &args).await;
183 let _ = utopia_store::audit::record(
184 &state.pool,
185 Some(kb_id),
186 user.id,
187 "mcp.tool_called",
188 "personal_token",
189 Some(auth.token_id),
190 json!({ "tool": name }),
191 )
192 .await;
193 ok(
194 id,
195 json!({
196 "content": [{ "type": "text", "text": text }],
197 "isError": false,
198 }),
199 )
200 }
201 other => rpc_err(id, -32601, &format!("Unknown method: {other}")),
202 })
203}