obsidian-mcp: 初次落地 Obsidian Vault MCP Server (.NET 10, read+write)
Build Docker Image / build (push) Failing after 9m21s
Build Docker Image / deploy (push) Has been skipped

把 Obsidian vault 通过 MCP 暴露给 Claude.ai,OAuth 走 nas-auth。
设计文档见 vault Coding/obsidian-mcp/obsidian-mcp 设计.md。
代码层落地参考 vault Coding/obsidian-mcp/MCP 实现指南.md。

V1+V2 同时实现(用户要求跳过分阶段直接全部):

读 Tools(需 scope=read:obsidian):
- list_vault_tree(一次性 vault 地图,限制深度)
- list_files / read_file(含 offset/limit 大文件分页)
- search(子串匹配 + glob 过滤,最多 50 hits)
- get_metadata(size / modified_at / has_frontmatter)

写 Tools(需 scope=write:obsidian):
- write_file / append_file
- 多重门禁:scope 校验 + 路径黑名单 + 写入白名单 + 永禁文件
  - 永禁写:任意目录的 AGENTS.md / PROFILE.md / README.md / CLAUDE.md / 01-Secret/**
  - 白名单:02-ShengquGames/logs/ + Coding/ + NAS/NAS 待办清单.md
- 写入审计日志按天 rotate(JSON line)

安全:
- VaultPathResolver chroot:path traversal + symlink 双拒绝
- JwtBearer (HS256, Current+Previous fallback, MapInboundClaims=false)
- aud=obsidian, iss=https://auth.zhengchentao.win
- 黑名单:01-Secret / .obsidian / .trash / .git

技术栈:
- .NET 10 + ModelContextProtocol SDK 1.0
- Streamable HTTP transport (POST /mcp)
- JwtBearer 10.0 + IdentityModel.Tokens 8.x

部署:
- Dockerfile multi-stage,runtime 装 ripgrep(V3 备用),non-root user
- .gitea/workflows/build-image.yml:build + deploy 双 job,buildkit v0.13.2
- 容器内 :8080,宿主端口 9090
- 子域名 obs.zhengchentao.win
- vault 挂载 /volume1/docker/webdav/data/Zhengchen:/vault:rw(V2 写入需要 rw)

测试:35/35 单测过(VaultPathResolver path traversal/blacklist/symlink + VaultWriteGuard whitelist/forbidden)

Co-Authored-By: Claude Opus 4.7 <noreply@anthropic.com>
This commit is contained in:
2026-05-06 01:32:11 +08:00
commit 28f9a54ba9
28 changed files with 1625 additions and 0 deletions
+81
View File
@@ -0,0 +1,81 @@
using System.ComponentModel;
using ModelContextProtocol.Server;
using ObsidianMcp.Auth;
using ObsidianMcp.Services;
namespace ObsidianMcp.Tools;
[McpServerToolType]
public class AppendFileTool(
VaultWriteGuard guard,
AuditLogger audit,
IHttpContextAccessor http)
{
[McpServerTool]
[Description(
"Append text to the end of a vault file (requires write:obsidian scope). " +
"Automatically prepends a newline if the file is non-empty and does not end with one. " +
"Ideal for adding entries to monthly work logs (02-ShengquGames/logs/YYYY-MM.md) " +
"or the NAS todo list (NAS/NAS 待办清单.md) without touching existing content. " +
"Same whitelist restrictions as write_file apply.")]
public async Task<WriteResult> AppendFile(
[Description("Vault-relative path (must be in writable whitelist). " +
"e.g. 'NAS/NAS 待办清单.md', '02-ShengquGames/logs/2026-05.md'")] string path,
[Description("Text to append (UTF-8). A newline is automatically inserted before this text " +
"if the file does not already end with one.")] string content)
{
// scope 校验
EnsureScope(ScopePolicies.WriteObsidian);
var user = GetUser();
var clientId = GetClientId();
try
{
var absPath = guard.EnsureWritable(path);
// 确保父目录存在
var dir = Path.GetDirectoryName(absPath)!;
Directory.CreateDirectory(dir);
// 如果文件已存在且末尾没有换行,先补一个
string prefix = string.Empty;
if (File.Exists(absPath))
{
var existing = await File.ReadAllTextAsync(absPath);
if (existing.Length > 0 && !existing.EndsWith('\n'))
prefix = Environment.NewLine;
}
await File.AppendAllTextAsync(absPath, prefix + content, System.Text.Encoding.UTF8);
var written = System.Text.Encoding.UTF8.GetByteCount(prefix + content);
audit.LogWrite(user, clientId, "append_file", path, written, ok: true);
return new WriteResult { Ok = true, WrittenBytes = written };
}
catch (Exception ex)
{
audit.LogWrite(user, clientId, "append_file", path, 0, ok: false, error: ex.Message);
throw;
}
}
private void EnsureScope(string requiredScope)
{
// OAuth 2.0 (RFC 6749) 规定 scope 大小写敏感,按 Ordinal 比对。
ToolScopeGuard.EnsureScope(http, requiredScope);
}
private string GetUser() =>
http.HttpContext?.User?.FindFirst("sub")?.Value ?? "unknown";
private string GetClientId() =>
http.HttpContext?.User?.FindFirst("client_id")?.Value ?? "unknown";
}
/// <summary>写入操作的返回值。</summary>
public class WriteResult
{
public bool Ok { get; set; }
public int WrittenBytes { get; set; }
}
+60
View File
@@ -0,0 +1,60 @@
using System.ComponentModel;
using ModelContextProtocol.Server;
using ObsidianMcp.Auth;
using ObsidianMcp.Services;
namespace ObsidianMcp.Tools;
[McpServerToolType]
public class GetMetadataTool(VaultPathResolver resolver, IHttpContextAccessor http)
{
[McpServerTool]
[Description(
"Get metadata for a vault file without reading its content. " +
"Returns size in bytes, last modified timestamp (UTC ISO-8601), " +
"and whether the file starts with YAML frontmatter (--- ... ---). " +
"Useful for deciding whether to read a file (staleness check, size guard before read_file).")]
public FileMetadata GetMetadata(
[Description("Vault-relative path to the file. " +
"e.g. 'NAS/NAS 总览.md'")] string path)
{
ToolScopeGuard.EnsureScope(http, ScopePolicies.ReadObsidian);
var absPath = resolver.Resolve(path);
if (!File.Exists(absPath))
throw new FileNotFoundException($"文件不存在:{path}");
var fi = new FileInfo(absPath);
// 简单判断是否有 frontmatter:读前 4 字节检查是否以 --- 开头
bool hasFrontmatter = false;
try
{
using var fs = File.OpenRead(absPath);
var header = new byte[4];
if (fs.Read(header, 0, 4) == 4)
hasFrontmatter = header[0] == '-' && header[1] == '-' && header[2] == '-';
}
catch
{
// 读取失败不影响其他字段
}
return new FileMetadata
{
Path = path,
SizeBytes = fi.Length,
ModifiedAt = fi.LastWriteTimeUtc.ToString("O"),
HasFrontmatter = hasFrontmatter,
};
}
}
public class FileMetadata
{
public string Path { get; set; } = "";
public long SizeBytes { get; set; }
public string ModifiedAt { get; set; } = "";
public bool HasFrontmatter { get; set; }
}
+55
View File
@@ -0,0 +1,55 @@
using System.ComponentModel;
using ModelContextProtocol.Server;
using ObsidianMcp.Auth;
using ObsidianMcp.Services;
namespace ObsidianMcp.Tools;
[McpServerToolType]
public class ListFilesTool(VaultPathResolver resolver, IHttpContextAccessor http)
{
[McpServerTool]
[Description(
"List files and immediate subdirectories in a vault directory. " +
"Returns a flat list of names (not full paths). " +
"Use list_vault_tree for a recursive overview, or this tool to drill into one directory. " +
"Hidden directories and blacklisted paths (01-Secret, .obsidian, etc.) are excluded.")]
public List<string> ListFiles(
[Description("Vault-relative path to list. Defaults to root if omitted. " +
"e.g. 'NAS', '02-ShengquGames/logs'")] string? path = null)
{
ToolScopeGuard.EnsureScope(http, ScopePolicies.ReadObsidian);
string absDir;
if (string.IsNullOrWhiteSpace(path))
{
absDir = resolver.VaultRoot;
}
else
{
absDir = resolver.Resolve(path);
}
if (!Directory.Exists(absDir))
throw new DirectoryNotFoundException($"目录不存在:{path}");
var result = new List<string>();
// 子目录(排除隐藏和黑名单)
foreach (var dir in Directory.GetDirectories(absDir).OrderBy(Path.GetFileName, StringComparer.OrdinalIgnoreCase))
{
var seg = Path.GetFileName(dir)!;
if (seg.StartsWith('.')) continue;
if (seg.Equals("01-Secret", StringComparison.OrdinalIgnoreCase)) continue;
result.Add(seg + "/");
}
// 文件
foreach (var file in Directory.GetFiles(absDir).OrderBy(Path.GetFileName, StringComparer.OrdinalIgnoreCase))
{
result.Add(Path.GetFileName(file));
}
return result;
}
}
+72
View File
@@ -0,0 +1,72 @@
using System.ComponentModel;
using ModelContextProtocol.Server;
using ObsidianMcp.Auth;
using ObsidianMcp.Services;
namespace ObsidianMcp.Tools;
[McpServerToolType]
public class ListVaultTreeTool(VaultPathResolver resolver, IHttpContextAccessor http)
{
[McpServerTool]
[Description(
"Return a depth-limited directory tree of the entire Obsidian vault as JSON. " +
"Use this first when you need an overview of the vault structure. " +
"Each node has { name, type (file|directory), children? }. " +
"Blacklisted directories (01-Secret, .obsidian, .trash, .git) are excluded. " +
"Prefer this over multiple list_files calls when you need the big picture.")]
public object ListVaultTree(
[Description("Maximum depth to traverse (default 3). Root is depth 0.")] int depth = 3)
{
ToolScopeGuard.EnsureScope(http, ScopePolicies.ReadObsidian);
if (depth < 0) depth = 0;
if (depth > 10) depth = 10; // 防止超大 vault 超时
var root = resolver.VaultRoot;
return BuildNode(root, root, depth);
}
private static object BuildNode(string path, string root, int remainingDepth)
{
var name = path == root ? "/" : Path.GetFileName(path);
if (File.Exists(path))
{
return new { name, type = "file" };
}
if (!Directory.Exists(path))
return new { name, type = "unknown" };
if (remainingDepth == 0)
return new { name, type = "directory" };
// 枚举子项,排序:目录先、文件后,各自按名字排序
List<object> children = [];
try
{
var entries = Directory.GetFileSystemEntries(path)
.OrderBy(e => File.Exists(e) ? 1 : 0)
.ThenBy(e => Path.GetFileName(e), StringComparer.OrdinalIgnoreCase);
foreach (var entry in entries)
{
var segName = Path.GetFileName(entry);
// 跳过隐藏文件/目录(以 . 开头)
if (segName.StartsWith('.')) continue;
// 跳过 01-Secret
if (segName.Equals("01-Secret", StringComparison.OrdinalIgnoreCase)) continue;
children.Add(BuildNode(entry, root, remainingDepth - 1));
}
}
catch (UnauthorizedAccessException)
{
// 无权限目录跳过
}
return new { name, type = "directory", children };
}
}
+55
View File
@@ -0,0 +1,55 @@
using System.ComponentModel;
using ModelContextProtocol.Server;
using ObsidianMcp.Auth;
using ObsidianMcp.Services;
namespace ObsidianMcp.Tools;
[McpServerToolType]
public class ReadFileTool(VaultPathResolver resolver, IHttpContextAccessor http)
{
[McpServerTool]
[Description(
"Read the full content of a vault file (UTF-8). " +
"This is the primary tool for reading notes, design docs, logs, and config files. " +
"Use get_metadata first if you want to check the file size before reading. " +
"For very large files (>100 KB), use the offset and limit parameters (in bytes) " +
"to read specific byte ranges and avoid context window overflow. " +
"Returns the raw Markdown text including frontmatter.")]
public async Task<string> ReadFile(
[Description("Vault-relative path to the file. " +
"e.g. 'NAS/NAS 总览.md', 'PROFILE.md', '02-ShengquGames/logs/2026-05.md'")] string path,
[Description("Byte offset to start reading from (0-based). Omit to read from the beginning.")] long? offset = null,
[Description("Number of bytes to read. Omit to read the entire file.")] long? limit = null)
{
ToolScopeGuard.EnsureScope(http, ScopePolicies.ReadObsidian);
var absPath = resolver.Resolve(path);
if (!File.Exists(absPath))
throw new FileNotFoundException($"文件不存在:{path}");
// 无分页时直接读全文
if (offset is null && limit is null)
return await File.ReadAllTextAsync(absPath);
// 有分页参数时按字节切片
await using var fs = new FileStream(absPath, FileMode.Open, FileAccess.Read, FileShare.Read);
long startByte = offset ?? 0;
if (startByte < 0) startByte = 0;
if (startByte >= fs.Length)
return string.Empty;
fs.Seek(startByte, SeekOrigin.Begin);
long bytesToRead = limit.HasValue
? Math.Min(limit.Value, fs.Length - startByte)
: fs.Length - startByte;
var buffer = new byte[bytesToRead];
var read = await fs.ReadAsync(buffer.AsMemory(0, (int)bytesToRead));
return System.Text.Encoding.UTF8.GetString(buffer, 0, read);
}
}
+37
View File
@@ -0,0 +1,37 @@
using System.ComponentModel;
using ModelContextProtocol.Server;
using ObsidianMcp.Auth;
using ObsidianMcp.Services;
namespace ObsidianMcp.Tools;
[McpServerToolType]
public class SearchTool(VaultSearchService searchSvc, IHttpContextAccessor http)
{
[McpServerTool]
[Description(
"Full-text search the Obsidian vault using case-insensitive literal substring match. " +
"Does NOT support regex or wildcards in the query string. " +
"Returns up to 50 hits by default, each with file path, line number, and a preview snippet. " +
"Use the glob parameter to narrow the search to specific directories or file patterns. " +
"For exact file reading use read_file instead. " +
"Examples: search for 'docker compose' across all files, or 'Uam' within '02-ShengquGames/**/*.md'.")]
public async Task<List<SearchHit>> Search(
[Description("Literal substring to search for (case-insensitive). " +
"e.g. 'docker compose', 'iptables PREROUTING', 'DOCKER_API_VERSION'")] string query,
[Description("Optional glob pattern to narrow files. " +
"e.g. 'NAS/**/*.md', '02-ShengquGames/**', '*.md'. " +
"Omit to search all .md files.")] string? glob = null,
[Description("Maximum number of results to return (default 50, max 200).")] int limit = 50)
{
ToolScopeGuard.EnsureScope(http, ScopePolicies.ReadObsidian);
if (string.IsNullOrWhiteSpace(query))
throw new ArgumentException("query 不能为空。");
if (limit <= 0) limit = 50;
if (limit > 200) limit = 200;
return await searchSvc.SearchAsync(query, glob, limit);
}
}
+69
View File
@@ -0,0 +1,69 @@
using System.ComponentModel;
using Microsoft.AspNetCore.Authorization;
using ModelContextProtocol.Server;
using ObsidianMcp.Auth;
using ObsidianMcp.Services;
namespace ObsidianMcp.Tools;
[McpServerToolType]
public class WriteFileTool(
VaultWriteGuard guard,
AuditLogger audit,
IHttpContextAccessor http)
{
[McpServerTool]
[Description(
"Overwrite a vault file with new content (requires write:obsidian scope). " +
"Completely replaces the existing content. " +
"Only whitelisted paths are allowed: " +
" - 02-ShengquGames/logs/ (monthly work logs), " +
" - Coding/ (personal infra notes), " +
" - NAS/NAS 待办清单.md (NAS todo list). " +
"Vault entry files (AGENTS.md, PROFILE.md, README.md, CLAUDE.md) and 01-Secret/ are always forbidden. " +
"Use append_file to add content without overwriting.")]
public async Task<WriteResult> WriteFile(
[Description("Vault-relative path (must be in writable whitelist). " +
"e.g. '02-ShengquGames/logs/2026-05.md'")] string path,
[Description("Full file content to write (UTF-8). Replaces existing content entirely.")] string content)
{
// scope 校验
EnsureScope(ScopePolicies.WriteObsidian);
var user = GetUser();
var clientId = GetClientId();
string? absPath = null;
try
{
absPath = guard.EnsureWritable(path);
// 确保父目录存在
var dir = Path.GetDirectoryName(absPath)!;
Directory.CreateDirectory(dir);
await File.WriteAllTextAsync(absPath, content, System.Text.Encoding.UTF8);
var written = System.Text.Encoding.UTF8.GetByteCount(content);
audit.LogWrite(user, clientId, "write_file", path, written, ok: true);
return new WriteResult { Ok = true, WrittenBytes = written };
}
catch (Exception ex)
{
audit.LogWrite(user, clientId, "write_file", path, 0, ok: false, error: ex.Message);
throw;
}
}
private void EnsureScope(string requiredScope)
{
// OAuth 2.0 (RFC 6749) 规定 scope 大小写敏感,按 Ordinal 比对。
ToolScopeGuard.EnsureScope(http, requiredScope);
}
private string GetUser() =>
http.HttpContext?.User?.FindFirst("sub")?.Value ?? "unknown";
private string GetClientId() =>
http.HttpContext?.User?.FindFirst("client_id")?.Value ?? "unknown";
}