refactor: update VaultTools to pass adapters to utils
Updated VaultTools to use adapters for all utility method calls: - SearchUtils.searchWaypoints() now receives vault adapter - WaypointUtils.isFolderNote() now receives vault adapter - LinkUtils.validateWikilinks() now receives vault and metadata adapters - LinkUtils.resolveLink() now receives vault and metadata adapters - LinkUtils.getBacklinks() now receives vault and metadata adapters Removed App dependency from VaultTools constructor - now only requires vault and metadata adapters. Updated factory and all test files accordingly. All tests passing (336/336).
This commit is contained in:
@@ -9,7 +9,6 @@ import { MetadataCacheAdapter } from '../adapters/metadata-adapter';
|
||||
export function createVaultTools(app: App): VaultTools {
|
||||
return new VaultTools(
|
||||
new VaultAdapter(app.vault),
|
||||
new MetadataCacheAdapter(app.metadataCache),
|
||||
app
|
||||
new MetadataCacheAdapter(app.metadataCache)
|
||||
);
|
||||
}
|
||||
@@ -1,4 +1,4 @@
|
||||
import { App, TFile, TFolder } from 'obsidian';
|
||||
import { TFile, TFolder } from 'obsidian';
|
||||
import { CallToolResult, FileMetadata, DirectoryMetadata, VaultInfo, SearchResult, SearchMatch, StatResult, ExistsResult, ListResult, FileMetadataWithFrontmatter, FrontmatterSummary, WaypointSearchResult, FolderWaypointResult, FolderNoteResult, ValidateWikilinksResult, ResolveWikilinkResult, BacklinksResult } from '../types/mcp-types';
|
||||
import { PathUtils } from '../utils/path-utils';
|
||||
import { ErrorMessages } from '../utils/error-messages';
|
||||
@@ -11,8 +11,7 @@ import { IVaultAdapter, IMetadataCacheAdapter } from '../adapters/interfaces';
|
||||
export class VaultTools {
|
||||
constructor(
|
||||
private vault: IVaultAdapter,
|
||||
private metadata: IMetadataCacheAdapter,
|
||||
private app: App // Still needed for waypoint methods (searchWaypoints, getFolderWaypoint, isFolderNote)
|
||||
private metadata: IMetadataCacheAdapter
|
||||
) {}
|
||||
|
||||
async getVaultInfo(): Promise<CallToolResult> {
|
||||
@@ -708,12 +707,12 @@ export class VaultTools {
|
||||
|
||||
async searchWaypoints(folder?: string): Promise<CallToolResult> {
|
||||
try {
|
||||
const waypoints = await SearchUtils.searchWaypoints(this.app, folder);
|
||||
const waypoints = await SearchUtils.searchWaypoints(this.vault, folder);
|
||||
|
||||
const result: WaypointSearchResult = {
|
||||
waypoints,
|
||||
totalWaypoints: waypoints.length,
|
||||
filesSearched: this.app.vault.getMarkdownFiles().filter(file => {
|
||||
filesSearched: this.vault.getMarkdownFiles().filter(file => {
|
||||
if (!folder) return true;
|
||||
const folderPath = folder.endsWith('/') ? folder : folder + '/';
|
||||
return file.path.startsWith(folderPath) || file.path === folder;
|
||||
@@ -741,10 +740,10 @@ export class VaultTools {
|
||||
try {
|
||||
// Normalize and validate path
|
||||
const normalizedPath = PathUtils.normalizePath(path);
|
||||
|
||||
// Resolve file
|
||||
const file = PathUtils.resolveFile(this.app, normalizedPath);
|
||||
if (!file) {
|
||||
|
||||
// Get file using adapter
|
||||
const file = this.vault.getAbstractFileByPath(normalizedPath);
|
||||
if (!file || !(file instanceof TFile)) {
|
||||
return {
|
||||
content: [{
|
||||
type: "text",
|
||||
@@ -755,7 +754,7 @@ export class VaultTools {
|
||||
}
|
||||
|
||||
// Read file content
|
||||
const content = await this.app.vault.read(file);
|
||||
const content = await this.vault.read(file);
|
||||
|
||||
// Extract waypoint block
|
||||
const waypointBlock = WaypointUtils.extractWaypointBlock(content);
|
||||
@@ -789,10 +788,10 @@ export class VaultTools {
|
||||
try {
|
||||
// Normalize and validate path
|
||||
const normalizedPath = PathUtils.normalizePath(path);
|
||||
|
||||
// Resolve file
|
||||
const file = PathUtils.resolveFile(this.app, normalizedPath);
|
||||
if (!file) {
|
||||
|
||||
// Get file using adapter
|
||||
const file = this.vault.getAbstractFileByPath(normalizedPath);
|
||||
if (!file || !(file instanceof TFile)) {
|
||||
return {
|
||||
content: [{
|
||||
type: "text",
|
||||
@@ -803,7 +802,7 @@ export class VaultTools {
|
||||
}
|
||||
|
||||
// Check if it's a folder note
|
||||
const folderNoteInfo = await WaypointUtils.isFolderNote(this.app, file);
|
||||
const folderNoteInfo = await WaypointUtils.isFolderNote(this.vault, file);
|
||||
|
||||
const result: FolderNoteResult = {
|
||||
path: file.path,
|
||||
@@ -850,34 +849,12 @@ export class VaultTools {
|
||||
};
|
||||
}
|
||||
|
||||
// Read file content
|
||||
const content = await this.vault.read(file);
|
||||
|
||||
// Parse wikilinks
|
||||
const wikilinks = LinkUtils.parseWikilinks(content);
|
||||
|
||||
const resolvedLinks: any[] = [];
|
||||
const unresolvedLinks: any[] = [];
|
||||
|
||||
for (const link of wikilinks) {
|
||||
const resolvedFile = this.metadata.getFirstLinkpathDest(link.target, normalizedPath);
|
||||
|
||||
if (resolvedFile) {
|
||||
resolvedLinks.push({
|
||||
text: link.raw,
|
||||
target: resolvedFile.path,
|
||||
alias: link.alias
|
||||
});
|
||||
} else {
|
||||
// Find suggestions (need to implement locally)
|
||||
const suggestions = this.findLinkSuggestions(link.target);
|
||||
unresolvedLinks.push({
|
||||
text: link.raw,
|
||||
line: link.line,
|
||||
suggestions
|
||||
});
|
||||
}
|
||||
}
|
||||
// Use LinkUtils to validate wikilinks
|
||||
const { resolvedLinks, unresolvedLinks } = await LinkUtils.validateWikilinks(
|
||||
this.vault,
|
||||
this.metadata,
|
||||
normalizedPath
|
||||
);
|
||||
|
||||
const result: ValidateWikilinksResult = {
|
||||
path: normalizedPath,
|
||||
@@ -903,56 +880,6 @@ export class VaultTools {
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Find potential matches for an unresolved link
|
||||
*/
|
||||
private findLinkSuggestions(linkText: string, maxSuggestions: number = 5): string[] {
|
||||
const allFiles = this.vault.getMarkdownFiles();
|
||||
const suggestions: Array<{ path: string; score: number }> = [];
|
||||
|
||||
// Remove heading/block references for matching
|
||||
const cleanLinkText = linkText.split('#')[0].split('^')[0].toLowerCase();
|
||||
|
||||
for (const file of allFiles) {
|
||||
const fileName = file.basename.toLowerCase();
|
||||
const filePath = file.path.toLowerCase();
|
||||
|
||||
// Calculate similarity score
|
||||
let score = 0;
|
||||
|
||||
// Exact basename match (highest priority)
|
||||
if (fileName === cleanLinkText) {
|
||||
score = 1000;
|
||||
}
|
||||
// Basename contains link text
|
||||
else if (fileName.includes(cleanLinkText)) {
|
||||
score = 500 + (cleanLinkText.length / fileName.length) * 100;
|
||||
}
|
||||
// Path contains link text
|
||||
else if (filePath.includes(cleanLinkText)) {
|
||||
score = 250 + (cleanLinkText.length / filePath.length) * 100;
|
||||
}
|
||||
// Levenshtein-like: count matching characters
|
||||
else {
|
||||
let matchCount = 0;
|
||||
for (const char of cleanLinkText) {
|
||||
if (fileName.includes(char)) {
|
||||
matchCount++;
|
||||
}
|
||||
}
|
||||
score = (matchCount / cleanLinkText.length) * 100;
|
||||
}
|
||||
|
||||
if (score > 0) {
|
||||
suggestions.push({ path: file.path, score });
|
||||
}
|
||||
}
|
||||
|
||||
// Sort by score (descending) and return top N
|
||||
suggestions.sort((a, b) => b.score - a.score);
|
||||
return suggestions.slice(0, maxSuggestions).map(s => s.path);
|
||||
}
|
||||
|
||||
/**
|
||||
* Resolve a single wikilink from a source note
|
||||
* Returns the target path if resolvable, or suggestions if not
|
||||
@@ -974,8 +901,8 @@ export class VaultTools {
|
||||
};
|
||||
}
|
||||
|
||||
// Try to resolve the link using metadata cache adapter
|
||||
const resolvedFile = this.metadata.getFirstLinkpathDest(linkText, normalizedPath);
|
||||
// Try to resolve the link using LinkUtils
|
||||
const resolvedFile = LinkUtils.resolveLink(this.vault, this.metadata, normalizedPath, linkText);
|
||||
|
||||
const result: ResolveWikilinkResult = {
|
||||
sourcePath: normalizedPath,
|
||||
@@ -986,7 +913,7 @@ export class VaultTools {
|
||||
|
||||
// If not resolved, provide suggestions
|
||||
if (!resolvedFile) {
|
||||
result.suggestions = this.findLinkSuggestions(linkText);
|
||||
result.suggestions = LinkUtils.findSuggestions(this.vault, linkText);
|
||||
}
|
||||
|
||||
return {
|
||||
@@ -1031,102 +958,13 @@ export class VaultTools {
|
||||
};
|
||||
}
|
||||
|
||||
// Get target file's basename for matching
|
||||
const targetBasename = targetFile.basename;
|
||||
|
||||
// Get all backlinks from MetadataCache using resolvedLinks
|
||||
const resolvedLinks = this.metadata.resolvedLinks;
|
||||
const backlinks: any[] = [];
|
||||
|
||||
// Find all files that link to our target
|
||||
for (const [sourcePath, links] of Object.entries(resolvedLinks)) {
|
||||
// Check if this source file links to our target
|
||||
if (!links[normalizedPath]) {
|
||||
continue;
|
||||
}
|
||||
|
||||
const sourceFile = this.vault.getAbstractFileByPath(sourcePath);
|
||||
if (!(sourceFile instanceof TFile)) {
|
||||
continue;
|
||||
}
|
||||
|
||||
// Read the source file to find link occurrences
|
||||
const content = await this.vault.read(sourceFile);
|
||||
const lines = content.split('\n');
|
||||
const occurrences: any[] = [];
|
||||
|
||||
// Parse wikilinks in the source file to find references to target
|
||||
const wikilinks = LinkUtils.parseWikilinks(content);
|
||||
|
||||
for (const link of wikilinks) {
|
||||
// Resolve this link to see if it points to our target
|
||||
const resolvedFile = this.metadata.getFirstLinkpathDest(link.target, sourcePath);
|
||||
|
||||
if (resolvedFile && resolvedFile.path === normalizedPath) {
|
||||
const snippet = includeSnippets ? this.extractSnippet(lines, link.line - 1, 100) : '';
|
||||
occurrences.push({
|
||||
line: link.line,
|
||||
snippet
|
||||
});
|
||||
}
|
||||
}
|
||||
|
||||
if (occurrences.length > 0) {
|
||||
backlinks.push({
|
||||
sourcePath,
|
||||
type: 'linked',
|
||||
occurrences
|
||||
});
|
||||
}
|
||||
}
|
||||
|
||||
// Process unlinked mentions if requested
|
||||
if (includeUnlinked) {
|
||||
const allFiles = this.vault.getMarkdownFiles();
|
||||
|
||||
// Build a set of files that already have linked backlinks
|
||||
const linkedSourcePaths = new Set(backlinks.map(b => b.sourcePath));
|
||||
|
||||
for (const file of allFiles) {
|
||||
// Skip if already in linked backlinks
|
||||
if (linkedSourcePaths.has(file.path)) {
|
||||
continue;
|
||||
}
|
||||
|
||||
// Skip the target file itself
|
||||
if (file.path === normalizedPath) {
|
||||
continue;
|
||||
}
|
||||
|
||||
const content = await this.vault.read(file);
|
||||
const lines = content.split('\n');
|
||||
const occurrences: any[] = [];
|
||||
|
||||
// Search for unlinked mentions of the target basename
|
||||
for (let i = 0; i < lines.length; i++) {
|
||||
const line = lines[i];
|
||||
|
||||
// Use word boundary regex to find whole word matches
|
||||
const regex = new RegExp(`\\b${this.escapeRegex(targetBasename)}\\b`, 'gi');
|
||||
|
||||
if (regex.test(line)) {
|
||||
const snippet = includeSnippets ? this.extractSnippet(lines, i, 100) : '';
|
||||
occurrences.push({
|
||||
line: i + 1, // 1-indexed
|
||||
snippet
|
||||
});
|
||||
}
|
||||
}
|
||||
|
||||
if (occurrences.length > 0) {
|
||||
backlinks.push({
|
||||
sourcePath: file.path,
|
||||
type: 'unlinked',
|
||||
occurrences
|
||||
});
|
||||
}
|
||||
}
|
||||
}
|
||||
// Use LinkUtils to get backlinks
|
||||
const backlinks = await LinkUtils.getBacklinks(
|
||||
this.vault,
|
||||
this.metadata,
|
||||
normalizedPath,
|
||||
includeUnlinked
|
||||
);
|
||||
|
||||
const result: BacklinksResult = {
|
||||
path: normalizedPath,
|
||||
@@ -1150,27 +988,4 @@ export class VaultTools {
|
||||
};
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Extract a snippet of text around a specific line
|
||||
*/
|
||||
private extractSnippet(lines: string[], lineIndex: number, maxLength: number): string {
|
||||
const line = lines[lineIndex] || '';
|
||||
|
||||
// If line is short enough, return it as-is
|
||||
if (line.length <= maxLength) {
|
||||
return line;
|
||||
}
|
||||
|
||||
// Truncate and add ellipsis
|
||||
const half = Math.floor(maxLength / 2);
|
||||
return line.substring(0, half) + '...' + line.substring(line.length - half);
|
||||
}
|
||||
|
||||
/**
|
||||
* Escape special regex characters
|
||||
*/
|
||||
private escapeRegex(str: string): string {
|
||||
return str.replace(/[.*+?^${}()|[\]\\]/g, '\\$&');
|
||||
}
|
||||
}
|
||||
|
||||
Reference in New Issue
Block a user