Textley / app · textley.ai / Sources / Textley / TextleyMCPTools.swift
| 1 | import AppKit |
| 2 | import CryptoKit |
| 3 | import Foundation |
| 4 | import MCP |
| 5 | import TextleyCore |
| 6 | |
| 7 | enum MCPAccessError: LocalizedError { |
| 8 | case message(String) |
| 9 | var errorDescription: String? { |
| 10 | switch self { case .message(let message): return message } |
| 11 | } |
| 12 | } |
| 13 | |
| 14 | @MainActor |
| 15 | enum TextleyMCPTools { |
| 16 | private static let string: Value = ["type": "string"] |
| 17 | private static let boolean: Value = ["type": "boolean"] |
| 18 | private static let integer: Value = ["type": "integer", "minimum": 0] |
| 19 | private static let location = ["vault_id": string, "path": string] |
| 20 | private static let identity = ["tab_id": string] |
| 21 | private static let revision = ["expected_revision": string] |
| 22 | private static let page = ["offset": integer, "limit": integer] |
| 23 | private static let fields = ["text": string, "old_text": string, "new_text": string] |
| 24 | private static let search = [ |
| 25 | "query": string, "regex": boolean, "match_case": boolean, "whole_word": boolean, |
| 26 | "wrap": boolean, "backward": boolean |
| 27 | ] |
| 28 | |
| 29 | static let tools = [ |
| 30 | tool("list_vaults", "List folders opened in Textley. Use the returned IDs with vault tools."), |
| 31 | tool("list_files", "List text files, images, and nested directories in one vault.", ["vault_id": string], page, required: ["vault_id"]), |
| 32 | tool("search_files", "Find files by name or by literal text in one vault. Returns matching paths. Use read_file for content.", |
| 33 | ["vault_id": string, "query": string, "search_contents": boolean], page, required: ["vault_id", "query"]), |
| 34 | tool("list_tabs", "List open tabs across Textley windows and identify the active tab."), |
| 35 | tool("read_file", "Read a text page and its current revision from an open tab or a vault path. Use tab_id or vault_id and path.", |
| 36 | identity, location, page), |
| 37 | tool("open_file", "Open a text or image file from a vault in Textley.", location, required: ["vault_id", "path"], writes: true), |
| 38 | tool("new_document", "Open an untitled text document in Textley.", writes: true), |
| 39 | tool("select_tab", "Focus an open tab.", identity, required: ["tab_id"], writes: true), |
| 40 | tool("close_tab", "Close an open tab. Unsaved edits must be saved or reviewed in the app first.", identity, required: ["tab_id"], writes: true), |
| 41 | tool("move_tab_to_new_window", "Move a tab to a new native window.", identity, required: ["tab_id"], writes: true), |
| 42 | tool("set_markdown_preview", "Switch a Markdown tab between rendered preview and editable source.", identity, ["enabled": boolean], required: ["tab_id", "enabled"], writes: true), |
| 43 | tool("set_syntax", "Set a tab’s syntax override. Use Automatic, Plain Text, Swift, JavaScript, TypeScript, JSON, HTML, CSS or Markdown.", |
| 44 | identity, ["language": string], required: ["tab_id", "language"], writes: true), |
| 45 | tool("go_to_line", "Select and scroll to a 1-based line in an open text tab.", identity, ["line": integer], required: ["tab_id", "line"], writes: true), |
| 46 | tool("find_text", "Set the find options and jump to a match in an open tab.", identity, search, required: ["tab_id", "query"], writes: true), |
| 47 | tool("replace_matches", "Replace one or all matching strings in a tab. Requires a fresh revision. Save separately.", |
| 48 | identity, search, revision, ["replacement": string, "all": boolean], |
| 49 | required: ["tab_id", "query", "replacement", "expected_revision"], writes: true, destructive: true), |
| 50 | tool("edit_text", "Replace the entire tab with text, or replace one exact unique passage using old_text and new_text. Read first. Save separately.", |
| 51 | identity, revision, fields, required: ["tab_id", "expected_revision"], writes: true, destructive: true), |
| 52 | tool("clean_up_text", "Apply trim, uppercase, lowercase or sort to the selection or entire tab. Save separately.", |
| 53 | identity, revision, ["operation": string], required: ["tab_id", "expected_revision", "operation"], writes: true, destructive: true), |
| 54 | tool("undo_redo", "Undo or redo one edit in a tab. Requires its current revision.", |
| 55 | identity, revision, ["redo": boolean], required: ["tab_id", "expected_revision"], writes: true, destructive: true), |
| 56 | tool("set_file_format", "Change encoding or line endings in a tab. Use UTF-8, UTF-8 with BOM, UTF-16 LE or UTF-16 BE and LF or CRLF.", |
| 57 | identity, revision, ["encoding": string, "line_ending": string], required: ["tab_id", "expected_revision"], writes: true), |
| 58 | tool("save_file", "Save a named tab in place. For an untitled tab or a copy, choose an unused path inside an open vault.", |
| 59 | identity, revision, location, required: ["tab_id", "expected_revision"], writes: true, destructive: true), |
| 60 | tool("create_file", "Create a new UTF-8 text file in an open vault. The parent folder must exist.", |
| 61 | location, ["text": string], required: ["vault_id", "path", "text"], writes: true), |
| 62 | tool("create_folder", "Create an empty folder inside an open vault. The parent folder must exist.", |
| 63 | location, required: ["vault_id", "path"], writes: true), |
| 64 | tool("rename_file", "Rename or move a closed file inside the same vault. The destination must be unused. Read the current revision first.", |
| 65 | location, revision, ["new_path": string], required: ["vault_id", "path", "new_path", "expected_revision"], writes: true), |
| 66 | tool("trash_file", "Move a closed text file to macOS Trash. Call only when requested by the user. Requires its current revision.", |
| 67 | location, revision, required: ["vault_id", "path", "expected_revision"], writes: true, destructive: true), |
| 68 | tool("get_editor_settings", "Read the font size, wrap and line-number settings."), |
| 69 | tool("set_editor_settings", "Update the font size, soft wrap, or line-number settings.", |
| 70 | ["font_size": integer, "wrap": boolean, "line_numbers": boolean], writes: true), |
| 71 | tool("set_sidebar", "Show or hide the sidebar in the active Textley window.", ["visible": boolean], required: ["visible"], writes: true) |
| 72 | ] |
| 73 | |
| 74 | private static func tool(_ name: String, _ description: String, _ parts: [String: Value]..., |
| 75 | required: [String] = [], writes: Bool = false, destructive: Bool = false) -> Tool { |
| 76 | let properties = parts.reduce(into: [String: Value]()) { result, next in |
| 77 | result.merge(next, uniquingKeysWith: { _, value in value }) |
| 78 | } |
| 79 | let title = name.split(separator: "_").map { $0 == "markdown" ? "Markdown" : $0.capitalized }.joined(separator: " ") |
| 80 | return Tool(name: name, description: description, inputSchema: [ |
| 81 | "type": "object", "properties": .object(properties), "required": .array(required.map(Value.string)), |
| 82 | "additionalProperties": false |
| 83 | ], annotations: .init(title: title, readOnlyHint: !writes, destructiveHint: destructive, |
| 84 | idempotentHint: !writes, openWorldHint: false)) |
| 85 | } |
| 86 | |
| 87 | static func call(_ params: CallTool.Parameters, store: TextleyApplication, allowsWriting: Bool, |
| 88 | authorization: @escaping @MainActor () -> Bool) async throws -> CallTool.Result { |
| 89 | guard let definition = tools.first(where: { $0.name == params.name }) else { throw error("Unknown Textley tool.") } |
| 90 | let values = Arguments(params.arguments ?? [:]) |
| 91 | let schema = definition.inputSchema.objectValue ?? [:] |
| 92 | let allowed = Set(schema["properties"]?.objectValue?.keys.map { $0 } ?? []) |
| 93 | let required = schema["required"]?.arrayValue?.compactMap(\.stringValue) ?? [] |
| 94 | guard Set(values.raw.keys).isSubset(of: allowed), required.allSatisfy({ values.raw[$0] != nil }) else { |
| 95 | throw error("Missing required or unexpected tool argument.") |
| 96 | } |
| 97 | if definition.annotations.readOnlyHint == false { |
| 98 | guard allowsWriting, authorization() else { |
| 99 | throw error("MCP is read only. Enable Read & write in Textley Settings → Integrations → MCP to allow changes.") |
| 100 | } |
| 101 | } |
| 102 | switch params.name { |
| 103 | case "list_vaults": |
| 104 | return try result(["vaults": store.mcpVaults.map { vault in |
| 105 | ["id": vaultID(vault.url), "name": vault.url.lastPathComponent, "available": vault.isAvailable] as [String: Any] |
| 106 | }]) |
| 107 | case "list_files", "search_files": |
| 108 | return try await findFiles(values, store: store, searching: params.name == "search_files") |
| 109 | case "list_tabs": |
| 110 | return try result(["tabs": store.mcpTabs.map { controller, document in |
| 111 | var info = metadata(document) |
| 112 | info["active"] = store.activeWindow === controller && controller.documents.active === document |
| 113 | return info |
| 114 | }]) |
| 115 | case "read_file": |
| 116 | return try read(values, store: store) |
| 117 | case "open_file": |
| 118 | let url = try urlFor(values, store: store) |
| 119 | return try result(metadata(store.openFileForMCP(url))) |
| 120 | case "new_document": |
| 121 | return try result(metadata(store.makeNewTab())) |
| 122 | case "get_editor_settings": |
| 123 | return try result(settings(store)) |
| 124 | case "set_editor_settings": |
| 125 | var preferences = store.preferences.editor |
| 126 | if let font = try values.optionalInt("font_size", range: 9...32) { preferences.fontSize = Double(font) } |
| 127 | if let wrap = try values.optionalBool("wrap") { preferences.wrap = wrap } |
| 128 | if let numbers = try values.optionalBool("line_numbers") { preferences.lineNumbers = numbers } |
| 129 | store.preferences.editor = try preferences.validated() |
| 130 | return try result(settings(store)) |
| 131 | case "set_sidebar": |
| 132 | guard let window = store.activeWindow else { throw error("Open a Textley window first.") } |
| 133 | window.documents.showsSidebar = try values.bool("visible") |
| 134 | return try result(["visible": window.documents.showsSidebar]) |
| 135 | case "create_file", "create_folder", "rename_file", "trash_file": |
| 136 | return try await manageFile(params.name, values, store: store, authorization: authorization) |
| 137 | default: |
| 138 | return try controlTab(params.name, values, store: store) |
| 139 | } |
| 140 | } |
| 141 | |
| 142 | private static func controlTab(_ name: String, _ args: Arguments, store: TextleyApplication) throws -> CallTool.Result { |
| 143 | let (controller, document) = try tab(args, store: store) |
| 144 | switch name { |
| 145 | case "select_tab": |
| 146 | controller.showWindow(nil) |
| 147 | controller.window?.makeKeyAndOrderFront(nil) |
| 148 | controller.select(document) |
| 149 | return try result(metadata(document)) |
| 150 | case "close_tab": |
| 151 | guard !document.isDirty else { throw error("The tab has unsaved edits. Save it or review it in Textley before closing.") } |
| 152 | controller.closeTab(document) |
| 153 | return try result(["closed": document.id.uuidString]) |
| 154 | case "move_tab_to_new_window": |
| 155 | controller.moveToNewWindow(document) |
| 156 | return try result(metadata(document)) |
| 157 | default: break |
| 158 | } |
| 159 | guard !document.isImage else { throw error("This tab is a read-only image.") } |
| 160 | if args.raw["expected_revision"] != nil { try checkRevision(args, actual: revisionOf(document)) } |
| 161 | switch name { |
| 162 | case "set_markdown_preview": |
| 163 | guard document.language == .markdown else { throw error("Choose Markdown syntax before opening a Markdown preview.") } |
| 164 | document.showsPreview = try args.bool("enabled") |
| 165 | case "set_syntax": |
| 166 | let language = try args.text("language", max: 40) |
| 167 | if language == "Automatic" { document.languageOverride = nil } |
| 168 | else if let syntax = SyntaxLanguage(rawValue: language) { document.languageOverride = syntax } |
| 169 | else { throw error("Unknown syntax. Use a language listed by set_syntax.") } |
| 170 | case "go_to_line": |
| 171 | let number = try args.int("line", default: 1, range: 1...Int.max) |
| 172 | guard document.goToLine(number) else { throw error("That line isn’t in this document.") } |
| 173 | case "find_text", "replace_matches": |
| 174 | var query = SearchQuery() |
| 175 | query.pattern = try args.text("query", max: 4000, allowEmpty: false) |
| 176 | query.isRegex = try args.bool("regex", default: false) |
| 177 | query.matchCase = try args.bool("match_case", default: false) |
| 178 | query.wholeWord = try args.bool("whole_word", default: false) |
| 179 | query.wraps = try args.bool("wrap", default: true) |
| 180 | _ = try query.expression() |
| 181 | document.search = query |
| 182 | if name == "find_text" { |
| 183 | document.openFind() |
| 184 | document.findNext(backward: try args.bool("backward", default: false)) |
| 185 | } else { |
| 186 | document.replacement = try args.text("replacement", max: 400_000) |
| 187 | if try args.bool("all", default: false) { document.replaceAll() } else { document.replaceOne() } |
| 188 | } |
| 189 | case "edit_text": |
| 190 | try applyEdit(args, to: document) |
| 191 | case "clean_up_text": |
| 192 | let requested = try args.text("operation", max: 15) |
| 193 | let operations: [String: Cleanup] = ["trim": .trim, "uppercase": .uppercase, "lowercase": .lowercase, "sort": .sort] |
| 194 | guard let operation = operations[requested] else { throw error("Use trim, uppercase, lowercase or sort.") } |
| 195 | document.apply(operation) |
| 196 | case "undo_redo": |
| 197 | if try args.bool("redo", default: false) { |
| 198 | if document.history.canRedo { document.history.redo() } |
| 199 | } else if document.history.canUndo { document.history.undo() } |
| 200 | case "set_file_format": |
| 201 | var format = document.format |
| 202 | if args.raw["encoding"] != nil { |
| 203 | guard let encoding = TextEncoding(rawValue: try args.text("encoding", max: 25)) else { throw error("Unsupported encoding.") } |
| 204 | format.encoding = encoding |
| 205 | } |
| 206 | if args.raw["line_ending"] != nil { |
| 207 | guard let ending = LineEnding(rawValue: try args.text("line_ending", max: 6)) else { throw error("Use LF or CRLF.") } |
| 208 | format.lineEnding = ending |
| 209 | } |
| 210 | document.changeFormat(format) |
| 211 | case "save_file": |
| 212 | let hasPath = args.raw["path"] != nil || args.raw["vault_id"] != nil |
| 213 | if hasPath { |
| 214 | let url = try urlFor(args, store: store, allowNew: true) |
| 215 | guard store.owner(of: url) == nil else { throw TextFileError.openDestination } |
| 216 | try document.save(to: url, copy: document.url != nil, exclusive: true) |
| 217 | store.noteRecent(url) |
| 218 | } else if let url = document.url { |
| 219 | try document.save(to: url) |
| 220 | store.noteRecent(url) |
| 221 | } else { |
| 222 | throw error("Choose an unused vault path for the untitled tab.") |
| 223 | } |
| 224 | controller.syncWindow() |
| 225 | default: throw error("Unknown Textley tool.") |
| 226 | } |
| 227 | var info = metadata(document) |
| 228 | info["revision"] = try revisionOf(document) |
| 229 | info["selection_utf16"] = [document.editor.selectedRange().location, document.editor.selectedRange().length] |
| 230 | if name == "find_text" || name == "replace_matches" { info["find_status"] = document.findMessage } |
| 231 | return try result(info) |
| 232 | } |
| 233 | |
| 234 | private static func applyEdit(_ args: Arguments, to document: EditorDocument) throws { |
| 235 | let current = document.text |
| 236 | if args.raw["text"] != nil { |
| 237 | guard args.raw["old_text"] == nil, args.raw["new_text"] == nil else { |
| 238 | throw error("Supply text or a single exact passage, not both.") |
| 239 | } |
| 240 | document.applyExternalEdit(range: NSRange(location: 0, length: current.utf16.count), |
| 241 | replacement: try args.text("text", max: 400_000)) |
| 242 | return |
| 243 | } |
| 244 | let old = try args.text("old_text", max: 400_000, allowEmpty: false) |
| 245 | let new = try args.text("new_text", max: 400_000) |
| 246 | let source = current as NSString |
| 247 | let range = source.range(of: old, options: .literal) |
| 248 | guard range.location != NSNotFound else { throw error("The exact passage was not found.") } |
| 249 | let afterStart = range.location + 1 |
| 250 | guard source.range(of: old, options: .literal, range: NSRange(location: afterStart, length: source.length - afterStart)).location == NSNotFound else { |
| 251 | throw error("The passage occurs more than once. Include more surrounding text.") |
| 252 | } |
| 253 | document.applyExternalEdit(range: range, replacement: new) |
| 254 | } |
| 255 | |
| 256 | private static func read(_ args: Arguments, store: TextleyApplication) throws -> CallTool.Result { |
| 257 | let document: EditorDocument? |
| 258 | let url: URL? |
| 259 | if args.raw["tab_id"] != nil { |
| 260 | guard args.raw["vault_id"] == nil, args.raw["path"] == nil else { throw error("Supply a tab ID or a vault path.") } |
| 261 | document = try tab(args, store: store).1 |
| 262 | url = document?.url |
| 263 | } else { |
| 264 | url = try urlFor(args, store: store) |
| 265 | document = url.flatMap { store.owner(of: $0)?.1 } |
| 266 | } |
| 267 | if let url, FolderEntry.isImage(url) { |
| 268 | let data = try TextFileAccess.read(url) |
| 269 | return try result(["kind": "image", "name": url.lastPathComponent, "bytes": data.count, "revision": digest(data)]) |
| 270 | } |
| 271 | let text: String |
| 272 | let format: TextFileFormat |
| 273 | let revision: String |
| 274 | if let document { |
| 275 | text = document.text |
| 276 | format = document.format |
| 277 | revision = try revisionOf(document) |
| 278 | } else if let url { |
| 279 | let data = try TextFileAccess.read(url) |
| 280 | let decoded = try TextFileFormat.decode(data) |
| 281 | text = decoded.text |
| 282 | format = decoded.format |
| 283 | revision = digest(data) |
| 284 | } else { throw error("Choose a file or an open tab.") } |
| 285 | |
| 286 | let offset = try args.int("offset", default: 0, range: 0...Int.max) |
| 287 | let limit = try args.int("limit", default: 12_000, range: 1...20_000) |
| 288 | let start = text.index(text.startIndex, offsetBy: offset, limitedBy: text.endIndex) ?? text.endIndex |
| 289 | let end = text.index(start, offsetBy: limit, limitedBy: text.endIndex) ?? text.endIndex |
| 290 | var info = document.map(metadata) ?? ["name": url?.lastPathComponent ?? "Untitled"] |
| 291 | info["kind"] = "text" |
| 292 | info["text"] = String(text[start..<end]) |
| 293 | info["revision"] = revision |
| 294 | info["encoding"] = format.encoding.rawValue |
| 295 | info["line_ending"] = format.lineEnding.rawValue |
| 296 | info["next_offset"] = end == text.endIndex ? NSNull() : offset + limit as Any |
| 297 | return try result(info) |
| 298 | } |
| 299 | |
| 300 | private static func findFiles(_ args: Arguments, store: TextleyApplication, searching: Bool) async throws -> CallTool.Result { |
| 301 | let vault = try resolveVault(args, store: store) |
| 302 | let root = vault.url |
| 303 | let query = searching ? try args.text("query", max: 500, allowEmpty: false) : nil |
| 304 | let searchContents = try args.bool("search_contents", default: false) |
| 305 | let offset = try args.int("offset", default: 0, range: 0...Int.max) |
| 306 | let limit = try args.int("limit", default: 50, range: 1...100) |
| 307 | let matches = await Task.detached(priority: .utility) { |
| 308 | var found: [(path: String, kind: String)] = [] |
| 309 | var inspected = 0 |
| 310 | func scan(_ entries: [FolderEntry], prefix: String = "") { |
| 311 | for entry in entries { |
| 312 | let path = prefix + entry.name |
| 313 | let kind = entry.isFolder ? "folder" : (entry.isImage ? "image" : "text") |
| 314 | var includes = query.map { path.localizedCaseInsensitiveContains($0) } ?? true |
| 315 | if !includes, let query, searchContents, kind == "text", inspected < 500, |
| 316 | let bytes = entry.size, bytes <= 1_000_000 { |
| 317 | inspected += 1 |
| 318 | if let url = try? VaultPath.resolve(path, in: root), |
| 319 | let data = try? TextFileAccess.read(url), let decoded = try? TextFileFormat.decode(data) { |
| 320 | includes = decoded.text.localizedCaseInsensitiveContains(query) |
| 321 | } |
| 322 | } |
| 323 | if includes { found.append((path, kind)) } |
| 324 | if let children = entry.children { scan(children, prefix: path + "/") } |
| 325 | } |
| 326 | } |
| 327 | scan(FolderEntry.list(root)) |
| 328 | return (found, inspected) |
| 329 | }.value |
| 330 | guard store.mcpVaults.contains(where: { $0.url == root }) else { throw error("This vault was closed.") } |
| 331 | let remaining = matches.0.dropFirst(min(offset, matches.0.count)) |
| 332 | let rows = remaining.prefix(limit).map { ["path": $0.path, "kind": $0.kind] } |
| 333 | return try result(["entries": rows, "next_offset": remaining.count > limit ? offset + limit as Any : NSNull(), |
| 334 | "content_files_examined": matches.1]) |
| 335 | } |
| 336 | |
| 337 | private static func manageFile(_ name: String, _ args: Arguments, store: TextleyApplication, |
| 338 | authorization: @escaping @MainActor () -> Bool) async throws -> CallTool.Result { |
| 339 | let creating = name == "create_file" || name == "create_folder" |
| 340 | let url = try urlFor(args, store: store, allowNew: creating) |
| 341 | if creating { |
| 342 | if name == "create_folder" { |
| 343 | try FileManager.default.createDirectory(at: url, withIntermediateDirectories: false) |
| 344 | return try result(["created": true]) |
| 345 | } |
| 346 | guard !FolderEntry.isImage(url) else { throw error("create_file writes plain text. Choose a text filename.") } |
| 347 | let bytes = try TextFileFormat().encode(args.text("text", max: 400_000)) |
| 348 | try TextFileAccess.write(bytes, to: url, exclusive: true) |
| 349 | return try result(["created": true, "revision": digest(bytes)]) |
| 350 | } |
| 351 | |
| 352 | guard store.owner(of: url) == nil else { throw error("Close the file in Textley before renaming or trashing it.") } |
| 353 | let data = try TextFileAccess.read(url) |
| 354 | try checkRevision(args, actual: digest(data)) |
| 355 | if name == "rename_file" { |
| 356 | let vault = try resolveVault(args, store: store) |
| 357 | let newPath = try args.text("new_path", max: 4000, allowEmpty: false) |
| 358 | let destination = try VaultPath.resolve(newPath, in: vault.url, allowNew: true) |
| 359 | try FileManager.default.moveItem(at: url, to: destination) |
| 360 | return try result(["path": newPath, "revision": digest(data)]) |
| 361 | } |
| 362 | _ = try TextFileFormat.decode(data) |
| 363 | guard authorization() else { throw error("MCP write access was revoked.") } |
| 364 | var resultingURL: NSURL? |
| 365 | try FileManager.default.trashItem(at: url, resultingItemURL: &resultingURL) |
| 366 | return try result(["trashed": true]) |
| 367 | } |
| 368 | |
| 369 | private static func settings(_ store: TextleyApplication) -> [String: Any] { |
| 370 | let editor = store.preferences.editor |
| 371 | return ["font_size": editor.fontSize, "wrap": editor.wrap, "line_numbers": editor.lineNumbers] |
| 372 | } |
| 373 | |
| 374 | private static func metadata(_ document: EditorDocument) -> [String: Any] { |
| 375 | ["tab_id": document.id.uuidString, "name": document.title, |
| 376 | "kind": document.isImage ? "image" : "text", "dirty": document.isDirty, |
| 377 | "syntax": document.language.rawValue, "markdown_preview": document.isShowingMarkdownPreview, |
| 378 | "location": document.caret, "saved": document.url != nil] |
| 379 | } |
| 380 | |
| 381 | private static func tab(_ args: Arguments, store: TextleyApplication) throws -> (EditorWindow, EditorDocument) { |
| 382 | guard let id = UUID(uuidString: try args.text("tab_id", max: 50)), |
| 383 | let found = store.mcpTabs.first(where: { $0.1.id == id }) else { throw error("This tab is no longer open.") } |
| 384 | return found |
| 385 | } |
| 386 | |
| 387 | private static func resolveVault(_ args: Arguments, store: TextleyApplication) throws -> FolderVault { |
| 388 | let id = try args.text("vault_id", max: 64) |
| 389 | guard let vault = store.mcpVaults.first(where: { vaultID($0.url) == id }), vault.isAvailable else { |
| 390 | throw error("Open the folder in Textley before accessing it.") |
| 391 | } |
| 392 | return vault |
| 393 | } |
| 394 | |
| 395 | private static func urlFor(_ args: Arguments, store: TextleyApplication, allowNew: Bool = false) throws -> URL { |
| 396 | try VaultPath.resolve(args.text("path", max: 4000, allowEmpty: false), |
| 397 | in: resolveVault(args, store: store).url, allowNew: allowNew) |
| 398 | } |
| 399 | |
| 400 | private static func vaultID(_ url: URL) -> String { digest(Data(url.path.utf8)) } |
| 401 | private static func revisionOf(_ document: EditorDocument) throws -> String { digest(try document.format.encode(document.text)) } |
| 402 | private static func digest(_ bytes: Data) -> String { SHA256.hash(data: bytes).map { String(format: "%02x", $0) }.joined() } |
| 403 | |
| 404 | private static func checkRevision(_ args: Arguments, actual: String) throws { |
| 405 | guard try args.text("expected_revision", max: 64) == actual else { |
| 406 | throw error("The revision is stale. Read the current file and review the differences before retrying.") |
| 407 | } |
| 408 | } |
| 409 | |
| 410 | private static func result(_ values: [String: Any]) throws -> CallTool.Result { |
| 411 | let data = try JSONSerialization.data(withJSONObject: values, options: [.sortedKeys]) |
| 412 | return .init(content: [.text(text: String(decoding: data, as: UTF8.self), annotations: nil, _meta: nil)], isError: false) |
| 413 | } |
| 414 | |
| 415 | private nonisolated static func error(_ text: String) -> MCPAccessError { .message(text) } |
| 416 | |
| 417 | private struct Arguments { |
| 418 | let raw: [String: Value] |
| 419 | init(_ raw: [String: Value]) { self.raw = raw } |
| 420 | |
| 421 | func text(_ key: String, max: Int, allowEmpty: Bool = true) throws -> String { |
| 422 | guard let value = raw[key]?.stringValue, value.utf8.count <= max, allowEmpty || !value.isEmpty else { |
| 423 | throw error("Invalid " + key + ".") |
| 424 | } |
| 425 | return value |
| 426 | } |
| 427 | |
| 428 | func optionalInt(_ key: String, range: ClosedRange<Int>) throws -> Int? { |
| 429 | guard let value = raw[key] else { return nil } |
| 430 | guard let number = value.intValue, range.contains(number) else { throw error("Invalid " + key + ".") } |
| 431 | return number |
| 432 | } |
| 433 | |
| 434 | func int(_ key: String, default fallback: Int, range: ClosedRange<Int>) throws -> Int { |
| 435 | try optionalInt(key, range: range) ?? fallback |
| 436 | } |
| 437 | |
| 438 | func optionalBool(_ key: String) throws -> Bool? { |
| 439 | guard let value = raw[key] else { return nil } |
| 440 | guard let flag = value.boolValue else { throw error("Invalid " + key + ".") } |
| 441 | return flag |
| 442 | } |
| 443 | |
| 444 | func bool(_ key: String, default fallback: Bool? = nil) throws -> Bool { |
| 445 | guard let flag = try optionalBool(key) ?? fallback else { throw error("Missing " + key + ".") } |
| 446 | return flag |
| 447 | } |
| 448 | } |
| 449 | } |
| 450 | |
| 451 | enum VaultPath { |
| 452 | static func resolve(_ relative: String, in root: URL, allowNew: Bool = false) throws -> URL { |
| 453 | let components = relative.split(separator: "/", omittingEmptySubsequences: false) |
| 454 | guard !components.isEmpty, !relative.contains("\\"), !relative.utf8.contains(0), |
| 455 | components.allSatisfy({ !$0.isEmpty && !$0.hasPrefix(".") }) else { |
| 456 | throw MCPAccessError.message("Use a visible path relative to an open Textley folder.") |
| 457 | } |
| 458 | guard root.resolvingSymlinksInPath().path == root.path else { |
| 459 | throw MCPAccessError.message("The vault location changed. Reopen it in Textley.") |
| 460 | } |
| 461 | var url = root |
| 462 | for (index, part) in components.enumerated() { |
| 463 | let final = index == components.count - 1 |
| 464 | url.appendPathComponent(String(part)) |
| 465 | let metadata = try? url.resourceValues(forKeys: [.isSymbolicLinkKey, .isDirectoryKey, .isPackageKey, .isRegularFileKey]) |
| 466 | if metadata?.isSymbolicLink == true || metadata?.isPackage == true { |
| 467 | throw MCPAccessError.message("Textley MCP does not follow symlinks or enter app packages.") |
| 468 | } |
| 469 | if final, allowNew { |
| 470 | guard metadata == nil, !FileManager.default.fileExists(atPath: url.path) else { |
| 471 | throw MCPAccessError.message("That path already exists. Choose an unused filename.") |
| 472 | } |
| 473 | } else if final { |
| 474 | guard metadata?.isRegularFile == true else { throw MCPAccessError.message("This path is not a regular file.") } |
| 475 | } else { |
| 476 | guard metadata?.isDirectory == true else { throw MCPAccessError.message("The parent folder does not exist.") } |
| 477 | } |
| 478 | } |
| 479 | return url |
| 480 | } |
| 481 | } |