MCP (Model Context Protocol) server for reading and writing an Obsidian vault, gated by OAuth-issued JWT bearer tokens. See README.md for setup.
This commit is contained in:
@@ -0,0 +1,80 @@
|
||||
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 a running log or todo file without touching existing content. " +
|
||||
"Same whitelist restrictions as write_file apply (path must be in Vault__WriteWhitelist).")]
|
||||
public async Task<WriteResult> AppendFile(
|
||||
[Description("Vault-relative path (must be in writable whitelist). " +
|
||||
"e.g. 'Notes/todo.md', 'Projects/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; }
|
||||
}
|
||||
@@ -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. 'Notes/index.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; }
|
||||
}
|
||||
@@ -0,0 +1,54 @@
|
||||
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 (.obsidian, .git, .trash) and any path configured in Vault__Blacklist are excluded.")]
|
||||
public List<string> ListFiles(
|
||||
[Description("Vault-relative path to list. Defaults to root if omitted. " +
|
||||
"e.g. 'Notes', 'Projects/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>();
|
||||
|
||||
// 子目录(排除隐藏目录;黑名单目录在尝试访问时由 VaultPathResolver 拦截)
|
||||
foreach (var dir in Directory.GetDirectories(absDir).OrderBy(Path.GetFileName, StringComparer.OrdinalIgnoreCase))
|
||||
{
|
||||
var seg = Path.GetFileName(dir)!;
|
||||
if (seg.StartsWith('.')) continue;
|
||||
result.Add(seg + "/");
|
||||
}
|
||||
|
||||
// 文件
|
||||
foreach (var file in Directory.GetFiles(absDir).OrderBy(Path.GetFileName, StringComparer.OrdinalIgnoreCase))
|
||||
{
|
||||
result.Add(Path.GetFileName(file));
|
||||
}
|
||||
|
||||
return result;
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,70 @@
|
||||
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? }. " +
|
||||
"Hidden directories (.obsidian, .trash, .git) and any path in Vault__Blacklist 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);
|
||||
// 跳过隐藏文件/目录(以 . 开头);其他黑名单目录在尝试访问时由 VaultPathResolver 拦截
|
||||
if (segName.StartsWith('.')) continue;
|
||||
|
||||
children.Add(BuildNode(entry, root, remainingDepth - 1));
|
||||
}
|
||||
}
|
||||
catch (UnauthorizedAccessException)
|
||||
{
|
||||
// 无权限目录跳过
|
||||
}
|
||||
|
||||
return new { name, type = "directory", children };
|
||||
}
|
||||
}
|
||||
@@ -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. 'Notes/index.md', 'README.md', 'Projects/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);
|
||||
}
|
||||
}
|
||||
@@ -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 'TODO' within 'Projects/**/*.md'.")]
|
||||
public async Task<List<SearchHit>> Search(
|
||||
[Description("Literal substring to search for (case-insensitive). " +
|
||||
"e.g. 'docker compose', 'TODO', 'API_KEY'")] string query,
|
||||
[Description("Optional glob pattern to narrow files. " +
|
||||
"e.g. 'Notes/**/*.md', 'Projects/**', '*.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);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,68 @@
|
||||
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 paths matching Vault__WriteWhitelist entries are allowed " +
|
||||
"(entries ending with '/' are prefix matches, otherwise exact-path matches). " +
|
||||
"Agent context files (AGENTS.md, README.md, CLAUDE.md) are always forbidden, " +
|
||||
"as are any paths in Vault__Blacklist. " +
|
||||
"Use append_file to add content without overwriting.")]
|
||||
public async Task<WriteResult> WriteFile(
|
||||
[Description("Vault-relative path (must be in writable whitelist). " +
|
||||
"e.g. 'Projects/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";
|
||||
}
|
||||
Reference in New Issue
Block a user