Skip to content

LLM Wiki is a cross-platform desktop application that turns your documents into an organized, interlinked knowledge base — automatically. Instead of traditional RAG (retrieve-and-answer from scratch every time), the LLM incrementally builds and maintains a persistent wiki from your sources。

TypeScript

feat: add verified MCP wiki page writes

nash_su4ffe41407b09
diff --git a/mcp-server/src/api-client.ts b/mcp-server/src/api-client.ts
index 42f2c699..451e83a7 100644
--- a/mcp-server/src/api-client.ts
+++ b/mcp-server/src/api-client.ts
@@ -46,6 +46,14 @@ export interface ApiPageEmbeddingResult {
status: string
}
+export interface ApiPageWriteResult {
+ path: string
+ bytes: number
+ allowOverwrite: boolean
+ verified: boolean
+ existedBefore: boolean
+}
+
export interface ApiChatReference {
title: string
path: string
@@ -352,6 +360,29 @@ export class LlmWikiApiClient {
}
}
+ async writePage(
+ path: string,
+ content: string,
+ projectId = "current",
+ allowOverwrite = false,
+ ): Promise<ApiPageWriteResult> {
+ const json = await this.request(`/projects/${encodeURIComponent(projectId)}/pages/write`, {
+ method: "POST",
+ body: { path, content, allowOverwrite },
+ })
+ const result = requireObject(json.result, "page write result")
+ if (result.verified !== true) {
+ throw new Error("page write result.verified: expected true")
+ }
+ return {
+ path: requireString(result.path, "page write result.path"),
+ bytes: requireNumber(result.bytes, "page write result.bytes"),
+ allowOverwrite: result.allowOverwrite === true,
+ verified: true,
+ existedBefore: result.existedBefore === true,
+ }
+ }
+
private async request(path: string, options: { method?: "GET" | "POST"; body?: unknown; auth?: boolean } = {}): Promise<Record<string, unknown>> {
const url = `${this.baseUrl}${apiPath(path)}`
const headers: Record<string, string> = { Accept: "application/json" }
diff --git a/mcp-server/src/index.ts b/mcp-server/src/index.ts
index 7726ffb3..35692db9 100644
--- a/mcp-server/src/index.ts
+++ b/mcp-server/src/index.ts
@@ -22,6 +22,7 @@ import { McpProjectBinding, withActiveProject } from "./project-binding.js"
const DEFAULT_PROJECT_ID = "current"
const MAX_TEXT_BYTES = 120_000
+const MAX_WRITE_PAGE_BYTES = 2 * 1024 * 1024
const client = new LlmWikiApiClient()
const projectBinding = new McpProjectBinding()
@@ -185,6 +186,21 @@ server.setRequestHandler(ListToolsRequestSchema, async () => ({
additionalProperties: false,
},
},
+ {
+ name: "llm_wiki_write_page",
+ description: "Create or explicitly overwrite one Markdown page under wiki/. Success is returned only after byte-for-byte persistence verification.",
+ inputSchema: {
+ type: "object",
+ properties: {
+ project_id: { type: "string", description: "Project UUID, project path, or 'current'. Defaults to current." },
+ path: { type: "string", description: "Canonical project-relative Markdown path under wiki/." },
+ content: { type: "string", description: "Exact UTF-8 page content to persist." },
+ allow_overwrite: { type: "boolean", description: "Defaults to false. Must be true to replace an existing page." },
+ },
+ required: ["path", "content"],
+ additionalProperties: false,
+ },
+ },
],
}))
@@ -295,6 +311,19 @@ server.setRequestHandler(CallToolRequestSchema, async (request) => {
const result = await client.embedPage(path, scope.id, boolArg(args.force, false))
return textResult(withActiveProject(JSON.stringify(result, null, 2), scope.project, scope.id))
}
+ case "llm_wiki_write_page": {
+ await assertMcpEnabled()
+ const path = wikiWritePathArg(args.path)
+ const content = writeContentArg(args.content)
+ const scope = await resolveProjectScope(args)
+ const result = await client.writePage(
+ path,
+ content,
+ scope.id,
+ boolArg(args.allow_overwrite, false),
+ )
+ return textResult(withActiveProject(JSON.stringify(result, null, 2), scope.project, scope.id))
+ }
default:
throw new McpError(ErrorCode.MethodNotFound, `Unknown tool: ${request.params.name}`)
}
@@ -359,6 +388,31 @@ function stringArg(value: unknown, name: string): string {
return value
}
+function wikiWritePathArg(value: unknown): string {
+ const path = stringArg(value, "path")
+ if (Buffer.byteLength(path, "utf8") > 4_096) {
+ throw new McpError(ErrorCode.InvalidParams, "path is too large")
+ }
+ if (path.includes("\\") || path.startsWith("/") || !path.startsWith("wiki/") || !path.endsWith(".md")) {
+ throw new McpError(ErrorCode.InvalidParams, "path must be a canonical Markdown path under wiki/")
+ }
+ const segments = path.split("/")
+ if (segments.some((segment) => !segment || segment === "." || segment === ".." || segment.startsWith("."))) {
+ throw new McpError(ErrorCode.InvalidParams, "path contains a noncanonical component")
+ }
+ return path
+}
+
+function writeContentArg(value: unknown): string {
+ if (typeof value !== "string") {
+ throw new McpError(ErrorCode.InvalidParams, "content is required")
+ }
+ if (Buffer.byteLength(value, "utf8") > MAX_WRITE_PAGE_BYTES) {
+ throw new McpError(ErrorCode.InvalidParams, "content is too large")
+ }
+ return value
+}
+
function optionalStringArg(value: unknown): string | undefined {
return typeof value === "string" && value.trim() !== "" ? value : undefined
}
diff --git a/mcp-server/test/api-client.test.ts b/mcp-server/test/api-client.test.ts
index 4ad1eb0d..19b7dfcf 100644
--- a/mcp-server/test/api-client.test.ts
+++ b/mcp-server/test/api-client.test.ts
@@ -115,6 +115,51 @@ test("embedPage rejects malformed success payloads", async () => {
)
})
+test("writePage posts exact content and requires verified persistence", async () => {
+ const fetchImpl: typeof fetch = async (input, init) => {
+ assert.equal(String(input), "http://127.0.0.1:19828/api/v1/projects/project%20a/pages/write")
+ assert.equal(init?.method, "POST")
+ assert.deepEqual(JSON.parse(String(init?.body)), {
+ path: "wiki/ops/page.md",
+ content: "# Exact\n",
+ allowOverwrite: true,
+ })
+ return new Response(JSON.stringify({
+ ok: true,
+ result: {
+ path: "wiki/ops/page.md",
+ bytes: 8,
+ allowOverwrite: true,
+ verified: true,
+ existedBefore: true,
+ },
+ }), { status: 200 })
+ }
+ const client = new LlmWikiApiClient({ fetchImpl })
+
+ assert.deepEqual(await client.writePage("wiki/ops/page.md", "# Exact\n", "project a", true), {
+ path: "wiki/ops/page.md",
+ bytes: 8,
+ allowOverwrite: true,
+ verified: true,
+ existedBefore: true,
+ })
+})
+
+test("writePage rejects an unverified success response", async () => {
+ const client = new LlmWikiApiClient({
+ fetchImpl: async () => new Response(JSON.stringify({
+ ok: true,
+ result: { path: "wiki/page.md", bytes: 1, verified: false },
+ }), { status: 200 }),
+ })
+
+ await assert.rejects(
+ () => client.writePage("wiki/page.md", "x"),
+ /verified: expected true/,
+ )
+})
+
test("chat posts agent request and parses references", async () => {
let url = ""
let body = ""
diff --git a/src-tauri/src/agent/tools.rs b/src-tauri/src/agent/tools.rs
index f4e31d52..92d38c9b 100644
--- a/src-tauri/src/agent/tools.rs
+++ b/src-tauri/src/agent/tools.rs
@@ -4,10 +4,11 @@ use std::fs;
use std::fs::OpenOptions;
use std::future::Future;
use std::hash::{Hash, Hasher};
-use std::io::{Read, Seek, SeekFrom};
+use std::io::{Read, Seek, SeekFrom, Write};
use std::path::{Component, Path, PathBuf};
use std::pin::Pin;
use std::process::Stdio;
+use std::sync::{Mutex, OnceLock};
use std::time::SystemTime;
use serde::{Deserialize, Serialize};
@@ -47,6 +48,7 @@ const SHELL_OUTPUT_DRAIN_TIMEOUT_SECS: u64 = 1;
const DEFAULT_ANYTXT_ENDPOINT: &str = "http://127.0.0.1:9920";
const DEFAULT_ANYTXT_LIMIT: usize = 20;
const ANYTXT_LAST_MODIFY_END: i64 = 2_147_483_647;
+static WIKI_WRITE_LOCK: OnceLock<Mutex<()>> = OnceLock::new();
#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq)]
#[serde(rename_all = "snake_case")]
@@ -327,6 +329,16 @@ pub struct WikiWriteOutput {
pub previous_content: Option<String>,
}
+#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq)]
+#[serde(rename_all = "camelCase")]
+pub struct VerifiedWikiWriteOutput {
+ pub path: String,
+ pub bytes: usize,
+ pub allow_overwrite: bool,
+ pub verified: bool,
+ pub existed_before: bool,
+}
+
#[derive(Debug, Clone, Serialize, Deserialize, Default)]
#[serde(rename_all = "camelCase")]
pub struct WebSearchConfig {
@@ -656,12 +668,32 @@ pub fn write_wiki_page_with_options(
Ok(write_wiki_page_with_activity(project_path, rel_path, content, allow_overwrite)?.reference)
}
+pub fn write_wiki_page_verified(
+ project_path: &str,
+ rel_path: &str,
+ content: &str,
+ allow_overwrite: bool,
+) -> Result<VerifiedWikiWriteOutput, String> {
+ let output = write_wiki_page_with_activity(project_path, rel_path, content, allow_overwrite)?;
+ Ok(VerifiedWikiWriteOutput {
+ path: output.reference.path,
+ bytes: content.len(),
+ allow_overwrite,
+ verified: true,
+ existed_before: output.existed_before,
+ })
+}
+
fn write_wiki_page_with_activity(
project_path: &str,
rel_path: &str,
content: &str,
allow_overwrite: bool,
) -> Result<WikiWriteOutput, String> {
+ let _write_guard = WIKI_WRITE_LOCK
+ .get_or_init(|| Mutex::new(()))
+ .lock()
+ .map_err(|_| "wiki.write_page lock is unavailable".to_string())?;
if content.len() > MAX_WRITE_PAGE_BYTES {
return Err("wiki.write_page content is too large".to_string());
}
@@ -684,10 +716,34 @@ fn write_wiki_page_with_activity(
.to_string(),
);
}
+ if path
+ .symlink_metadata()
+ .map(|metadata| metadata.file_type().is_symlink())
+ .unwrap_or(false)
+ {
+ return Err("wiki.write_page refuses to overwrite a symlink".to_string());
+ }
let existed_before = path.is_file();
+ let previous_bytes = existed_before
+ .then(|| fs::read(&path))
+ .transpose()
+ .map_err(|err| format!("Failed to read existing wiki page before replacement: {err}"))?;
let previous_content = workspace_rollback_snapshot(&path);
crate::commands::file_history::record_file_version(&path, "baseline", "before.wiki.write_page");
- fs::write(&path, content).map_err(|err| format!("Failed to write wiki page: {err}"))?;
+ atomic_replace_file(&path, content.as_bytes())?;
+ let persisted =
+ fs::read(&path).map_err(|err| format!("Failed to verify persisted wiki page: {err}"))?;
+ if persisted != content.as_bytes() {
+ let rollback = if let Some(previous) = previous_bytes {
+ atomic_replace_file(&path, &previous)
+ } else {
+ fs::remove_file(&path).map_err(|err| format!("Failed to remove unverified page: {err}"))
+ };
+ return Err(match rollback {
+ Ok(()) => "Persisted wiki page did not match the requested content; the previous state was restored".to_string(),
+ Err(err) => format!("Persisted wiki page did not match the requested content, and rollback failed: {err}"),
+ });
+ }
crate::commands::file_history::record_file_version(&path, "agent", "wiki.write_page");
Ok(WikiWriteOutput {
reference: AgentReference {
@@ -710,6 +766,67 @@ fn write_wiki_page_with_activity(
})
}
+fn atomic_replace_file(path: &Path, content: &[u8]) -> Result<(), String> {
+ let parent = path
+ .parent()
+ .ok_or_else(|| "Failed to resolve wiki page parent directory".to_string())?;
+ let file_name = path
+ .file_name()
+ .and_then(|name| name.to_str())
+ .ok_or_else(|| "wiki.write_page path must be valid UTF-8".to_string())?;
+ let nonce = SystemTime::now()
+ .duration_since(SystemTime::UNIX_EPOCH)
+ .unwrap_or_default()
+ .as_nanos();
+ let temp = parent.join(format!(
+ ".{file_name}.llm-wiki-{}-{nonce}.tmp",
+ std::process::id()
+ ));
+ let mut file = OpenOptions::new()
+ .write(true)
+ .create_new(true)
+ .open(&temp)
+ .map_err(|err| format!("Failed to create wiki page temp file: {err}"))?;
+ if let Err(err) = file.write_all(content).and_then(|_| file.sync_all()) {
+ let _ = fs::remove_file(&temp);
+ return Err(format!("Failed to write wiki page temp file: {err}"));
+ }
+ drop(file);
+
+ #[cfg(not(windows))]
+ {
+ if let Err(err) = fs::rename(&temp, path) {
+ let _ = fs::remove_file(&temp);
+ return Err(format!("Failed to replace wiki page: {err}"));
+ }
+ }
+
+ #[cfg(windows)]
+ {
+ let backup = parent.join(format!(
+ ".{file_name}.llm-wiki-{}-{nonce}.bak",
+ std::process::id()
+ ));
+ let had_target = path.exists();
+ if had_target {
+ fs::rename(path, &backup)
+ .map_err(|err| format!("Failed to stage existing wiki page: {err}"))?;
+ }
+ if let Err(err) = fs::rename(&temp, path) {
+ if had_target {
+ let _ = fs::rename(&backup, path);
+ }
+ let _ = fs::remove_file(&temp);
+ return Err(format!("Failed to replace wiki page: {err}"));
+ }
+ if had_target {
+ let _ = fs::remove_file(backup);
+ }
+ }
+
+ Ok(())
+}
+
fn write_workspace_file(
project_path: &str,
rel_path: &str,
@@ -2604,6 +2721,10 @@ fn normalize_rel_path(path: &str) -> String {
}
fn normalize_wiki_write_path(path: &str) -> Result<String, String> {
+ let trimmed = path.trim();
+ if trimmed.starts_with('/') || trimmed.starts_with('\\') {
+ return Err("wiki.write_page path must stay inside the project".to_string());
+ }
let rel = normalize_rel_path(path);
let lower = rel.to_ascii_lowercase();
if !lower.starts_with("wiki/") || !lower.ends_with(".md") {
@@ -3204,6 +3325,14 @@ mod tests {
false
)
.is_err());
+ let absolute_error = write_wiki_page_with_options(
+ root.to_str().unwrap(),
+ "/wiki/absolute.md",
+ "# Absolute",
+ false,
+ )
+ .unwrap_err();
+ assert!(absolute_error.contains("must stay inside the project"));
assert!(write_wiki_page_with_options(
root.to_str().unwrap(),
"raw/sources/a.md",
@@ -3282,6 +3411,43 @@ mod tests {
)
.unwrap();
assert_eq!(overwritten.title, "Replaced");
+
+ let verified = write_wiki_page_verified(
+ root.to_str().unwrap(),
+ "wiki/queries/verified.md",
+ "# Verified\n",
+ false,
+ )
+ .unwrap();
+ assert_eq!(verified.path, "wiki/queries/verified.md");
+ assert_eq!(verified.bytes, "# Verified\n".len());
+ assert!(verified.verified);
+ assert!(!verified.existed_before);
+ let _ = fs::remove_dir_all(root);
+ }
+
+ #[cfg(unix)]
+ #[test]
+ fn write_wiki_page_refuses_symlink_targets() {
+ use std::os::unix::fs::symlink;
+
+ let root = std::env::temp_dir().join(format!("llm-wiki-agent-link-{}", Uuid::new_v4()));
+ fs::create_dir_all(root.join("wiki")).unwrap();
+ fs::write(root.join("purpose.md"), "protected").unwrap();
+ symlink(root.join("purpose.md"), root.join("wiki/linked.md")).unwrap();
+
+ let error = write_wiki_page_verified(
+ root.to_str().unwrap(),
+ "wiki/linked.md",
+ "overwritten",
+ true,
+ )
+ .unwrap_err();
+ assert!(error.contains("symlink"));
+ assert_eq!(
+ fs::read_to_string(root.join("purpose.md")).unwrap(),
+ "protected"
+ );
let _ = fs::remove_dir_all(root);
}
diff --git a/src-tauri/src/api_server.rs b/src-tauri/src/api_server.rs
index 13c5be9e..266862e5 100644
--- a/src-tauri/src/api_server.rs
+++ b/src-tauri/src/api_server.rs
@@ -24,6 +24,9 @@ const PORT: u16 = 19828;
const API_PREFIX: &str = "/api/v1";
const MAX_BODY_BYTES: usize = 1024 * 1024;
const MAX_CHAT_BODY_BYTES: usize = 40 * 1024 * 1024;
+// JSON may encode one input byte as a six-byte `\u00XX` escape. Keep the
+// transport boundary above the authoritative 2 MiB decoded-content limit.
+const MAX_PAGE_WRITE_BODY_BYTES: usize = 6 * 2 * 1024 * 1024 + 16 * 1024;
const MAX_FILE_CONTENT_BYTES: u64 = 2 * 1024 * 1024;
const DEFAULT_MAX_FILES: usize = 2_000;
const HARD_MAX_FILES: usize = 10_000;
@@ -374,6 +377,9 @@ fn handle_request(
(&Method::Post, ["projects", project_id, "pages", "embed"]) => {
handle_embed_page(app, project_id, body)
}
+ (&Method::Post, ["projects", project_id, "pages", "write"]) => {
+ handle_write_page(app, project_id, body)
+ }
(&Method::Post, ["projects", project_id, "chat"]) => handle_chat(app, project_id, body),
(&Method::Post, ["projects", project_id, "chat", session_id, "cancel"]) => {
handle_cancel_chat(app, project_id, session_id)
@@ -425,7 +431,11 @@ fn is_token_required_request(method: &Method, path: &str) -> bool {
let Some(parts) = api_path_parts(path) else {
return false;
};
- method == &Method::Post && matches!(parts.as_slice(), ["projects", _, "pages", "embed"])
+ method == &Method::Post
+ && matches!(
+ parts.as_slice(),
+ ["projects", _, "pages", "embed"] | ["projects", _, "pages", "write"]
+ )
}
fn chat_project_id<'a>(method: &Method, path: &'a str) -> Option<&'a str> {
@@ -481,15 +491,13 @@ fn wants_streaming_chat(
fn body_limit_for_request(method: &Method, url: &str) -> usize {
let (path, _) = split_url(url);
let parts = api_path_parts(&path);
- if method == &Method::Post
- && parts
- .as_deref()
- .map(|parts| matches!(parts, ["projects", _, "chat"]))
- .unwrap_or(false)
- {
- MAX_CHAT_BODY_BYTES
- } else {
- MAX_BODY_BYTES
+ if method != &Method::Post {
+ return MAX_BODY_BYTES;
+ }
+ match parts.as_deref() {
+ Some(["projects", _, "chat"]) => MAX_CHAT_BODY_BYTES,
+ Some(["projects", _, "pages", "write"]) => MAX_PAGE_WRITE_BODY_BYTES,
+ _ => MAX_BODY_BYTES,
}
}
@@ -1778,6 +1786,55 @@ struct EmbedPageRequest {
force: bool,
}
+#[derive(Deserialize)]
+#[serde(rename_all = "camelCase", deny_unknown_fields)]
+struct WritePageRequest {
+ path: String,
+ content: String,
+ #[serde(default)]
+ allow_overwrite: bool,
+}
+
+fn handle_write_page(app: &AppHandle, project_id: &str, body: &str) -> ApiResponse {
+ let project = match resolve_project(app, project_id) {
+ Ok(project) => project,
+ Err(e) => return err(404, e),
+ };
+ let req: WritePageRequest = match serde_json::from_str(body) {
+ Ok(req) => req,
+ Err(e) => return err(400, format!("Invalid JSON: {e}")),
+ };
+ if req.path.trim().is_empty() {
+ return err(400, "path is required");
+ }
+ match agent::tools::write_wiki_page_verified(
+ &project.path,
+ &req.path,
+ &req.content,
+ req.allow_overwrite,
+ ) {
+ Ok(result) => ok(json!({
+ "ok": true,
+ "projectId": project.id,
+ "result": result,
+ })),
+ Err(error) => {
+ let lower = error.to_ascii_lowercase();
+ let status = if lower.contains("without allowoverwrite") {
+ 409
+ } else if lower.contains("path")
+ || lower.contains("markdown file")
+ || lower.contains("too large")
+ {
+ 400
+ } else {
+ 500
+ };
+ err(status, error)
+ }
+ }
+}
+
struct PageEmbedSlot;
impl Drop for PageEmbedSlot {
@@ -3626,6 +3683,10 @@ mod tests {
body_limit_for_request(&Method::Post, "/api/v1/projects/current/search"),
MAX_BODY_BYTES
);
+ assert_eq!(
+ body_limit_for_request(&Method::Post, "/api/v1/projects/current/pages/write"),
+ MAX_PAGE_WRITE_BODY_BYTES
+ );
}
#[test]
@@ -3654,6 +3715,10 @@ mod tests {
&Method::Post,
"/api/v1/projects/current/pages/embed"
));
+ assert!(is_token_required_request(
+ &Method::Post,
+ "/api/v1/projects/current/pages/write"
+ ));
assert!(is_token_required_request(
&Method::Post,
"/api/v1/projects/current/chat"