Skip to content

World's first open-source enterprise world model.

An agent can record over MCP, and the card says which agent (#318)

WaylandYang57680e999678
diff --git a/crates/utopia-core/src/models.rs b/crates/utopia-core/src/models.rs
index 87e20c07..27283f51 100644
--- a/crates/utopia-core/src/models.rs
+++ b/crates/utopia-core/src/models.rs
@@ -1136,9 +1136,24 @@ pub struct PendingFactView {
pub quote: String,
pub proposed_by: Option<Uuid>,
pub proposed_by_name: Option<String>,
+ /// 经 MCP 记进来时,那枚令牌的名字(0014 里人给 agent 起的名)。
+ /// 网页端对话记的记忆这一位是空的——那时「谁说的」就是那个人本人
+ pub proposed_token_name: Option<String>,
pub created_at: DateTime<Utc>,
}
+/// 一句记忆是谁提的。
+///
+/// **两层,不是一层**:`user_id` 是人(令牌代表的就是他,0014),`token_id` 是
+/// 他挂在这个库上的哪一个 agent。同一个人可以同时连着三个客户端,只记人
+/// 就等于让审核的人在三条一模一样的「张三说的」之间猜。
+#[derive(Debug, Clone, Copy, Default)]
+pub struct Proposer {
+ pub user_id: Option<Uuid>,
+ /// None = 不经 MCP(网页端对话,或批量摄入)
+ pub token_id: Option<Uuid>,
+}
+
#[derive(Debug, Clone, Copy, Default, Serialize, sqlx::FromRow)]
pub struct ReviewCounts {
/// 记忆抽出、等人点头的事实(0015)。排第一:它是人自己说的话
diff --git a/crates/utopia-server/src/api/chat.rs b/crates/utopia-server/src/api/chat.rs
index 5c9546c4..bf0859d0 100644
--- a/crates/utopia-server/src/api/chat.rs
+++ b/crates/utopia-server/src/api/chat.rs
@@ -46,7 +46,9 @@ pub struct ChatReq {
pub message: String,
}
-fn tools_schema(can_write: bool, data_source_names: &[String]) -> serde_json::Value {
+/// 工具清单。**MCP 也用这一份**(`mcp.rs`):名字、描述、参数 schema 抄成
+/// 两套迟早分叉,而它们是与 `tools.rs` 执行侧的契约
+pub(super) fn tools_schema(can_write: bool, data_source_names: &[String]) -> serde_json::Value {
let mut tools = base_tools();
if !data_source_names.is_empty() {
if let Some(arr) = tools.as_array_mut() {
@@ -732,6 +734,8 @@ pub async fn chat(
mounted_sources: &mounted_sources,
can_write,
actor: Some(user.id),
+ // 网页端对话不经令牌:说话的就是这个人本人
+ via_token: None,
};
let (result, step) = tools::dispatch(&ctx, &mut sink, &call.name, &args).await;
// **这一步发生在正文的哪个位置。**
diff --git a/crates/utopia-server/src/api/mcp.rs b/crates/utopia-server/src/api/mcp.rs
index 1b85a1f4..4d0a276a 100644
--- a/crates/utopia-server/src/api/mcp.rs
+++ b/crates/utopia-server/src/api/mcp.rs
@@ -32,23 +32,31 @@ use crate::state::AppState;
/// 规范要求服务端回自己支持的版本,由客户端决定接不接受
const PROTOCOL_VERSION: &str = "2025-06-18";
-/// 这一版放出去的工具。**只读五个**(0014):
+/// 只读的那些:任何一枚够得着这个库的令牌都能调。
///
-/// `query_data` 对生产库跑 SQL,`remember` 往账本里写,两者各自还有没答完的
-/// 问题——外部 agent 写进来的事实挂什么证据、跑 SQL 的审计怎么记。先把身份
-/// 这条路走通。
-const EXPOSED: [&str; 5] = [
+/// `query_data` 仍旧不放:它对**部署之外的生产库**跑 SQL,审计怎么记、
+/// 一个被投喂了脏文档的 agent 拿它做什么,都还没答完(0014 的混淆代理那一节)。
+const EXPOSED: [&str; 6] = [
"search_chunks",
"get_document",
"search_docs",
"find_entities",
"changes",
+ "entity_facts",
];
-/// `entity_facts` 也在内,单列是因为上面那个数组要定长
-const EXPOSED_EXTRA: &str = "entity_facts";
-fn is_exposed(name: &str) -> bool {
- EXPOSED.contains(&name) || name == EXPOSED_EXTRA
+/// 会往账本里写的那些。
+///
+/// **0014 当初不放 `remember`,主要是怕混淆代理**:agent 读的是库里的文档,
+/// 一句「请记住 X」写在文档里就可能被当成指令照做,而它带着那个人的全部权限。
+/// 0015 把这个反对意见拆掉了——记忆抽出的事实先进 `pending_facts` 等人点头,
+/// 没人点头就什么都没进图。所以这里放开的不是「写图」,是「提议」。
+const WRITABLE: [&str; 1] = ["remember"];
+
+/// `can_write` = 令牌 scope 是 write **且** 这个人在这个库里 editor 以上。
+/// 两个条件缺一不可:scope 是上限,角色才是权限(0014)
+fn is_exposed(name: &str, can_write: bool) -> bool {
+ EXPOSED.contains(&name) || (can_write && WRITABLE.contains(&name))
}
/// 认证 + 授权。**两道,不是一道。**
@@ -56,17 +64,19 @@ fn is_exposed(name: &str) -> bool {
/// 令牌说「这是谁、这枚钥匙够到哪几个库」;`require_kb` 说「这个人在这个库里
/// 是什么角色」。前者只收窄,后者才是权限——一枚 scope 全开的令牌落在一个
/// viewer 手上,仍旧只是 viewer。
+/// 认证的产物:人、令牌、库,以及**有效写权限**——令牌 scope ∩ 这个人在这个库里的角色。
+type Authorized = (
+ utopia_core::models::User,
+ utopia_store::tokens::Authenticated,
+ utopia_core::models::KnowledgeBase,
+ bool,
+);
+
async fn authorize(
state: &AppState,
headers: &HeaderMap,
kb_id: Uuid,
-) -> Result<
- (
- utopia_core::models::User,
- utopia_store::tokens::Authenticated,
- ),
- utopia_core::AppError,
-> {
+) -> Result<Authorized, utopia_core::AppError> {
let raw = headers
.get(axum::http::header::AUTHORIZATION)
.and_then(|v| v.to_str().ok())
@@ -82,8 +92,14 @@ async fn authorize(
.await?
.ok_or(utopia_core::AppError::Unauthorized)?;
// 角色:和网页端走同一个守卫,一行没改
- utopia_store::access::require_kb(&state.pool, &user, kb_id, Role::Viewer).await?;
- Ok((user, auth))
+ let kb = utopia_store::access::require_kb(&state.pool, &user, kb_id, Role::Viewer).await?;
+ // **收窄两次。** 令牌勾了 write 只是没把写排除掉;能不能写,问的是这个人
+ // 在这个库里的角色——一枚 scope 全开的令牌落在 viewer 手上仍旧只能读
+ let can_write = auth.can_write()
+ && utopia_store::access::kb_role(&state.pool, &user, &kb)
+ .await?
+ .is_some_and(|role| role >= Role::Editor);
+ Ok((user, auth, kb, can_write))
}
/// OpenAI 形状 → MCP 形状。
@@ -95,7 +111,7 @@ async fn authorize(
/// 已知的瑕疵:描述是给应用内助手写的,`search_chunks` 那句还提着「可以引用
/// 成 [n]」,而 MCP 客户端拿不到引用编号。共用一份的好处大过这句话的代价,
/// 真要分开时再说。
-fn to_mcp_tools(openai: &Value) -> Vec<Value> {
+fn to_mcp_tools(openai: &Value, can_write: bool) -> Vec<Value> {
openai
.as_array()
.map(|arr| {
@@ -103,7 +119,7 @@ fn to_mcp_tools(openai: &Value) -> Vec<Value> {
.filter_map(|t| {
let f = t.get("function")?;
let name = f.get("name")?.as_str()?;
- if !is_exposed(name) {
+ if !is_exposed(name, can_write) {
return None;
}
Some(json!({
@@ -138,7 +154,7 @@ pub async fn handle(
headers: HeaderMap,
Json(req): Json<Value>,
) -> ApiResult<Json<Value>> {
- let (user, auth) = authorize(&state, &headers, kb_id).await?;
+ let (user, auth, kb, can_write) = authorize(&state, &headers, kb_id).await?;
let id = req.get("id").cloned();
let method = req.get("method").and_then(|m| m.as_str()).unwrap_or("");
let params = req.get("params").cloned().unwrap_or(json!({}));
@@ -156,33 +172,43 @@ pub async fn handle(
// 回 202 语义更准,这里为了保持处理器签名统一回一个空结果
"notifications/initialized" | "notifications/cancelled" => ok(None, json!({})),
"ping" => ok(id, json!({})),
+ // **列表跟着这枚令牌变。** 写不了的令牌看不见 `remember`——
+ // 列出一个调不动的工具,等于让对面的 agent 反复试
"tools/list" => ok(
id,
- json!({ "tools": to_mcp_tools(&super::chat::base_tools()) }),
+ json!({
+ // 传空的数据源列表:`query_data` 没放出来,那份描述也就不必生成
+ "tools": to_mcp_tools(&super::chat::tools_schema(can_write, &[]), can_write)
+ }),
),
"tools/call" => {
let name = params.get("name").and_then(|n| n.as_str()).unwrap_or("");
let args = params.get("arguments").cloned().unwrap_or(json!({}));
- if !is_exposed(name) {
- // 未暴露的工具(query_data / remember)要说清是「这一版没放出来」,
- // 而不是「没有这个工具」——前者客户端不会反复重试
- return Ok(rpc_err(
- id,
- -32601,
- &format!("Tool '{name}' is not exposed over MCP in this version"),
- ));
+ if !is_exposed(name, can_write) {
+ // 三种「不行」要分得开,否则客户端只能反复重试:
+ // 拿不到的工具(query_data)是「这一版没放出来」,写工具是
+ // 「这枚令牌/这个人写不了」——后者人改得了,前者改不了
+ let message = if WRITABLE.contains(&name) {
+ format!(
+ "Tool '{name}' needs a token with the write scope, \
+ held by an editor in this base"
+ )
+ } else {
+ format!("Tool '{name}' is not exposed over MCP in this version")
+ };
+ return Ok(rpc_err(id, -32601, &message));
}
- let kb = utopia_store::kbs::get(&state.pool, kb_id).await?;
- // 这一版只放只读工具,所以 mounted_sources 空、can_write 假:
- // **就算令牌 scope 是 write 也不放开**——scope 是上限不是授权,
- // 而这一版的上限由 EXPOSED 定
+ // `mounted_sources` 仍旧空着:`query_data` 没放出来,给了也没人用。
+ // `can_write` 不再写死 false——它现在是令牌与角色一起算出来的
let ctx = ToolCtx {
state: &state,
kb_id,
workspace_id: kb.workspace_id,
mounted_sources: &[],
- can_write: false,
+ can_write,
actor: Some(user.id),
+ // 「谁说的」要答到 agent 这一层:一个人可以同时挂三个客户端
+ via_token: Some(auth.token_id),
};
let mut sink = ToolSink::default();
let (text, _step) = tools::dispatch(&ctx, &mut sink, name, &args).await;
diff --git a/crates/utopia-server/src/api/tools.rs b/crates/utopia-server/src/api/tools.rs
index 8a0d8feb..b16a4971 100644
--- a/crates/utopia-server/src/api/tools.rs
+++ b/crates/utopia-server/src/api/tools.rs
@@ -39,6 +39,9 @@ pub struct ToolCtx<'a> {
/// 在说话的人。`remember` 把它记成「谁说的」,一路跟到待确认队列(0015)。
/// 对话里恒有值;MCP 也有——令牌以人的身份行事(0014)
pub actor: Option<Uuid>,
+ /// 经 MCP 时,是哪一枚令牌在说话。**人之外还要记它**:一个人可以同时挂
+ /// 三个 agent,审核卡上只写人名分不出是哪一个记的(0026)。对话里为 None
+ pub via_token: Option<Uuid>,
}
/// 工具执行过程中往外攒的东西。
@@ -443,7 +446,11 @@ pub async fn remember(ctx: &ToolCtx<'_>, args: &serde_json::Value) -> ToolResult
let _ = utopia_store::jobs::enqueue(
&ctx.state.pool,
"memory_ingest",
- json!({ "document_id": doc_id, "proposed_by": ctx.actor }),
+ json!({
+ "document_id": doc_id,
+ "proposed_by": ctx.actor,
+ "proposed_token": ctx.via_token,
+ }),
)
.await;
ctx.state.emit_document(ctx.kb_id, doc_id);
diff --git a/crates/utopia-server/src/extraction.rs b/crates/utopia-server/src/extraction.rs
index 7888d9f1..d921ca45 100644
--- a/crates/utopia-server/src/extraction.rs
+++ b/crates/utopia-server/src/extraction.rs
@@ -8,6 +8,7 @@ use crate::state::AppState;
use sqlx::PgPool;
use std::collections::{HashMap, HashSet};
use std::time::Duration;
+use utopia_core::models::Proposer;
use uuid::Uuid;
/// 限流最多退避重试几次。**只对 429 生效**:密钥错了重试一万次还是错。
@@ -273,14 +274,15 @@ async fn enqueue_bootstrap(state: &AppState, kb_id: Uuid) -> anyhow::Result<()>
Ok(())
}
-/// `proposed_by`:这篇文档若是记忆日志,抽出的事实等人点头,这一列记「谁说的」。
-/// 批量摄入的文档传 None——那条路不经待确认队列,这个值用不上
+/// `proposer`:这篇文档若是记忆日志,抽出的事实等人点头,据此记下「谁说的」
+/// ——人,以及经 MCP 时那个 agent(0014 的令牌)。批量摄入的文档传默认值:
+/// 那条路不经待确认队列,这两位都用不上
pub async fn extract_document(
state: &AppState,
document_id: Uuid,
- proposed_by: Option<Uuid>,
+ proposer: Proposer,
) -> anyhow::Result<()> {
- match run(state, document_id, proposed_by).await {
+ match run(state, document_id, proposer).await {
Ok(()) => Ok(()),
Err(e) => {
// 原因随状态落库:只进日志的错误等于没有错误
@@ -540,7 +542,7 @@ async fn resolve_bare(
Ok(id)
}
-async fn run(state: &AppState, document_id: Uuid, proposed_by: Option<Uuid>) -> anyhow::Result<()> {
+async fn run(state: &AppState, document_id: Uuid, proposer: Proposer) -> anyhow::Result<()> {
let doc = utopia_store::documents::get(&state.pool, document_id).await?;
// 排队之后被删了(#268):墓碑不抽——抽出来的事实会活在一个已删除的出处上
if doc.deleted_at.is_some() {
@@ -1129,7 +1131,8 @@ async fn run(state: &AppState, document_id: Uuid, proposed_by: Option<Uuid>) ->
validity,
confidence,
chunk_id: chunk.id,
- proposed_by,
+ proposed_by: proposer.user_id,
+ proposed_token: proposer.token_id,
},
)
.await?
@@ -1250,7 +1253,8 @@ async fn run(state: &AppState, document_id: Uuid, proposed_by: Option<Uuid>) ->
validity,
confidence,
chunk_id: chunk.id,
- proposed_by,
+ proposed_by: proposer.user_id,
+ proposed_token: proposer.token_id,
},
)
.await?
@@ -1556,7 +1560,8 @@ async fn run(state: &AppState, document_id: Uuid, proposed_by: Option<Uuid>) ->
validity,
confidence,
chunk_id: chunk.id,
- proposed_by,
+ proposed_by: proposer.user_id,
+ proposed_token: proposer.token_id,
},
)
.await?
diff --git a/crates/utopia-server/src/main.rs b/crates/utopia-server/src/main.rs
index 5383077d..4154f7fc 100644
--- a/crates/utopia-server/src/main.rs
+++ b/crates/utopia-server/src/main.rs
@@ -35,12 +35,19 @@ use utopia_core::config::AppConfig;
use utopia_search::SearchIndex;
use uuid::Uuid;
-/// 记忆那条路带着「谁说的」(0015);别的任务没有这个字段,读到 None 本就该如此
-fn payload_proposed_by(payload: &serde_json::Value) -> Option<Uuid> {
- payload
- .get("proposed_by")
- .and_then(|v| v.as_str())
- .and_then(|s| s.parse().ok())
+/// 记忆那条路带着「谁说的」(0015、0026);别的任务没有这两个字段,
+/// 读到默认值本就该如此
+fn payload_proposer(payload: &serde_json::Value) -> utopia_core::models::Proposer {
+ let uuid = |key: &str| {
+ payload
+ .get(key)
+ .and_then(|v| v.as_str())
+ .and_then(|s| s.parse().ok())
+ };
+ utopia_core::models::Proposer {
+ user_id: uuid("proposed_by"),
+ token_id: uuid("proposed_token"),
+ }
}
fn payload_document_id(payload: &serde_json::Value) -> anyhow::Result<Uuid> {
@@ -329,7 +336,7 @@ async fn dispatch(st: &state::AppState, job: &utopia_store::jobs::Job) -> anyhow
}
"memory_ingest" => {
let id = payload_document_id(&job.payload)?;
- pipeline::memory_ingest(st, id, payload_proposed_by(&job.payload)).await
+ pipeline::memory_ingest(st, id, payload_proposer(&job.payload)).await
}
"explore_mappings" => {
let kb_id: Uuid = job
@@ -376,7 +383,7 @@ async fn dispatch(st: &state::AppState, job: &utopia_store::jobs::Job) -> anyhow
}
"extract_document" => {
let id = payload_document_id(&job.payload)?;
- extraction::extract_document(st, id, payload_proposed_by(&job.payload)).await
+ extraction::extract_document(st, id, payload_proposer(&job.payload)).await
}
"bootstrap_ontology" => {
let kb_id: Uuid = job
diff --git a/crates/utopia-server/src/pipeline.rs b/crates/utopia-server/src/pipeline.rs
index 25d225a9..096414a7 100644
--- a/crates/utopia-server/src/pipeline.rs
+++ b/crates/utopia-server/src/pipeline.rs
@@ -3,6 +3,7 @@
use crate::llm_util;
use crate::state::AppState;
+use utopia_core::models::Proposer;
use uuid::Uuid;
const EMBED_BATCH: usize = 16;
@@ -99,11 +100,12 @@ async fn run(state: &AppState, document_id: Uuid) -> anyhow::Result<()> {
/// 重建全文索引、触发增量抽取(extracted_at 为空的新 chunk 才会被抽)。
/// 免解析免分块——episode 落库时已是 chunk。
///
-/// `proposed_by`:说这句话的人。一路传到抽取,落在 `pending_facts.proposed_by`(0015)
+/// `proposer`:说这句话的人,以及经 MCP 时那个 agent。一路传到抽取,落在
+/// `pending_facts.proposed_by` / `proposed_token`(0015、0026)
pub async fn memory_ingest(
state: &AppState,
document_id: Uuid,
- proposed_by: Option<Uuid>,
+ proposer: Proposer,
) -> anyhow::Result<()> {
let doc = utopia_store::documents::get(&state.pool, document_id).await?;
if doc.deleted_at.is_some() {
@@ -147,7 +149,11 @@ pub async fn memory_ingest(
utopia_store::jobs::enqueue(
&state.pool,
"extract_document",
- serde_json::json!({ "document_id": document_id, "proposed_by": proposed_by }),
+ serde_json::json!({
+ "document_id": document_id,
+ "proposed_by": proposer.user_id,
+ "proposed_token": proposer.token_id,
+ }),
)
.await?;
}
diff --git a/crates/utopia-store/src/pending.rs b/crates/utopia-store/src/pending.rs
index 6d5fd233..b4115502 100644
--- a/crates/utopia-store/src/pending.rs
+++ b/crates/utopia-store/src/pending.rs
@@ -32,6 +32,8 @@ pub struct Proposal<'a> {
pub confidence: f32,
pub chunk_id: Uuid,
pub proposed_by: Option<Uuid>,
+ /// 经 MCP 提的话,是哪一枚令牌说的(0026)。网页端对话为空
+ pub proposed_token: Option<Uuid>,
}
/// 提议的去向。三种「没提」都不是错误——重抽一句记忆会再次算出同样的三元组,
@@ -111,8 +113,8 @@ pub async fn propose(pool: &PgPool, p: Proposal<'_>) -> AppResult<Outcome> {
"INSERT INTO pending_facts
(id, kb_id, subject_id, predicate_id, object_id, object_value, proposed_predicate,
valid_from, valid_from_precision, valid_to, valid_to_precision,
- confidence, chunk_id, proposed_by)
- VALUES ($1, $2, $3, $4, $5, $6, $7, $8, $9, $10, $11, $12, $13, $14)",
+ confidence, chunk_id, proposed_by, proposed_token)
+ VALUES ($1, $2, $3, $4, $5, $6, $7, $8, $9, $10, $11, $12, $13, $14, $15)",
)
.bind(id)
.bind(p.kb_id)
@@ -128,6 +130,7 @@ pub async fn propose(pool: &PgPool, p: Proposal<'_>) -> AppResult<Outcome> {
.bind(p.confidence)
.bind(p.chunk_id)
.bind(p.proposed_by)
+ .bind(p.proposed_token)
.execute(pool)
.await?;
Ok(Outcome::Proposed(id))
@@ -140,13 +143,15 @@ const VIEW_SELECT: &str = "\
p.object_id, o.canonical_name AS object_name, p.object_value,
p.valid_from, p.valid_from_precision, p.valid_to, p.valid_to_precision,
p.confidence, p.chunk_id, c.text AS quote,
- p.proposed_by, u.display_name AS proposed_by_name, p.created_at
+ p.proposed_by, u.display_name AS proposed_by_name,
+ t.name AS proposed_token_name, p.created_at
FROM pending_facts p
JOIN entities s ON s.id = p.subject_id
LEFT JOIN relation_types r ON r.id = p.predicate_id
LEFT JOIN entities o ON o.id = p.object_id
JOIN chunks c ON c.id = p.chunk_id
- LEFT JOIN users u ON u.id = p.proposed_by";
+ LEFT JOIN users u ON u.id = p.proposed_by
+ LEFT JOIN personal_tokens t ON t.id = p.proposed_token";
pub async fn list(
pool: &PgPool,
diff --git a/crates/utopia-store/tests/a_fact_awaits_a_nod.rs b/crates/utopia-store/tests/a_fact_awaits_a_nod.rs
index 97c843bb..e91ea22f 100644
--- a/crates/utopia-store/tests/a_fact_awaits_a_nod.rs
+++ b/crates/utopia-store/tests/a_fact_awaits_a_nod.rs
@@ -122,6 +122,7 @@ async fn a_remembered_fact_waits_for_a_nod() -> anyhow::Result<()> {
confidence: 0.9,
chunk_id: f.chunk,
proposed_by: None,
+ proposed_token: None,
},
)
};
diff --git a/crates/utopia-store/tests/an_agent_can_record.rs b/crates/utopia-store/tests/an_agent_can_record.rs
new file mode 100644
index 00000000..99cf08d3
--- /dev/null
+++ b/crates/utopia-store/tests/an_agent_can_record.rs
@@ -0,0 +1,186 @@
+//! 经 MCP 提的记忆,审核卡上要认得出是**哪一个 agent**(#304 / 0026)。
+//!
+//! 为什么非要连库:这条身份链整个由 SQL 承担——一列外键、一个 LEFT JOIN、
+//! 一个 `AS` 别名。写错列名、join 错表、别名和 `FromRow` 的字段对不上,
+//! `cargo check` 一个字都不会说,界面上只会安静地少显示半行字。
+//!
+//! 两条都要断言,因为它们坏的方式不同:
+//! - 带令牌的提议,视图要给出令牌的名字(join 漏了 → 永远是空)
+//! - 不带令牌的提议(网页端对话),那一位要是空(join 写成内连接 → 整条不见了)
+//!
+//! 自建自拆:一次性 org/workspace/kb,跑完连 org 一起删。
+
+use sqlx::PgPool;
+use utopia_store::graph::Validity;
+use utopia_store::pending::{Outcome, Proposal};
+use uuid::Uuid;
+
+struct Fixture {
+ org: Uuid,
+ kb: Uuid,
+ /// 令牌记的那一条
+ by_agent: Uuid,
+ /// 网页端对话记的那一条
+ by_person: Uuid,
+}
+
+async fn seed(pool: &PgPool) -> anyhow::Result<Fixture> {
+ let (org, ws, kb) = (Uuid::now_v7(), Uuid::now_v7(), Uuid::now_v7());
+ let (user, token) = (Uuid::now_v7(), Uuid::now_v7());
+ let (etype, doc, chunk) = (Uuid::now_v7(), Uuid::now_v7(), Uuid::now_v7());
+ let (acme, zenith) = (Uuid::now_v7(), Uuid::now_v7());
+ let tag = Uuid::now_v7();
+
+ sqlx::query("INSERT INTO organizations (id, name) VALUES ($1, 'agent-test')")
+ .bind(org)
+ .execute(pool)
+ .await?;
+ sqlx::query("INSERT INTO workspaces (id, org_id, name) VALUES ($1, $2, 'agent-test')")
+ .bind(ws)
+ .bind(org)
+ .execute(pool)
+ .await?;
+ sqlx::query(
+ "INSERT INTO knowledge_bases (id, workspace_id, name) VALUES ($1, $2, 'agent-test')",
+ )
+ .bind(kb)
+ .bind(ws)
+ .execute(pool)
+ .await?;
+ // 邮箱唯一:带一次性后缀,别撞上库里留下的账号
+ sqlx::query(
+ "INSERT INTO users (id, org_id, email, password_hash, display_name)
+ VALUES ($1, $2, $3, 'x', 'Zhang San')",
+ )
+ .bind(user)
+ .bind(org)
+ .bind(format!("agent-test-{tag}@utopia.test"))
+ .execute(pool)
+ .await?;
+ // token_hash 也唯一
+ sqlx::query(
+ "INSERT INTO personal_tokens (id, user_id, name, token_hash, token_prefix, scope)
+ VALUES ($1, $2, 'Meeting notes agent', $3, 'utp_pat_test', 'write')",
+ )
+ .bind(token)
+ .bind(user)
+ .bind(format!("hash-{tag}"))
+ .execute(pool)
+ .await?;
+ sqlx::query(
+ "INSERT INTO entity_types (id, kb_id, key, label) VALUES ($1, $2, 'org', 'Organization')",
+ )
+ .bind(etype)
+ .bind(kb)
+ .execute(pool)
+ .await?;
+ for (id, name) in [(acme, "Acme"), (zenith, "Zenith")] {
+ sqlx::query(
+ "INSERT INTO entities (id, kb_id, type_id, canonical_name) VALUES ($1, $2, $3, $4)",
+ )
+ .bind(id)
+ .bind(kb)
+ .bind(etype)
+ .bind(name)
+ .execute(pool)
+ .await?;
+ }
+ // blob 按 sha 跨库共用,sha 也带一次性后缀
+ sqlx::query(
+ "INSERT INTO documents (id, kb_id, filename, sha256, status)
+ VALUES ($1, $2, 'memory-log.md', $3, 'ready')",
+ )
+ .bind(doc)
+ .bind(kb)
+ .bind(format!("sha-{tag}"))
+ .execute(pool)
+ .await?;
+ sqlx::query(
+ "INSERT INTO chunks (id, kb_id, document_id, seq, text)
+ VALUES ($1, $2, $3, 0, 'Acme partnered with Zenith on 2026-03-01.')",
+ )
+ .bind(chunk)
+ .bind(kb)
+ .bind(doc)
+ .execute(pool)
+ .await?;
+
+ let propose = |object_id: Uuid, proposed_token: Option<Uuid>| {
+ let p = Proposal {
+ kb_id: kb,
+ subject_id: acme,
+ predicate_id: None,
+ object_id: Some(object_id),
+ object_value: None,
+ proposed_predicate: Some("partnered with"),
+ validity: Validity::default(),
+ confidence: 0.6,
+ chunk_id: chunk,
+ proposed_by: Some(user),
+ proposed_token,
+ };
+ async move {
+ match utopia_store::pending::propose(pool, p).await? {
+ Outcome::Proposed(id) => Ok::<Uuid, anyhow::Error>(id),
+ other => anyhow::bail!("提议没有入队:{other:?}"),
+ }
+ }
+ };
+ let by_agent = propose(zenith, Some(token)).await?;
+ // 同一个 (主语, 谓词, 宾语) 会被判成 AlreadyPending,所以第二条换个宾语
+ let by_person = propose(acme, None).await?;
+
+ Ok(Fixture {
+ org,
+ kb,
+ by_agent,
+ by_person,
+ })
+}
+
+#[tokio::test]
+async fn a_pending_fact_names_the_agent_that_proposed_it() -> anyhow::Result<()> {
+ let Some(url) = utopia_store::test_db::url() else {
+ return Ok(());
+ };
+ let pool = PgPool::connect(&url).await?;
+ let f = seed(&pool).await?;
+
+ let queue = utopia_store::pending::list(&pool, f.kb, 50, 0).await?;
+ let find = |id: Uuid| {
+ queue
+ .iter()
+ .find(|v| v.id == id)
+ .expect("待确认项不在队列里")
+ };
+
+ // 1. 令牌记的那条:人和 agent 都答得出。人是身份,agent 是「哪一个客户端」——
+ // 同一个人挂三个 agent 时,卡片上只有后者分得开
+ let agent = find(f.by_agent);
+ assert_eq!(agent.proposed_by_name.as_deref(), Some("Zhang San"));
+ assert_eq!(
+ agent.proposed_token_name.as_deref(),
+ Some("Meeting notes agent"),
+ "令牌名没跟出来——多半是 VIEW_SELECT 少了那个 join"
+ );
+
+ // 2. 网页端对话记的那条:没有 agent,但**这一条本身不能消失**
+ // (join 写成内连接就会整条不见,而那是最难发现的一种丢失)
+ let person = find(f.by_person);
+ assert_eq!(person.proposed_by_name.as_deref(), Some("Zhang San"));
+ assert_eq!(person.proposed_token_name, None);
+
+ // **先删库再删 org。** 删 org 级联到 users,而 `pending_facts.proposed_by`
+ // 是不带 ON DELETE 的外键(台账该拦住这种删除);库不跟着 org 级联,
+ // 所以顺序反了就会被外键顶回来
+ sqlx::query("DELETE FROM knowledge_bases WHERE id = $1")
+ .bind(f.kb)
+ .execute(&pool)
+ .await?;
+ let gone = sqlx::query("DELETE FROM organizations WHERE id = $1")
+ .bind(f.org)
+ .execute(&pool)
+ .await?;
+ assert_eq!(gone.rows_affected(), 1, "一次性 org 没删掉");
+ Ok(())
+}
diff --git a/migrations/0026_an_agent_records_over_mcp.sql b/migrations/0026_an_agent_records_over_mcp.sql
new file mode 100644
index 00000000..12995404
--- /dev/null
+++ b/migrations/0026_an_agent_records_over_mcp.sql
@@ -0,0 +1,12 @@
+-- 经 MCP 记进来的那句话,是**哪一个 agent** 说的。
+--
+-- 人已经在 `proposed_by` 里(0015),但一个库上可以连着好几个 agent,
+-- 而它们共用同一个人的身份。审核卡上三条「张三说的」分不出是哪个客户端记的,
+-- 而「谁说的」正是人裁决时唯一能依据的东西——一条来自代码助手的记忆和一条
+-- 来自会议纪要 agent 的记忆,可信度不是一回事。
+--
+-- 令牌撤销是**痕迹**不是删除(0014),行还在,所以这一列平时不会变空;
+-- ON DELETE SET NULL 是为了人被删除时连带删掉令牌的那条路——待确认的事实
+-- 不该跟着消失,它已经等在那里了。
+ALTER TABLE pending_facts
+ ADD COLUMN proposed_token UUID REFERENCES personal_tokens(id) ON DELETE SET NULL;
diff --git a/web/src/api.ts b/web/src/api.ts
index db954c11..72f0a889 100644
--- a/web/src/api.ts
+++ b/web/src/api.ts
@@ -595,6 +595,8 @@ export interface PendingFactItem {
quote: string;
proposed_by: string | null;
proposed_by_name: string | null;
+ /** 经 MCP 记进来时,那个 agent 的令牌名;网页端对话里为空 */
+ proposed_token_name: string | null;
created_at: string;
}
diff --git a/web/src/docs/mcp.md b/web/src/docs/mcp.md
index 67179bc1..462329e9 100644
--- a/web/src/docs/mcp.md
+++ b/web/src/docs/mcp.md
@@ -1,6 +1,6 @@
# Agents over MCP
-Utopia serves every knowledge base as a **Model Context Protocol** server. Any MCP client — Claude Desktop, Cursor, an agent framework, a script — can search a base, read a document, look up an entity and ask what changed, with the same permissions as the person whose token it carries. This version exposes **read tools only**; nothing an agent does over MCP changes the base.
+Utopia serves every knowledge base as a **Model Context Protocol** server. Any MCP client — Claude Desktop, Cursor, an agent framework, a script — can search a base, read a document, look up an entity and ask what changed, with the same permissions as the person whose token it carries. Reading needs nothing but a token. One tool records: `remember` asks a `write` token held by an editor, and what it records **waits for a person's nod** before it reaches the graph.
## Get a token
@@ -9,7 +9,7 @@ Tokens belong to people, not to bases: **Account → Agents & tokens → Persona
| Field | Meaning |
|---|---|
| Name | For your own bookkeeping; shows in the token list and in the audit log |
-| Scope | `read` (default) or `write`. Scope is a **ceiling**, not a grant: a token can never do more than its owner can, and this version's MCP tools are read-only even for a `write` token |
+| Scope | `read` (default) or `write`. Scope is a **ceiling**, not a grant: a token can never do more than its owner can. `remember` needs both — the `write` scope, and editor rights in that base. A viewer's `write` token still cannot record |
| Knowledge bases | Optional. Leave empty and the token reaches every base its owner can open; pick some to narrow it |
| Expires in | 90 days by default |
@@ -43,9 +43,18 @@ Three methods are served:
| `entity_facts` | One entity's facts with validity ranges. Pass `at` (a date) to see the world as of that day; this is the tool for "who was X in 2024" |
| `changes` | What the graph learned or revised in a window of **record** time: asserted, corrected, rejected, merged. Needs no entity; use it when the question names a period, not a subject |
| `search_docs` | Utopia's own manual, for questions about how the platform works. Never the user's documents |
+| `remember` | Record one sentence into the base's memory. **Needs a `write` token held by an editor**; a token without it does not see this tool in `tools/list`, and calling it anyway says why |
The two time axes matter here. `entity_facts` reads **world time** (when something was true); `changes` reads **record time** (when Utopia came to believe it, and when it revised that belief). An agent that confuses them will answer "what happened in March" with "what we learned in March".
+## What an agent records waits for a nod
+
+`remember` stores the sentence immediately — searchable at once, attributed to the token's owner. The facts extracted from it do **not** enter the graph. They queue in Review as proposals, each shown beneath the sentence it came from, and a person confirms or rejects them one at a time.
+
+That gate is why the tool can be served at all. An agent reads documents in the base, and a document can say "remember that X" — so an agent may be talked into recording something by the very material it was asked to read. A proposal that waits for a person costs a click; an assertion that does not costs a wrong edge on the graph, indistinguishable from one someone meant.
+
+The Review card names the agent, not only the person: several clients can share one owner's identity, and "which one said this" is most of what a reviewer has to go on. Never claim to a user that a fact was added — say the sentence was recorded and its facts await confirmation.
+
## Try it from a shell
List the tools:
@@ -91,5 +100,5 @@ One entry per knowledge base you want the agent to reach. The agent sees the sam
## What is not here yet
-- **Writing.** `remember` (recording an episode) and `query_data` (SQL over a mounted database) are chat tools today and are not served over MCP. When they are, the write path will go through the same confirmation step a person's own "remember" does: an agent proposes, a person confirms, and only then does anything enter the graph.
+- **SQL.** `query_data` (a read-only query against a mounted database) is a chat tool and is not served over MCP. It reaches production databases outside this deployment, and what a borrowed agent should be able to ask them is a question this version does not answer.
- **Streaming.** Responses are single JSON-RPC replies; there is no server-sent event channel.
diff --git a/web/src/i18n/en.ts b/web/src/i18n/en.ts
index 2b740876..5f6befd0 100644
--- a/web/src/i18n/en.ts
+++ b/web/src/i18n/en.ts
@@ -1501,6 +1501,8 @@ export const en = {
pendingNoPredicate: "The ontology has no relation for this; the word is the model's own.",
pendingNoPredicateChip: "no relation in ontology",
pendingSaidBy: (name: string) => `said by ${name}`,
+ /* 同一个人可以挂着好几个 agent,只写人名分不出是哪一个记的 */
+ pendingSaidVia: (name: string, agent: string) => `said by ${name} · via ${agent}`,
nodCardTitle: (n: number) =>
n === 1
? "One fact extracted from this. Confirm to add it to the graph, or reject."
diff --git a/web/src/i18n/zh.ts b/web/src/i18n/zh.ts
index 12484c98..5cf8098e 100644
--- a/web/src/i18n/zh.ts
+++ b/web/src/i18n/zh.ts
@@ -1334,6 +1334,7 @@ export const zh: Strings = {
pendingNoPredicate: "本体里没有这个关系,这个词是模型自己的说法。",
pendingNoPredicateChip: "本体里没有这个关系",
pendingSaidBy: (name: string) => `${name} 说的`,
+ pendingSaidVia: (name: string, agent: string) => `${name} 说的 · 经 ${agent}`,
nodCardTitle: (n: number) =>
n === 1 ? "从这句话里抽出 1 条事实。确认进图,或驳回。" : `从这句话里抽出 ${n} 条事实。确认进图,或驳回。`,
lowConfidenceHint:
diff --git a/web/src/pages/PendingFacts.tsx b/web/src/pages/PendingFacts.tsx
index 94e5ef3d..fe2524a1 100644
--- a/web/src/pages/PendingFacts.tsx
+++ b/web/src/pages/PendingFacts.tsx
@@ -85,7 +85,12 @@ export function PendingFactRow({
<div className="mt-3 flex items-center gap-2">
{fact.proposed_by_name && (
<span className="text-[11px] text-neutral-600">
- {S.review.pendingSaidBy(fact.proposed_by_name)}
+ {fact.proposed_token_name
+ ? S.review.pendingSaidVia(
+ fact.proposed_by_name,
+ fact.proposed_token_name,
+ )
+ : S.review.pendingSaidBy(fact.proposed_by_name)}
</span>
)}
{canDecide && (