omnifocus_mcp 1.0.2 → 1.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (41) hide show
  1. checksums.yaml +4 -4
  2. data/CHANGELOG.md +9 -0
  3. data/README.md +16 -3
  4. data/docs/superpowers/plans/2026-11-17-server-gap-fixes.md +192 -0
  5. data/lib/omnifocus_mcp/infrastructure/apple_script.rb +83 -19
  6. data/lib/omnifocus_mcp/infrastructure/script_runner.rb +5 -4
  7. data/lib/omnifocus_mcp/json_rpc_compat.rb +1 -2
  8. data/lib/omnifocus_mcp/logger.rb +1 -0
  9. data/lib/omnifocus_mcp/resources/base.rb +2 -37
  10. data/lib/omnifocus_mcp/resources/stats_resource.rb +1 -1
  11. data/lib/omnifocus_mcp/tools/database_stats.rb +3 -3
  12. data/lib/omnifocus_mcp/tools/definitions/add_omni_focus_task_tool.rb +5 -1
  13. data/lib/omnifocus_mcp/tools/definitions/add_project_tool.rb +4 -1
  14. data/lib/omnifocus_mcp/tools/definitions/batch_add_items_tool.rb +5 -3
  15. data/lib/omnifocus_mcp/tools/definitions/date_formatter.rb +6 -3
  16. data/lib/omnifocus_mcp/tools/definitions/edit_item_tool.rb +25 -6
  17. data/lib/omnifocus_mcp/tools/definitions/key_normalizer.rb +21 -1
  18. data/lib/omnifocus_mcp/tools/definitions/query_omnifocus_tool.rb +1 -2
  19. data/lib/omnifocus_mcp/tools/generators/add_omni_focus_task.rb +8 -13
  20. data/lib/omnifocus_mcp/tools/generators/add_project.rb +4 -6
  21. data/lib/omnifocus_mcp/tools/generators/database_stats.rb +1 -2
  22. data/lib/omnifocus_mcp/tools/generators/edit_item.rb +38 -53
  23. data/lib/omnifocus_mcp/tools/generators/note_edit.rb +108 -0
  24. data/lib/omnifocus_mcp/tools/generators/query_omnifocus.rb +11 -7
  25. data/lib/omnifocus_mcp/tools/generators/remove_item.rb +1 -1
  26. data/lib/omnifocus_mcp/tools/messages/add_omni_focus_task.rb +5 -3
  27. data/lib/omnifocus_mcp/tools/operations/add_omni_focus_task.rb +5 -3
  28. data/lib/omnifocus_mcp/tools/operations/add_project.rb +3 -3
  29. data/lib/omnifocus_mcp/tools/operations/batch_add_items/bulk_executor.rb +1 -1
  30. data/lib/omnifocus_mcp/tools/operations/batch_add_items.rb +4 -2
  31. data/lib/omnifocus_mcp/tools/operations/database_stats.rb +3 -3
  32. data/lib/omnifocus_mcp/tools/operations/edit_item.rb +3 -3
  33. data/lib/omnifocus_mcp/tools/operations/list_perspectives.rb +1 -1
  34. data/lib/omnifocus_mcp/tools/operations/remove_item.rb +3 -3
  35. data/lib/omnifocus_mcp/tools/params/mcp_boundary.rb +4 -2
  36. data/lib/omnifocus_mcp/tools/params.rb +2 -2
  37. data/lib/omnifocus_mcp/tools/presenters/query_results.rb +12 -8
  38. data/lib/omnifocus_mcp/utils/blank.rb +4 -0
  39. data/lib/omnifocus_mcp/utils/date_filter.rb +1 -2
  40. data/lib/omnifocus_mcp/version.rb +1 -1
  41. metadata +4 -2
@@ -17,7 +17,7 @@ module OmnifocusMcp
17
17
  tool_name "edit_item"
18
18
  description "Edit a task or project in OmniFocus"
19
19
 
20
- # rubocop:disable Metrics/BlockLength
20
+ # rubocop:disable-next Metrics/BlockLength
21
21
  arguments do
22
22
  optional(:id).filled(:string).description("The ID of the task or project to edit")
23
23
  optional(:name).filled(:string)
@@ -26,7 +26,18 @@ module OmnifocusMcp
26
26
  .description("Type of item to edit ('task' or 'project')")
27
27
 
28
28
  optional(:newName).filled(:string).description("New name for the item")
29
- optional(:newNote).filled(:string).description("New note for the item")
29
+ optional(:newNote).filled(:string).description("New note for the item (replaces the whole note)")
30
+ optional(:noteReplacements).array(:hash) do
31
+ required(:find).filled(:string)
32
+ required(:replace).value(:string)
33
+ end.description(
34
+ "Replace text inside the note: every occurrence of each 'find' becomes its 'replace' (case-sensitive). " \
35
+ "If any 'find' is not in the note, nothing on the item is changed. Applied after newNote. " \
36
+ "Links, attachments and styles elsewhere in the note are kept."
37
+ )
38
+ optional(:appendNote).filled(:string).description(
39
+ "Text to add to the end of the note, on a new line. Applied after noteReplacements."
40
+ )
30
41
  optional(:newDueDate).maybe(:string).description(
31
42
  "New due date in ISO format (YYYY-MM-DD or full ISO date); set to empty string to clear"
32
43
  )
@@ -45,9 +56,18 @@ module OmnifocusMcp
45
56
  "repeating tasks \u2014 it completes the current occurrence to trigger the next repeat, then " \
46
57
  "drops the completed instance."
47
58
  )
48
- optional(:addTags).array(:string).description("Tags to add to the task")
49
- optional(:removeTags).array(:string).description("Tags to remove from the task")
50
- optional(:replaceTags).array(:string).description("Tags to replace all existing tags with")
59
+ optional(:addTags).array(:string).description(
60
+ "Tags to add to the task. " \
61
+ "Use 'Parent/Child' for a nested tag, e.g. 'Work/Mac'; missing tags are created at that path"
62
+ )
63
+ optional(:removeTags).array(:string).description(
64
+ "Tags to remove from the task. " \
65
+ "Use 'Parent/Child' for a nested tag, e.g. 'Work/Mac'; missing tags are ignored"
66
+ )
67
+ optional(:replaceTags).array(:string).description(
68
+ "Tags to replace all existing tags with. " \
69
+ "Use 'Parent/Child' for a nested tag, e.g. 'Work/Mac'; missing tags are created at that path"
70
+ )
51
71
  optional(:newProjectName).maybe(:string).description(
52
72
  "Move this task to a different project by name or folder path (e.g. 'My Project' or " \
53
73
  "'Work/My Project' to disambiguate). Pass an empty string or 'inbox' to move the task to " \
@@ -59,7 +79,6 @@ module OmnifocusMcp
59
79
  optional(:newProjectStatus).filled(included_in?: %w[active completed dropped onHold])
60
80
  .description("New status for projects")
61
81
  end
62
- # rubocop:enable Metrics/BlockLength
63
82
 
64
83
  extend OperationFactory
65
84
 
@@ -18,11 +18,31 @@ module OmnifocusMcp
18
18
  end
19
19
  end
20
20
 
21
+ def camel_keys(obj)
22
+ case obj
23
+ when Hash
24
+ obj.each_with_object({}) do |(k, v), out|
25
+ out[camel_case_key(k)] = camel_keys(v)
26
+ end
27
+ when Array
28
+ obj.map { |item| camel_keys(item) }
29
+ else
30
+ obj
31
+ end
32
+ end
33
+
21
34
  def snake_case_key(key)
22
- return key unless key.is_a?(Symbol) || key.is_a?(String)
35
+ return key unless key in Symbol | String
23
36
 
24
37
  key.to_s.gsub(/([a-z\d])([A-Z])/, '\1_\2').downcase.to_sym
25
38
  end
39
+
40
+ def camel_case_key(key)
41
+ return key unless key in Symbol | String
42
+
43
+ parts = key.to_s.split("_")
44
+ ([parts.first] + parts.drop(1).map(&:capitalize)).join
45
+ end
26
46
  end
27
47
  end
28
48
  end
@@ -22,7 +22,7 @@ module OmnifocusMcp
22
22
 
23
23
  DATE_FILTER_FIELDS = %i[due_within deferred_until planned_within due_on defer_on planned_on].freeze
24
24
 
25
- # rubocop:disable Metrics/BlockLength
25
+ # rubocop:disable-next Metrics/BlockLength
26
26
  arguments do
27
27
  required(:entity).filled(included_in?: %w[tasks projects folders]).description(
28
28
  "Type of entity to query. Choose 'tasks' for individual tasks, 'projects' for projects, " \
@@ -146,7 +146,6 @@ module OmnifocusMcp
146
146
  .filled(:bool)
147
147
  .description("Return only count of matches, not full details. Efficient for statistics. Default: false")
148
148
  end
149
- # rubocop:enable Metrics/BlockLength
150
149
 
151
150
  extend OperationFactory
152
151
 
@@ -69,7 +69,7 @@ module OmnifocusMcp
69
69
  def applescript_run_failure(stderr:, status:)
70
70
  exit_code = status.respond_to?(:exitstatus) ? status.exitstatus : status
71
71
  message = "osascript failed (exit #{exit_code})"
72
- message += ": #{stderr.strip}" unless stderr.nil? || stderr.empty?
72
+ message += ": #{stderr.strip}" unless Utils::Blank.blank?(stderr)
73
73
  message
74
74
  end
75
75
 
@@ -78,7 +78,7 @@ module OmnifocusMcp
78
78
  def extract_fields(params)
79
79
  {
80
80
  name: Infrastructure::AppleScript.escape(params.name.to_s),
81
- note: Infrastructure::AppleScript.escape(params.note.to_s),
81
+ note: Infrastructure::AppleScript.multiline_string(params.note.to_s),
82
82
  project_name: Infrastructure::AppleScript.escape(params.project_name.to_s),
83
83
  parent_task_id: Infrastructure::AppleScript.escape(params.parent_task_id.to_s),
84
84
  parent_task_name: Infrastructure::AppleScript.escape(params.parent_task_name.to_s),
@@ -132,7 +132,7 @@ module OmnifocusMcp
132
132
  "-- Get the task ID",
133
133
  "set taskId to id of newTask as string",
134
134
  tag_assignments_block(fields[:tags]),
135
- finalize == :bulk ? bulk_record_result : success_return(fields[:name])
135
+ finalize == :bulk ? bulk_record_result : success_return
136
136
  ].compact.join("\n")
137
137
  end
138
138
 
@@ -173,10 +173,10 @@ module OmnifocusMcp
173
173
  APPLESCRIPT
174
174
  end
175
175
 
176
- def success_return(escaped_name)
176
+ def success_return
177
177
  payload = [
178
178
  %(\\"taskId\\":\\"" & taskId & "\\"),
179
- %(\\"name\\":\\"#{escaped_name}\\"),
179
+ %(\\"name\\":\\"" & my jsonEscape(name of newTask) & "\\"),
180
180
  %(\\"placement\\":\\"" & placement & "\\")
181
181
  ].join(",")
182
182
  %(return "{\\"success\\":true,#{payload}}")
@@ -215,7 +215,7 @@ module OmnifocusMcp
215
215
  APPLESCRIPT
216
216
  end
217
217
 
218
- # rubocop:disable Metrics/MethodLength
218
+ # rubocop:disable-next Metrics/MethodLength
219
219
  def parent_lookup_by_name(fields)
220
220
  <<~APPLESCRIPT.chomp
221
221
  if parentTask is missing value and "#{fields[:parent_task_name]}" is not "" then
@@ -244,7 +244,6 @@ module OmnifocusMcp
244
244
  end if
245
245
  APPLESCRIPT
246
246
  end
247
- # rubocop:enable Metrics/MethodLength
248
247
 
249
248
  # Pick the container: explicit parent, project root, or inbox.
250
249
  def task_creation(fields)
@@ -286,7 +285,7 @@ module OmnifocusMcp
286
285
  ["-- Set #{label} date", "set #{label} date of newTask to #{value}"]
287
286
  end
288
287
 
289
- # rubocop:disable Metrics/MethodLength
288
+ # rubocop:disable-next Metrics/MethodLength
290
289
  def placement_derivation(project_name)
291
290
  <<~APPLESCRIPT.chomp
292
291
  -- Derive placement from container; distinguish real parent vs project root task
@@ -323,16 +322,12 @@ module OmnifocusMcp
323
322
  end try
324
323
  APPLESCRIPT
325
324
  end
326
- # rubocop:enable Metrics/MethodLength
327
325
 
328
326
  def tag_assignments_block(tags)
329
327
  return nil if tags.empty?
330
328
 
331
329
  blocks = tags.map do |tag|
332
- Infrastructure::AppleScript.tag_assignment(
333
- item_var: "newTask",
334
- tag_name: Infrastructure::AppleScript.escape(tag.to_s)
335
- )
330
+ Infrastructure::AppleScript.tag_assignment(item_var: "newTask", tag_path: tag.to_s)
336
331
  end
337
332
 
338
333
  "\n-- Add tags if provided\n#{blocks.join("\n")}"
@@ -36,7 +36,7 @@ module OmnifocusMcp
36
36
  def extract_fields(params)
37
37
  {
38
38
  name: Infrastructure::AppleScript.escape(params.name.to_s),
39
- note: Infrastructure::AppleScript.escape(params.note.to_s),
39
+ note: Infrastructure::AppleScript.multiline_string(params.note.to_s),
40
40
  folder_name: params.folder_name.to_s,
41
41
  flagged: params.flagged == true,
42
42
  sequential: params.sequential == true,
@@ -76,7 +76,8 @@ module OmnifocusMcp
76
76
  "-- Get the project ID",
77
77
  "set projectId to id of newProject as string",
78
78
  tag_assignments_block(fields[:tags]),
79
- %(return "{\\"success\\":true,\\"projectId\\":\\"" & projectId & "\\",\\"name\\":\\"#{fields[:name]}\\"}")
79
+ %(return "{\\"success\\":true,\\"projectId\\":\\"" & projectId & ) +
80
+ %("\\",\\"name\\":\\"" & my jsonEscape(name of newProject) & "\\"}")
80
81
  ].compact.join("\n")
81
82
  end
82
83
 
@@ -125,10 +126,7 @@ module OmnifocusMcp
125
126
  return nil if tags.empty?
126
127
 
127
128
  blocks = tags.map do |tag|
128
- Infrastructure::AppleScript.tag_assignment(
129
- item_var: "newProject",
130
- tag_name: Infrastructure::AppleScript.escape(tag.to_s)
131
- )
129
+ Infrastructure::AppleScript.tag_assignment(item_var: "newProject", tag_path: tag.to_s)
132
130
  end
133
131
 
134
132
  "\n-- Add tags if provided\n#{blocks.join("\n")}"
@@ -63,7 +63,7 @@ module OmnifocusMcp
63
63
 
64
64
  def stats_script = STATS_SCRIPT
65
65
 
66
- # rubocop:disable Metrics/MethodLength
66
+ # rubocop:disable-next Metrics/MethodLength
67
67
  def changes_script(since_iso)
68
68
  escaped_since = Infrastructure::JsEmbed.double_quoted_string(since_iso)
69
69
 
@@ -139,7 +139,6 @@ module OmnifocusMcp
139
139
  })();
140
140
  JS
141
141
  end
142
- # rubocop:enable Metrics/MethodLength
143
142
  end
144
143
  end
145
144
  end
@@ -7,6 +7,7 @@ require_relative "../../utils/blank"
7
7
  require_relative "../../result"
8
8
  require_relative "../../infrastructure/script_runner"
9
9
  require_relative "../params"
10
+ require_relative "note_edit"
10
11
 
11
12
  module OmnifocusMcp
12
13
  module Tools
@@ -39,6 +40,7 @@ module OmnifocusMcp
39
40
  # Generate pure AppleScript for item editing. Dates are constructed
40
41
  # outside the `tell` block then referenced from within.
41
42
  class << self
43
+ # rubocop:disable-next Metrics/AbcSize
42
44
  def generate_apple_script(params)
43
45
  params = Params::McpBoundary.coerce(Params::EditItemParams, params)
44
46
  return missing_identifier_error if Utils::Blank.blank?(params.id, params.name)
@@ -65,7 +67,7 @@ module OmnifocusMcp
65
67
  def run_script(script)
66
68
  stdout, stderr, status = Infrastructure::ScriptRunner.execute_applescript(script)
67
69
 
68
- OmnifocusMcp.logger.warn("[edit_item] AppleScript stderr: #{stderr}") if stderr && !stderr.empty?
70
+ OmnifocusMcp.logger.warn("[edit_item] AppleScript stderr: #{stderr}") if Utils::Blank.present?(stderr)
69
71
  return OmnifocusMcp::Result.error(applescript_run_failure(stderr:, status:)) unless status.success?
70
72
 
71
73
  parse_result(stdout)
@@ -86,7 +88,7 @@ module OmnifocusMcp
86
88
  def applescript_run_failure(stderr:, status:)
87
89
  exit_code = status.respond_to?(:exitstatus) ? status.exitstatus : status
88
90
  message = "osascript failed (exit #{exit_code})"
89
- message += ": #{stderr.strip}" unless stderr.nil? || stderr.empty?
91
+ message += ": #{stderr.strip}" unless Utils::Blank.blank?(stderr)
90
92
  message
91
93
  end
92
94
 
@@ -137,16 +139,18 @@ module OmnifocusMcp
137
139
  "set itemId to id of foundItem as string",
138
140
  "set changedProperties to {}"
139
141
  ]
142
+ steps << NoteEdit.guard_step(params)
140
143
  steps.concat(property_update_steps(item_type, params, date_assignments).compact)
141
144
  steps << finalize_and_return
142
145
 
143
- steps.join("\n\n")
146
+ steps.compact.join("\n\n")
144
147
  end
145
148
 
146
149
  def property_update_steps(item_type, params, date_assignments)
147
150
  [
148
151
  update_string_property("name", params, :new_name),
149
- update_string_property("note", params, :new_note),
152
+ update_string_property("note", params, :new_note, escaper: :multiline_string),
153
+ NoteEdit.apply_step(params),
150
154
  update_date_step("due date", date_assignments["due date"]),
151
155
  update_date_step("defer date", date_assignments["defer date"]),
152
156
  update_date_step("planned date", date_assignments["planned date"]),
@@ -176,10 +180,10 @@ module OmnifocusMcp
176
180
  end
177
181
 
178
182
  # `set foo of foundItem to "escaped string"` + changedProperties bump.
179
- def update_string_property(label, params, key)
183
+ def update_string_property(label, params, key, escaper: :escape)
180
184
  return nil unless param_provided?(params, key)
181
185
 
182
- value = Infrastructure::AppleScript.escape(params.public_send(key).to_s)
186
+ value = Infrastructure::AppleScript.public_send(escaper, params.public_send(key).to_s)
183
187
  <<~APPLESCRIPT.chomp
184
188
  -- Update #{label}
185
189
  set #{label} of foundItem to "#{value}"
@@ -221,7 +225,7 @@ module OmnifocusMcp
221
225
  end repeat
222
226
 
223
227
  -- Return success with details
224
- return "{\\"success\\":true,\\"id\\":\\"" & itemId & "\\",\\"name\\":\\"" & itemName & "\\",\\"changedProperties\\":\\"" & changedPropsText & "\\"}"
228
+ return "{\\"success\\":true,\\"id\\":\\"" & itemId & "\\",\\"name\\":\\"" & my jsonEscape(itemName) & "\\",\\"changedProperties\\":\\"" & changedPropsText & "\\"}"
225
229
  APPLESCRIPT
226
230
  end
227
231
 
@@ -229,10 +233,14 @@ module OmnifocusMcp
229
233
  return nil unless param_provided?(params, :new_status)
230
234
 
231
235
  case params.new_status.to_s
232
- when "completed" then task_status_completed
233
- when "dropped" then task_status_dropped
234
- when "skipped" then task_status_skipped
235
- when "incomplete" then task_status_incomplete
236
+ when "completed"
237
+ task_status_completed
238
+ when "dropped"
239
+ task_status_dropped
240
+ when "skipped"
241
+ task_status_skipped
242
+ when "incomplete"
243
+ task_status_incomplete
236
244
  end
237
245
  end
238
246
 
@@ -298,73 +306,50 @@ module OmnifocusMcp
298
306
 
299
307
  def non_empty?(value) = value && !value.empty?
300
308
 
301
- # rubocop:disable Metrics/MethodLength
302
309
  def tag_replace_block(tags)
303
- tags_list = tags.map { |t| %("#{Infrastructure::AppleScript.escape(t.to_s)}") }.join(", ")
304
310
  <<~APPLESCRIPT.chomp
305
- -- Replace all tags
306
- set tagNames to {#{tags_list}}
311
+ -- Replace all tags: first clear the existing ones
307
312
  set existingTags to tags of foundItem
308
-
309
- -- First clear all existing tags
310
313
  repeat with existingTag in existingTags
311
314
  remove existingTag from tags of foundItem
312
315
  end repeat
313
316
 
314
- -- Then add new tags
315
- repeat with tagName in tagNames
316
- set tagObj to missing value
317
- try
318
- set tagObj to first flattened tag where name = (tagName as string)
319
- on error
320
- -- Tag doesn't exist, create it
321
- set tagObj to make new tag with properties {name:(tagName as string)}
322
- end try
323
- if tagObj is not missing value then
324
- add tagObj to tags of foundItem
325
- end if
326
- end repeat
317
+ #{add_tag_lines(tags)}
327
318
  set end of changedProperties to "tags (replaced)"
328
319
  APPLESCRIPT
329
320
  end
330
- # rubocop:enable Metrics/MethodLength
331
321
 
332
322
  def tag_add_block(tags)
333
- tags_list = tags.map { |t| %("#{Infrastructure::AppleScript.escape(t.to_s)}") }.join(", ")
334
323
  <<~APPLESCRIPT.chomp
335
324
  -- Add tags
336
- set tagNames to {#{tags_list}}
337
- repeat with tagName in tagNames
338
- set tagObj to missing value
339
- try
340
- set tagObj to first flattened tag where name = (tagName as string)
341
- on error
342
- -- Tag doesn't exist, create it
343
- set tagObj to make new tag with properties {name:(tagName as string)}
344
- end try
345
- if tagObj is not missing value then
346
- add tagObj to tags of foundItem
347
- end if
348
- end repeat
325
+ #{add_tag_lines(tags)}
349
326
  set end of changedProperties to "tags (added)"
350
327
  APPLESCRIPT
351
328
  end
352
329
 
353
330
  def tag_remove_block(tags)
354
- tags_list = tags.map { |t| %("#{Infrastructure::AppleScript.escape(t.to_s)}") }.join(", ")
355
- <<~APPLESCRIPT.chomp
356
- -- Remove tags
357
- set tagNames to {#{tags_list}}
358
- repeat with tagName in tagNames
331
+ removals = tags.map do |tag|
332
+ lookup = Infrastructure::AppleScript.tag_lookup(var: "theTag", tag_path: tag.to_s, create: false)
333
+ <<~APPLESCRIPT.chomp
359
334
  try
360
- set tagObj to first flattened tag where name = (tagName as string)
361
- remove tagObj from tags of foundItem
335
+ #{Infrastructure::AppleScript.indent(text: lookup, prefix: " ")}
336
+ if theTag is not missing value then remove theTag from tags of foundItem
362
337
  end try
363
- end repeat
338
+ APPLESCRIPT
339
+ end
340
+
341
+ <<~APPLESCRIPT.chomp
342
+ -- Remove tags
343
+ #{removals.join("\n")}
364
344
  set end of changedProperties to "tags (removed)"
365
345
  APPLESCRIPT
366
346
  end
367
347
 
348
+ def add_tag_lines(tags)
349
+ tags.map { |tag| Infrastructure::AppleScript.tag_assignment(item_var: "foundItem", tag_path: tag.to_s) }
350
+ .join("\n")
351
+ end
352
+
368
353
  def apply_new_project_name(params)
369
354
  return nil unless param_provided?(params, :new_project_name)
370
355
 
@@ -0,0 +1,108 @@
1
+ # frozen_string_literal: true
2
+
3
+ require "json"
4
+
5
+ require_relative "../../infrastructure/apple_script"
6
+
7
+ module OmnifocusMcp
8
+ module Tools
9
+ module Generators
10
+ # AppleScript steps for `edit_item`'s `noteReplacements` and `appendNote`.
11
+ #
12
+ # Both edit the note's rich text through Omni Automation (`noteText`),
13
+ # so links, attachments and styles outside the changed text survive.
14
+ # Setting `note of foundItem` from AppleScript would flatten the note.
15
+ module NoteEdit
16
+ # Called as (itemId, mode, startText, replacements, appendText).
17
+ # mode "check" returns "" or an error; mode "apply" edits the note.
18
+ # `startText` is the newNote value when one is set in the same call.
19
+ SCRIPT = <<~'JS'.lines.map(&:strip).join(" ")
20
+ ((id, mode, start, reps, append) => {
21
+ const project = Project.byIdentifier(id);
22
+ const item = Task.byIdentifier(id) || (project ? project.task : null);
23
+ if (!item) return "Item not found";
24
+ if (mode === "check") {
25
+ let s = start === null ? item.noteText.string : start;
26
+ for (const r of reps) {
27
+ if (!s.includes(r.find)) return "Note text not found: " + r.find;
28
+ s = s.split(r.find).join(r.replace);
29
+ }
30
+ return "";
31
+ }
32
+ const text = item.noteText;
33
+ const mark = "";
34
+ const swap = (from, to, times) => {
35
+ for (let i = 0; i < times; i++) {
36
+ const range = text.find(from, null, null);
37
+ if (!range) break;
38
+ text.replace(range, new Text(to, text.style));
39
+ }
40
+ };
41
+ for (const r of reps) {
42
+ const count = text.string.split(r.find).length - 1;
43
+ swap(r.find, mark, count);
44
+ swap(mark, r.replace, count);
45
+ }
46
+ if (append !== null) {
47
+ text.append(new Text((text.string.length > 0 ? "\n" : "") + append, text.style));
48
+ }
49
+ return "";
50
+ })
51
+ JS
52
+ private_constant :SCRIPT
53
+
54
+ class << self
55
+ # Fails the edit before anything changes when a `find` is missing.
56
+ def guard_step(params)
57
+ return nil if replacements(params).empty?
58
+
59
+ <<~APPLESCRIPT.chomp
60
+ -- Check every note replacement can apply before changing anything
61
+ #{evaluate("noteCheck", params, mode: "check")}
62
+ if noteCheck is not "" then
63
+ return "{\\"success\\":false,\\"error\\":\\"" & my jsonEscape(noteCheck) & "\\"}"
64
+ end if
65
+ APPLESCRIPT
66
+ end
67
+
68
+ # Applies replacements, then the append, after any newNote.
69
+ def apply_step(params)
70
+ changes = []
71
+ changes << "note (replaced text)" unless replacements(params).empty?
72
+ changes << "note (appended)" unless params.append_note.nil?
73
+ return nil if changes.empty?
74
+
75
+ labels = changes.map { |label| %(set end of changedProperties to "#{label}") }
76
+ <<~APPLESCRIPT.chomp
77
+ -- Edit the note's rich text in place
78
+ #{evaluate("noteEdit", params, mode: "apply")}
79
+ #{labels.join("\n")}
80
+ APPLESCRIPT
81
+ end
82
+
83
+ private
84
+
85
+ def replacements(params) = Array(params.note_replacements)
86
+
87
+ # `set <var> to evaluate javascript (...)`, with the item id spliced
88
+ # in from the AppleScript variable `itemId`.
89
+ def evaluate(var, params, mode:)
90
+ prefix = Infrastructure::AppleScript.escape(%[#{SCRIPT}(])
91
+ suffix = Infrastructure::AppleScript.escape(%[, #{js_args(params, mode).join(", ")})])
92
+ %(tell application "OmniFocus" to set #{var} to evaluate javascript ) +
93
+ %{("#{prefix}" & quote & itemId & quote & "#{suffix}")}
94
+ end
95
+
96
+ def js_args(params, mode)
97
+ pairs = replacements(params).map { |r| { find: normalize(r[:find]), replace: normalize(r[:replace]) } }
98
+ [
99
+ mode, normalize(params.new_note), pairs, normalize(params.append_note)
100
+ ].map { |arg| JSON.generate(arg) }
101
+ end
102
+
103
+ def normalize(value) = value&.to_s&.gsub(/\r\n?/, "\n")
104
+ end
105
+ end
106
+ end
107
+ end
108
+ end
@@ -59,6 +59,7 @@ module OmnifocusMcp
59
59
  # JSON.parse hands us String keys; pattern matching wants Symbols. A
60
60
  # non-Hash response (e.g. raw stdout from a parse failure) becomes
61
61
  # +nil+ here so the +in nil+ arm can surface it as an error.
62
+ # rubocop:disable-next Metrics/CyclomaticComplexity
62
63
  def classify_response(response:, summary:)
63
64
  shape = response.is_a?(Hash) ? response.transform_keys(&:to_sym) : nil
64
65
 
@@ -82,6 +83,7 @@ module OmnifocusMcp
82
83
  def build_match(items:, count:, summary:) = Match.new(items: summary ? nil : items, count: count)
83
84
 
84
85
  # Build the full JXA query script for the given params.
86
+ # rubocop:disable-next Metrics/AbcSize
85
87
  def generate_query_script(params)
86
88
  params = Params::McpBoundary.coerce(Params::QueryOmnifocusParams, params)
87
89
 
@@ -196,7 +198,7 @@ module OmnifocusMcp
196
198
  JS
197
199
  end
198
200
 
199
- # rubocop:disable Metrics/MethodLength
201
+ # rubocop:disable-next Metrics/MethodLength
200
202
  def apply_task_id_filters(filters:, conditions:)
201
203
  if filters[:project_id]
202
204
  safe_id = escape_jxa(filters[:project_id])
@@ -228,12 +230,9 @@ module OmnifocusMcp
228
230
  }
229
231
  JS
230
232
  end
231
- # rubocop:enable Metrics/MethodLength
232
233
 
233
234
  def apply_tag_status_filters(filters:, conditions:, entity:)
234
- if entity == "tasks" && filters[:tags] && !filters[:tags].empty?
235
- conditions << tag_filter_condition(filters[:tags])
236
- end
235
+ conditions << tag_filter_condition(filters[:tags]) if filtering_tasks_by_tags?(filters:, entity:)
237
236
 
238
237
  return unless filters[:status] && !filters[:status].empty?
239
238
 
@@ -246,6 +245,10 @@ module OmnifocusMcp
246
245
  conditions << "if (!(#{status_condition})) return false;"
247
246
  end
248
247
 
248
+ def filtering_tasks_by_tags?(filters:, entity:)
249
+ entity == "tasks" && filters[:tags] && !filters[:tags].empty?
250
+ end
251
+
249
252
  def tag_filter_condition(tags)
250
253
  tag_condition = tags.map do |tag|
251
254
  %(item.tags.some(t => t.name === "#{escape_jxa(tag)}"))
@@ -253,6 +256,7 @@ module OmnifocusMcp
253
256
  "if (!(#{tag_condition})) return false;"
254
257
  end
255
258
 
259
+ # rubocop:disable-next Metrics/AbcSize
256
260
  def apply_task_date_filters(filters:, conditions:)
257
261
  conditions << "if (item.flagged !== #{filters[:flagged]}) return false;" unless filters[:flagged].nil?
258
262
 
@@ -281,7 +285,7 @@ module OmnifocusMcp
281
285
 
282
286
  unless filters[:has_note].nil?
283
287
  conditions << <<~JS
284
- const hasNote = item.note && item.note.trim().length > 0;
288
+ const hasNote = (item.note || "").trim().length > 0;
285
289
  if (hasNote !== #{filters[:has_note]}) return false;
286
290
  JS
287
291
  end
@@ -508,7 +512,7 @@ module OmnifocusMcp
508
512
  const entityType = "#{entity}";
509
513
 
510
514
  if (entityType === "tasks") {
511
- items = flattenedTasks;
515
+ items = flattenedTasks.filter(task => task.project === null);
512
516
  } else if (entityType === "projects") {
513
517
  items = flattenedProjects;
514
518
  } else if (entityType === "folders") {
@@ -48,7 +48,7 @@ module OmnifocusMcp
48
48
  delete foundItem
49
49
 
50
50
  -- Return success
51
- return "{\\"success\\":true,\\"id\\":\\"" & itemId & "\\",\\"name\\":\\"" & itemName & "\\"}"
51
+ return "{\\"success\\":true,\\"id\\":\\"" & itemId & "\\",\\"name\\":\\"" & my jsonEscape(itemName) & "\\"}"
52
52
  else
53
53
  return "{\\"success\\":false,\\"error\\":\\"Item not found\\"}"
54
54
  end if
@@ -27,9 +27,11 @@ module OmnifocusMcp
27
27
 
28
28
  def location_for(args, placement)
29
29
  case placement
30
- when "parent" then "under the parent task"
31
- when "project" then args[:projectName] ? %(in project "#{args[:projectName]}") : "in a project"
32
- else "in your inbox"
30
+ when "parent"
31
+ "under the parent task"
32
+ when "project"
33
+ args[:projectName] ? %(in project "#{args[:projectName]}") : "in a project"
34
+ else "in your inbox"
33
35
  end
34
36
  end
35
37
 
@@ -37,7 +37,7 @@ module OmnifocusMcp
37
37
 
38
38
  def call(params)
39
39
  params = Params::McpBoundary.coerce(Params::AddTaskParams, params)
40
- generator.generate_apple_script(params).then { |script| run_script(script) }
40
+ generator.generate_apple_script(params).then { run_script(it) }
41
41
  rescue StandardError => e
42
42
  OmnifocusMcp.logger.warn("[add_omnifocus_task] Error: #{e}")
43
43
  OmnifocusMcp::Result.error(e.message || "Unknown error in add_omnifocus_task")
@@ -50,7 +50,9 @@ module OmnifocusMcp
50
50
  def run_script(script)
51
51
  stdout, stderr, status = script_runner.execute_applescript(script)
52
52
 
53
- OmnifocusMcp.logger.warn("[add_omnifocus_task] AppleScript stderr: #{stderr}") if stderr && !stderr.empty?
53
+ if Utils::Blank.present?(stderr)
54
+ OmnifocusMcp.logger.warn("[add_omnifocus_task] AppleScript stderr: #{stderr}")
55
+ end
54
56
  return OmnifocusMcp::Result.error(applescript_run_failure(stderr:, status:)) unless status.success?
55
57
 
56
58
  parse_result(stdout)
@@ -65,7 +67,7 @@ module OmnifocusMcp
65
67
  def applescript_run_failure(stderr:, status:)
66
68
  exit_code = status.respond_to?(:exitstatus) ? status.exitstatus : status
67
69
  message = "osascript failed (exit #{exit_code})"
68
- message += ": #{stderr.strip}" unless stderr.nil? || stderr.empty?
70
+ message += ": #{stderr.strip}" unless Utils::Blank.blank?(stderr)
69
71
  message
70
72
  end
71
73
  end