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: bind MCP sessions to projects

nash_su8eebc68c543e
diff --git a/mcp-server/README.md b/mcp-server/README.md
index bcdfd3ca..6ee090d2 100644
--- a/mcp-server/README.md
+++ b/mcp-server/README.md
@@ -54,6 +54,7 @@ When API unauthenticated mode is enabled, omit `LLM_WIKI_API_TOKEN`. If MCP acce
- `llm_wiki_status`: health and current project summary.
- `llm_wiki_projects`: known projects and active project.
+- `llm_wiki_set_project`: pin the MCP process session to a project. Once pinned, other project tools reject attempts to access a different project.
- `llm_wiki_files`: list project files. `project_id` can be a project UUID, a project filesystem path, or `current`.
- `llm_wiki_read_file`: read an allowed text file such as `wiki/index.md`.
- `llm_wiki_reviews`: list Review tab items. Defaults to unresolved items and supports `status`, `type`, and `limit` filters.
@@ -71,5 +72,6 @@ The MCP server inherits the desktop API's security model:
- File reads go through the API path allow-list. Internal app state files are not exposed.
- Review data is exposed only through the dedicated Review endpoint/tool, which defaults to unresolved items rather than opening internal state files directly.
- Search and graph tools operate on projects known to the app; use `project_id: "current"` for the active project.
+- For multi-project use, call `llm_wiki_set_project` once. The resolved project ID remains fixed for the lifetime of the MCP subprocess even if the desktop UI switches projects, and every project-tool response includes an `activeProject` marker.
Do not pass API tokens via command-line arguments. Prefer environment variables so they do not appear in shell history.
diff --git a/mcp-server/src/index.ts b/mcp-server/src/index.ts
index 352ad031..49cc3189 100644
--- a/mcp-server/src/index.ts
+++ b/mcp-server/src/index.ts
@@ -15,13 +15,16 @@ import {
type ApiReviewsResponse,
type ApiChatResponse,
type ApiSearchResult,
+ type ApiProject,
} from "./api-client.js"
import { VERSION } from "./version.js"
+import { McpProjectBinding, withActiveProject } from "./project-binding.js"
const DEFAULT_PROJECT_ID = "current"
const MAX_TEXT_BYTES = 120_000
const client = new LlmWikiApiClient()
+const projectBinding = new McpProjectBinding()
const server = new Server(
{ name: "llm-wiki", version: VERSION },
@@ -48,6 +51,18 @@ server.setRequestHandler(ListToolsRequestSchema, async () => ({
additionalProperties: false,
},
},
+ {
+ name: "llm_wiki_set_project",
+ description: "Pin this MCP process session to one LLM Wiki project. Once pinned, project tools cannot access another project until this tool changes the binding.",
+ inputSchema: {
+ type: "object",
+ properties: {
+ project_id: { type: "string", description: "Project UUID, exact filesystem path, or 'current'." },
+ },
+ required: ["project_id"],
+ additionalProperties: false,
+ },
+ },
{
name: "llm_wiki_files",
description: "List files from a project using the desktop app's API permissions. project_id may be a UUID, filesystem path, or 'current'.",
@@ -166,49 +181,66 @@ server.setRequestHandler(CallToolRequestSchema, async (request) => {
client.health(),
client.projects().catch(() => ({ projects: [], currentProject: null })),
])
- return textResult(JSON.stringify({ ...health, ...projects }, null, 2))
+ return textResult(JSON.stringify({ ...health, ...projects, sessionProject: projectBinding.project }, null, 2))
}
case "llm_wiki_projects": {
await assertMcpEnabled()
- return textResult(JSON.stringify(await client.projects(), null, 2))
+ return textResult(JSON.stringify({ ...(await client.projects()), sessionProject: projectBinding.project }, null, 2))
+ }
+ case "llm_wiki_set_project": {
+ await assertMcpEnabled()
+ const requested = stringArg(args.project_id, "project_id")
+ const projects = await client.projects()
+ let pinned: ApiProject
+ try {
+ pinned = projectBinding.pin(requested, projects.projects, projects.currentProject)
+ } catch (error) {
+ throw new McpError(ErrorCode.InvalidParams, scopedErrorMessage(error))
+ }
+ return textResult(JSON.stringify({ activeProject: pinned, pinned: true }, null, 2))
}
case "llm_wiki_files": {
await assertMcpEnabled()
- const response = await client.files(projectId(args), {
+ const scope = await resolveProjectScope(args)
+ const response = await client.files(scope.id, {
root: enumArg(args.root, ["wiki", "sources", "all"] as const, "wiki"),
recursive: boolArg(args.recursive, true),
maxFiles: numberArg(args.max_files),
})
- return textResult(formatFileTree(response.files, response.truncated))
+ return textResult(withActiveProject(formatFileTree(response.files, response.truncated), scope.project, scope.id))
}
case "llm_wiki_read_file": {
await assertMcpEnabled()
const relPath = stringArg(args.path, "path")
- const { path, content } = await client.fileContent(projectId(args), relPath)
- return textResult(`# ${path}\n\n${truncateText(content, MAX_TEXT_BYTES)}`)
+ const scope = await resolveProjectScope(args)
+ const { path, content } = await client.fileContent(scope.id, relPath)
+ return textResult(withActiveProject(`# ${path}\n\n${truncateText(content, MAX_TEXT_BYTES)}`, scope.project, scope.id))
}
case "llm_wiki_reviews": {
await assertMcpEnabled()
- const reviews = await client.reviews(projectId(args), {
+ const scope = await resolveProjectScope(args)
+ const reviews = await client.reviews(scope.id, {
status: enumArg(args.status, ["unresolved", "resolved", "all"] as const, "unresolved"),
type: optionalStringArg(args.type),
limit: numberArg(args.limit),
})
- return textResult(formatReviews(reviews))
+ return textResult(withActiveProject(formatReviews(reviews), scope.project, scope.id))
}
case "llm_wiki_search": {
await assertMcpEnabled()
const query = stringArg(args.query, "query")
- const search = await client.search(projectId(args), query, {
+ const scope = await resolveProjectScope(args)
+ const search = await client.search(scope.id, query, {
topK: numberArg(args.top_k),
includeContent: boolArg(args.include_content, false),
})
- return textResult(formatSearchResults(query, search))
+ return textResult(withActiveProject(formatSearchResults(query, search), scope.project, scope.id))
}
case "llm_wiki_chat": {
await assertMcpEnabled()
const message = stringArg(args.message, "message")
- const chat = await client.chat(projectId(args), message, {
+ const scope = await resolveProjectScope(args)
+ const chat = await client.chat(scope.id, message, {
sessionId: optionalStringArg(args.session_id),
mode: enumArg(args.mode, ["fast", "standard", "deep", "local_first"] as const, "standard"),
topK: numberArg(args.top_k),
@@ -219,29 +251,33 @@ server.setRequestHandler(CallToolRequestSchema, async (request) => {
skills: stringArrayArg(args.skills),
persistSession: optionalStringArg(args.session_id) !== undefined,
})
- return textResult(formatChatResponse(chat))
+ return textResult(withActiveProject(formatChatResponse(chat), scope.project, scope.id))
}
case "llm_wiki_graph": {
await assertMcpEnabled()
- const graph = await client.graph(projectId(args), {
+ const scope = await resolveProjectScope(args)
+ const graph = await client.graph(scope.id, {
q: optionalStringArg(args.q),
nodeType: optionalStringArg(args.node_type),
limit: numberArg(args.limit),
})
- return textResult(formatGraph(graph.nodes, graph.edges))
+ return textResult(withActiveProject(formatGraph(graph.nodes, graph.edges), scope.project, scope.id))
}
case "llm_wiki_rescan_sources": {
await assertMcpEnabled()
- return textResult(JSON.stringify(await client.rescan(projectId(args)), null, 2))
+ const scope = await resolveProjectScope(args)
+ return textResult(withActiveProject(JSON.stringify(await client.rescan(scope.id), null, 2), scope.project, scope.id))
}
default:
throw new McpError(ErrorCode.MethodNotFound, `Unknown tool: ${request.params.name}`)
}
} catch (err) {
- if (err instanceof McpError) throw err
+ if (err instanceof McpError) {
+ throw new McpError(err.code, scopedErrorMessage(err.message))
+ }
throw new McpError(
ErrorCode.InternalError,
- err instanceof Error ? err.message : String(err),
+ scopedErrorMessage(err),
)
}
})
@@ -267,8 +303,26 @@ function asObject(value: unknown): Record<string, unknown> {
return value as Record<string, unknown>
}
-function projectId(args: Record<string, unknown>): string {
- return optionalStringArg(args.project_id) ?? DEFAULT_PROJECT_ID
+async function resolveProjectScope(args: Record<string, unknown>): Promise<{ id: string; project: ApiProject | null }> {
+ let id: string
+ try {
+ id = projectBinding.resolve(optionalStringArg(args.project_id) ?? undefined)
+ } catch (error) {
+ throw new McpError(ErrorCode.InvalidParams, scopedErrorMessage(error))
+ }
+ if (projectBinding.project) return { id, project: projectBinding.project }
+ const projects = await client.projects()
+ const project = id === DEFAULT_PROJECT_ID
+ ? projects.currentProject
+ : projects.projects.find((candidate) => candidate.id === id || candidate.path === id) ?? null
+ return { id, project }
+}
+
+function scopedErrorMessage(error: unknown): string {
+ const message = error instanceof Error ? error.message : String(error)
+ const project = projectBinding.project
+ if (!project || message.includes("[activeProject:")) return message
+ return `[activeProject: ${project.name} (${project.id})] ${message}`
}
function stringArg(value: unknown, name: string): string {
diff --git a/mcp-server/src/project-binding.ts b/mcp-server/src/project-binding.ts
new file mode 100644
index 00000000..f7ae08c9
--- /dev/null
+++ b/mcp-server/src/project-binding.ts
@@ -0,0 +1,45 @@
+import type { ApiProject } from "./api-client.js"
+
+export class McpProjectBinding {
+ private pinned: ApiProject | null = null
+
+ get project(): ApiProject | null {
+ return this.pinned
+ }
+
+ clear(): void {
+ this.pinned = null
+ }
+
+ pin(requested: string, projects: ApiProject[], current: ApiProject | null): ApiProject {
+ const candidate = requested === "current"
+ ? current
+ : projects.find((project) => project.id === requested || project.path === requested) ?? null
+ if (!candidate) throw new Error(`Unknown LLM Wiki project: ${requested}`)
+ this.pinned = candidate
+ return candidate
+ }
+
+ resolve(requested?: string): string {
+ if (!this.pinned) return requested ?? "current"
+ if (
+ requested &&
+ requested !== "current" &&
+ requested !== this.pinned.id &&
+ requested !== this.pinned.path
+ ) {
+ throw new Error(
+ `This MCP session is pinned to ${this.pinned.name} (${this.pinned.id}); ` +
+ `project override ${requested} was rejected. Call llm_wiki_set_project to change scope.`,
+ )
+ }
+ return this.pinned.id
+ }
+}
+
+export function withActiveProject(text: string, project: ApiProject | null, requestedId: string): string {
+ const scope = project
+ ? `${project.name} (${project.id})`
+ : requestedId
+ return `[activeProject: ${scope}]\n\n${text}`
+}
diff --git a/mcp-server/test/project-binding.test.ts b/mcp-server/test/project-binding.test.ts
new file mode 100644
index 00000000..a2d5e50d
--- /dev/null
+++ b/mcp-server/test/project-binding.test.ts
@@ -0,0 +1,30 @@
+import assert from "node:assert/strict"
+import { test } from "node:test"
+import { McpProjectBinding, withActiveProject } from "../src/project-binding.js"
+
+const alpha = { id: "p1", name: "Alpha", path: "/wiki/alpha", current: true }
+const beta = { id: "p2", name: "Beta", path: "/wiki/beta", current: false }
+
+test("pin resolves current to a stable project id", () => {
+ const binding = new McpProjectBinding()
+ binding.pin("current", [alpha, beta], alpha)
+ assert.equal(binding.resolve(), "p1")
+ assert.equal(binding.resolve("current"), "p1")
+})
+
+test("pinned sessions reject cross-project overrides", () => {
+ const binding = new McpProjectBinding()
+ binding.pin("p1", [alpha, beta], alpha)
+ assert.equal(binding.resolve("/wiki/alpha"), "p1")
+ assert.throws(() => binding.resolve("p2"), /override p2 was rejected/)
+})
+
+test("unbound sessions preserve the current-project compatibility default", () => {
+ const binding = new McpProjectBinding()
+ assert.equal(binding.resolve(), "current")
+ assert.equal(binding.resolve("p2"), "p2")
+})
+
+test("responses carry a structural active-project reminder", () => {
+ assert.match(withActiveProject("result", alpha, "p1"), /^\[activeProject: Alpha \(p1\)\]/)
+})