Files
obsidian-mcp/Tools/AppendFileTool.cs
T
zhengchen.tao 28f9a54ba9
Build Docker Image / build (push) Failing after 9m21s
Build Docker Image / deploy (push) Has been skipped
obsidian-mcp: 初次落地 Obsidian Vault MCP Server (.NET 10, read+write)
把 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>
2026-05-06 01:32:11 +08:00

82 lines
2.9 KiB
C#

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; }
}